Implements a custom optimization algorithm, because implementation of the algorithm
shown in Annex J.2 created LONGER binary sequences.
481330
private static QrMode[] applyOptimisation(int version, QrMode[] inputMode) {

        int inputLength = inputMode.length;
        int blockCount = 0;
        int i, j;
        QrMode currentMode = QrMode.NULL;

        for (i = 0; i < inputLength; i++) {
            if (inputMode[i] != currentMode) {
                currentMode = inputMode[i];
                blockCount++;
            }
        }

        int[] blockLength = new int[blockCount];
        QrMode[] blockMode = new QrMode[blockCount];

        j = -1;
        currentMode = QrMode.NULL;
        for (i = 0; i < inputLength; i++) {
            if (inputMode[i] != currentMode) {
                j++;
                blockLength[j] = 1;
                blockMode[j] = inputMode[i];
                currentMode = inputMode[i];
            } else {
                blockLength[j]++;
            }
        }

        if (blockCount > 1) {
            // Search forward
            for (i = 0; i <= (blockCount - 2); i++) {
                if (blockMode[i] == QrMode.BINARY) {
                    switch (blockMode[i + 1]) {
                        case KANJI:
                            if (blockLength[i + 1] < tribus(version, 4, 5, 6)) {
                                blockMode[i + 1] = QrMode.BINARY;
                            }
                            break;
                        case ALPHANUM:
                            if (blockLength[i + 1] < tribus(version, 7, 8, 9)) {
                                blockMode[i + 1] = QrMode.BINARY;
                            }
                            break;
                        case NUMERIC:
                            if (blockLength[i + 1] < tribus(version, 3, 4, 5)) {
                                blockMode[i + 1] = QrMode.BINARY;
                            }
                            break;
                    }
                }

                if ((blockMode[i] == QrMode.ALPHANUM)
                        && (blockMode[i + 1] == QrMode.NUMERIC)) {
                    if (blockLength[i + 1] < tribus(version, 6, 8, 10)) {
                        blockMode[i + 1] = QrMode.ALPHANUM;
                    }
                }
            }

            // Search backward
            for (i = blockCount - 1; i > 0; i--) {
                if (blockMode[i] == QrMode.BINARY) {
                    switch (blockMode[i - 1]) {
                        case KANJI:
                            if (blockLength[i - 1] < tribus(version, 4, 5, 6)) {
                                blockMode[i - 1] = QrMode.BINARY;
                            }
                            break;
                        case ALPHANUM:
                            if (blockLength[i - 1] < tribus(version, 7, 8, 9)) {
                                blockMode[i - 1] = QrMode.BINARY;
                            }
                            break;
                        case NUMERIC:
                            if (blockLength[i - 1] < tribus(version, 3, 4, 5)) {
                                blockMode[i - 1] = QrMode.BINARY;
                            }
                            break;
                    }
                }

                if ((blockMode[i] == QrMode.ALPHANUM)
                        && (blockMode[i - 1] == QrMode.NUMERIC)) {
                    if (blockLength[i - 1] < tribus(version, 6, 8, 10)) {
                        blockMode[i - 1] = QrMode.ALPHANUM;
                    }
                }
            }
        }

        // ZINT NOTE: this method is different from the original Zint code in that it creates a
        // new array to hold the optimized values and returns it, rather than modifying the
        // original array; this allows this method to be called as many times as we want without
        // worrying about side effects

        QrMode[] optimized = new QrMode[inputMode.length];

        j = 0;
        for (int block = 0; block < blockCount; block++) {
            currentMode = blockMode[block];
            for (i = 0; i < blockLength[block]; i++) {
                optimized[j] = currentMode;
                j++;
            }
        }

        return optimized;
    }
439147
public void runOptimization(int maxi) throws StructureException{
		superimposeBySet();
		if ( debug)
			System.err.println("   initial rmsd " + rmsd);

//      if (showAlig)
//         showCurrentAlignment(equLen, equSet, "after initial superimposeBySet Len:" +equLen + " rmsd:" +rmsd);

		maxKeepStep = 4;
		keepStep = 0;

		optimize(maxi);
	}
313515
def extend_array(edges, binsz, lo, hi):
    """"""

    numlo = int(np.ceil((edges[0] - lo) / binsz))
    numhi = int(np.ceil((hi - edges[-1]) / binsz))

    edges = copy.deepcopy(edges)
    if numlo > 0:
        edges_lo = np.linspace(edges[0] - numlo * binsz, edges[0], numlo + 1)
        edges = np.concatenate((edges_lo[:-1], edges))

    if numhi > 0:
        edges_hi = np.linspace(edges[-1], edges[-1] + numhi * binsz, numhi + 1)
        edges = np.concatenate((edges, edges_hi[1:]))

    return edges
918177
public BasicNDArrayCompressor setDefaultCompression(@NonNull String algorithm) {
        algorithm = algorithm.toUpperCase();
        //       if (!codecs.containsKey(algorithm))
        //            throw new RuntimeException("Non-existent compression algorithm requested: [" + algorithm + "]");

        synchronized (this) {
            defaultCompression = algorithm;
        }

        return this;
    }
149796
function Layout(algorithmName, options) {
  // Save the algorithmName as our algorithm (assume function)
  var algorithm = algorithmName || 'top-down';

  // If the algorithm is a string, look it up
  if (typeof algorithm === 'string') {
    algorithm = algorithms[algorithmName];

    // Assert that the algorithm was found
    assert(algorithm, 'Sorry, the \'' + algorithmName +'\' algorithm could not be loaded.');
  }

  // Create a new PackingSmith with our algorithm and return
  var retSmith = new PackingSmith(algorithm, options);
  return retSmith;
}
46796
public static Builder start(AlgorithmOptions opts) {
        Builder b = new Builder();
        if (opts.algorithm != null)
            b.algorithm(opts.getAlgorithm());
        if (opts.traversalMode != null)
            b.traversalMode(opts.getTraversalMode());
        if (opts.weighting != null)
            b.weighting(opts.getWeighting());
        if (opts.maxVisitedNodes >= 0)
            b.maxVisitedNodes(opts.maxVisitedNodes);
        if (!opts.hints.isEmpty())
            b.hints(opts.hints);

        return b;
    }
700875
def xorc_constraint(v=0, sense="maximize"):
    
    assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__()
    model, x, y, z = _init()
    r = model.addVar("r", "B")
    n = model.addVar("n", "I") # auxiliary
    model.addCons(r+quicksum([x,y,z]) == 2*n)
    model.addCons(x==v)
    model.setObjective(r, sense=sense)
    _optimize("Custom XOR (as variable)", model)
401510
@Override
  public BigInteger computeClientEvidence(
      SRP6CryptoParams cryptoParams, SRP6ClientEvidenceContext ctx) {

    MessageDigest digest;
    try {
      digest = MessageDigest.getInstance(cryptoParams.H);
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException("Could not locate requested algorithm", e);
    }
    digest.update(SrpHandler.bigIntegerToUnsignedByteArray(cryptoParams.N));
    byte[] hN = digest.digest();

    digest.update(SrpHandler.bigIntegerToUnsignedByteArray(cryptoParams.g));
    byte[] hg = digest.digest();

    byte[] hNhg = xor(hN, hg);

    digest.update(ctx.userID.getBytes(StandardCharsets.UTF_8));
    byte[] hu = digest.digest();

    digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.S));
    byte[] hS = digest.digest();

    digest.update(hNhg);
    digest.update(hu);
    digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.s));
    digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.A));
    digest.update(SrpHandler.bigIntegerToUnsignedByteArray(ctx.B));
    digest.update(hS);
    BigInteger ret = new BigInteger(1, digest.digest());
    return ret;
  }
1252136
def execute(self, **minimize_options):
        
        if 'minimizer_kwargs' not in minimize_options:
            minimize_options['minimizer_kwargs'] = {}

        if 'method' not in minimize_options['minimizer_kwargs']:
            # If no minimizer was set by the user upon execute, use local_minimizer
            minimize_options['minimizer_kwargs']['method'] = self.local_minimizer.method_name()
        if 'jac' not in minimize_options['minimizer_kwargs'] and isinstance(self.local_minimizer, GradientMinimizer):
            # Assign the jacobian
            minimize_options['minimizer_kwargs']['jac'] = self.local_minimizer.wrapped_jacobian
        if 'constraints' not in minimize_options['minimizer_kwargs'] and isinstance(self.local_minimizer, ConstrainedMinimizer):
            # Assign constraints
            minimize_options['minimizer_kwargs']['constraints'] = self.local_minimizer.wrapped_constraints
        if 'bounds' not in minimize_options['minimizer_kwargs'] and isinstance(self.local_minimizer, BoundedMinimizer):
            # Assign bounds
            minimize_options['minimizer_kwargs']['bounds'] = self.local_minimizer.bounds

        ans = basinhopping(
            self.objective,
            self.initial_guesses,
            **minimize_options
        )
        return self._pack_output(ans)
854814
MutableBigInteger modInverseMP2(int k) {
        if (isEven())
            throw new ArithmeticException("Non-invertible. (GCD != 1)");

        if (k > 64)
            return euclidModInverse(k);

        int t = inverseMod32(value[offset+intLen-1]);

        if (k < 33) {
            t = (k == 32 ? t : t & ((1 << k) - 1));
            return new MutableBigInteger(t);
        }

        long pLong = (value[offset+intLen-1] & LONG_MASK);
        if (intLen > 1)
            pLong |=  ((long)value[offset+intLen-2] << 32);
        long tLong = t & LONG_MASK;
        tLong = tLong * (2 - pLong * tLong);  // 1 more Newton iter step
        tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1));

        MutableBigInteger result = new MutableBigInteger(new int[2]);
        result.value[0] = (int)(tLong >>> 32);
        result.value[1] = (int)tLong;
        result.intLen = 2;
        result.normalize();
        return result;
    }
1126604
public boolean addAlgorithm(Algorithm algorithm) {
		if (algorithm == null || idsToAlgorithms.containsKey(algorithm.getId())) {
			return false;
		}

		idsToAlgorithms.put(algorithm.getId(), algorithm);
		algorithms = null;
		return true;
	}
1199820
@Override
	public int optimize() throws Exception {
		log.info("optimize");
		
		LPOptimizationRequest lpRequest = getLPOptimizationRequest();
		if(log.isDebugEnabled() && lpRequest.isDumpProblem()){
			log.debug("LP problem: " + lpRequest.toString());
		}
		
		//standard form conversion
		LPStandardConverter lpConverter = new LPStandardConverter();//the slack variables will have default unboundedUBValue
		
		lpConverter.toStandardForm(getC(), getG(), getH(), getA(), getB(), getLb(), getUb());
		int nOfSlackVariables = lpConverter.getStandardS();
		log.debug("nOfSlackVariables: " + nOfSlackVariables);
		DoubleMatrix1D standardC = lpConverter.getStandardC();
		DoubleMatrix2D standardA = lpConverter.getStandardA();
		DoubleMatrix1D standardB = lpConverter.getStandardB();
		DoubleMatrix1D standardLb = lpConverter.getStandardLB();
		DoubleMatrix1D standardUb = lpConverter.getStandardUB();
		
		//solve the standard form problem
		LPOptimizationRequest standardLPRequest = lpRequest.cloneMe();
		standardLPRequest.setC(standardC);
		standardLPRequest.setA(standardA);
		standardLPRequest.setB(standardB);
		standardLPRequest.setLb(ColtUtils.replaceValues(standardLb, lpConverter.getUnboundedLBValue(), minLBValue));//substitute not-double numbers
		standardLPRequest.setUb(ColtUtils.replaceValues(standardUb, lpConverter.getUnboundedUBValue(), maxUBValue));//substitute not-double numbers
		if(getInitialPoint()!=null){
			standardLPRequest.setInitialPoint(lpConverter.getStandardComponents(getInitialPoint().toArray()));
		}
		if(getNotFeasibleInitialPoint()!=null){
			standardLPRequest.setNotFeasibleInitialPoint(lpConverter.getStandardComponents(getNotFeasibleInitialPoint().toArray()));
		}
		
		//optimization
		LPPrimalDualMethod opt = new LPPrimalDualMethod(minLBValue, maxUBValue);
		opt.setLPOptimizationRequest(standardLPRequest);
		if(opt.optimizeStandardLP(nOfSlackVariables) == OptimizationResponse.FAILED){
			return OptimizationResponse.FAILED;
		}
		
		//back to original form
		LPOptimizationResponse lpResponse = opt.getLPOptimizationResponse();
		double[] standardSolution = lpResponse.getSolution();
		double[] originalSol = lpConverter.postConvert(standardSolution);
		lpResponse.setSolution(originalSol);
		setLPOptimizationResponse(lpResponse);
		return lpResponse.getReturnCode();
	}
840469
private static int calcAdjustedMinimumSequenceLength(
			List<Subunit> subunits, int absMinLen, double fraction, int minLen) {

		int maxLength = Integer.MIN_VALUE;
		int minLength = Integer.MAX_VALUE;

		// Extract the length List, the min and the max
		List<Integer> lengths = new ArrayList<Integer>();
		for (int i = 0; i < subunits.size(); i++) {
			if (subunits.get(i).size() >= absMinLen) {
				maxLength = Math.max(subunits.get(i).size(), maxLength);
				minLength = Math.min(subunits.get(i).size(), minLength);
				lengths.add(subunits.get(i).size());

			}
		}

		int adjustedMinimumSequenceLength = minLen;

		if (lengths.size() < 2)
			return adjustedMinimumSequenceLength;

		// Calculate the median of the lengths
		double median = 0;
		Collections.sort(lengths);
		if (lengths.size() % 2 == 1) {
			int middle = (lengths.size() - 1) / 2;
			median = lengths.get(middle);
		} else {
			int middle2 = lengths.size() / 2;
			int middle1 = middle2 - 1;
			median = 0.5 * (lengths.get(middle1) + lengths.get(middle2));
		}

		// If the median * fraction is lower than the minLength
		if (minLength >= median * fraction) {
			adjustedMinimumSequenceLength = Math.min(minLength, minLen);
		}

		return adjustedMinimumSequenceLength;
	}
738144
private static ImmutableBiMap<FactoryMethodDescriptor, ImplementationMethodDescriptor>
      createDuplicateMethodDescriptorsBiMap(
          ImmutableSet<FactoryMethodDescriptor> factoryMethodDescriptors,
          ImmutableSet<ImplementationMethodDescriptor> implementationMethodDescriptors) {

    ImmutableBiMap.Builder<FactoryMethodDescriptor, ImplementationMethodDescriptor> builder =
        ImmutableBiMap.builder();

    for (FactoryMethodDescriptor factoryMethodDescriptor : factoryMethodDescriptors) {
      for (ImplementationMethodDescriptor implementationMethodDescriptor :
          implementationMethodDescriptors) {

        boolean areDuplicateMethodDescriptors =
            areDuplicateMethodDescriptors(factoryMethodDescriptor, implementationMethodDescriptor);
        if (areDuplicateMethodDescriptors) {
          builder.put(factoryMethodDescriptor, implementationMethodDescriptor);
          break;
        }
      }
    }

    return builder.build();
  }
187061
function XPathOptimizationCache(newMaxSize) {
// private
    var cache = new BoundedCache(newMaxSize);

// public
    /**
     * Returns the optimized item by document markup and XPath, or null if
     * it is not found in the cache. Never calls put() on the underlying cache.
     */
    this.get = function(html, xpath) {
        var byHtml = cache.get(html);

        return byHtml ? byHtml[xpath] : null;
    };

    /**
     * Returns the optimization item by document markup and XPath. Returns an
     * empty map object that has been added to the cache if the item did not
     * exist previously. Never returns null.
     */
    this.getOrCreate = function(html, xpath) {
        var byHtml = cache.get(html);

        if (byHtml == null) {
            var result = {};
            var optimizations = {};

            optimizations[xpath] = result;
            cache.put(html, optimizations);
            return result;
        }

        var item = byHtml[xpath];

        if (item == null) {
            var result = {};

            byHtml[xpath] = result;
            return result;
        }

        return item;
    };
}
25357
function optimize(file, callback) {
        var src = file.src,
            realDest = path.join(file.dest, path.basename(src, path.extname(src)) + options.ext),
            realDestExists = grunt.file.exists(realDest);

        if(realDestExists && !options.force) {
            grunt.log.writeln('Optimization skipped on ' + src.cyan + ' because it exists in destination. (force option is false!)');
            totalPercent.push(0);
            callback();
            return;
        }

        // optimize a temporary file
        tmp.tmpName({ postfix: '.png' }, function(error, tmpDest) {
            if(error) {
                callback(error);
                totalPercent.push(0);
                return;
            }

            grunt.file.copy(src, tmpDest);

            var args = [],
                qual = options.quality,
                tries = 1;

            if(options.iebug) { args.push('--iebug'); }
            if(options.nofs) { args.push('--nofs'); }
            if(qual != null) {
                if(_.isString(qual)) {
                    args.push('--quality=' + qual);
                }
                else if(_.isObject(qual) && _.isNumber(qual.min) && _.isNumber(qual.max)) {
                    args.push('--quality=' + qual.min + '-' + qual.max);
                }
                else if(_.isArray(qual) && _.isNumber(qual[0]) && _.isNumber(qual[1])) {
                    args.push('--quality=' + qual[0] + '-' + qual[1]);
                }
            }

            args.push('--ext=.png', '--force', '--speed=' + options.speed, '--', tmpDest);

            var cb = function(error, result, code) {
                if(options.retry && error && code === 99 && tries === 1) {
                    args = _.filter(args, function(arg) {
                        if(_.isString(arg) && arg.indexOf('--quality') === 0) {
                            return false;
                        }
                        return true;
                    });
                    tries++;
                    grunt.log.writeln(realDest.yellow + ' could not be optimized with quality option. Trying again without quality option!');
                    runPngquant(args, cb);
                    return;
                }

                if(error) {
                    callback(error);
                    totalPercent.push(0);
                    return;
                }

                var oldFile = fs.statSync(src).size,
                    newFile = fs.statSync(tmpDest).size,
                    savings = Math.floor((oldFile - newFile) / oldFile * 100);

                if(savings > 0) {
                    grunt.file.copy(tmpDest, realDest);

                    grunt.log.writeln('Optimized ' + realDest.cyan +
                                      ' [saved ' + savings + ' % - ' + filesize(oldFile) + ' → ' + filesize(newFile) + ']');
                    totalPercent.push(savings);
                    totalSize += oldFile - newFile;
                }
                else {
                    if(!realDestExists) {
                        grunt.file.copy(src, realDest);
                    }

                    grunt.log.writeln('Optimization would increase file size by ' + (savings * -1) + ' % so optimization was skipped on file ' + realDest.yellow);
                    totalPercent.push(0);
                }

                grunt.file.delete(tmpDest, {force: true});

                callback();
            };

            runPngquant(args, cb);
        });
    }
727454
private Producer<CloseableReference<CloseableImage>> newBitmapCacheGetToDecodeSequence(
      Producer<EncodedImage> inputProducer) {
    if (FrescoSystrace.isTracing()) {
      FrescoSystrace.beginSection("ProducerSequenceFactory#newBitmapCacheGetToDecodeSequence");
    }
    DecodeProducer decodeProducer = mProducerFactory.newDecodeProducer(inputProducer);
    Producer<CloseableReference<CloseableImage>> result =
        newBitmapCacheGetToBitmapCacheSequence(decodeProducer);
    if (FrescoSystrace.isTracing()) {
      FrescoSystrace.endSection();
    }
    return result;
  }