Identify easily discarded meaningless swaps.

        This is motivated by the cost of millions of swaps being simulated.
423134
def _swap_optimizer_allows(self, p1, p2):
        
        # setup local shortcuts
        a = self._array
        tile1 = a[p1]
        tile2 = a[p2]
        # 1) disallow same tiles
        if tile1 == tile2:
            return False
        # 2) disallow matches unless a wildcard is involved
        if tile1.matches(tile2) and not any(t.is_wildcard()
                                            for t in (tile1, tile2)):
            return False
        # 3) disallow when both tiles (post-swap) are surrounded by non-matches
        center_other_pairs = ((p1, p2), (p2, p1))

        class MatchedTiles(Exception):
            pass
        try:
            for center_p, other_p in center_other_pairs:
                up_down_left_right = ((center_p[0] - 1, center_p[1]),
                                      (center_p[0] + 1, center_p[1]),
                                      (center_p[0],     center_p[1] - 1),
                                      (center_p[0],     center_p[1] + 1))
                post_swap_center_tile = a[other_p]
                for surrounding_p in up_down_left_right:
                    # ignore out of bounds positions
                    # and ignore the inner swap which is handled elsewhere
                    if any((not (0 <= surrounding_p[0] <= 7),  # out of bounds
                            not (0 <= surrounding_p[1] <= 7),  # out of bounds
                            surrounding_p == other_p)):  # inner swap
                        continue
                    surrounding_tile = a[surrounding_p]
                    if post_swap_center_tile.matches(surrounding_tile):
                        raise MatchedTiles()
        except MatchedTiles:
            pass  # if any match found, stop checking and pass this filter
        else:
            return False  # if no match is found, then this can be filtered
        return True
758353
private int[] reIndexIndices(SortableVertex[] sortVertices, int[] indices) {
        // Create temporary lookup-array, O(n)
        int[] indexLUT = new int[sortVertices.length];
        int[] newIndices = new int[indices.length];

        for (int i = 0; i < sortVertices.length; ++i) {
            indexLUT[sortVertices[i].originalIndex] = i;
        }

        // Convert old indices to new indices, O(n)
        for (int i = 0; i < indices.length; ++i) {
            newIndices[i] = indexLUT[indices[i]];
        }


        return newIndices;
    }
745191
def _rebin(self,xdx,rebin):
        

        x = xdx[0]
        dx = xdx[1]
        rebin = int(rebin)
        
        # easy end condition
        if rebin <= 1:
            return (x,dx)
        
        # Rebin Discard unused bins
        lenx = len(x)
        x_rebin = []
        dx_rebin = []
        
        # avoid dividing by zero
        dx[dx==0] = np.inf
        
        # weighted mean
        for i in np.arange(0,lenx,rebin):
            w = 1./dx[i:i+rebin-1]**2
            wsum = np.sum(w)
            
            if wsum == 0:
                x_rebin.append(np.mean(x[i:i+rebin-1]))
                dx_rebin.append(np.std(x[i:i+rebin-1]))
            else:
                x_rebin.append(np.sum(x[i:i+rebin-1]*w)/wsum)
                dx_rebin.append(1./wsum**0.5)
        return np.array([x_rebin,dx_rebin])
1167735
def swap(self, c2):
        '''
        
        '''
        inv = False
        c1 = self
        if c1.order > c2.order:
            ct = c1
            c1 = c2
            c2 = ct
            inv = True
        return inv, c1, c2
58429
def _simulated_EOT(self, state):
        """"""
        # determine if this is a manadrain or just end of turn
        is_manadrain = True  # default mana drain until valid swap found
        for swap_pair in state.board.potential_swaps():
            result_board, destroyed_groups = \
                state.board.execute_once(swap=swap_pair,
                                         random_fill=self.random_fill)
            if destroyed_groups:
                is_manadrain = False
                break  # stop when the first valid swap found
        # attach appropriate EOT or ManaDrain
        if is_manadrain:
            end = self._simulated_mana_drain(state)
        else:
            end = EOT(False)
            state.graft_child(end)
        return end
562718
def swapper_map(index)
      array = (0..9).to_a
      10.times.collect.with_index do |i|
        array.rotate!(index + i ^ spin).pop
      end
    end
314301
private int buildHistogramByAccumulatingCounts() {
		int sum = 0;
		for (int i = 0; i < counterHistogram.length; ++i) {
			int currentSlotValue = counterHistogram[i];
			counterHistogram[i] = sum;
			sum += currentSlotValue;
		}
		return sum;
	}
1206285
def discardID(self, idVal):
        
        for i in self:
            if i.id == idVal:
                self._collection.discard(i)
                return
932372
def multiply_tickers(t1, t2):
    
    t1pair = t1.market.split("_")
    t2pair = t2.market.split("_")
    assert t1pair[1] == t2pair[0]
    market = t1pair[0] + "_" + t2pair[1]
    bid = t1.bid * Amount("%s %s" % (t2.bid.number(), t1.bid.commodity))
    ask = t1.ask * Amount("%s %s" % (t2.ask.number(), t1.ask.commodity))
    high = t1.high * Amount("%s %s" % (t2.high.number(), t1.high.commodity))  # meaningless
    low = t1.low * Amount("%s %s" % (t2.low.number(), t1.low.commodity))  # meaningless
    volume = 0  # meaningless
    last = t1.last * Amount("%s %s" % (t2.last.number(), t1.last.commodity))
    return em.Ticker(bid=bid, ask=ask, high=high, low=low, volume=volume, last=last, market=market, exchange='multiple')
953917
public void computeOptimalStrategy() {
		long heavyMin, revHeavyMin, leftMin, revLeftMin, rightMin, revRightMin;
		long min = -1;
		int strategy = -1;
		int parent1 = -1;
		int parent2 = -1;
		boolean[] nodeTypeLeft1 = it1.nodeType[LEFT];
		boolean[] nodeTypeLeft2 = it2.nodeType[LEFT];
		boolean[] nodeTypeRigt1 = it1.nodeType[RIGHT];
		boolean[] nodeTypeRight2 = it2.nodeType[RIGHT];
		boolean[] nodeTypeHeavy1 = it1.nodeType[HEAVY];
		boolean[] nodeTypeHeavy2 = it2.nodeType[HEAVY];
		int[] post2size1 = it1.info[POST2_SIZE];
		int[] post2size2 = it2.info[POST2_SIZE];
		int[] post2descSum1 = it1.info[POST2_DESC_SUM];
		int[] post2descSum2 = it2.info[POST2_DESC_SUM];
		int[] post2krSum1 = it1.info[POST2_KR_SUM];
		int[] post2krSum2 = it2.info[POST2_KR_SUM];
		int[] post2revkrSum1 = it1.info[POST2_REV_KR_SUM];
		int[] post2revkrSum2 = it2.info[POST2_REV_KR_SUM];
		int[] post2parent1 = it1.info[POST2_PARENT];
		int[] post2parent2 = it2.info[POST2_PARENT];

		str = new int[size1][size2];

		// v represents nodes of left input tree in postorder
		// w represents nodes of right input tree in postorder
		for (int v = 0; v < size1; v++) {
			Arrays.fill(costW[0], 0);
			Arrays.fill(costW[1], 0);
			Arrays.fill(costW[2], 0);
			for (int w = 0; w < size2; w++) {
				if (post2size2[w] == 1) {
					// putTree zeros into arrays
					costW[LEFT][w] = 0;
					costW[RIGHT][w] = 0;
					costW[HEAVY][w] = 0;
				}
				if (post2size1[v] == 1) {
					// putTree zeros into arrays
					costV[LEFT][v][w] = 0;
					costV[RIGHT][v][w] = 0;
					costV[HEAVY][v][w] = 0;
				}

				// TODO: some things below may be putTree to outer loop

				// count the minimum + get the strategy
				heavyMin = (long) post2size1[v] * (long) post2descSum2[w]
						+ costV[HEAVY][v][w];
				revHeavyMin = (long) post2size2[w] * (long) post2descSum1[v]
						+ costW[HEAVY][w];

				leftMin = (long) post2size1[v] * (long) post2krSum2[w]
						+ costV[LEFT][v][w];
				revLeftMin = (long) post2size2[w] * (long) post2krSum1[v]
						+ costW[LEFT][w];

				rightMin = (long) post2size1[v] * (long) post2revkrSum2[w]
						+ costV[RIGHT][v][w];
				revRightMin = (long) post2size2[w] * (long) post2revkrSum1[v]
						+ costW[RIGHT][w];

				long[] mins = { leftMin, rightMin, heavyMin, Long.MAX_VALUE,
						revLeftMin, revRightMin, revHeavyMin };

				min = leftMin;
				strategy = 0;
				for (int i = 1; i <= 6; i++) {
					if (mins[i] < min) {
						min = mins[i];
						strategy = i;
					}
				}

				// store the strategy for the minimal cost
				str[v][w] = strategy;

				// fill the cost arrays
				parent1 = post2parent1[v];
				if (parent1 != -1) {
					costV[HEAVY][parent1][w] += nodeTypeHeavy1[v] ? costV[HEAVY][v][w]
							: min;
					costV[RIGHT][parent1][w] += nodeTypeRigt1[v] ? costV[RIGHT][v][w]
							: min;
					costV[LEFT][parent1][w] += nodeTypeLeft1[v] ? costV[LEFT][v][w]
							: min;
				}
				parent2 = post2parent2[w];
				if (parent2 != -1) {
					costW[HEAVY][parent2] += nodeTypeHeavy2[w] ? costW[HEAVY][w]
							: min;
					costW[LEFT][parent2] += nodeTypeLeft2[w] ? costW[LEFT][w]
							: min;
					costW[RIGHT][parent2] += nodeTypeRight2[w] ? costW[RIGHT][w]
							: min;
				}
			}
		}
	}
343087
def fake(cls, gsimlt=None):
        
        weight = 1
        gsim_lt = gsimlt or logictree.GsimLogicTree.from_('[FromFile]')
        fakeSM = logictree.LtSourceModel(
            'scenario', weight,  'b1',
            [sourceconverter.SourceGroup('*', eff_ruptures=1)],
            gsim_lt.get_num_paths(), ordinal=0, samples=1)
        return cls(gsim_lt, seed=0, num_samples=0, source_models=[fakeSM],
                   totweight=0)
285924
private boolean recreateMismatching() {
		List<Configuration> mismatching = inventory.removeMismatching();
		mismatching.forEach(entry->{
			try {
				inventory.add(InventoryEntry.create(entry.copyWithIdentifier(inventory.nextIdentifier()), newConfigurationFile()));
			} catch (IOException e1) {
				logger.log(Level.WARNING, "Failed to write a configuration.", e1);
			}
		});
		return !mismatching.isEmpty();
	}
624009
def from_dict(data, ctx):
        

        data = data.copy()

        if data.get('price') is not None:
            data['price'] = ctx.convert_decimal_number(
                data.get('price')
            )

        if data.get('initialUnits') is not None:
            data['initialUnits'] = ctx.convert_decimal_number(
                data.get('initialUnits')
            )

        if data.get('initialMarginRequired') is not None:
            data['initialMarginRequired'] = ctx.convert_decimal_number(
                data.get('initialMarginRequired')
            )

        if data.get('currentUnits') is not None:
            data['currentUnits'] = ctx.convert_decimal_number(
                data.get('currentUnits')
            )

        if data.get('realizedPL') is not None:
            data['realizedPL'] = ctx.convert_decimal_number(
                data.get('realizedPL')
            )

        if data.get('unrealizedPL') is not None:
            data['unrealizedPL'] = ctx.convert_decimal_number(
                data.get('unrealizedPL')
            )

        if data.get('marginUsed') is not None:
            data['marginUsed'] = ctx.convert_decimal_number(
                data.get('marginUsed')
            )

        if data.get('averageClosePrice') is not None:
            data['averageClosePrice'] = ctx.convert_decimal_number(
                data.get('averageClosePrice')
            )


        if data.get('financing') is not None:
            data['financing'] = ctx.convert_decimal_number(
                data.get('financing')
            )

        if data.get('clientExtensions') is not None:
            data['clientExtensions'] = \
                ctx.transaction.ClientExtensions.from_dict(
                    data['clientExtensions'], ctx
                )

        return TradeSummary(**data)
116250
private void expungeStaleEntries() {
	for (Object x; (x = queue.poll()) != null;) {
	    synchronized (queue) {
		@SuppressWarnings("unchecked")
		Entry<K, V> e = (Entry<K, V>) x;
		int i = indexFor(e.hash, table.length);

		Entry<K, V> prev = table[i];
		Entry<K, V> p = prev;
		while (p != null) {
		    Entry<K, V> next = p.next;
		    if (p == e) {
			if (prev == e) table[i] = next;
			else prev.next = next;
			// Must not null out e.next;
			// stale entries may be in use by a HashIterator
			e.value = null; // Help GC
			size--;
			break;
		    }
		    prev = p;
		    p = next;
		}
	    }
	}
    }
156255
function (items) {
            for (var i = items.length - 1; i > 0; i--) {
                var j = Math.floor(Math.random() * (i + 1));
                util.swap(items, i, j);
            }
        }
164594
public static <K, V> HashBagMultimap<V, K> flip(BagMultimap<K, V> bagMultimap)
    {
        final HashBagMultimap<V, K> result = new HashBagMultimap<V, K>();
        bagMultimap.forEachKeyMultiValues(new Procedure2<K, Iterable<V>>()
        {
            public void value(final K key, Iterable<V> values)
            {
                Iterate.forEach(values, new Procedure<V>()
                {
                    public void value(V value)
                    {
                        result.put(value, key);
                    }
                });
            }
        });
        return result;
    }
1180890
def delist(values):
    """"""
    assert isinstance(values, list)

    if not values:
        return None
    elif len(values) == 1:
        return values[0]

    return values