Off-line tracking function using sub-optimal query-matching algorithm
779823
def tracking(oracle, obs, trn_type=1, reverse_init=False, method='else', decay=1.0):
    
    N = len(obs)
    if reverse_init:
        r_oracle = create_reverse_oracle(oracle)
        _ind = [r_oracle.n_states - rsfx for rsfx in r_oracle.rsfx[0][:]]
        init_ind = []
        for i in _ind:
            s = i
            while oracle.sfx[s] != 0:
                s = oracle.sfx[s]
            init_ind.append(s)
        K = r_oracle.num_clusters()
    else:
        init_ind = oracle.rsfx[0][:]
        K = oracle.num_clusters()

    P = np.zeros((N, K), dtype='int')
    T = np.zeros((N,), dtype='int')
    map_k_outer = partial(_query_k, oracle=oracle, query=obs)
    map_query = partial(_query_init, oracle=oracle, query=obs[0], method=method)
    #     map_query = partial(_query_init, oracle=oracle, query=obs[0], method)

    argmin = np.argmin

    P[0], C = zip(*map(map_query, init_ind))
    C = np.array(C)
    T[0] = P[0][argmin(C)]

    if trn_type == 1:
        trn = _create_trn_self
    elif trn_type == 2:
        trn = _create_trn_sfx_rsfx
    else:
        trn = _create_trn

    distance_cache = np.zeros(oracle.n_states)

    for i in range(1, N):  # iterate over the rest of query
        state_cache = []
        dist_cache = distance_cache

        map_k_inner = partial(map_k_outer, i=i, P=P, trn=trn, state_cache=state_cache, dist_cache=dist_cache)
        P[i], _c = zip(*map(map_k_inner, range(K)))
        C = decay * C + np.array(_c)
        T[i] = P[i][argmin(C)]

    return T
784951
async def get_tracks(self, query) -> Tuple[Track, ...]:
        
        if not self._warned:
            log.warn("get_tracks() is now deprecated. Please switch to using load_tracks().")
            self._warned = True
        result = await self.load_tracks(query)
        return result.tracks
381103
def track_parallel(items, sub_type):
    
    out = []
    for i, args in enumerate(items):
        item_i, item = _get_provitem_from_args(args)
        if item:
            sub_entity = "%s.%s.%s" % (item["provenance"]["entity"], sub_type, i)
            item["provenance"]["entity"] = sub_entity
            args = list(args)
            args[item_i] = item
        out.append(args)
    # TODO: store mapping of entity to sub identifiers
    return out
1090577
def fast_approximate_personalized_pagerank(s,
                                           r,
                                           w_i,
                                           a_i,
                                           out_degree,
                                           in_degree,
                                           seed_node,
                                           rho=0.2,
                                           epsilon=0.00001):
    
    # Initialize approximate PageRank and residual distributions
    # s = np.zeros(number_of_nodes, dtype=np.float64)
    # r = np.zeros(number_of_nodes, dtype=np.float64)
    r[seed_node] = 1.0

    # Initialize queue of nodes to be pushed
    pushable = deque()
    pushable.append(seed_node)

    # Do one push anyway
    push_node = pushable.popleft()

    pagerank_limit_push(s,
                        r,
                        w_i[push_node],
                        a_i[push_node],
                        push_node,
                        rho)
    number_of_push_operations = 1

    i = np.where(np.divide(r[a_i[push_node]], in_degree[a_i[push_node]]) >= epsilon)[0]
    if i.size > 0:
        pushable.extend(a_i[push_node][i])

    while len(pushable) > 0:
        # While there are nodes with large residual probabilities, push
        push_node = pushable.popleft()
        if r[push_node]/in_degree[push_node] >= epsilon:
            pagerank_limit_push(s,
                                r,
                                w_i[push_node],
                                a_i[push_node],
                                push_node,
                                rho)
            number_of_push_operations += 1

            i = np.where(np.divide(r[a_i[push_node]], in_degree[a_i[push_node]]) >= epsilon)[0]
            if i.size > 0:
                pushable.extend(a_i[push_node][i])

    return number_of_push_operations
1201720
def robots(self):
        """"""
        r = 'noindex' if self.is_noindex else 'index'
        r += ','
        r += 'nofollow' if self.is_nofollow else 'follow'
        return r
590275
function(points, callback, fromIndex, toIndex) {
	var i, len, index, currentDistance, currentSpeed, fastestSpeed = 0, slowestSpeed = 100000000;
	var result;
	len = points.length - 1;
	i = 0;
	if(fromIndex && fromIndex > 0 && fromIndex < len) {
		i = fromIndex;
	}
	if(toIndex && toIndex < len) {
		len = toIndex;
	}
	if(points.length < 2 || len - i < 2) {
		return callback(new Error('Result can not be calculated properly with data points less than 2'), null);
	}

	try {
		result = new TrackingResult();
		index = 0;
		result.points[index] = Trackpoint.copy(points[i]);
		result.points[index].distance = 0;
		for(; i < len; i++, index++) {
			result.points[index + 1] = Trackpoint.copy(points[i + 1]);
			currentDistance = distance.getDistance(result.points[index].lng, result.points[index].lat, result.points[index + 1].lng, result.points[index + 1].lat);
			currentSpeed = speed.calculateSpeed(currentDistance, result.points[index].time, result.points[index + 1].time);
			result.totalDistance += currentDistance;
			result.points[index + 1].distance = result.points[index].distance + currentDistance;
			result.points[index + 1].speed = currentSpeed;
			if(currentSpeed > fastestSpeed) {
				fastestSpeed = currentSpeed;
			}
			if(currentSpeed < slowestSpeed) {
				slowestSpeed = currentSpeed;
			}
		}
		result.points[0].speed = result.points[1].speed;
		result.averageSpeed = speed.calculateSpeed(result.totalDistance, result.points[0].time, result.points[index].time);
		result.fastestSpeed = fastestSpeed;
		result.slowestSpeed = slowestSpeed;
		result.totalTime = time.getDiffInSecs(result.points[0].time, result.points[index].time);
		callback(null, result);
	} catch(e) {
		callback(e, null);
	}
}
385210
def _find_row_label_positions(self, match_value_or_fct, levels=None):
        """"""
        allmatches = find_locations(self.df.index, match_value_or_fct, levels)
        if allmatches and self.inc_index:  # tramslate back
            allmatches = [m + self.nhdrs for m in allmatches]
        return allmatches
986725
private boolean kNNABOD(Database db, Relation<V> relation, DBIDs ids, WritableDoubleDataStore abodvalues, DoubleMinMax minmaxabod) {
    DistanceQuery<V> dq = db.getDistanceQuery(relation, SquaredEuclideanDistanceFunction.STATIC);
    KNNQuery<V> knnq = db.getKNNQuery(dq, DatabaseQuery.HINT_OPTIMIZED_ONLY);
    boolean squared = true;
    if(knnq == null) {
      dq = db.getDistanceQuery(relation, EuclideanDistanceFunction.STATIC);
      knnq = db.getKNNQuery(dq, DatabaseQuery.HINT_OPTIMIZED_ONLY);
      if(knnq == null) {
        return false;
      }
      squared = false;
    }
    SimilarityQuery<V> lk = db.getSimilarityQuery(relation, LinearKernelFunction.STATIC);
    int k1 = k + 1; // We will get the query point back by the knnq.

    MeanVariance s = new MeanVariance();
    for(DBIDIter pA = ids.iter(); pA.valid(); pA.advance()) {
      KNNList nl = knnq.getKNNForDBID(pA, k1);
      double simAA = lk.similarity(pA, pA);

      s.reset();
      DoubleDBIDListIter iB = nl.iter(), iC = nl.iter();
      for(; iB.valid(); iB.advance()) {
        double dAB = iB.doubleValue();
        double simAB = lk.similarity(pA, iB);
        if(!(dAB > 0.)) {
          continue;
        }
        for(iC.seek(iB.getOffset() + 1); iC.valid(); iC.advance()) {
          double dAC = iC.doubleValue();
          double simAC = lk.similarity(pA, iC);
          if(!(dAC > 0.)) {
            continue;
          }
          // Exploit bilinearity of scalar product:
          // <B-A, C-A> = <B, C-A> - <A,C-A>
          // = <B,C> - <B,A> - <A,C> + <A,A>
          double simBC = lk.similarity(iB, iC);
          double numerator = simBC - simAB - simAC + simAA;
          if(squared) {
            double div = 1. / (dAB * dAC);
            s.put(numerator * div, FastMath.sqrt(div));
          }
          else {
            double sqrtdiv = 1. / (dAB * dAC);
            s.put(numerator * sqrtdiv * sqrtdiv, sqrtdiv);
          }
        }
      }
      final double abof = s.getNaiveVariance();
      minmaxabod.put(abof);
      abodvalues.putDouble(pA, abof);
    }
    return true;
  }
1362424
def _match_auto(self, screen, search_img, threshold):
        
        # 1. try template first
        ret = ac.find_template(screen, search_img)
        if ret and ret['confidence'] > threshold:
            return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_TMPL, matched=True)

        # 2. try sift
        ret = ac.find_sift(screen, search_img, min_match_count=10)
        if ret is None:
            return None

        matches, total = ret['confidence']
        if 1.0*matches/total > 0.5: # FIXME(ssx): sift just write here
            return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_SIFT, matched=True)
        return None
649358
void match(Input<RAW> rawInput, Input<BASE> baseInput, Tracking<RAW, BASE> tracking) {
    BlockHashSequence rawHashSequence = rawInput.getBlockHashSequence();
    BlockHashSequence baseHashSequence = baseInput.getBlockHashSequence();

    Multimap<Integer, RAW> rawsByLine = groupByLine(tracking.getUnmatchedRaws(), rawHashSequence);
    Multimap<Integer, BASE> basesByLine = groupByLine(tracking.getUnmatchedBases(), baseHashSequence);
    Map<Integer, HashOccurrence> occurrencesByHash = new HashMap<>();

    for (Integer line : basesByLine.keySet()) {
      int hash = baseHashSequence.getBlockHashForLine(line);
      HashOccurrence hashOccurrence = occurrencesByHash.get(hash);
      if (hashOccurrence == null) {
        // first occurrence in base
        hashOccurrence = new HashOccurrence();
        hashOccurrence.baseLine = line;
        hashOccurrence.baseCount = 1;
        occurrencesByHash.put(hash, hashOccurrence);
      } else {
        hashOccurrence.baseCount++;
      }
    }

    for (Integer line : rawsByLine.keySet()) {
      int hash = rawHashSequence.getBlockHashForLine(line);
      HashOccurrence hashOccurrence = occurrencesByHash.get(hash);
      if (hashOccurrence != null) {
        hashOccurrence.rawLine = line;
        hashOccurrence.rawCount++;
      }
    }

    for (HashOccurrence hashOccurrence : occurrencesByHash.values()) {
      if (hashOccurrence.baseCount == 1 && hashOccurrence.rawCount == 1) {
        // Guaranteed that baseLine has been moved to rawLine, so we can map all issues on baseLine to all issues on rawLine
        map(rawsByLine.get(hashOccurrence.rawLine), basesByLine.get(hashOccurrence.baseLine), tracking);
        basesByLine.removeAll(hashOccurrence.baseLine);
        rawsByLine.removeAll(hashOccurrence.rawLine);
      }
    }

    // Check if remaining number of lines exceeds threshold. It avoids processing too many combinations.
    if (basesByLine.keySet().size() * rawsByLine.keySet().size() >= 250_000) {
      return;
    }

    List<LinePair> possibleLinePairs = Lists.newArrayList();
    for (Integer baseLine : basesByLine.keySet()) {
      for (Integer rawLine : rawsByLine.keySet()) {
        int weight = lengthOfMaximalBlock(baseInput.getLineHashSequence(), baseLine, rawInput.getLineHashSequence(), rawLine);
        if (weight > 0) {
          possibleLinePairs.add(new LinePair(baseLine, rawLine, weight));
        }
      }
    }
    Collections.sort(possibleLinePairs, LinePairComparator.INSTANCE);
    for (LinePair linePair : possibleLinePairs) {
      // High probability that baseLine has been moved to rawLine, so we can map all issues on baseLine to all issues on rawLine
      map(rawsByLine.get(linePair.rawLine), basesByLine.get(linePair.baseLine), tracking);
    }
  }
1371169
def _find_closest_trackpoint(self,R,vR,vT,z,vz,phi,interp=True,xy=False,
                                 usev=False):
        """"""
        return self.find_closest_trackpoint(R,vR,vT,z,vz,phi,
                                            interp=interp,xy=xy,
                                            usev=usev)
941397
function getFollowersIt(T, user_id, followers, cursor, max_followers, finish) {
  if (followers.length >= max_followers) {
    return finish(followers);
  }

  T.get('followers/list', {user_id: user_id, cursor: cursor}, function (err, data) {
    if (err) {
      console.log(err);
      return delay(function () {
        getFollowersIt(T, user_id, followers, cursor, max_followers, finish);
      });
    }

    // user.followers_ids = data.users.map(function (user) { 
    //   return user.id;
    // });
    // finish(data.users);
    followers = followers.concat(data.users);
    getFollowersIt(T, user_id, followers, data.next_cursor, max_followers, finish);
  });
}
1096295
def run_tracking(self, label_image_1, label_image_2):
        
        self.scale = self.parameters_tracking["avgCellDiameter"] / 35.0

        detections_1 = self.derive_detections(label_image_1)

        detections_2 = self.derive_detections(label_image_2)

        # Calculate tracking based on cell features and position.
        traces = self.find_initials_traces(detections_1, detections_2)

        # Use neighbourhoods to improve tracking.
        for _ in range(int(self.parameters_tracking["iterations"])):
            traces = self.improve_traces(detections_1, detections_2, traces)

        # Filter traces.
        return [(trace.previous_cell.number, trace.current_cell.number) for trace in traces]
497152
protected boolean trackFeature() {

		pairs.reset();
		// total number of tracks which contribute to FB error
		int numTracksFB = 0;
		// tracks which are not dropped
		int numTracksRemaining = 0;

		for( int i = 0; i < tracks.length; i++ ) {
			Track t = tracks[i];
			if( !t.active )
				continue;

			float prevX = t.klt.x;
			float prevY = t.klt.y;

			// track in forwards direction
			tracker.setImage(currentImage,currentDerivX,currentDerivY);
			KltTrackFault result = tracker.track(t.klt);
			if( result != KltTrackFault.SUCCESS ) {
				t.active = false;
				continue;
			}

			float currX = t.klt.x;
			float currY = t.klt.y;

			// track in reverse direction
			tracker.setDescription(t.klt);
			tracker.setImage(previousImage, previousDerivX, previousDerivY);
			result = tracker.track(t.klt);
			if( result != KltTrackFault.SUCCESS ) {
				t.active = false;
				continue;
			}

			// compute forward-backwards error
			double errorForwardBackwards = UtilPoint2D_F32.distanceSq(prevX,prevY,t.klt.x,t.klt.y);

			// put into lists for computing the median error
			errorsFB[numTracksFB++] = errorForwardBackwards;

			// discard if error is too large
			if( errorForwardBackwards > maxErrorFB ) {
				t.active = false;
				continue;
			}

			// create data structure used for group motion estimation
			AssociatedPair p = pairs.grow();
			p.p1.set( prevX, prevY );
			p.p2.set( currX, currY );

			numTracksRemaining++;
		}

		// if the forward-backwards error is too large, give up
		double medianFB = QuickSelect.select(errorsFB,numTracksFB/2,numTracksFB);

//		System.out.println("Median tracking error FB: "+medianFB);

		if( medianFB > maxErrorFB || numTracksRemaining < 4 )
			return false;

		return true;
	}
582960
function TrackChinaPostInfo(obj) {
    this.id = obj.id
    this.state = obj.states[obj.states.length - 1].state
    this.states = obj.states.reverse()

    this.trackerWebsite = trackchinapost.getLink(null)
}
1124019
function next_step(response, search){

	ll('init start...');

	// Prevent future actions (the register would be sticky).
	search.unregister('search', 'next step');

	// Take a look at the two facets that we'll be iterating over.
	ll('Gathering functions for term data...');
	var reqs_to_do = 0;
	f1 = response.facet_field(global_facet1);
	f2 = response.facet_field(global_facet2);
	ll('f1: ' + f1);
	ll('f2: ' + f2);

	// Collect the initial node information for the two axes.
	// Also collect the initial index by id for both axes.
	var id_to_index = {};
	us.each([f1, f2], function(set){
	    us.each(set, function(set_pair, set_index){
		var sid = set_pair[0];
		nodes.push({id: sid, index: set_index});
		id_to_index[sid] = set_index;
	    });
	});
	ll('id_to_index #: ' + us.keys(id_to_index).length);

	// Now collect the batch URLs along one facet in reference to
	// the other (arbitrary)--we should be able to get what we
	// want by just looking at once facet and checking the other
	// as we vary it.
	var collected_functions = [];
	us.each(f1, function(f1_pair){
	    reqs_to_do++;
	    collected_functions.push(
		function(){
		    var f1_id = f1_pair[0];
		    
		    // Return the state.
		    // We have to reset the rows as well since rows is
		    // not sticky across a search action (think about
		    // it).
		    search.set('rows', 0); // we don't need any actual rows
		    search.set_facet_limit(flimit);
		    search.reset_query_filters();
		    
		    search.add_query_filter(global_facet1, f1_id);
		    return search.search();
		});
	});

	// Fetch the data and scrape out what we want.
	var reqs_done = 0;
	var accumulator_fun = function(resp){

	    // Update progress bar.
	    reqs_done++;
	    var per = Math.round((reqs_done / reqs_to_do) * 100);
	    //ll(reqs_done + ' of ' + reqs_to_do + ' = ' + per + '%');
	    // jQuery(pwidget).progressbar('value', per);
	    jQuery(pwidget_bs3_bar).css('width', per + '%');
	    jQuery(pwidget_bs3_bar).attr('aria-valuenow', per);

	    // Recover the facet that we're currently looking at: 1.
	    var f1_name = '???';
    	    var fq_set = resp.parameter('fq');
	    //ll('accumu: ' + dump(fq_set));
	    us.each(fq_set, function(fq_item){
		// Split up each line in the set.
		var two_part = bbop.first_split(':', fq_item);
    		var fkey = two_part[0];
    		var fval = bbop.dequote(two_part[1]);
    		//ll('Looking at info for: ' + fval);
		
		// Check to see if it matches. If it does, that's the
		// recovered value.
		if( fkey === global_facet1 ){
		    f1_name = fval;		     
		}
	    });
	    ll('got: ' + f1_name);

	    // Now grab out all of the second-facet information.
	    //ll('accumu: ' + resp.raw());
	    var incoming_facet = resp.facet_field(global_facet2);
	    var in_hash = bbop.hashify(incoming_facet);	
	    ll('in_hash: ' + bbop.dump(in_hash));
	    us.each(f2, function(f2_line, f2_index){

		// Figure out the value for this pair.
		var f2_name = f2_line[0];
		//var comb_val = f2_line[1];
		var comb_val = 0;
		var results_val = 0;
		if( typeof(in_hash[f2_name]) !== 'undefined' ){
		    results_val = in_hash[f2_name];
		}
		ll([f1_name, f2_name].join(', ') + ': ' + results_val);
		
		// Up the max.
		if( results_val > max_val ){
		    max_val = results_val;
		}
		
		// While we're here, let's also create a lookup
		// structure.
		if( typeof(val_hash[f1_name]) === 'undefined' ){
		    val_hash[f1_name] = {}; }
		if( typeof(val_hash[f2_name]) === 'undefined' ){
		    val_hash[f2_name] = {}; }
		if( typeof(val_hash[f1_name][f2_name]) === 'undefined' ){
		    val_hash[f1_name][f2_name] = results_val; }
		if( typeof(val_hash[f2_name][f1_name]) === 'undefined' ){
		    val_hash[f2_name][f1_name] = results_val; }
	    });
	};

	///
	/// Coloration functions using D3.
	/// We have the max_val now, so we can compute color.
	///

	// A value from our values domain in to a color in our range.
	// 0 always maps to a white-ish color.
	var c = d3.scale.linear().domain([0,max_val]).rangeRound([127,255]);
	function value_to_color_dark(val){
	    //var retval = '#efefef';
	    var retval = '#fafafa';
	    if( val !== 0 ){
		var cval = c(val);
		var cinv = 255 - cval;
		var chex = cinv.toString(16);
		if( cval ){
		    if( chex.length === 1 ){ chex = '0' + chex; }
		    retval = '#' + chex + chex + chex + '';
		}
	    }
	    return retval;
	}
	function value_to_color_step(val){
	    //var retval = '#efefef';
	    var retval = '#fafafa';
	    if( val !== 0 ){
		// 1-3 = pale green
		// 4-10 = yellow
		// 11-100 = orange
		// 101+ = red 
		if( val <= 3 ){
		    retval = '#79f853'; // green
		}else if( val <= 10 ){
		    //retval = '#f5ff2b'; // yellow
		    retval = '#e8f129'; // yellow
		}else if( val <= 100 ){
		    retval = '#fd953b'; // orange		
		}else{
		    retval = '#ff4e53';
		}
	    }
	    return retval;
	}	
	// Decide our coloration live at this point.
	//var value_to_color = value_to_color_dark; // default
	value_to_color = value_to_color_step; // default
	// var curr_color_selection =
	// 	jQuery("input:radio[name=color]:checked").val();
	
	// The final function is the data renderer.
	var final_fun = function(){
	    ll('Entering final_fun...');

	    // We are done!
	    jQuery(pwidget_bs3_container).hide();

	    //render(matrix, nodes, max_val);
	    render();
	};

	// The final function is the data renderer.
	var error_fun = function(err){
	    alert('Encountered error while running: ' + err.toString());
	};

	search.run_promise_functions(collected_functions,
				     accumulator_fun, final_fun, error_fun);
    }
1366201
def _twofilter_smoothing_ON2(self, t, ti, info, phi, lwinfo):
        
        sp, sw = 0., 0.
        upb = lwinfo.max() + self.wgt[t].lw.max()
        if hasattr(self.model, 'upper_bound_trans'):
            upb += self.model.upper_bound_trans(t + 1)
        # Loop over n, to avoid having in memory a NxN matrix
        for n in range(self.N):
            omegan = np.exp(lwinfo + self.wgt[t].lw[n] - upb
                            + self.model.logpt(t + 1, self.X[t][n],
                                               info.hist.X[ti]))
            sp += np.sum(omegan * phi(self.X[t][n], info.hist.X[ti]))
            sw += np.sum(omegan)
        return sp / sw