Example #1
1
  public static void viewAd(String id) {

    Ad ad = Ad.findById(Long.parseLong(id));
    List<Category> cats = Category.find("categorytype_id=?1 order by id", "1").fetch();

    EntityManager entityManager = play.db.jpa.JPA.em();
    List<BigInteger> bCounts =
        entityManager
            .createNativeQuery(
                "select count(*) as maxCount from Ad as a group by category_id order by maxCount")
            .getResultList();
    int min = bCounts.get(0).intValue();
    int max = bCounts.get(bCounts.size() - 1).intValue();
    bCounts =
        entityManager
            .createNativeQuery(
                "select count(*) as maxCount from Ad as a group by category_id order by category_id ")
            .getResultList();
    List<String> fonts = new ArrayList<String>();
    for (int i = 0; i < bCounts.size(); i++) {
      BigInteger count = bCounts.get(i);
      int x = Ads.getFontSize(count.intValue(), min, max);
      fonts.add(String.valueOf(x));
    }

    render(ad, fonts, min, max, cats);
  }
Example #2
0
 /**
  * Returns the square root of {@code x}, rounded with the specified rounding mode.
  *
  * @throws IllegalArgumentException if {@code x < 0}
  * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code
  *     sqrt(x)} is not an integer
  */
 @GwtIncompatible // TODO
 @SuppressWarnings("fallthrough")
 public static BigInteger sqrt(BigInteger x, RoundingMode mode) {
   checkNonNegative("x", x);
   if (fitsInLong(x)) {
     return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode));
   }
   BigInteger sqrtFloor = sqrtFloor(x);
   switch (mode) {
     case UNNECESSARY:
       checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through
     case FLOOR:
     case DOWN:
       return sqrtFloor;
     case CEILING:
     case UP:
       int sqrtFloorInt = sqrtFloor.intValue();
       boolean sqrtFloorIsExact =
           (sqrtFloorInt * sqrtFloorInt == x.intValue()) // fast check mod 2^32
               && sqrtFloor.pow(2).equals(x); // slow exact check
       return sqrtFloorIsExact ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
     case HALF_DOWN:
     case HALF_UP:
     case HALF_EVEN:
       BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor);
       /*
        * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x
        * and halfSquare are integers, this is equivalent to testing whether or not x <=
        * halfSquare.
        */
       return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
     default:
       throw new AssertionError();
   }
 }
  /**
   * Given 10 features (and metacards) exist that match search criteria, since page size=4 and
   * startIndex=0, should get 4 results back - metacards 1 thru 4.
   *
   * @throws WfsException
   * @throws TransformerConfigurationException
   * @throws UnsupportedQueryException
   */
  @Test
  public void testPagingStartIndexZero()
      throws WfsException, TransformerConfigurationException, UnsupportedQueryException {

    // Setup
    int pageSize = 4;
    int startIndex = 0;

    WfsSource source =
        getWfsSource(
            ONE_TEXT_PROPERTY_SCHEMA,
            MockWfsServer.getFilterCapabilities(),
            Wfs20Constants.EPSG_4326_URN,
            10,
            false);
    Filter filter = builder.attribute(Metacard.ANY_TEXT).is().like().text(LITERAL);
    Query query = new QueryImpl(filter, startIndex, pageSize, null, false, 0);

    // Execute
    GetFeatureType featureType = source.buildGetFeatureRequest(query);
    BigInteger startIndexGetFeature = featureType.getStartIndex();
    BigInteger countGetFeature = featureType.getCount();

    // Verify
    assertThat(countGetFeature.intValue(), is(pageSize));
    assertThat(startIndexGetFeature.intValue(), is(startIndex));
  }
  public int getNumberPosition() {

    boolean updated = false;
    BigInteger left = ((Ind) this.getObject()).getLeft();
    int leftInt = 0;
    if (left != null) {
      leftInt = left.intValue();
    }

    BigInteger firstLine = ((Ind) this.getObject()).getFirstLine();
    BigInteger hanging = ((Ind) this.getObject()).getHanging();

    // SPEC: The firstLine and hanging attributes are mutually exclusive, if both are specified,
    // then
    // the firstLine value is ignored.
    if (hanging != null) {
      // <w:ind w:left="360" w:hanging="360"/>

      int hangingInt = hanging.intValue();

      return (leftInt - hangingInt);

    } else {

      int firstLineInt = 0;
      if (firstLine != null) {
        firstLineInt = firstLine.intValue();
      }
      return (leftInt + firstLineInt);
    }
  }
  @Override
  public void setXslFO(Element foElement) {

    // <w:ind w:left="360" w:hanging="360"/>

    boolean updated = false;
    BigInteger left = ((Ind) this.getObject()).getLeft();
    if (left != null) {
      foElement.setAttribute(FO_NAME, UnitsOfMeasurement.twipToBest(left.intValue()));
      updated = true;
    }
    BigInteger firstLine = ((Ind) this.getObject()).getFirstLine();
    BigInteger hanging = ((Ind) this.getObject()).getHanging();
    // SPEC: The firstLine and hanging attributes are mutually exclusive, if both are specified,
    // then
    // the firstLine value is ignored.
    if (hanging != null) {
      foElement.setAttribute(
          FO_NAME_TEXT_INDENT, UnitsOfMeasurement.twipToBest(-hanging.intValue()));
    } else if (firstLine != null) {
      foElement.setAttribute(
          FO_NAME_TEXT_INDENT, UnitsOfMeasurement.twipToBest(firstLine.intValue()));
      updated = true;
    }

    if (!updated) {
      log.warn("Only left/first-line indentation is handled at present");
    }
  }
  @Override
  public String getCssProperty() {

    // Note regarding numbering case; handling of tab after the number:-
    // We get this right in the PDF case, via setXslFOListBlock below.
    // We don't attempt to get the tab right in the HTML case,
    // since without some research, I don't know what markup would be required.

    String prop = "position: relative; ";

    BigInteger left = ((Ind) this.getObject()).getLeft();
    if (left != null) {
      prop = prop + composeCss(CSS_NAME, UnitsOfMeasurement.twipToBest(left.intValue()));
    }

    // SPEC: The firstLine and hanging attributes are mutually exclusive, if both are specified,
    // then
    // the firstLine value is ignored.
    BigInteger firstline = ((Ind) this.getObject()).getFirstLine();
    BigInteger hanging = ((Ind) this.getObject()).getHanging();
    if (hanging != null) {
      prop =
          prop + composeCss("text-indent", "-" + UnitsOfMeasurement.twipToBest(hanging.intValue()));
    } else if (firstline != null) {
      prop = prop + composeCss("text-indent", UnitsOfMeasurement.twipToBest(firstline.intValue()));
    }

    if (left == null && firstline == null && hanging == null) {
      log.debug("What to do with " + XmlUtils.marshaltoString(this.getObject(), true, true));
      prop = CSS_NULL;
    }
    return prop;
  }
Example #7
0
  public static void main(String[] args) {

    Map<Integer, CalcularPolignos> poligono = new HashMap<>();

    Scanner sc = new Scanner(System.in);
    System.out.println("Digite o número de lados do poligono: ");
    BigInteger lados = sc.nextBigInteger();

    int opcao = 0;

    if (lados.intValue() < 3) {
      System.out.println("Valor negativo para número de lados do poligno, tente novamente!");
      main(args);
    } else if (lados.intValue() == 3) {
      opcao = 1;
    } else if (lados.intValue() == 4) {
      opcao = 2;
    } else if (lados.intValue() > 4) {
      opcao = 3;
    }

    System.out.println("Digite o Tamanho do Lado do Poligono: ");
    BigDecimal tamanho = sc.nextBigDecimal();

    poligono.put(1, new Triagulo(lados, tamanho));
    poligono.put(2, new Quadrilatero(lados, tamanho));
    poligono.put(3, new OutrosPoligonos(lados, tamanho));

    Controller cont = new Controller();
    cont.calcular(lados, poligono.get(opcao));
  }
  /**
   * Converts, if possible, a key specification into a {@link BCMcElieceCCA2PrivateKey}. Currently,
   * the following key specifications are supported: {@link McElieceCCA2PrivateKeySpec}, {@link
   * PKCS8EncodedKeySpec}.
   *
   * @param keySpec the key specification
   * @return the McEliece CCA2 private key
   * @throws InvalidKeySpecException if the KeySpec is not supported.
   */
  public PrivateKey generatePrivate(KeySpec keySpec) throws InvalidKeySpecException {
    if (keySpec instanceof McElieceCCA2PrivateKeySpec) {
      return new BCMcElieceCCA2PrivateKey((McElieceCCA2PrivateKeySpec) keySpec);
    } else if (keySpec instanceof PKCS8EncodedKeySpec) {
      // get the DER-encoded Key according to PKCS#8 from the spec
      byte[] encKey = ((PKCS8EncodedKeySpec) keySpec).getEncoded();

      // decode the PKCS#8 data structure to the pki object
      PrivateKeyInfo pki;

      try {
        pki = PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(encKey));
      } catch (IOException e) {
        throw new InvalidKeySpecException("Unable to decode PKCS8EncodedKeySpec: " + e);
      }

      try {
        // get the inner type inside the BIT STRING
        ASN1Primitive innerType = pki.parsePrivateKey().toASN1Primitive();

        // build and return the actual key
        ASN1Sequence privKey = (ASN1Sequence) innerType;

        // decode oidString (but we don't need it right now)
        String oidString = ((ASN1ObjectIdentifier) privKey.getObjectAt(0)).toString();

        // decode <n>
        BigInteger bigN = ((ASN1Integer) privKey.getObjectAt(1)).getValue();
        int n = bigN.intValue();

        // decode <k>
        BigInteger bigK = ((ASN1Integer) privKey.getObjectAt(2)).getValue();
        int k = bigK.intValue();

        // decode <fieldPoly>
        byte[] encFieldPoly = ((ASN1OctetString) privKey.getObjectAt(3)).getOctets();
        // decode <goppaPoly>
        byte[] encGoppaPoly = ((ASN1OctetString) privKey.getObjectAt(4)).getOctets();
        // decode <p>
        byte[] encP = ((ASN1OctetString) privKey.getObjectAt(5)).getOctets();
        // decode <h>
        byte[] encH = ((ASN1OctetString) privKey.getObjectAt(6)).getOctets();
        // decode <qInv>
        ASN1Sequence qSeq = (ASN1Sequence) privKey.getObjectAt(7);
        byte[][] encQInv = new byte[qSeq.size()][];
        for (int i = 0; i < qSeq.size(); i++) {
          encQInv[i] = ((ASN1OctetString) qSeq.getObjectAt(i)).getOctets();
        }

        return new BCMcElieceCCA2PrivateKey(
            new McElieceCCA2PrivateKeySpec(
                OID, n, k, encFieldPoly, encGoppaPoly, encP, encH, encQInv));

      } catch (IOException cce) {
        throw new InvalidKeySpecException("Unable to decode PKCS8EncodedKeySpec.");
      }
    }

    throw new InvalidKeySpecException("Unsupported key specification: " + keySpec.getClass() + ".");
  }
 /** @tests java.math.BigInteger#intValue() */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "intValue",
     args = {})
 public void test_intValue() {
   assertTrue("Incorrect intValue for 2**70", twoToTheSeventy.intValue() == 0);
   assertTrue("Incorrect intValue for 2", two.intValue() == 2);
 }
  /** wrapper method for UnsignedIntegers that use BigIntegers to store value */
  private final String getName(final BigInteger value) {
    logger.warn(
        "AntennaEventType must convert BigInteger "
            + value
            + " to Integer value "
            + value.intValue());

    return getName(value.intValue());
  }
  /** wrapper method for UnsignedIntegers that use BigIntegers to store value */
  private final boolean isValidValue(final BigInteger value) {
    logger.warn(
        "AntennaEventType must convert BigInteger "
            + value
            + " to Integer value "
            + value.intValue());

    return isValidValue(value.intValue());
  }
  /** wrapper method for UnsignedIntegers that use BigIntegers to store value */
  private final boolean isValidValue(final BigInteger value) {
    logger.warn(
        "AirProtocolsArray must convert BigInteger "
            + value
            + " to Integer value "
            + value.intValue());

    return isValidValue(value.intValue());
  }
  /** wrapper method for UnsignedIntegers that use BigIntegers to store value */
  private final String getName(final BigInteger value) {
    logger.warn(
        "AirProtocolsArray must convert BigInteger "
            + value
            + " to Integer value "
            + value.intValue());

    return getName(value.intValue());
  }
Example #14
0
 /**
  * Title: deleteMenuItem
  *
  * <p>Description:
  *
  * @param menuItemId
  * @param MenuGroupId
  * @return
  * @throws Exception
  * @see com.topit.frame.busniess.base.ISysMenuService#deleteMenuItem(java.math.BigInteger,
  *     java.math.BigInteger)
  */
 public boolean deleteMenuItem(BigInteger menuItemId) throws Exception {
   boolean flag = false;
   SysMenuItem source = menuOptionDao.findById(menuItemId.intValue());
   // 跟新源节点周围的链接状态
   menuOptionDao.UpdateSourceNodes(source);
   menuOptionDao.delete(menuItemId.intValue());
   flag = true;
   return flag;
 }
Example #15
0
  // Determines if a specified integer is prime using the Miller-Rabin
  // primality test.
  //
  // Performance: O(k log^3(n))
  //
  // Args:
  //    n (BigInteger): The number to perform the primality test.
  //           k (int): The number of iterations to perform.
  //
  // Returns:
  //    (bool): Denotes the results of the primality test.
  public boolean is_prime(BigInteger n, int k) {
    if (n.compareTo(TWO) < 0) return false;
    else if (n.compareTo(TWO) == 0) return true;
    else if (n.mod(TWO).compareTo(ZERO) == 0) return false;

    BigInteger i = ZERO;

    // Express n - 1 = 2^i * d, where d is odd by
    // factoring powers of 2 from n - 1.
    while (true) {
      BigInteger modulus = TWO.pow(i.intValue());
      BigInteger m = n.subtract(ONE).mod(modulus);

      if (m.compareTo(ZERO) == 0) i = i.add(ONE);
      else if (m.compareTo(ZERO) > 0) break;
    }

    i = i.subtract(ONE);

    BigInteger divisor = TWO.pow(i.intValue());
    BigInteger d = n.subtract(ONE).divide(divisor);

    // The more k iterations, the more accurate the result. It decreases
    // the likelihood of a composite number passing the Miller-Rabin test.
    for (int j = 0; j < k; ++j) {
      // Pick a random integer a in the range [2, n - 1].
      BigInteger a = random(TWO, n.subtract(ONE));

      // Let x = a^d mod n.
      BigInteger x = a.modPow(d, n);

      // Either n is prime or a is a strong liar for n. Try another
      // random a to determine if a is truly prime.
      if (x.compareTo(ONE) == 0 || x.compareTo(n.subtract(ONE)) == 0) continue;

      boolean flag = false;

      // Repeat i - 1 times to determine if n is prime.
      for (BigInteger p = ZERO; p.compareTo(i.subtract(ONE)) < 0; p = p.add(ONE)) {
        // Let x = x^2 mod n.
        x = x.modPow(TWO, n);

        // Retry with another random a.
        if (x.compareTo(n.subtract(ONE)) == 0) {
          flag = true;
          break;
        }
      }

      // Most likely n is composite.
      if (!flag) return false;
    }

    return true;
  }
  /**
   * Signals the start of a new message to process with this <code>UST</code> with a designated
   * <emIndex</em> value.
   *
   * @param ndx the <em>Index</em> to use with the new message.
   * @throws LimitReachedException if the value of the <em>Index</em> has reached its allowed upper
   *     bound. To use this <code>UST</code> instance a new initialisation (with a new user-supplied
   *     key material) should occur.
   * @throws InvalidKeyException if the underlying cipher, used in either or both the Integrity
   *     Protection and Confidentiality Protection functions has detected an exception.
   */
  public void beginMessageWithIndex(BigInteger ndx)
      throws LimitReachedException, InvalidKeyException {
    if (ndx.compareTo(maxIndex) > 0) {
      throw new LimitReachedException();
    }

    index = ndx;

    // depending on the desired services, get keying material from the
    // internal keystream generator and complete the relevant attributes.
    // the key size shall be the same size as the user-supplied key material.
    // remember we need the 1st generator if integrity is required even when
    // confidentiality is not
    if (wantConfidentiality || wantIntegrity) {
      byte[] cpKey = new byte[keysize];
      keystream.nextBytes(cpKey, 0, keysize);
      cpAttributes.put(IBlockCipher.KEY_MATERIAL, cpKey);
      if (cpStream instanceof ICMGenerator) {
        cpAttributes.put(ICMGenerator.SEGMENT_INDEX, index);
      } else {
        cpAttributes.put(UMacGenerator.INDEX, new Integer(index.intValue()));
      }

      cpStream.init(cpAttributes);
    }

    if (wantIntegrity) {
      byte[] ipKey = new byte[keysize];
      keystream.nextBytes(ipKey, 0, keysize);
      ipAttributes.put(IBlockCipher.KEY_MATERIAL, ipKey);
      if (ipStream instanceof ICMGenerator) {
        ipAttributes.put(ICMGenerator.SEGMENT_INDEX, index);
      } else {
        ipAttributes.put(UMacGenerator.INDEX, new Integer(index.intValue()));
      }

      ipStream.init(ipAttributes);

      // get prefix bytes
      byte[] prefix = new byte[macLength];
      cpStream.nextBytes(prefix, 0, macLength);
      macAttributes.put(TMMH16.PREFIX, prefix);

      mac = new TMMH16();
      macAttributes.put(TMMH16.KEYSTREAM, ipStream);
      mac.init(macAttributes);
    }

    ready = true;
  }
Example #17
0
  private static void checkNormaliseBaseTenResult(ExpandedDouble orig, NormalisedDecimal result) {
    String sigDigs = result.getSignificantDecimalDigits();
    BigInteger frac = orig.getSignificand();
    while (frac.bitLength() + orig.getBinaryExponent() < 200) {
      frac = frac.multiply(BIG_POW_10);
    }
    int binaryExp = orig.getBinaryExponent() - orig.getSignificand().bitLength();

    String origDigs = frac.shiftLeft(binaryExp + 1).toString(10);

    if (!origDigs.startsWith(sigDigs)) {
      throw new AssertionFailedError("Expected '" + origDigs + "' but got '" + sigDigs + "'.");
    }

    double dO = Double.parseDouble("0." + origDigs.substring(sigDigs.length()));
    double d1 = Double.parseDouble(result.getFractionalPart().toPlainString());
    BigInteger subDigsO = BigInteger.valueOf((int) (dO * 32768 + 0.5));
    BigInteger subDigsB = BigInteger.valueOf((int) (d1 * 32768 + 0.5));

    if (subDigsO.equals(subDigsB)) {
      return;
    }
    BigInteger diff = subDigsB.subtract(subDigsO).abs();
    if (diff.intValue() > 100) {
      // 100/32768 ~= 0.003
      throw new AssertionFailedError("minor mistake");
    }
  }
Example #18
0
  /** See CMIS 1.0 section 2.2.2.4 getTypeDescendants */
  public List<TypeDefinitionContainer> getTypesDescendants(
      String typeId, BigInteger depth, Boolean includePropertyDefinitions) {

    List<TypeDefinitionContainer> result = new ArrayList<TypeDefinitionContainer>();

    // check depth
    int d = depth == null ? -1 : depth.intValue();
    if (d == 0) {
      throw new CmisInvalidArgumentException("Depth must not be 0!");
    }

    // set property definition flag to default value if not set
    boolean ipd = Boolean.TRUE.equals(includePropertyDefinitions);

    if (typeId == null) {
      result.add(getTypesDescendants(d, fTypes.get(FOLDER_TYPE_ID), ipd));
      result.add(getTypesDescendants(d, fTypes.get(DOCUMENT_TYPE_ID), ipd));
    } else {
      TypeDefinitionContainer tc = fTypes.get(typeId);
      if (tc != null) {
        result.add(getTypesDescendants(d, tc, ipd));
      }
    }

    return result;
  }
 @AuditTrail
 public Invoice loadLast(BigInteger accountId) {
   return this.jdbcTemplate.queryForObject(
       "select * from invoice where account_id = ? and period_to = (select max(period_to) from invoice) limit 1",
       new Object[] {accountId.intValue()},
       new InvoiceRowMapper());
 }
  protected void convertVertexLayout(
      final LayoutVertexFactsType vertex, final GraphicsType graphics) throws CanoniserException {
    if (vertex != null) {
      final FillType fill = ANF_FACTORY.createFillType();

      // Convert all Attributes
      final LayoutAttributesFactsType attr = vertex.getAttributes();
      for (final JAXBElement<?> element : attr.getAutosizeOrBackgroundColorOrBendable()) {
        final Object elementValue = element.getValue();
        if (elementValue instanceof LayoutRectangleType) {
          try {
            convertLayoutRectangleAttribute((LayoutRectangleType) elementValue, graphics);
          } catch (final ParseException e) {
            throw new CanoniserException(
                "Could not convert layout of element " + vertex.getId(), e);
          }
        }
        if (element.getName().getLocalPart().equals(BACKGROUND_COLOR)
            && element.getValue() != null) {
          final BigInteger color = (BigInteger) element.getValue();
          fill.setColor(ConversionUtils.convertColorToString(color.intValue()));
        }
      }

      fill.setImage(vertex.getIconpath());
      graphics.setFill(fill);
    }
  }
  public static synchronized int generateMD5Id(Object... object) {
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos;
      oos = new ObjectOutputStream(baos);

      for (Object x : object) {
        if (x == null) oos.writeChars("null");
        else if (x instanceof Integer) oos.writeInt((Integer) x);
        else if (x instanceof String) oos.writeChars((String) x);
        else if (x instanceof Double) oos.writeDouble((Double) x);
        else if (x instanceof Class) oos.writeChars(((Class<?>) x).getName());
      }

      oos.close();
      MessageDigest m = MessageDigest.getInstance("MD5");
      m.update(baos.toByteArray());
      BigInteger testObjectHash = new BigInteger(m.digest());
      return testObjectHash.intValue();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return 0;
  }
Example #22
0
  /**
   * Convert decimal to hexadecimal�iNo limit string length�j <br>
   * Return hexadecimal string (unsigned integer number string) from decimal(integer number) <br>
   * In case parameter is a minus number, return blank string <br>
   *
   * @param argStr decimal string
   * @return hexadecimal string
   */
  public static String chgHexString(String argStr) {

    // In case parameter is a minus number, return blank string
    if (argStr.charAt(0) == '-') {
      return "";
    }

    StringBuffer hexb = new StringBuffer();
    BigInteger bi = new BigInteger(argStr);
    int tempInt;
    BigInteger tempBi;

    // Convert each 4 bit, start from the end.
    for (int bitlength = bi.bitLength(); bitlength > 0; bitlength -= 4) {
      tempBi = bi.and(HEX_MASK);
      tempInt = tempBi.intValue();
      hexb.append(HEX_STR.charAt(tempInt));
      bi = bi.shiftRight(4);
    }
    // correction after converting
    int hexlength = hexb.length();
    if (hexlength == 0) {
      // In case value =0, put "00"
      hexb.append("00");
    } else if ((hexlength % 2) == 1) {
      // After converting, if result is a old number string, add "0" at
      // the end of string
      hexb.append("0");
    }

    // Reverse result string (because string was converted from the
    // 4-bit-end)
    return hexb.reverse().toString();
  }
Example #23
0
 public static String set(final String lhs, BigInteger index, char value) {
   int idx = index.intValue();
   // hmmm, not exactly efficient!
   StringBuilder sb = new StringBuilder(lhs);
   sb.setCharAt(idx, value);
   return sb.toString();
 }
  public static void main(String argv[]) {

    // do some simple operations
    System.out.println("SimpleITK says 'Hello World' from Java");

    if (argv.length < 2) {
      System.out.println("Usage: java ImageConnection <input> <output>");
      return;
    }

    ImageFileReader reader = new ImageFileReader();

    reader.setFileName(argv[0]);

    Image img = reader.execute();

    PixelContainer pixelsContainer = img.getPixelContainer();

    java.math.BigInteger t = pixelsContainer.getNumberOfPixels();

    int numberOfPixels = t.intValue();

    int[] buffer = new int[numberOfPixels];

    buffer[0] = 13;
    buffer[1] = 2;
    buffer[2] = 19;

    pixelsContainer.setBufferAsUnsignedInt8(buffer, numberOfPixels);
  }
Example #25
0
 @Test(timeout = 5000L)
 public void powExactIntIntExact() {
   for (int base : INTS) {
     for (int power : INTS) {
       if (power < 0) continue;
       boolean overflow =
           BigInteger.valueOf(31 - Integer.numberOfLeadingZeros(Math.abs(base)))
                   .multiply(BigInteger.valueOf(power))
                   .compareTo(BigInteger.valueOf(32))
               > 0;
       BigInteger expected = overflow ? null : BigInteger.valueOf(base).pow(power);
       if (expected != null && expected.bitLength() <= 31) {
         int value = powExact(base, power);
         assertEquals(base + " ^ " + power, expected.intValue(), value);
         assertEquals(base + " ^ " + power, (int) Math.pow(base, power), value);
         assertEquals(base + " ^ " + power, pow(base, power), value);
       } else {
         try {
           powExact(base, power);
           fail("Should overflow: " + base + " ^ " + power);
         } catch (ArithmeticException e) {
         }
       }
     }
   }
 }
Example #26
0
 /**
  * Finds factorial value of given number.
  *
  * @param n number of which factorial to find
  * @return factorial value
  */
 public static BigInteger factorial(BigInteger n) {
   BigInteger result = BigInteger.ONE;
   for (int i = 1; i <= n.intValue(); i++) {
     result = result.multiply(new BigInteger(i + ""));
   }
   return result;
 }
Example #27
0
  public void init(BigInteger prime, BigInteger N, BigInteger root) {
    int target = N.mod(prime).intValue();
    this.prime = prime.intValue();
    log = Math.log(this.prime);

    long[] flats = MathUtils.ressol(this.prime, target);

    int solutions = 0;
    for (int i = 0; i < flats.length; i++) {
      if (flats[i] > -1) {
        solutions++;
      }
    }

    positions = new long[solutions];
    for (int i = 0; i < flats.length; i++) {
      if (flats[i] <= -1) {
        continue;
      }
      positions[i] = flats[i] - root.mod(prime).intValue();
      if (positions[i] < 0) {
        positions[i] += this.prime;
      }
    }

    if (positions.length == 2 && positions[0] > positions[1]) {
      long tmp = positions[0];
      positions[0] = positions[1];
      positions[1] = tmp;
    }
  }
 @Override
 public int hashCode() {
   byte[] bytes = name.toString().getBytes();
   BigInteger bigInt = new BigInteger(bytes);
   int val = bigInt.bitCount() + bigInt.intValue();
   return val + idx;
 }
  protected void convertNumberToInt() throws IOException, JsonParseException {
    // First, converting from long ought to be easy
    if ((_numTypesValid & NR_LONG) != 0) {
      // Let's verify it's lossless conversion by simple roundtrip
      int result = (int) _numberLong;
      if (((long) result) != _numberLong) {
        _reportError("Numeric value (" + getText() + ") out of range of int");
      }
      _numberInt = result;
    } else if ((_numTypesValid & NR_BIGINT) != 0) {
      // !!! Should check for range...
      _numberInt = _numberBigInt.intValue();
    } else if ((_numTypesValid & NR_DOUBLE) != 0) {
      // Need to check boundaries
      if (_numberDouble < MIN_INT_D || _numberDouble > MAX_INT_D) {
        reportOverflowInt();
      }
      _numberInt = (int) _numberDouble;
    } else if ((_numTypesValid & NR_BIGDECIMAL) != 0) {
      if (BD_MIN_INT.compareTo(_numberBigDecimal) > 0
          || BD_MAX_INT.compareTo(_numberBigDecimal) < 0) {
        reportOverflowInt();
      }
      _numberInt = _numberBigDecimal.intValue();
    } else {
      _throwInternal(); // should never get here
    }

    _numTypesValid |= NR_INT;
  }
 public int Decrypto(BigInteger c) {
   BigInteger nSquare = n.multiply(n);
   BigInteger Ans = c.modPow(lambda, nSquare);
   Ans = Ans.subtract(BigInteger.ONE).divide(n);
   Ans = Ans.remainder(n).multiply(nu).remainder(n);
   return Ans.intValue();
 }