A recursive Fibonacci to exercise task switching.
359841
def fibonacci(n):
  """"""
  if n <= 1:
    raise ndb.Return(n)
  a, b = yield fibonacci(n - 1), fibonacci(n - 2)
  raise ndb.Return(a + b)
1210859
private static final <T> void swap(long[] keys, T[] values, double[] probs, int i, int j) {
    long keySwap = keys[i];
    keys[i] = keys[j];
    keys[j] = keySwap;

    T swapValue = values[i];
    values[i] = values[j];
    values[j] = swapValue;
    
    double swapProb = probs[i];
    probs[i] = probs[j];
    probs[j] = swapProb;
  }
623365
function fibonacci(num) {
  return Array(num).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
}
931314
def bitwise_or(self, t):
        
        """
        This implementation combines the approaches used by 'WYSINWYX: what you see is not what you execute'
        paper and 'Signedness-Agnostic Program Analysis: Precise Integer Bounds for Low-Level Code'. The
        first paper provides an sound way to approximate the stride, whereas the second provides a way
        to calculate the or operation using wrapping intervals.
        Note that, even though according Warren's work 'Hacker's delight', one should follow different
        approaches to calculate the minimun/maximum values of an or operations according on the type
        of the operands (signed/unsigned). On the other other hand, by splitting the wrapping-intervals
        at the south pole, we can safely and soundly only use the Warren's functions for unsigned
        integers.
        """
        s = self
        result_interval = list()

        for u in s._ssplit():
            for v in t._ssplit():
                w = u.bits
                # u |w v
                if u.is_integer:
                    s_t = StridedInterval._ntz(v.stride)
                elif v.is_integer:
                    s_t = StridedInterval._ntz(u.stride)
                else:
                    s_t = min(StridedInterval._ntz(u.stride), StridedInterval._ntz(v.stride))

                if u.is_integer and u.lower_bound == 0:
                    new_stride = v.stride
                elif v.is_integer and v.lower_bound == 0:
                    new_stride = u.stride
                else:
                    new_stride = 2 ** s_t
                mask = (1 << s_t) - 1
                r = (u.lower_bound & mask) | (v.lower_bound & mask)
                m = (2 ** w) - 1
                low_bound = WarrenMethods.min_or(u.lower_bound & (~mask & m), u.upper_bound & (~mask & m), v.lower_bound & (~mask & m), v.upper_bound & (~mask & m), w)
                upper_bound = WarrenMethods.max_or(u.lower_bound & (~mask & m), u.upper_bound & (~mask & m), v.lower_bound & (~mask & m), v.upper_bound & (~mask & m), w)
                if low_bound == upper_bound:
                    new_stride = 0

                new_interval = StridedInterval(lower_bound=((low_bound & (~mask & m)) | r), upper_bound=((upper_bound & (~mask & m)) | r), bits=w, stride=new_stride)
                result_interval.append(new_interval)

        return StridedInterval.least_upper_bound(*result_interval).normalize()
188144
def fill_n_todo(self):
        
        left = self.left
        right = self.right
        top = self.top
        bottom = self.bottom
        for i in xrange(self.n_chunks):
            self.n_todo.ravel()[i] = np.sum([left.ravel()[i].n_todo,
                                            right.ravel()[i].n_todo,
                                            top.ravel()[i].n_todo,
                                            bottom.ravel()[i].n_todo])
752390
private double update(double[][] data, double T, int k, double[][] centroids, double[][] posteriori, double[] priori) {
        int n = data.length;
        int d = data[0].length;

        double D = 0.0;
        double H = 0.0;

        int iter = 0;
        double currentDistortion = Double.MAX_VALUE;
        double newDistortion = Double.MAX_VALUE / 2;
        while (iter < 100 && currentDistortion > newDistortion) {
            currentDistortion = newDistortion;

            D = Double.NaN;
            H = 0.0;

            if (tasks != null) {
                try {
                    D = 0.0;
                    for (UpdateThread t : tasks) {
                        t.k = k;
                        t.T = T;
                    }
                    
                    for (UpdateThread t : MulticoreExecutor.run(tasks)) {
                        D += t.D;
                        H += t.H;
                    }
                } catch (Exception ex) {
                    logger.error("Failed to run Deterministic Annealing on multi-core", ex);

                    D = Double.NaN;
                }
            }

            if (Double.isNaN(D)) {
                D = 0.0;
                double[] dist = new double[k];

                for (int i = 0; i < n; i++) {
                    double p = 0.0;

                    for (int j = 0; j < k; j++) {
                        dist[j] = Math.squaredDistance(data[i], centroids[j]);
                        posteriori[i][j] = priori[j] * Math.exp(-dist[j] / T);
                        p += posteriori[i][j];
                    }

                    double r = 0.0;
                    for (int j = 0; j < k; j++) {
                        posteriori[i][j] /= p;
                        D += posteriori[i][j] * dist[j];
                        r += -posteriori[i][j] * Math.log(posteriori[i][j]);
                    }
                    H += r;
                }
            }
            
            for (int i = 0; i < k; i++) {
                priori[i] = 0;
                for (int j = 0; j < n; j++) {
                    priori[i] += posteriori[j][i];
                }
                priori[i] /= n;
            }

            boolean parallel = false;
            if (ctasks != null) {
                try {
                    for (CentroidThread t : ctasks) {
                        t.k = k;
                    }
                    
                    MulticoreExecutor.run(ctasks);
                    parallel = true;
                } catch (Exception ex) {
                    logger.error("Failed to run Deterministic Annealing on multi-core", ex);

                    parallel = false;
                }
            }

            if (!parallel) {
                for (int i = 0; i < k; i++) {
                    Arrays.fill(centroids[i], 0.0);
                    for (int j = 0; j < d; j++) {
                        for (int m = 0; m < n; m++) {
                            centroids[i][j] += data[m][j] * posteriori[m][i];
                        }
                        centroids[i][j] /= (n * priori[i]);
                    }
                }
            }

            newDistortion = D - T * H;
            iter++;
        }

        logger.info(String.format("Deterministic Annealing clustering entropy after %3d iterations at temperature %.4f and k = %d: %.5f (soft distortion = %.5f )%n", iter, T, k / 2, H, D));

        return currentDistortion;
    }
213599
function (o) {
      var pattern, state;
      /** @type {string[]} */
      var stateArray;
      var i;
      //
      // 1. Collect all states
      //
      /** @type {Transitions} */
      var transitions = {};
      for (pattern in o) {
        for (state in o[pattern]) {
          stateArray = state.split("|");
          o[pattern][state].stateArray = stateArray;
          for (i=0; i<stateArray.length; i++) {
            transitions[stateArray[i]] = [];
          }
        }
      }
      //
      // 2. Fill states
      //
      for (pattern in o) {
        for (state in o[pattern]) {
          stateArray = o[pattern][state].stateArray || [];
          for (i=0; i<stateArray.length; i++) {
            //
            // 2a. Normalize actions into array:  'text=' ==> [{type_:'text='}]
            // (Note to myself: Resolving the function here would be problematic. It would need .bind (for *this*) and currying (for *option*).)
            //
            /** @type {any} */
            var p = o[pattern][state];
            if (p.action_) {
              p.action_ = [].concat(p.action_);
              for (var k=0; k<p.action_.length; k++) {
                if (typeof p.action_[k] === "string") {
                  p.action_[k] = { type_: p.action_[k] };
                }
              }
            } else {
              p.action_ = [];
            }
            //
            // 2.b Multi-insert
            //
            var patternArray = pattern.split("|");
            for (var j=0; j<patternArray.length; j++) {
              if (stateArray[i] === '*') {  // insert into all
                for (var t in transitions) {
                  transitions[t].push({ pattern: patternArray[j], task: p });
                }
              } else {
                transitions[stateArray[i]].push({ pattern: patternArray[j], task: p });
              }
            }
          }
        }
      }
      return transitions;
    }
916930
def iterintervals(self, n=2):
        
        # tee the original iterator into n identical iterators
        streams = tee(iter(self), n)

        # advance the "cursor" on each iterator by an increasing
        # offset, e.g. if n=3:
        #
        #                   [a, b, c, d, e, f, ..., w, x, y, z]
        #  first cursor -->  *
        # second cursor -->     *
        #  third cursor -->        *
        for stream_index, stream in enumerate(streams):
            for i in range(stream_index):
                next(stream)

        # now, zip the offset streams back together to yield tuples,
        # in the n=3 example it would yield:
        # (a, b, c), (b, c, d), ..., (w, x, y), (x, y, z)
        for intervals in zip(*streams):
            yield intervals
655258
function(seq1, seq2, eq){

    var l1 = seq1.length,
        l2 = seq2.length,
        distMap = Array.apply(null, {length: l1 + 1}).map(function(){return [];}),
        stepMap = Array.apply(null, {length: l1 + 1}).map(function(){return [];}),
        i, j;

    eq = eq || defaultEqual;

    for(i = 0; i <= l1; i++){
        for(j = 0; j <= l2; j++){

            if(i === 0 || j === 0){
                distMap[i][j] = i || j;
                stepMap[i][j] = i > 0 ? STEP_REMOVE : STEP_INSERT;

            }else{
                var equal = eq(seq1[i-1], seq2[j-1]),

                    removeDist = distMap[i-1][j] + 1,
                    insertDist = distMap[i][j-1] + 1,
                    replaceDist = distMap[i-1][j-1] + (equal ? 0 : 2),
                    dist = Math.min(replaceDist, removeDist, insertDist);

                distMap[i][j] = dist;

                switch(dist){
                
                case replaceDist:
                    stepMap[i][j] = equal ? STEP_NOCHANGE : STEP_REPLACE;
                    break;
                
                case removeDist:
                    stepMap[i][j] = STEP_REMOVE;
                    break;
                
                case insertDist:
                    stepMap[i][j] = STEP_INSERT;

                }
            }
        }
    }

    return stepMap;
}
736739
private Counters incrementTaskCounters(Counters counters,
                                         TaskInProgress[] tips) {
    for (TaskInProgress tip : tips) {
      counters.incrAllCounters(tip.getCounters());
    }
    return counters;
  }
298734
def generateSteps(self, minStep):
        """"""
        self.checkFinite(minStep)

        if self.binary:
            base = 2.0
            mantissas = [1.0]
            exponent = math.floor(math.log(minStep, 2) - EPSILON)
        else:
            base = 10.0
            mantissas = [1.0, 2.0, 5.0]
            exponent = math.floor(math.log10(minStep) - EPSILON)

        while True:
            multiplier = base ** exponent
            for mantissa in mantissas:
                value = mantissa * multiplier
                if value >= minStep * (1.0 - EPSILON):
                    yield value
            exponent += 1
127745
function walk(arr, key, fn) {
        var l = arr.length,
            children;

        while (l--) {
            children = arr[l][key];

            if (children) {
                walk(children, key, fn);
            }
            fn(arr[l]);
        }
    }
302738
function(word,iteration)
		{
			/* rotate the 32-bit word 8 bits to the left */
			word = this.rotate(word);
			/* apply S-Box substitution on all 4 parts of the 32-bit word */
			for (var i = 0; i < 4; ++i)
				word[i] = this.sbox[word[i]];
			/* XOR the output of the rcon operation with i to the first part (leftmost) only */
			word[0] = word[0]^this.Rcon[iteration];
			return word;
		}
685534
private void randomPermute(int[] permute) {
        for (int i = 0; i < indexVectorSize; i++)
            permute[i] = i;
        for (int i = indexVectorSize - 1; i > 0; i--) {
            int w = (int) Math.floor(Math.random() * (i+1));
            int temp = permute[w];
            permute[w] = permute[i];
            permute[i] = permute[w];
        }
    }
211631
def pairwise(values):
    
    i = iter(values)
    a = next(i)

    for b in i:
        yield (a, b)
        a = b
1223849
def walk_recursive(f, data):
    
    results = {}
    if isinstance(data, list):
        return [walk_recursive(f, d) for d in data]
    elif isinstance(data, dict):
        results = funcy.walk_keys(f, data)

        for k, v in data.iteritems():
            if isinstance(v, dict):
                results[f(k)] = walk_recursive(f, v)
            elif isinstance(v, list):
                results[f(k)] = [walk_recursive(f, d) for d in v]
    else:
        return f(data)

    return results
887025
def ff(items, targets):
    
    bins = [(target, []) for target in targets]
    skip = []

    for item in items:
        for target, content in bins:
            if item <= (target - sum(content)):
                content.append(item)
                break
        else:
            skip.append(item)
    return bins, skip