Java Code Examples for java.util.SortedMap#Entry

The following examples show how to use java.util.SortedMap#Entry . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Algebra.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 
 * @param jas
 * @param modIntegerRing
 * @param poly
 * @param factorSquareFree
 * @return <code>F.NIL</code> if evaluation is impossible.
 */
public static IAST factorModulus(JASModInteger jas, ModLongRing modIntegerRing, GenPolynomial<ModLong> poly,
		boolean factorSquareFree) {
	SortedMap<GenPolynomial<ModLong>, Long> map;
	try {
		FactorAbstract<ModLong> factorAbstract = FactorFactory.getImplementation(modIntegerRing);
		if (factorSquareFree) {
			map = factorAbstract.squarefreeFactors(poly);
		} else {
			map = factorAbstract.factors(poly);
		}
	} catch (RuntimeException rex) {
		// JAS may throw RuntimeExceptions
		return F.NIL;
	}
	IASTAppendable result = F.TimesAlloc(map.size());
	for (SortedMap.Entry<GenPolynomial<ModLong>, Long> entry : map.entrySet()) {
		GenPolynomial<ModLong> singleFactor = entry.getKey();
		Long val = entry.getValue();
		result.append(F.Power(jas.modLongPoly2Expr(singleFactor), F.ZZ(val)));
	}
	return result;
}
 
Example 2
Source File: JAS.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
public void testComplexFactor() {
	final int variableSize = 2;

	String[] vars = new String[] { "x0", "x1" };
	ComplexRing<BigRational> cfac = new ComplexRing<BigRational>(BigRational.ZERO);
	GenPolynomialRing<Complex<BigRational>> cpfac = new GenPolynomialRing<Complex<BigRational>>(cfac, variableSize,
			TermOrderByName.INVLEX,vars);
	GenPolynomial<Complex<BigRational>> a = cpfac.parse("x1^4 + x0^4");
	// GenPolynomial<Complex<BigRational>> a = cpfac.parse("x1^8 + x0^8") ;
	// GenPolynomial<Complex<BigRational>> a = cpfac.parse("x1^12 - x0^12") ;
	FactorComplex<BigRational> factorAbstract = new FactorComplex<BigRational>(cfac);
	SortedMap<GenPolynomial<Complex<BigRational>>, Long> map = factorAbstract.factors(a);

	for (SortedMap.Entry<GenPolynomial<Complex<BigRational>>, Long> entry : map.entrySet()) {
		if (entry.getKey().isONE() && entry.getValue().equals(1L)) {
			continue;
		}
		System.out.println(" ( " + entry.getKey() + " ) ^ " + entry.getValue());
	}
}
 
Example 3
Source File: ClientUtils.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * copy values into a TreeMap to get them in sorted order and print it
 *
 * @param rowResult Holds row name and then a map of columns to cells
 */
public static void printRow(final TRowResult rowResult) {

  TreeMap<String, TCell> sorted = new TreeMap<>();
  for (Map.Entry<ByteBuffer, TCell> column : rowResult.columns.entrySet()) {
    sorted.put(utf8(column.getKey().array()), column.getValue());
  }

  StringBuilder rowStr = new StringBuilder();
  for (SortedMap.Entry<String, TCell> entry : sorted.entrySet()) {
    rowStr.append(entry.getKey());
    rowStr.append(" => ");
    rowStr.append(utf8(entry.getValue().value.array()));
    rowStr.append("; ");
  }
  System.out.println("row: " + utf8(rowResult.row.array()) + ", cols: " + rowStr);

}
 
Example 4
Source File: Algebra.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 
 * @param polynomial
 *            the complex-rational polynomial which should be factored
 * @param jas
 * @param head
 *            the head of the factorization result AST (typically <code>F.Times</code> or <code>F.List</code>)
 * @param cfac
 * @return
 */
private static IExpr factorComplex(IExpr expr, GenPolynomial<Complex<BigRational>> polynomial,
		JASConvert<? extends RingElem<?>> jas, ISymbol head, ComplexRing<BigRational> cfac) {
	FactorComplex<BigRational> factorAbstract = new FactorComplex<BigRational>(cfac);
	SortedMap<GenPolynomial<Complex<BigRational>>, Long> map = factorAbstract.factors(polynomial);

	IASTAppendable result = F.ast(head, map.size(), false);
	for (SortedMap.Entry<GenPolynomial<Complex<BigRational>>, Long> entry : map.entrySet()) {
		if (entry.getKey().isONE() && entry.getValue().equals(1L)) {
			continue;
		}
		IExpr key = jas.complexPoly2Expr(entry.getKey());
		if (entry.getValue().equals(1L) && map.size() <= 2 && (key.equals(F.CNI) || key.equals(F.CI))) {
			// hack: factoring -I and I out of an expression should give no new factorized expression
			return expr;
		}
		result.append(F.Power(jas.complexPoly2Expr(entry.getKey()), F.ZZ(entry.getValue())));
	}
	return result;
}
 
Example 5
Source File: Algebra.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
public static IAST factorRational(GenPolynomial<BigRational> polyRat, JASConvert<BigRational> jas, ISymbol head) {
	Object[] objects = jas.factorTerms(polyRat);
	GenPolynomial<edu.jas.arith.BigInteger> poly = (GenPolynomial<edu.jas.arith.BigInteger>) objects[2];
	FactorAbstract<edu.jas.arith.BigInteger> factorAbstract = FactorFactory
			.getImplementation(edu.jas.arith.BigInteger.ONE);
	SortedMap<GenPolynomial<edu.jas.arith.BigInteger>, Long> map;
	map = factorAbstract.factors(poly);
	IASTAppendable result = F.ast(head, map.size() + 1, false);
	java.math.BigInteger gcd = (java.math.BigInteger) objects[0];
	java.math.BigInteger lcm = (java.math.BigInteger) objects[1];
	if (!gcd.equals(java.math.BigInteger.ONE) || !lcm.equals(java.math.BigInteger.ONE)) {
		result.append(F.fraction(gcd, lcm));
	}
	for (SortedMap.Entry<GenPolynomial<edu.jas.arith.BigInteger>, Long> entry : map.entrySet()) {
		if (entry.getKey().isONE() && entry.getValue().equals(1L)) {
			continue;
		}
		if (entry.getValue() == 1L) {
			result.append(jas.integerPoly2Expr(entry.getKey()));
		} else {
			result.append(F.Power(jas.integerPoly2Expr(entry.getKey()), F.ZZ(entry.getValue())));
		}
	}
	return result;
}
 
Example 6
Source File: JAS.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
public void testSimplexFactor001() {
	final int variableSize = 1;
	String[] vars = new String[] { "x" };
	ComplexRing<BigRational> cfac = new ComplexRing<BigRational>(BigRational.ZERO);
	GenPolynomialRing<Complex<BigRational>> cpfac = new GenPolynomialRing<Complex<BigRational>>(cfac, variableSize,
			TermOrderByName.INVLEX,vars);
	GenPolynomial<Complex<BigRational>> a = cpfac.parse("x^2 + 4*x + 4"); 
	FactorComplex<BigRational> factorAbstract = new FactorComplex<BigRational>(cfac);
	SortedMap<GenPolynomial<Complex<BigRational>>, Long> map = factorAbstract.factors(a);

	for (SortedMap.Entry<GenPolynomial<Complex<BigRational>>, Long> entry : map.entrySet()) {
		if (entry.getKey().isONE() && entry.getValue().equals(1L)) {
			continue;
		}
		System.out.println(" ( " + entry.getKey() + " ) ^ " + entry.getValue());
	}
}
 
Example 7
Source File: StatisticsChart.java    From ade with GNU General Public License v3.0 5 votes vote down vote up
/** Apply mapping on a given map.
 * Map keys are renamed, and those missing are removed
 * 
 * @param src Map to be processed.
 * @param mapping Mapping according to which to process src
 * @return
 */
static <T> TreeMap<String, T> applyResultMapping(SortedMap<String, T> src, SortedMap<String, String> mapping) {
    if (src == null) {
        return null;
    }
    final TreeMap<String, T> result = new TreeMap<String, T>();
    for (SortedMap.Entry<String, T> entry : src.entrySet()) {
        final String newName = mapping.get(entry.getKey());
        if (newName != null) {
            result.put(newName, entry.getValue());
        }
    }
    return result;
}
 
Example 8
Source File: Algebra.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
private static IExpr factorList(IExpr expr, List<IExpr> varList, boolean factorSquareFree)
		throws JASConversionException {
	if (!expr.isAST()) {
		if (expr.isNumber()) {
			return F.List(F.List(expr, F.C1));
		}
		return F.List(F.List(F.C1, F.C1), F.List(expr, F.C1));
	}
	JASConvert<BigRational> jas = new JASConvert<BigRational>(varList, BigRational.ZERO);
	GenPolynomial<BigRational> polyRat = jas.expr2JAS(expr, false);
	Object[] objects = jas.factorTerms(polyRat);
	java.math.BigInteger gcd = (java.math.BigInteger) objects[0];
	java.math.BigInteger lcm = (java.math.BigInteger) objects[1];
	SortedMap<GenPolynomial<edu.jas.arith.BigInteger>, Long> map;
	try {
		GenPolynomial<edu.jas.arith.BigInteger> poly = (GenPolynomial<edu.jas.arith.BigInteger>) objects[2];
		FactorAbstract<edu.jas.arith.BigInteger> factorAbstract = FactorFactory
				.getImplementation(edu.jas.arith.BigInteger.ONE);

		if (factorSquareFree) {
			map = factorAbstract.squarefreeFactors(poly);// factors(poly);
		} else {
			map = factorAbstract.factors(poly);
		}
	} catch (RuntimeException rex) {
		// JAS may throw RuntimeExceptions
		return F.List(expr);
	}
	IASTAppendable result = F.ListAlloc(map.size() + 1);
	if (!gcd.equals(java.math.BigInteger.ONE) || !lcm.equals(java.math.BigInteger.ONE)) {
		result.append(F.List(F.fraction(gcd, lcm), F.C1));
	}
	for (SortedMap.Entry<GenPolynomial<edu.jas.arith.BigInteger>, Long> entry : map.entrySet()) {
		if (entry.getKey().isONE() && entry.getValue().equals(1L)) {
			continue;
		}
		result.append(F.List(jas.integerPoly2Expr(entry.getKey()), F.ZZ(entry.getValue())));
	}
	return result;
}
 
Example 9
Source File: LinuxSandboxedSpawnRunner.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * This method does the following things: - If mount source does not exist on the host system,
 * throw an error message - If mount target exists, check whether the source and target are of the
 * same type - If mount target does not exist on the host system, throw an error message
 *
 * @param bindMounts the bind mounts map with target as key and source as value
 * @throws UserExecException
 */
private void validateBindMounts(SortedMap<Path, Path> bindMounts) throws UserExecException {
  for (SortedMap.Entry<Path, Path> bindMount : bindMounts.entrySet()) {
    final Path source = bindMount.getValue();
    final Path target = bindMount.getKey();
    // Mount source should exist in the file system
    if (!source.exists()) {
      throw new UserExecException(
          createFailureDetail(
              String.format("Mount source '%s' does not exist.", source),
              Code.MOUNT_SOURCE_DOES_NOT_EXIST));
    }
    // If target exists, but is not of the same type as the source, then we cannot mount it.
    if (target.exists()) {
      boolean areBothDirectories = source.isDirectory() && target.isDirectory();
      boolean isSourceFile = source.isFile() || source.isSymbolicLink();
      boolean isTargetFile = target.isFile() || target.isSymbolicLink();
      boolean areBothFiles = isSourceFile && isTargetFile;
      if (!(areBothDirectories || areBothFiles)) {
        // Source and target are not of the same type; we cannot mount it.
        throw new UserExecException(
            createFailureDetail(
                String.format(
                    "Mount target '%s' is not of the same type as mount source '%s'.",
                    target, source),
                Code.MOUNT_SOURCE_TARGET_TYPE_MISMATCH));
      }
    } else {
      // Mount target should exist in the file system
      throw new UserExecException(
          createFailureDetail(
              String.format(
                  "Mount target '%s' does not exist. Bazel only supports bind mounting on top of "
                      + "existing files/directories. Please create an empty file or directory at "
                      + "the mount target path according to the type of mount source.",
                  target),
              Code.MOUNT_TARGET_DOES_NOT_EXIST));
    }
  }
}
 
Example 10
Source File: HealthCheckResource.java    From pay-publicapi with MIT License 5 votes vote down vote up
private Map<String, Map<String, Boolean>> getResponse(SortedMap<String, HealthCheck.Result> results) {
    Map<String, Map<String, Boolean>> response = new HashMap<>();
    for (SortedMap.Entry<String, HealthCheck.Result> entry : results.entrySet() ) {
        response.put(entry.getKey(), ImmutableMap.of(HEALTHY, entry.getValue().isHealthy()));
    }
    return response;
}
 
Example 11
Source File: UtteranceRewriter.java    From speechutils with Apache License 2.0 5 votes vote down vote up
public String[] getErrorsAsStringArray() {
    SortedMap<Integer, String> errors = mCommandHolder.getErrors();
    String[] array = new String[errors.size()];
    int i = 0;
    for (SortedMap.Entry<Integer, String> entry : errors.entrySet()) {
        array[i++] = "#" + entry.getKey() + ": " + entry.getValue();
    }
    return array;
}
 
Example 12
Source File: DistributedLogTool.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private Map<BookieSocketAddress, Integer> getBookieStats(LogSegmentMetadata segment) throws Exception {
    Map<BookieSocketAddress, Integer> stats = new HashMap<BookieSocketAddress, Integer>();
    LedgerHandle lh = bkc.client().get().openLedgerNoRecovery(segment.getLedgerId(), BookKeeper.DigestType.CRC32,
            getConf().getBKDigestPW().getBytes(UTF_8));
    long eidFirst = 0;
    for (SortedMap.Entry<Long, ArrayList<BookieSocketAddress>> entry : LedgerReader.bookiesForLedger(lh).entrySet()) {
        long eidLast = entry.getKey().longValue();
        long count = eidLast - eidFirst + 1;
        for (BookieSocketAddress bookie : entry.getValue()) {
            merge(stats, bookie, (int) count);
        }
        eidFirst = eidLast;
    }
    return stats;
}
 
Example 13
Source File: DistributedLogTool.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private Map<BookieSocketAddress, Integer> getBookieStats(LogSegmentMetadata segment) throws Exception {
    Map<BookieSocketAddress, Integer> stats = new HashMap<BookieSocketAddress, Integer>();
    LedgerHandle lh = bkc.client().get().openLedgerNoRecovery(segment.getLogSegmentId(),
            BookKeeper.DigestType.CRC32, getConf().getBKDigestPW().getBytes(UTF_8));
    long eidFirst = 0;
    for (SortedMap.Entry<Long, ArrayList<BookieSocketAddress>>
            entry : LedgerReader.bookiesForLedger(lh).entrySet()) {
        long eidLast = entry.getKey().longValue();
        long count = eidLast - eidFirst + 1;
        for (BookieSocketAddress bookie : entry.getValue()) {
            merge(stats, bookie, (int) count);
        }
        eidFirst = eidLast;
    }
    return stats;
}
 
Example 14
Source File: GenerateJflexTLDMacros.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Partition TLDs by whether they are prefixes of other TLDs and then by suffix length.
 * We only care about TLDs that are prefixes and are exactly one character shorter than another TLD.
 * See LUCENE-8278 and LUCENE-5391.
 */
private void partitionTLDprefixesBySuffixLength() {
  TLDsBySuffixLength.add(new TreeSet<>());            // initialize set for zero-suffix TLDs
  for (SortedMap.Entry<String,Boolean> entry : processedTLDsLongestFirst.entrySet()) {
    String TLD = entry.getKey();
    if (entry.getValue()) {
      // System.out.println("Skipping already processed: " + TLD);
      continue;
    }
    // System.out.println("Adding zero-suffix TLD: " + TLD);
    TLDsBySuffixLength.get(0).add(TLD);
    for (int suffixLength = 1 ; (TLD.length() - suffixLength) >= 2 ; ++suffixLength) {
      String TLDprefix = TLD.substring(0, TLD.length() - suffixLength);
      if (false == processedTLDsLongestFirst.containsKey(TLDprefix)) {
        // System.out.println("Ignoring non-TLD prefix: " + TLDprefix);
        break;                                        // shorter prefixes can be ignored
      }
      if (processedTLDsLongestFirst.get(TLDprefix)) {
        // System.out.println("Skipping already processed prefix: " + TLDprefix);
        break;                                        // shorter prefixes have already been processed 
      }

      processedTLDsLongestFirst.put(TLDprefix, true); // mark as processed
      if (TLDsBySuffixLength.size() == suffixLength)
        TLDsBySuffixLength.add(new TreeSet<>());
      SortedSet<String> TLDbucket = TLDsBySuffixLength.get(suffixLength);
      TLDbucket.add(TLDprefix);
      // System.out.println("Adding TLD prefix of " + TLD + " with suffix length " + suffixLength + ": " + TLDprefix);
    }
  }
}
 
Example 15
Source File: SS7FirewallAPI_V1_0.java    From SigFW with GNU Affero General Public License v3.0 5 votes vote down vote up
@GET
@Consumes("text/plain")
@Produces("text/plain")
@Path("map_cat2_oc_blacklist_list")
public String map_cat2_oc_blacklist_list() {
    String s = "";
    for (SortedMap.Entry<String, String> entry : SS7FirewallConfig.map_cat2_oc_blacklist.entrySet()) {
        s += entry.getKey() + "\n";
    }
    return s;
}
 
Example 16
Source File: SS7FirewallAPI_V1_0.java    From SigFW with GNU Affero General Public License v3.0 5 votes vote down vote up
@GET
@Consumes("text/plain")
@Produces("text/plain")
@Path("sccp_calling_gt_blacklist_list")
public String sccp_calling_gt_blacklist_list() {
    String s = "";
    for (SortedMap.Entry<String, String> entry : SS7FirewallConfig.sccp_calling_gt_blacklist.entrySet()) {
        s += entry.getKey() + "\n";
    }
    return s;
}
 
Example 17
Source File: DiameterFirewallAPI_V1_0.java    From SigFW with GNU Affero General Public License v3.0 5 votes vote down vote up
@GET
@Consumes("text/plain")
@Produces("text/plain")
@Path("diameter_application_id_whitelist_list")
public String diameter_application_id_whitelist_list() {
    String s = "";
    for (SortedMap.Entry<String, String> entry : DiameterFirewallConfig.diameter_application_id_whitelist.entrySet()) {
        s += entry.getKey() + "\n";
    }
    return s;
}
 
Example 18
Source File: DiameterFirewallAPI_V1_0.java    From SigFW with GNU Affero General Public License v3.0 5 votes vote down vote up
@GET
@Consumes("text/plain")
@Produces("text/plain")
@Path("diameter_origin_realm_blacklist_list")
public String diameter_origin_realm_blacklist_list() {
    String s = "";
    for (SortedMap.Entry<String, String> entry : DiameterFirewallConfig.diameter_origin_realm_blacklist.entrySet()) {
        s += entry.getKey() + "\n";
    }
    return s;
}
 
Example 19
Source File: Command.java    From speechutils with Apache License 2.0 4 votes vote down vote up
public String toTsv(SortedMap<Integer, String> header) {
    StringBuilder sb = new StringBuilder();
    boolean isFirst = true;
    for (SortedMap.Entry<Integer, String> entry : header.entrySet()) {
        if (isFirst) {
            isFirst = false;
        } else {
            sb.append('\t');
        }
        switch (entry.getValue()) {
            case UtteranceRewriter.HEADER_LABEL:
                sb.append(escape(mLabel));
                break;
            case UtteranceRewriter.HEADER_COMMENT:
                sb.append(escape(mComment));
                break;
            case UtteranceRewriter.HEADER_LOCALE:
                sb.append(escape(mLocale));
                break;
            case UtteranceRewriter.HEADER_SERVICE:
                sb.append(escape(mService));
                break;
            case UtteranceRewriter.HEADER_APP:
                sb.append(escape(mApp));
                break;
            case UtteranceRewriter.HEADER_UTTERANCE:
                sb.append(escape(mUtt));
                break;
            case UtteranceRewriter.HEADER_REPLACEMENT:
                sb.append(escape(mReplacement));
                break;
            case UtteranceRewriter.HEADER_COMMAND:
                sb.append(escape(mCommand));
                break;
            case UtteranceRewriter.HEADER_ARG1:
                if (mArgs.length > 0) {
                    sb.append(escape(mArgs[0]));
                }
                break;
            case UtteranceRewriter.HEADER_ARG2:
                if (mArgs.length > 1) {
                    sb.append(escape(mArgs[1]));
                }
                break;
            default:
                break;
        }
    }
    return sb.toString();
}
 
Example 20
Source File: MetricsController.java    From metrics with Apache License 2.0 4 votes vote down vote up
private void changeMetricLevel(MetricRegistry registry, MetricFilter filter, MetricLevel levelToChange) {
    for (SortedMap.Entry<MetricName, Metric> entry: registry.getMetrics(filter).entrySet()) {
        entry.getKey().level(levelToChange);
    }
}