Generalized cultural Moran process.

    At eachtime step, an individual is chosen to receive information from
    another individual. Nobody dies, but perhaps their ideas do.
351215
def moran_cultural(network):
    
    if not network.transmissions():  # first step, replacer is a source
        replacer = random.choice(network.nodes(type=Source))
        replacer.transmit()
    else:
        replacer = random.choice(network.nodes(type=Agent))
        replaced = random.choice(
            replacer.neighbors(direction="to", type=Agent))

        from operator import attrgetter

        replacer.transmit(
            what=max(replacer.infos(), key=attrgetter('creation_time')),
            to_whom=replaced)
605582
private void processConversationDeliveredAt(String conversationId, int convType, long timestamp) {
    AVConversationHolder conversation = session.getConversationHolder(conversationId, convType);
    conversation.onConversationDeliveredAtEvent(timestamp);
  }
198393
function gossipLastMessageAtFixedInterval(){
    if(p_phase_timeout >0 && Date.now() - p_phase_timeout > constants.BYZANTINE_PHASE_TIMEOUT){

        if(bByzantineUnderWay && last_prevote_gossip &&
            typeof last_prevote_gossip !== 'undefined' &&
            Object.keys(last_prevote_gossip).length > 0){
            if(last_prevote_gossip.type === constants.BYZANTINE_PREVOTE && h_p === last_prevote_gossip.h){
                // console.log("byllllogg gossipLastMessageAtFixedInterval broadcastPrevote" + JSON.stringify(last_prevote_gossip));
                broadcastPrevote(last_prevote_gossip.h, last_prevote_gossip.p, last_prevote_gossip.idv);
            }
        }
        if(bByzantineUnderWay && last_precommit_gossip &&
            typeof last_precommit_gossip !== 'undefined' &&
            Object.keys(last_precommit_gossip).length > 0){
            if(last_precommit_gossip.type === constants.BYZANTINE_PRECOMMIT && h_p === last_precommit_gossip.h){
                if(last_precommit_gossip.idv !== null && assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal
                    && typeof assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal !== 'undefined'){
                    var lastProposal = assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal;
                    broadcastProposal(last_precommit_gossip.h, last_precommit_gossip.p, lastProposal, lastProposal.vp);
                }
                // console.log("byllllogg gossipLastMessageAtFixedInterval broadcastPrecommit" + JSON.stringify(last_precommit_gossip));
                broadcastPrecommit(last_precommit_gossip.h, last_precommit_gossip.p, last_precommit_gossip.sig, last_precommit_gossip.idv);
            }        
        }
    }
}
329816
private void initHeap(ObjectHeap<CASHInterval> heap, Relation<ParameterizationFunction> relation, int dim, DBIDs ids) {
    CASHIntervalSplit split = new CASHIntervalSplit(relation, minPts);

    // determine minimum and maximum function value of all functions
    double[] minMax = determineMinMaxDistance(relation, dim);

    double d_min = minMax[0], d_max = minMax[1];
    double dIntervalLength = d_max - d_min;
    int numDIntervals = (int) FastMath.ceil(dIntervalLength / jitter);
    double dIntervalSize = dIntervalLength / numDIntervals;
    double[] d_mins = new double[numDIntervals],
        d_maxs = new double[numDIntervals];

    if(LOG.isVerbose()) {
      LOG.verbose(new StringBuilder().append("d_min ").append(d_min)//
          .append("\nd_max ").append(d_max)//
          .append("\nnumDIntervals ").append(numDIntervals)//
          .append("\ndIntervalSize ").append(dIntervalSize).toString());
    }

    // alpha intervals
    double[] alphaMin = new double[dim - 1], alphaMax = new double[dim - 1];
    Arrays.fill(alphaMax, Math.PI);

    for(int i = 0; i < numDIntervals; i++) {
      d_mins[i] = (i == 0) ? d_min : d_maxs[i - 1];
      d_maxs[i] = (i < numDIntervals - 1) ? d_mins[i] + dIntervalSize : d_max - d_mins[i];

      HyperBoundingBox alphaInterval = new HyperBoundingBox(alphaMin, alphaMax);
      ModifiableDBIDs intervalIDs = split.determineIDs(ids, alphaInterval, d_mins[i], d_maxs[i]);
      if(intervalIDs != null && intervalIDs.size() >= minPts) {
        heap.add(new CASHInterval(alphaMin, alphaMax, split, intervalIDs, -1, 0, d_mins[i], d_maxs[i]));
      }
    }

    if(LOG.isDebuggingFiner()) {
      LOG.debugFiner(new StringBuilder().append("heap.size: ").append(heap.size()).toString());
    }
  }
844820
function() {
		gui.Broadcast.dispatch(gui.BROADCAST_WILL_SPIRITUALIZE);
		this._spiritualizeinitially();
		gui.Broadcast.dispatch(gui.BROADCAST_DID_SPIRITUALIZE);
	}
669595
function makerelation (model, relation) {
	let options = {
		as: relation.As,
		foreignKey: relation.key
	};
	let target = exp.databases[inflector.pluralize(relation.Children)];
	if (relation.Rel !== 'manyToMany') {
		exp.databases[model][relation.Rel](target, options);
	} else {
		exp.databases[model].prototype.many2many = exp.databases[model].prototype.many2many || {};
		exp.databases[model].prototype.many2many[relation.Parent] = function (id, id2) {
			if (id && id2) {
				return exp.databases[relation.Children].findcre({
					[`${model}ID`]: id,
					[`${relation.Parent}ID`]: id2
				});
			}
			return exp.databases[relation.Children].find({
				where: {
					[`${model}ID`]: id
				}
			}).then(records => {
				let all = [];
				for (const record of records) {
					all.push(exp.databases[relation.Parent].findById(record[`${relation.Parent}ID`]));
				}
				return Promise.all(all);
			});
		};
	}
}
493790
@Override
	public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
		parseBindType(roundEnv);
		
		// Build model
		for (Element element : roundEnv.getElementsAnnotatedWith(BindType.class)) {
			final Element item = element;

			AssertKripton.assertTrueOrInvalidKindForAnnotationException(item.getKind() == ElementKind.CLASS, item, BindType.class);
			BindEntityBuilder.parse(model, (TypeElement) item);
		}
		

		if (globalBeanElements.size() == 0) {
			info("No class with @%s annotation was found", BindType.class.getSimpleName());
		}

		// Generate classes for model
		try {
			generateClasses();
		} catch (IOException e) {
			e.printStackTrace();
			throw(new KriptonRuntimeException(e));
		}

		return true;
	}
692556
function(p, callback) {
					var data = {
						visibility: {
							code: 'anyone'
						}
					};

					if (p.data.id) {

						data.attribution = {
							share: {
								id: p.data.id
							}
						};

					}
					else {
						data.comment = p.data.message;
						if (p.data.picture && p.data.link) {
							data.content = {
								'submitted-url': p.data.link,
								'submitted-image-url': p.data.picture
							};
						}
					}

					p.data = JSON.stringify(data);

					callback('people/~/shares?format=json');
				}
453198
@Override public void processMiniBatch(long seed, double[] responses, double[] offsets, int n) {
    assert(_training);
    if (_localmodel.get_params()._reproducible) {
      seed += _localmodel.get_processed_global(); //avoid periodicity
    } else {
      seed = _dropout_rng.nextLong(); // non-reproducible case - make a fast & good random number
    }
    fpropMiniBatch(seed, _neurons, _localmodel, _localmodel.get_params()._elastic_averaging ? _sharedmodel : null, _training, responses, offsets, n);
    bpropMiniBatch(_neurons, n);
  }
758562
def GenerarRemito(self, id_req, archivo="qr.png"):
        ""
        if not self.remito['arrayContingencias']:
            del self.remito['arrayContingencias']
        response = self.client.generarRemito(
                                authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit},
                                idReq=id_req, remito=self.remito) 
        ret = response.get("generarRemitoReturn")
        if ret:
            self.__analizar_errores(ret)
            self.__analizar_observaciones(ret)
            self.__analizar_evento(ret)
            self.AnalizarRemito(ret, archivo)
        return bool(self.CodRemito)
1012788
private void generalSelectMetricHistory(final LinkedList<InMemoryHistoryNode> selectedLists) {
    logger.debug("selecting snapshots evenly from across the time interval");
    if (selectedLists.size() > this.numInstances) {
      final double step = (double) selectedLists.size() / this.numInstances;
      long nextIndex = 0, currentIndex = 0, numSelectedInstances = 1;
      final Iterator<InMemoryHistoryNode> ite = selectedLists.iterator();
      while (ite.hasNext()) {
        ite.next();
        if (currentIndex == nextIndex) {
          nextIndex = (long) Math.floor(numSelectedInstances * step + 0.5);
          numSelectedInstances++;
        } else {
          ite.remove();
        }
        currentIndex++;
      }
    }
  }
672048
def random_cohort(size, cache_dir, data_dir=None,
                  min_random_variants=None,
                  max_random_variants=None,
                  seed_val=1234):
    
    seed(seed_val)
    d = {}
    d["id"] = [str(id) for id in range(size)]
    d["age"] = choice([10, 15, 28, 32, 59, 62, 64, 66, 68], size)
    d["smoker"] = choice([False, True], size)
    d["OS"] = [randint(10, 1000) for i in range(size)]
    d["PFS"] = [int(os * 0.6) for os in d["OS"]]
    d["benefit"] = [pfs < 50 for pfs in d["PFS"]]
    d["random"] = [randint(100) for i in range(size)]
    d["random_boolean"] = choice([False, True], size)
    d["benefit_correlate"] = [randint(50) if benefit else randint(20) for benefit in d["benefit"]]
    d["benefit_correlate_boolean"] = [True if corr > 10 else False for corr in d["benefit_correlate"]]
    d["deceased"] = choice([False, True], size)
    d["progressed_or_deceased"] = [deceased or choice([False, True]) for deceased in d["deceased"]]
    df = pd.DataFrame(d)
    patients = []
    for i, row in df.iterrows():
        snv_vcf_paths = None
        if max_random_variants is not None and min_random_variants is not None:
            if data_dir is None:
                raise ValueError("data_dir must be provided if random variants are being generated.")
            vcf_path = path.join(data_dir, "patient_%s_mutect.vcf" % row["id"])
            generate_simple_vcf(
                vcf_path, generate_random_missense_variants(num_variants=randint(min_random_variants, max_random_variants)))
            snv_vcf_paths = [vcf_path]
        patient = Patient(
            id=row["id"],
            os=row["OS"],
            pfs=row["PFS"],
            benefit=row["benefit"],
            deceased=row["deceased"],
            progressed_or_deceased=row["progressed_or_deceased"],
            hla_alleles=["HLA-A02:01"],
            variants={"snv": snv_vcf_paths},
            additional_data=row)
        patients.append(patient)
    return Cohort(
        patients=patients,
        cache_dir=cache_dir,
        mhc_class=RandomBindingPredictor)
833370
function(sentences, numberOfTopics, numberOfTermsPerTopic, languages, alphaValue, betaValue, randomSeed) {
    // The result will consist of topics and their included terms [[{"term":"word1", "probability":0.065}, {"term":"word2", "probability":0.047}, ... ], [{"term":"word1", "probability":0.085}, {"term":"word2", "probability":0.024}, ... ]].
    var result = [];
    // Index-encoded array of sentences, with each row containing the indices of the words in the vocabulary.
    var documents = new Array();
    // Hash of vocabulary words and the count of how many times each word has been seen.
    var f = {};
    // Vocabulary of unique words (porter stemmed).
    var vocab=new Array();
    // Vocabulary of unique words in their original form.
    var vocabOrig = {};
    // Array of stop words
    languages = languages || Array('en');

    if (sentences && sentences.length > 0) {
      var stopwords = new Array();

      languages.forEach(function(value) {
          var stopwordsLang = require('./stopwords_' + value + ".js");
          stopwords = stopwords.concat(stopwordsLang.stop_words);
      });

      for(var i=0;i<sentences.length;i++) {
          if (sentences[i]=="") continue;
          documents[i] = new Array();

          var words = sentences[i] ? sentences[i].split(/[\s,\"]+/) : null;

          if(!words) continue;
          for(var wc=0;wc<words.length;wc++) {
              var w=words[wc].toLowerCase().replace(/[^a-z\'A-Z0-9\u00C0-\u00ff ]+/g, '');
              var wStemmed = stem(w);
              if (w=="" || !wStemmed || w.length==1 || stopwords.indexOf(w.replace("'", "")) > -1 || stopwords.indexOf(wStemmed) > -1 || w.indexOf("http")==0) continue;
              if (f[wStemmed]) { 
                  f[wStemmed]=f[wStemmed]+1;
              } 
              else if(wStemmed) { 
                  f[wStemmed]=1; 
                  vocab.push(wStemmed);
                  vocabOrig[wStemmed] = w;
              };
              
              documents[i].push(vocab.indexOf(wStemmed));
          }
      }

      var V = vocab.length;
      var M = documents.length;
      var K = parseInt(numberOfTopics);
      var alpha = alphaValue || 0.1;  // per-document distributions over topics
      var beta = betaValue || .01;  // per-topic distributions over words
      documents = documents.filter((doc) => { return doc.length }); // filter empty documents

      lda.configure(documents,V,10000, 2000, 100, 10, randomSeed);
      lda.gibbs(K, alpha, beta);

      var theta = lda.getTheta();
      var phi = lda.getPhi();

      var text = '';

      //topics
      var topTerms=numberOfTermsPerTopic;
      for (var k = 0; k < phi.length; k++) {
          var things = new Array();
          for (var w = 0; w < phi[k].length; w++) {
               things.push(""+phi[k][w].toPrecision(2)+"_"+vocab[w] + "_" + vocabOrig[vocab[w]]);
          }
          things.sort().reverse();
          //console.log(things);
          if(topTerms>vocab.length) topTerms=vocab.length;

          //console.log('Topic ' + (k + 1));
          var row = [];
          
          for (var t = 0; t < topTerms; t++) {
              var topicTerm=things[t].split("_")[2];
              var prob=parseInt(things[t].split("_")[0]*100);
              if (prob<2) continue;
              
              //console.log('Top Term: ' + topicTerm + ' (' + prob + '%)');
              
              var term = {};
              term.term = topicTerm;
              term.probability = parseFloat(things[t].split("_")[0]);
              row.push(term);
          }

          result.push(row);
      }
    }
    
    return result;
}
1334850
function (name_type, gender, style) {
		if (typeof name_type === 'undefined' || name_type === '' || name_type === 'random') {
			// randomize a type...
			name_type = randomizer.rollRandom(Object.keys(namedata.options));
		}
		if (typeof style === 'undefined') { style = ''; }
		if (!namedata[name_type]) { return ''; }
		if (typeof gender === 'undefined' || (gender !== 'male' && gender !== 'female')) { gender = randomizer.rollRandom(['male', 'female']); }
		
		const mkey = `${name_type}_${gender}`;
		let lastname = '';
		let thename = '';
		
		if (!markov.memory) {
			markov = new MarkovGenerator({ order: 3 });
		}
		
		if (!markov.memory[mkey]) {
			// console.log('learn '+mkey);
			let namelist = [];
			if (gender === '') {
				namelist = namedata[name_type]['male'];
				namelist = namelist.concat(namedata[name_type]['female']);
			} else {
				namelist = namedata[name_type][gender];
			}
			namelist.forEach((v) => {
				markov.learn(mkey, v);
			});
		}
		
		if (style !== 'first' && !r_helpers.isEmpty(namedata[name_type]['surname'])) {
			const skey = name_type + '_last';
			if (!markov.memory[skey]) {
				// console.log('learn surname '+skey);
				const namelist = namedata[name_type]['surname'];
				namelist.forEach((v) => {
					markov.learn(skey, v);
				});
			}
			lastname = markov.generate(skey);
		}
		
		thename = `${markov.generate(mkey)} ${lastname}`;
		return capitalizeName(thename.trim());
	}
213283
@Override
  public double[][] processIds(DBIDs ids, Relation<? extends NumberVector> database) {
    return CovarianceMatrix.make(database, ids).destroyToPopulationMatrix();
  }
600763
def randomprune(self,n):
        """"""
        self.data = random.sample(self.data, n)
468272
def initial_individual(self):
        """"""
        ind = creator.Individual(
            [random.uniform(-1, 1)
             for _ in range(len(self._params['value_means']))])
        return ind