Recalculate form counts from scratch.
196753
async def _calcFormCounts(self):
        '''
        
        '''
        logger.info('Calculating form counts from scratch.')
        self.counts.clear()

        nameforms = list(self.model.forms.items())
        fairiter = 5
        tcount = 0
        for i, (name, form) in enumerate(nameforms, 1):
            logger.info('Calculating form counts for [%s] [%s/%s]',
                        name, i, len(nameforms))
            count = 0

            async for buid, valu in self.view.layers[0].iterFormRows(name):

                count += 1
                tcount += 1

                if count % fairiter == 0:
                    await asyncio.sleep(0)
                    # identity check for small integer
                    if fairiter == 5 and tcount > 100000:
                        fairiter = 1000

            self.counts[name] = count

        for name, valu in self.counts.items():
            byts = s_common.int64en(valu)
            self.slab.put(name.encode('utf8'), byts, db=self.formcountdb)
        logger.info('Done calculating form counts.')
1276386
def process_sub_grow(ref, alt_str):
    """"""
    if len(alt_str) == 0:
        raise exceptions.InvalidRecordException("Invalid VCF, empty ALT")
    elif len(alt_str) == 1:
        if ref[0] == alt_str[0]:
            return record.Substitution(record.DEL, alt_str)
        else:
            return record.Substitution(record.INDEL, alt_str)
    else:
        return record.Substitution(record.INDEL, alt_str)
94323
def update_counts(self, current):
        
        for item in current:
            try:
                self.counts[item] += 1
            except KeyError:
                self.counts[item] = 1
161645
public function recalculateStats()
	{
		if (empty($this->stats)) {
			$this->stats = new Stats();
		}

		$this->stats->reset();

		if (empty($this->points)) {
			return;
		}

		$pointCount = count($this->points);

		$firstPoint = &$this->points[0];
		$lastPoint = end($this->points);

		$this->stats->startedAt = $firstPoint->time;
		$this->stats->finishedAt = $lastPoint->time;
		$this->stats->minAltitude = $firstPoint->elevation;

		list($this->stats->cumulativeElevationGain, $this->stats->cumulativeElevationLoss) =
			ElevationGainLossCalculator::calculate($this->getPoints());

		$this->stats->distance = DistanceCalculator::calculate($this->getPoints());

		for ($p = 0; $p < $pointCount; $p++) {
			if ((phpGPX::$IGNORE_ELEVATION_0 === false || $this->points[$p]->elevation > 0) && $this->stats->minAltitude > $this->points[$p]->elevation) {
				$this->stats->minAltitude = $this->points[$p]->elevation;
			}

			if ($this->stats->maxAltitude < $this->points[$p]->elevation) {
				$this->stats->maxAltitude = $this->points[$p]->elevation;
			}

			if ($this->stats->minAltitude > $this->points[$p]->elevation) {
				$this->stats->minAltitude = $this->points[$p]->elevation;
			}
		}

		if (($firstPoint->time instanceof \DateTime) && ($lastPoint->time instanceof \DateTime)) {
			$this->stats->duration = $lastPoint->time->getTimestamp() - $firstPoint->time->getTimestamp();

			if ($this->stats->duration != 0) {
				$this->stats->averageSpeed = $this->stats->distance / $this->stats->duration;
			}

			if ($this->stats->distance != 0) {
				$this->stats->averagePace = $this->stats->duration / ($this->stats->distance / 1000);
			}
		}
	}
307514
def number_of_changes(slots, events, original_schedule, X, **kwargs):
    
    changes = 0
    original_array = schedule_to_array(original_schedule, events=events,
                                       slots=slots)
    for row, event in enumerate(original_array):
        for col, slot in enumerate(event):
            if slot == 0:
                changes += X[row, col]
            else:
                changes += 1 - X[row, col]
    return changes
613637
def update(self, data):
        """"""
        for character in data:
            if PY3:
                ch = character
            else:
                ch = ord(character)
            self.count += 1

            # incr accumulators for triplets
            if self.lastch[1] > -1:
                self.acc[self.tran3(ch, self.lastch[0], self.lastch[1], 0)] +=1
            if self.lastch[2] > -1:
                self.acc[self.tran3(ch, self.lastch[0], self.lastch[2], 1)] +=1
                self.acc[self.tran3(ch, self.lastch[1], self.lastch[2], 2)] +=1
            if self.lastch[3] > -1:
                self.acc[self.tran3(ch, self.lastch[0], self.lastch[3], 3)] +=1
                self.acc[self.tran3(ch, self.lastch[1], self.lastch[3], 4)] +=1
                self.acc[self.tran3(ch, self.lastch[2], self.lastch[3], 5)] +=1
                self.acc[self.tran3(self.lastch[3], self.lastch[0], ch, 6)] +=1
                self.acc[self.tran3(self.lastch[3], self.lastch[2], ch, 7)] +=1

            # adjust last seen chars
            self.lastch = [ch] + self.lastch[:3]
1352706
def _restore_auto_increment(self, table):
        """"""
        query, seq_table, seq_column, seq_name = self._get_auto_increment_info(table)
        if query:
            queries = [query, "select nextval('{}')".format(seq_name)]
            return self._run_queries(queries)
888614
def reload(self):
        ''
        self.rows = []

#        if len(self.origCols) == 1 and self.origCols[0].type in (int, float, currency):
#            self.numericBinning()
#        else:
        self.discreteBinning()

        # automatically add cache to all columns now that everything is binned
        for c in self.nonKeyVisibleCols:
            c._cachedValues = collections.OrderedDict()
315583
def rebind_calculations(portal):
    """"""
    logger.info("Rebinding calculations to analyses ...")
    review_states = ["sample_due",
                     "attachment_due",
                     "sample_received",
                     "to_be_verified"]

    calcs = {}
    brains = api.search(dict(portal_type="Calculation"), "bika_setup_catalog")
    for calc in brains:
        calc = api.get_object(calc)
        calc.setFormula(calc.getFormula())
        calcs[api.get_uid(calc)] = calc

    query = dict(review_state=review_states)
    analyses = api.search(query, CATALOG_ANALYSIS_LISTING)
    total = len(analyses)
    for num, analysis in enumerate(analyses):
        if num % 100 == 0:
            logger.info("Rebinding calculations to analyses: {0}/{1}"
                        .format(num, total))
        analysis = api.get_object(analysis)
        calc = analysis.getCalculation()
        if not calc:
            continue

        calc_uid = api.get_uid(calc)
        if calc_uid not in calcs:
            logger.warn("Calculation with UID {} not found!".format(calc_uid))
            continue

        calc = calcs[calc_uid]
        an_interims = analysis.getInterimFields()
        an_interims_keys = map(lambda interim: interim.get('keyword'),
                               an_interims)
        calc_interims = filter(lambda interim: interim.get('keyword')
                                            not in an_interims_keys,
                            calc.getInterimFields())
        analysis.setCalculation(calc)
        analysis.setInterimFields(an_interims + calc_interims)
27443
def visit_Num(self, node: ast.Num) -> Union[int, float]:
        """"""
        result = node.n

        self.recomputed_values[node] = result
        return result
1185997
protected void recalculateData() {
        Node currentChild = this.getChild();
        if (currentChild != null) {
            ClusKernel currentData = this.getData();
            currentData.clear();
            Entry[] entries = currentChild.getEntries();
            for (int i = 0; i < entries.length; i++) {
                currentData.add(entries[i].getData());
            }
        } else {
            this.clear();
        }
    }
33551
def recalculate_satistics(self):
        '''
        
        '''
        gframe = wx.BusyInfo(
            "Re-calculating statistics for all specimens\n Please wait..", self)

        for specimen in list(self.Data.keys()):
            if 'pars' not in list(self.Data[specimen].keys()):
                continue
            if 'specimen_int_uT' not in list(self.Data[specimen]['pars'].keys()):
                continue
            tmin = self.Data[specimen]['pars']['measurement_step_min']
            tmax = self.Data[specimen]['pars']['measurement_step_max']
            pars = thellier_gui_lib.get_PI_parameters(
                self.Data, self.acceptance_criteria, self.preferences, specimen, tmin, tmax, self.GUI_log, THERMAL, MICROWAVE)
            self.Data[specimen]['pars'] = pars
            self.Data[specimen]['pars']['lab_dc_field'] = self.Data[specimen]['lab_dc_field']
            self.Data[specimen]['pars']['er_specimen_name'] = self.Data[specimen]['er_specimen_name']
            self.Data[specimen]['pars']['er_sample_name'] = self.Data[specimen]['er_sample_name']
        del gframe
673976
def recarray(self):
        """"""

        if self.records is None:
            self.parse()
        try:
            # simple (should this also be subjected to convert.to_int64() ?)
            return numpy.rec.fromrecords(self.records, names=self.names)
        except ValueError:
            # complicated because fromrecords cannot deal with records of lists
            # Quick hack: use objects for lists etc (instead of building the proper
            # data types (see docs for numpy.dtype , eg dtype('coord', (float, 3)) )

            D = numpy.empty(len(self.records[0]), dtype=object)    # number of fields from first record
            types = numpy.array([map(type, r) for r in self.records])  # types of all fields
            for icol, isSame in enumerate([numpy.all(col) for col in types.T]):
                if isSame:
                    D[icol] = types[0][icol]
                else:
                    D[icol] = object
            dtype = numpy.dtype(zip(self.names, D))
            # from numpy.rec.records
            # TODO: this is not working properly yet; for instance, text fields
            # are reduced to length 0 (<U0) and the final convert.to_int64 dies
            # with '<U0'*** TypeError: TypeError('data type not understood',)
            retval = numpy.array(self.records, dtype=dtype)
            res = retval.view(numpy.recarray)
            ## res.dtype = numpy.dtype((numpy.rec.record, res.dtype))  # fails -- ARGH, this makes it a recarray
            return convert.to_int64(res)
325331
def __recordFmt(self):
        """"""
        if not self.numRecords:
            self.__dbfHeader()
        fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in self.fields])
        fmtSize = calcsize(fmt)
        return (fmt, fmtSize)
436582
public function recalculateRatings()
    {
        // Compute rating value.
        // @todo Need to know weather comments has changed or not.
        // Unfortunately, persistent collection gets no dirty flag,
        // if existing entries are changed....
        // We limit recalculates to the cases where comments gets loaded from
        // the database (which still does not neccessarly mean, there are changes...

        $comments = $this->getComments();
        if ($comments instanceof ArrayCollection // new Comments
            || $comments->isInitialized() // Comments were loaded and eventually changed (we do not know)
            || $comments->isDirty() // new Comments added w/o initializing
        ) {
            $this->getRating(/*recalculate*/ true);
        }
    }
955051
def update_subtotals(self, current, sub_key):
        

        if not self.sub_counts.get(sub_key):
            self.sub_counts[sub_key] = {}
        for item in current:
            try:
                self.sub_counts[sub_key][item] += 1
            except KeyError:
                self.sub_counts[sub_key][item] = 1
240209
def ajax_recalculate_records(self):
        
        out = {}

        # The sorted records from the request
        records = self.get_records()

        for n, record in enumerate(records):

            # Mapping of client UID -> client object info
            client_metadata = {}
            # Mapping of contact UID -> contact object info
            contact_metadata = {}
            # Mapping of sample UID -> sample object info
            sample_metadata = {}
            # Mapping of sampletype UID -> sampletype object info
            sampletype_metadata = {}
            # Mapping of specification UID -> specification object info
            specification_metadata = {}
            # Mapping of specification UID -> list of service UIDs
            specification_to_services = {}
            # Mapping of service UID -> list of specification UIDs
            service_to_specifications = {}
            # Mapping of template UID -> template object info
            template_metadata = {}
            # Mapping of template UID -> list of service UIDs
            template_to_services = {}
            # Mapping of service UID -> list of template UIDs
            service_to_templates = {}
            # Mapping of profile UID -> list of service UIDs
            profile_to_services = {}
            # Mapping of service UID -> list of profile UIDs
            service_to_profiles = {}
            # Profile metadata for UI purposes
            profile_metadata = {}
            # Mapping of service UID -> service object info
            service_metadata = {}
            # mapping of service UID -> unmet service dependency UIDs
            unmet_dependencies = {}

            # Mappings of UID -> object of selected items in this record
            _clients = self.get_objs_from_record(record, "Client_uid")
            _contacts = self.get_objs_from_record(record, "Contact_uid")
            _specifications = self.get_objs_from_record(
                record, "Specification_uid")
            _templates = self.get_objs_from_record(record, "Template_uid")
            _samples = self.get_objs_from_record(record, "PrimaryAnalysisRequest_uid")
            _profiles = self.get_objs_from_record(record, "Profiles_uid")
            _services = self.get_objs_from_record(record, "Analyses")
            _sampletypes = self.get_objs_from_record(record, "SampleType_uid")

            # CLIENTS
            for uid, obj in _clients.iteritems():
                # get the client metadata
                metadata = self.get_client_info(obj)
                # remember the sampletype metadata
                client_metadata[uid] = metadata

            # CONTACTS
            for uid, obj in _contacts.iteritems():
                # get the client metadata
                metadata = self.get_contact_info(obj)
                # remember the sampletype metadata
                contact_metadata[uid] = metadata

            # SPECIFICATIONS
            for uid, obj in _specifications.iteritems():
                # get the specification metadata
                metadata = self.get_specification_info(obj)
                # remember the metadata of this specification
                specification_metadata[uid] = metadata
                # get the spec'd service UIDs
                service_uids = metadata["service_uids"]
                # remember a mapping of specification uid -> spec'd services
                specification_to_services[uid] = service_uids
                # remember a mapping of service uid -> specifications
                for service_uid in service_uids:
                    if service_uid in service_to_specifications:
                        service_to_specifications[service_uid].append(uid)
                    else:
                        service_to_specifications[service_uid] = [uid]

            # AR TEMPLATES
            for uid, obj in _templates.iteritems():
                # get the template metadata
                metadata = self.get_template_info(obj)
                # remember the template metadata
                template_metadata[uid] = metadata

                # profile from the template
                profile = obj.getAnalysisProfile()
                # add the profile to the other profiles
                if profile is not None:
                    profile_uid = api.get_uid(profile)
                    _profiles[profile_uid] = profile

                # get the template analyses
                # [{'partition': 'part-1', 'service_uid': '...'},
                # {'partition': 'part-1', 'service_uid': '...'}]
                analyses = obj.getAnalyses() or []
                # get all UIDs of the template records
                service_uids = map(
                    lambda rec: rec.get("service_uid"), analyses)
                # remember a mapping of template uid -> service
                template_to_services[uid] = service_uids
                # remember a mapping of service uid -> templates
                for service_uid in service_uids:
                    # append service to services mapping
                    service = self.get_object_by_uid(service_uid)
                    # remember the template of all services
                    if service_uid in service_to_templates:
                        service_to_templates[service_uid].append(uid)
                    else:
                        service_to_templates[service_uid] = [uid]

                    # remember the service metadata
                    if service_uid not in service_metadata:
                        metadata = self.get_service_info(service)
                        service_metadata[service_uid] = metadata

            # PROFILES
            for uid, obj in _profiles.iteritems():
                # get the profile metadata
                metadata = self.get_profile_info(obj)
                # remember the profile metadata
                profile_metadata[uid] = metadata
                # get all services of this profile
                services = obj.getService()
                # get all UIDs of the profile services
                service_uids = map(api.get_uid, services)
                # remember all services of this profile
                profile_to_services[uid] = service_uids
                # remember a mapping of service uid -> profiles
                for service in services:
                    # get the UID of this service
                    service_uid = api.get_uid(service)
                    # add the service to the other services
                    _services[service_uid] = service
                    # remember the profiles of this service
                    if service_uid in service_to_profiles:
                        service_to_profiles[service_uid].append(uid)
                    else:
                        service_to_profiles[service_uid] = [uid]

            # PRIMARY ANALYSIS REQUESTS
            for uid, obj in _samples.iteritems():
                # get the sample metadata
                metadata = self.get_sample_info(obj)
                # remember the sample metadata
                sample_metadata[uid] = metadata

            # SAMPLETYPES
            for uid, obj in _sampletypes.iteritems():
                # get the sampletype metadata
                metadata = self.get_sampletype_info(obj)
                # remember the sampletype metadata
                sampletype_metadata[uid] = metadata

            # SERVICES
            for uid, obj in _services.iteritems():
                # get the service metadata
                metadata = self.get_service_info(obj)

                # remember the services' metadata
                service_metadata[uid] = metadata

            #  DEPENDENCIES
            for uid, obj in _services.iteritems():
                # get the dependencies of this service
                deps = get_service_dependencies_for(obj)

                # check for unmet dependencies
                for dep in deps["dependencies"]:
                    # we use the UID to test for equality
                    dep_uid = api.get_uid(dep)
                    if dep_uid not in _services.keys():
                        if uid in unmet_dependencies:
                            unmet_dependencies[uid].append(
                                self.get_base_info(dep))
                        else:
                            unmet_dependencies[uid] = [self.get_base_info(dep)]
                # remember the dependencies in the service metadata
                service_metadata[uid].update({
                    "dependencies": map(
                        self.get_base_info, deps["dependencies"]),
                })

            # Each key `n` (1,2,3...) contains the form data for one AR Add
            # column in the UI.
            # All relevant form data will be set accoriding to this data.
            out[n] = {
                "client_metadata": client_metadata,
                "contact_metadata": contact_metadata,
                "sample_metadata": sample_metadata,
                "sampletype_metadata": sampletype_metadata,
                "specification_metadata": specification_metadata,
                "specification_to_services": specification_to_services,
                "service_to_specifications": service_to_specifications,
                "template_metadata": template_metadata,
                "template_to_services": template_to_services,
                "service_to_templates": service_to_templates,
                "profile_metadata": profile_metadata,
                "profile_to_services": profile_to_services,
                "service_to_profiles": service_to_profiles,
                "service_metadata": service_metadata,
                "unmet_dependencies": unmet_dependencies,
            }

        return out