Beispiel #1
0
  public static void testICDE() {
    // Number of total operations
    int numberOfTests = 5;
    // Length of the p, note that n=p.q
    int lengthp = 512;

    Paillier esystem = new Paillier();
    Random rd = new Random();
    PaillierPrivateKey key = KeyGen.PaillierKey(lengthp, 122333356);
    esystem.setDecryptEncrypt(key);
    // let's test our algorithm by encrypting and decrypting few instances

    long start = System.currentTimeMillis();
    for (int i = 0; i < numberOfTests; i++) {
      BigInteger m1 = BigInteger.valueOf(Math.abs(rd.nextLong()));
      BigInteger m2 = BigInteger.valueOf(Math.abs(rd.nextLong()));
      BigInteger c1 = esystem.encrypt(m1);
      BigInteger c2 = esystem.encrypt(m2);
      BigInteger c3 = esystem.multiply(c1, m2);
      c1 = esystem.add(c1, c2);
      c1 = esystem.add(c1, c3);

      esystem.decrypt(c1);
    }
    long stop = System.currentTimeMillis();
    System.out.println(
        "Running time per comparison in milliseconds: " + ((stop - start) / numberOfTests));
  }
Beispiel #2
0
 /**
  * Adds the time zone to the specified token builder.
  *
  * @param tb token builder
  */
 void zone(final TokenBuilder tb) {
   if (tz == Short.MAX_VALUE) return;
   if (tz == 0) {
     tb.add('Z');
   } else {
     tb.add(tz > 0 ? '+' : '-');
     prefix(tb, Math.abs(tz) / 60, 2);
     tb.add(':');
     prefix(tb, Math.abs(tz) % 60, 2);
   }
 }
  private int findClosestIndexOf(String context, int oldIndex, String content) {

    Matcher matcher = Pattern.compile(Pattern.quote(context)).matcher(content);
    int index = 0;

    while (matcher.find()) {
      if (Math.abs(oldIndex - matcher.start()) < (Math.abs(oldIndex - index))) {
        index = matcher.start();
      }
    }

    return index;
  }
Beispiel #4
0
  /** Dummy test method. */
  public static boolean dan(Point p1, Point p2) {
    //		Point p1 = mech1.getLocation();
    //		Point p2 = mech2.getLocation();
    int p1x = p1.getx();
    int p1y = p1.gety();
    int p2x = p2.getx();
    int p2y = p2.gety();
    int dx = p2x - p1x;
    int dy = p2y - p1y;
    int xdir = sign(dx);
    int ydir = sign(dy);
    //		double dist = Math.sqrt(dx*dx+dy*dy);
    double changex = (double) Math.abs(dx); // Diff in x
    double changey = (double) Math.abs(dy); // Diff in y

    double currentx = p1x;
    double currenty = p1y;
    int nextx = p1x;
    int nexty = p1y;
    double xdist, ydist;
    double xcost, ycost;

    int width = 5;

    while ((p2x - nextx) * xdir > 0 || (p2y - nexty) * ydir > 0) {
      xdist =
          dist(
              currentx, width,
              xdir); // total distance need to encounter next terrain object in x direction
      ydist = dist(currenty, width, ydir);

      xcost = (changex == 0) ? 10000 : xdist / changex;
      ycost = (changey == 0) ? 10000 : ydist / changey;

      if (xcost <= ycost) ydist = xdist * (changey / changex);
      else xdist = ydist * (changex / changey);

      currentx += xdir * xdist;
      currenty += ydir * ydist;

      nextx = (int) round(currentx, ydir);
      nexty = (int) round(currenty, ydir);

      //			if (Map.getNearestGrid(nextx,nexty).getType() !=0) return false;
    }

    System.out.println("Nextx: " + nextx + " Nexty: " + nexty);
    System.out.println("Currentx: " + currentx + " Currenty: " + currenty);
    return true;
  }
Beispiel #5
0
 public static int rules(
     String top, Vector<String> first, Vector<String> second, Vector<String> afia) {
   while (!first.isEmpty() && !second.isEmpty()) {
     if (count % 2 == 0) {
       boolean check = false;
       for (int i = 0; i < first.size(); i++) {
         check =
             matcher(
                 top,
                 first.elementAt(
                     i)); // performs a linear search on player1's whot to see if any matches the
         // top card
         if (check == true) {
           place.addElement(first.elementAt(i));
           first.removeElementAt(i);
           break;
         }
       }
       if (check == false) {
         Random rd = new Random();
         int pick = Math.abs(rd.nextInt(afia.size() - 1)) % (afia.size() - 1);
         first.addElement(afia.elementAt(pick));
         afia.removeElementAt(pick);
       }
     } else {
       boolean check = false;
       for (int i = 0; i < second.size(); i++) {
         check =
             matcher(
                 top,
                 second.elementAt(
                     i)); // performs a linear search on player1's whot to see if any matches the
         // top card
         if (check == true) {
           place.addElement(second.elementAt(i));
           second.removeElementAt(i);
           break;
         }
       }
       if (check == false) {
         Random rd = new Random();
         int pick = Math.abs(rd.nextInt(afia.size() - 1)) % (afia.size() - 1);
         second.addElement(afia.elementAt(pick));
         afia.removeElementAt(pick);
       }
     }
   }
   return 1;
 }
 // BEGIN KAWIGIEDIT TESTING
 // Generated by KawigiEdit-pf 2.3.0
 private static boolean KawigiEdit_RunTest(
     int testNum, int[] p0, int[] p1, boolean hasAnswer, double p2) {
   System.out.print("Test " + testNum + ": [" + "{");
   for (int i = 0; p0.length > i; ++i) {
     if (i > 0) {
       System.out.print(",");
     }
     System.out.print(p0[i]);
   }
   System.out.print("}" + "," + "{");
   for (int i = 0; p1.length > i; ++i) {
     if (i > 0) {
       System.out.print(",");
     }
     System.out.print(p1[i]);
   }
   System.out.print("}");
   System.out.println("]");
   GreaterGame obj;
   double answer;
   obj = new GreaterGame();
   long startTime = System.currentTimeMillis();
   answer = obj.calc(p0, p1);
   long endTime = System.currentTimeMillis();
   boolean res;
   res = true;
   System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds");
   if (hasAnswer) {
     System.out.println("Desired answer:");
     System.out.println("\t" + p2);
   }
   System.out.println("Your answer:");
   System.out.println("\t" + answer);
   if (hasAnswer) {
     res = answer == answer && Math.abs(p2 - answer) <= 1e-9 * Math.max(1.0, Math.abs(p2));
   }
   if (!res) {
     System.out.println("DOESN'T MATCH!!!!");
   } else if ((endTime - startTime) / 1000.0 >= 2) {
     System.out.println("FAIL the timeout");
     res = false;
   } else if (hasAnswer) {
     System.out.println("Match :-)");
   } else {
     System.out.println("OK, but is it right?");
   }
   System.out.println("");
   return res;
 }
Beispiel #7
0
  /** Returns cost of moving specified distance in specified map grid. */
  public static int getTerrainCost(MapGrid grid, int distance, int currentElevation) {
    int cost = 0;

    if (grid.getType() == 1) // Rough terrain cost
    {
      cost = cost + (distance * 2);
    } else if (grid.getType() == 2) // Light woods cost
    {
      cost = cost + (distance * 2);
    } else if (grid.getType() == 3) // Heavy woods cost
    {
      cost = cost + (distance * 3);
    } else if ((grid.getType() == 4) && (grid.getElevation() == 1)) // Depth 1 Water cost
    {
      cost = cost + (distance * 2);
    } else if ((grid.getType() == 4) && (grid.getElevation() >= 2)) // Depth 2+ Water cost
    {
      cost = cost + (distance * 4);
    } else {
      cost = cost + distance;
    } // Clear terrain

    cost = cost * grid.getSize();

    if (grid.getElevation() != currentElevation) {
      cost = cost + (Math.abs(grid.getElevation() - currentElevation) * 60);
    } // Elevation change cost

    return (cost);
  }
Beispiel #8
0
  /** Returns angle in degrees from specified origin to specified destination. */
  public static int getAngle(Point origin, Point destination) // origin != destination
      {
    double distance = getDistance(origin, destination);
    int add = 0;
    int x = destination.getx() - origin.getx();
    int y = origin.gety() - destination.gety(); // Java flips things around

    double angleRad = Math.asin(Math.abs(y) / distance);
    double angleDeg = Math.toDegrees(angleRad);

    if ((x >= 0) && (y >= 0)) // Quadrant 1
    {
      angleDeg = angleDeg;
    }
    if ((x < 0) && (y > 0)) // Quadrant 2
    {
      angleDeg = 180 - angleDeg;
    }
    if ((x <= 0) && (y <= 0)) // Quadrant 3
    {
      angleDeg = 180 + angleDeg;
    }
    if ((x > 0) && (y < 0)) // Quadrant 4
    {
      angleDeg = 360 - angleDeg;
    }

    float angleFloat = Math.round(angleDeg);
    int angleInt = Math.round(angleFloat);

    return (angleInt);
  }
Beispiel #9
0
 /**
  * Adds the time to the specified token builder.
  *
  * @param tb token builder
  */
 final void time(final TokenBuilder tb) {
   if (sec.remainder(DAYSECONDS).signum() == 0) return;
   tb.add('T');
   final long h = hou();
   if (h != 0) {
     tb.addLong(Math.abs(h));
     tb.add('H');
   }
   final long m = min();
   if (m != 0) {
     tb.addLong(Math.abs(m));
     tb.add('M');
   }
   final BigDecimal sc = sec();
   if (sc.signum() == 0) return;
   tb.add(Token.chopNumber(Token.token(sc.abs().toPlainString()))).add('S');
 }
Beispiel #10
0
  /** Returns distance to next map grid. */
  public static double dist(double num, int width, int dir) {
    // distance to next terrain square
    double next = num + width * dir;
    int square = (int) (round((next / width), dir)) * width;
    double dist = (square - num) - dir * ((double) width / 2);

    return Math.abs(dist);
  }
Beispiel #11
0
 public Fraction(BigDecimal original) {
   super();
   double A, C, D, X, Y, M;
   C = original.doubleValue();
   A = C;
   D = C;
   X = 1;
   Y = 0;
   do {
     M = Y;
     Y = X + Y * Math.round(C);
     X = M;
     if (C != Math.round(C)) {
       C = 1 / (C - Math.round(C));
     }
     M = Math.round(D * Y);
   } while (M != MathUtilities.toFix(D * Y, 10));
   if ((Math.abs(M) > 100000) || (Math.abs(Y) > 100000) || (Math.abs(Y) == 1)) {
     this.numerator = original;
     this.denominator = BigInteger.ONE;
   } else {
     this.numerator =
         BigDecimal.valueOf(Math.round((Math.abs(M) / M) * (Math.abs(Y) / Y) * Math.abs(M)));
     this.denominator = new BigInteger(Long.toString(Math.round(Math.abs(Y))));
   }
 }
Beispiel #12
0
 /**
  * Adds the date to the specified token builder.
  *
  * @param tb token builder
  */
 final void date(final TokenBuilder tb) {
   tb.add('P');
   final long y = yea();
   if (y != 0) {
     tb.addLong(Math.abs(y));
     tb.add('Y');
   }
   final long m = mon();
   if (m != 0) {
     tb.addLong(Math.abs(m));
     tb.add('M');
   }
   final long d = day();
   if (d != 0) {
     tb.addLong(Math.abs(d));
     tb.add('D');
   }
 }
Beispiel #13
0
 public static ArrayList<Vector> share(
     Vector<String> allgames) { // shares the games to the players
   Vector<String> play1 = new Vector<String>();
   Vector<String> play2 = new Vector<String>();
   ArrayList<Vector> al = new ArrayList<Vector>();
   Random rd = new Random();
   for (int i = 0; i < 4; i++) {
     int first = Math.abs(rd.nextInt(allgames.size() - 1)) % (allgames.size());
     play1.addElement(allgames.elementAt(first));
     allgames.removeElementAt(first);
     int second = Math.abs(rd.nextInt(allgames.size() - 1)) % (allgames.size());
     play2.addElement(allgames.elementAt(second));
     allgames.removeElementAt(second);
   }
   al.add(play1);
   al.add(play2);
   v = allgames;
   return al;
 }
  private TextConstraint exactMatch(String primaryContent, TextConstraint originalConstraint)
      throws NoMatchFoundException {

    // find the text before the annotation
    // int startPos = primaryContent.indexOf(this.beforeContext);
    int startPos =
        findClosestIndexOf(
            this.beforeContext,
            originalConstraint.getStartPos() - this.beforeContext.length(),
            primaryContent);

    startPos += this.beforeContext.length();

    // find text after annotation
    // int endPos = primaryContent.indexOf(this.afterContext);
    int endPos =
        findClosestIndexOf(this.afterContext, originalConstraint.getEndPos(), this.totalSelection);

    if (endPos < 0 || startPos < 0) {
      // search through the selected content

      int positionTotal = 0;
      if (this.beginSel.length() > 0 && this.endSel.length() > 0) {
        int originalPosTotal =
            (originalConstraint.getStartPos()
                + (originalConstraint.getEndPos() - this.endSel.length()));

        // search beginning source selection, then end
        // selection, respectively
        int beginTotal =
            findClosestIndexOf(this.beginSel, originalConstraint.getStartPos(), primaryContent);

        int afterTotal =
            findClosestIndexOf(
                this.endSel,
                (originalConstraint.getEndPos() - this.endSel.length()),
                primaryContent);

        positionTotal = beginTotal + afterTotal;

        if (Math.abs(positionTotal - originalPosTotal) > 5) {
          return null;
        }

      } else {
        // search through total selection
        positionTotal =
            findClosestIndexOf(
                this.totalSelection, originalConstraint.getStartPos(), primaryContent);
        if (positionTotal < 0) return null;
      }
    }

    return new TextConstraint(startPos, endPos);
  }
Beispiel #15
0
 int computeDifference() {
   for (int i = 0; i < elements.length; i++) {
     for (int j = i + 1; j < elements.length; j++) {
       int d = Math.abs(elements[i] - elements[j]);
       if (d >= maximumDifference) {
         this.maximumDifference = d;
       }
     }
   }
   return this.maximumDifference;
 }
Beispiel #16
0
 private double evaluateAt(double a[], int start, double where) {
   int deg = a.length - 1;
   if (Math.abs(where) <= 1.0) {
     double result = a[deg];
     for (int i = deg - 2; i >= start; i--) result = result * where + a[i];
     return result;
   } else {
     double result = a[0 + start];
     for (int i = 1 + start; i < deg; i++) result = result / where + a[i];
     return result * Math.pow(where, deg - start);
   }
 }
Beispiel #17
0
  /**
   * The cost of this solution is based on how well the KK algorithm would do with this
   * prepartitioning scheme.
   */
  public long cost() {
    int i;
    long[] ppseq = new long[sol.length];
    for (i = 0; i < sol.length; i++) ppseq[i] = 0;
    for (i = 0; i < sol.length; i++) ppseq[sol[i]] += sequence[i];

    /*System.out.printf("\nProcessed sequence: ");
    for (i=0; i<sol.length; i++)
    	System.out.printf("%d\t",ppseq[i]);
    System.out.println("");*/

    return Math.abs(numpartition.karmarkar_karp(ppseq, sol.length));
  }
Beispiel #18
0
  public double EVAL(
      UnivariatePolynomial p, double lowerBound, double upperBound, double fl, double fu) {
    // System.out.println( "EVAL on (" + lowerBound + "," + upperBound + ") |-> (" + fl + "," + fu +
    // ")" );
    double m = (lowerBound + upperBound) / 2.0;
    double r = (upperBound - lowerBound) / 2.0;
    // System.out.println( "(m,r)=("+m+","+r+")" );
    if (upperBound - lowerBound < EPSILON) {
      //  System.out.println( "epsilon reached" );
      // prevent infinite loop (e.g. for non-squarefree polynomials)
      if (fl * fu < 0.0) return m;
      else return m; // java.lang.Double.NaN;
    }

    // test for exclusion predicate: no real root in (m-r,m+r)
    UnivariatePolynomial t = p.shift(m);
    // System.out.println( "Taylor exp. of f(x-" + m + "): " + t );
    double fm = t.getCoeff(0);
    double ta[] = t.getCoeffs();
    ta[0] = -Math.abs(ta[0]);
    for (int i = 1; i < ta.length; ++i) ta[i] = Math.abs(ta[i]);
    if (0.0 > new UnivariatePolynomial(ta).evaluateAt(r)) return java.lang.Double.NaN;
    // System.out.println( "Exclusion predicate false" );

    // test for inclusion predicate: exactly one real root in (m-r,m+r)
    UnivariatePolynomial t_der = p.derive().shift(m);
    // System.out.println( "Taylor exp. of f'(x-" + m + "): " + t_der );
    double ta_der[] = t_der.getCoeffs();
    ta_der[0] = -Math.abs(ta_der[0]);
    for (int i = 1; i < ta_der.length; ++i) ta_der[i] = Math.abs(ta_der[i]);

    if (fl * fu <= 0.0 && 0.0 > new UnivariatePolynomial(ta_der).evaluateAt(r))
      return bisect(p, lowerBound, upperBound, fl, fu);
    // System.out.println( "Inclusion predicate false" );        System.out.println();
    // bisect
    double result_left = EVAL(p, lowerBound, m, fl, fm);
    if (!java.lang.Double.isNaN(result_left)) return result_left;
    else return EVAL(p, m, upperBound, fm, fu);
  }
 public static String calculateUsual(double[] averageData, String[] month) {
   int n = averageData.length;
   double sum = 0;
   String result = "";
   for (int i = 0; i < n; i++) {
     sum += averageData[i];
   }
   sum = sum / n;
   double[] minus = new double[n];
   for (int i = 0; i < n; i++) {
     minus[i] = averageData[i] - sum;
     minus[i] = Math.abs(minus[i] / sum);
     if (minus[i] > 0.1) {
       System.out.print(i + "data" + averageData[i] + ":" + minus[i]);
       result = month[i] + ":";
     }
   }
   return result;
 }
Beispiel #20
0
  /**
   * Adjusts the timezone.
   *
   * @param zone timezone
   * @param spec indicates if zone has been specified (may be {@code null})
   * @param ii input info
   * @throws QueryException query exception
   */
  void tz(final DTDur zone, final boolean spec, final InputInfo ii) throws QueryException {
    final short t;
    if (spec && zone == null) {
      t = Short.MAX_VALUE;
    } else {
      if (zone == null) {
        final Calendar c = Calendar.getInstance();
        t = (short) ((c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)) / 60000);
      } else {
        t = (short) (zone.min() + zone.hou() * 60);
        if (zone.sec().signum() != 0) throw ZONESEC_X.get(ii, zone);
        if (Math.abs(t) > 60 * 14 || zone.day() != 0) throw INVALZONE_X.get(ii, zone);
      }

      // change time if two competing time zones exist
      if (tz != Short.MAX_VALUE) add(BigDecimal.valueOf(60L * (t - tz)));
    }
    tz = t;
  }
Beispiel #21
0
  private static double bisect(
      UnivariatePolynomial p, double lowerBound, double upperBound, double fl, double fu) {
    double[] a = p.getCoeffs();

    assert fl * fu < 0.0 : "tried bisection on interval without sign change";

    while (Math.abs(upperBound - lowerBound) > EPSILON) {
      double center = 0.5 * (lowerBound + upperBound);
      double fc = a[a.length - 1];
      for (int i = a.length - 2; i >= 0; i--) fc = fc * center + a[i];

      if (fc * fl < 0.0) {
        upperBound = center;
        fu = fc;
      } else if (fc == 0.0) {
        return center;
      } else {
        lowerBound = center;
        fl = fc;
      }
    }
    return lowerBound;
  }
Beispiel #22
0
 @Override
 public byte[] string(final InputInfo ii) {
   final TokenBuilder tb = new TokenBuilder();
   final boolean ymd = yea != Long.MAX_VALUE;
   if (ymd) {
     if (yea <= 0) tb.add('-');
     prefix(tb, Math.abs(yea()), 4);
     tb.add('-');
     prefix(tb, mon(), 2);
     tb.add('-');
     prefix(tb, day(), 2);
   }
   if (hou >= 0) {
     if (ymd) tb.add('T');
     prefix(tb, hou(), 2);
     tb.add(':');
     prefix(tb, min(), 2);
     tb.add(':');
     if (sec.intValue() < 10) tb.add('0');
     tb.addExt(Token.chopNumber(Token.token(sec().abs().toPlainString())));
   }
   zone(tb);
   return tb.finish();
 }
Beispiel #23
0
  /**
   * Formats the specified number and returns a string representation.
   *
   * @param item item
   * @param pics pictures
   * @param ii input info
   * @return picture variables
   * @throws QueryException query exception
   */
  private byte[] format(final ANum item, final Picture[] pics, final InputInfo ii)
      throws QueryException {

    // Rule 1: return results for NaN
    final double d = item.dbl(ii);
    if (Double.isNaN(d)) return nan;

    // Rule 2: check if value if negative (smaller than zero or -0)
    final boolean neg = d < 0 || d == 0 && Double.doubleToLongBits(d) == Long.MIN_VALUE;
    final Picture pic = pics[neg && pics.length == 2 ? 1 : 0];
    final IntList res = new IntList(), intgr = new IntList(), fract = new IntList();
    int exp = 0;

    // Rule 3: percent/permille
    ANum num = item;
    if (pic.pc) num = (ANum) Calc.MULT.ev(num, Int.get(100), ii);
    if (pic.pm) num = (ANum) Calc.MULT.ev(num, Int.get(1000), ii);

    if (Double.isInfinite(num.dbl(ii))) {
      // Rule 4: infinity
      intgr.add(new TokenParser(inf).toArray());
    } else {
      // Rule 5: exponent
      if (pic.minExp != 0 && d != 0) {
        BigDecimal dec = num.dec(ii).abs().stripTrailingZeros();
        int scl = 0;
        if (dec.compareTo(BigDecimal.ONE) >= 0) {
          scl = dec.setScale(0, RoundingMode.HALF_DOWN).precision();
        } else {
          while (dec.compareTo(BigDecimal.ONE) < 0) {
            dec = dec.multiply(BigDecimal.TEN);
            scl--;
          }
          scl++;
        }
        exp = scl - pic.min[0];
        if (exp != 0) {
          final BigDecimal n = BigDecimal.TEN.pow(Math.abs(exp));
          num = (ANum) Calc.MULT.ev(num, Dec.get(exp > 0 ? BigDecimal.ONE.divide(n) : n), ii);
        }
      }
      num = num.round(pic.maxFrac, true).abs();

      // convert positive number to string
      final String s =
          (num instanceof Dbl || num instanceof Flt
                  ? Dec.get(BigDecimal.valueOf(num.dbl(ii)))
                  : num)
              .toString();

      // integer/fractional separator
      final int sep = s.indexOf('.');

      // create integer part
      final int sl = s.length();
      final int il = sep == -1 ? sl : sep;
      for (int i = il; i < pic.min[0]; ++i) intgr.add(zero);
      // fractional number: skip leading 0
      if (!s.startsWith("0.") || pic.min[0] > 0) {
        for (int i = 0; i < il; i++) intgr.add(zero + s.charAt(i) - '0');
      }

      // squeeze in grouping separators
      if (pic.group[0].length == 1 && pic.group[0][0] > 0) {
        // regular pattern with repeating separators
        for (int p = intgr.size() - (neg ? 2 : 1); p > 0; --p) {
          if (p % pic.group[0][0] == 0) intgr.insert(intgr.size() - p, grouping);
        }
      } else {
        // irregular pattern, or no separators at all
        final int gl = pic.group[0].length;
        for (int g = 0; g < gl; ++g) {
          final int pos = intgr.size() - pic.group[0][g];
          if (pos > 0) intgr.insert(pos, grouping);
        }
      }

      // create fractional part
      final int fl = sep == -1 ? 0 : sl - il - 1;
      if (fl != 0) for (int i = sep + 1; i < sl; i++) fract.add(zero + s.charAt(i) - '0');
      for (int i = fl; i < pic.min[1]; ++i) fract.add(zero);

      // squeeze in grouping separators in a reverse manner
      final int ul = fract.size();
      for (int p = pic.group[1].length - 1; p >= 0; p--) {
        final int pos = pic.group[1][p];
        if (pos < ul) fract.insert(pos, grouping);
      }
    }

    // add minus sign
    if (neg && pics.length != 2) res.add(minus);
    // add prefix and integer part
    res.add(pic.prefSuf[0].toArray()).add(intgr.finish());
    // add fractional part
    if (!fract.isEmpty()) res.add(decimal).add(fract.finish());
    // add exponent
    if (pic.minExp != 0) {
      res.add(exponent);
      if (exp < 0) res.add(minus);
      final String s = Integer.toString(Math.abs(exp));
      final int sl = s.length();
      for (int i = sl; i < pic.minExp; i++) res.add(zero);
      for (int i = 0; i < sl; i++) res.add(zero + s.charAt(i) - '0');
    }
    // add suffix
    res.add(pic.prefSuf[1].toArray());
    return new TokenBuilder(res.finish()).finish();
  }
  public void fire() throws IllegalActionException {

    if (_state == RUNNING) {
      if (alfa.isKnown() && !emmode.isKnown()) {
        // if(alfa.isKnown()) {
        if (alfa.hasToken(0)) {
          double _alfa = ((DoubleToken) alfa.get(0)).doubleValue();

          /*
          if(_count > 0) {   // so atualiza se um evento true deu inicio
              _count++;
          }*/

          if (Math.abs(_alfa) >= 0.10) { // tem um evento
            // _sensorCount++;
            // if(_count == 0) {
            //    _count = 1;
            // }
            _count++;
          } else {
            _count = 0;
          }

          if (_count == 25) {
            emmode.broadcast(new Token());
            System.out.println("Entering Emergency Mode");
            _reset(); // uma vez setado o emmode, so na proxima....
          }

          /*
          if(_count == 50) {   // deu os 100ms
              if(_maxSensorCount >= 25 ||
                 _sensorCount >= 25) {
                  emmode.broadcast(new Token());
                  System.out.println("Entering Emergency Mode");

                  _reset(); // uma vez setado o emmode, so na proxima....
              }
              else {
                  _count = 0;
                  _sensorCount = 0;
                  _maxSensorCount = 0;
              }
          }
          else {
              if(Math.abs(_alfa) >= 0.10) {      // tem um evento
                  _sensorCount++;
                  if(_count == 0) {
                      _count = 1;
                  }
              }
              if((Math.abs(_alfa) < 0.1) && _count > 0) {    // nao tem mais , e estava contando
                  if(_sensorCount > _maxSensorCount) {
                      _maxSensorCount = _sensorCount;
                  }
                  _sensorCount = 0;
              }
          } */
        }
      }
    }

    if (alfa.isKnown() && !emmode.isKnown()) {
      emmode.broadcastClear();
    }
  }
Beispiel #25
0
  /** This main method basically tests the different features of the Paillier encryption */
  public static void test() {
    Random rd = new Random();
    long num = 0;
    long num1 = 0;
    BigInteger m = null;
    BigInteger c = null;
    int numberOfTests = 10;
    int j = 0;
    BigInteger decryption = null;
    Paillier esystem = new Paillier();
    PaillierPrivateKey key = KeyGen.PaillierKey(512, 122333356);
    esystem.setDecryptEncrypt(key);
    // let's test our algorithm by encrypting and decrypting a few instances
    for (int i = 0; i < numberOfTests; i++) {
      num = Math.abs(rd.nextLong());
      m = BigInteger.valueOf(num);
      System.out.println("number chosen  : " + m.toString());
      c = esystem.encrypt(m);
      System.out.println("encrypted value: " + c.toString());
      decryption = esystem.decrypt(c);
      System.out.println("decrypted value: " + decryption.toString());
      if (m.compareTo(decryption) == 0) {
        System.out.println("OK");
        j++;
      } else System.out.println("PROBLEM");
    }
    System.out.println(
        "out of "
            + (new Integer(numberOfTests)).toString()
            + "random encryption,# many of "
            + (new Integer(j)).toString()
            + " has passed");
    // Let us check the commutative properties of the paillier encryption
    System.out.println("Checking the additive properteries of the Paillier encryption");
    //   Obviously 1+0=1
    System.out.println(
        "1+0="
            + (esystem.decrypt(esystem.add(esystem.encryptone(), esystem.encryptzero())))
                .toString());
    // 1+1=2
    System.out.println(
        "1+1="
            + (esystem.decrypt(
                    esystem.add(esystem.encrypt(BigInteger.ONE), esystem.encrypt(BigInteger.ONE))))
                .toString());

    // 1+1+1=3
    System.out.println(
        "1+1+1="
            + (esystem.decrypt(
                    esystem.add(
                        esystem.add(
                            esystem.encrypt(BigInteger.ONE), esystem.encrypt(BigInteger.ONE)),
                        esystem.encrypt(BigInteger.ONE))))
                .toString());

    // 0+0=0
    System.out.println(
        "0+0="
            + (esystem.decrypt(
                    esystem.add(
                        esystem.encrypt(BigInteger.ZERO), esystem.encrypt(BigInteger.ZERO))))
                .toString());
    // 1+-1=0
    System.out.println(
        "1+-1="
            + (esystem.decrypt(
                    esystem.add(
                        esystem.encrypt(BigInteger.valueOf(-1).mod(key.getN())),
                        esystem.encrypt(BigInteger.ONE))))
                .toString());

    do {
      num = rd.nextLong();
    } while (key.inModN(BigInteger.valueOf(num)) == false);
    do {
      num1 = rd.nextLong();
    } while (key.inModN(BigInteger.valueOf(num1)) == false);
    BigInteger numplusnum1 = BigInteger.valueOf(num).add(BigInteger.valueOf(num1));
    BigInteger summodnsquare = numplusnum1.mod(key.getN());
    // D(E(num)+E(num1))=num+num1
    System.out.println(numplusnum1.toString());
    System.out.println(
        summodnsquare.toString()
            + "=\n"
            + esystem
                .decrypt(
                    esystem.add(
                        esystem.encrypt(BigInteger.valueOf(num)),
                        esystem.encrypt(BigInteger.valueOf(num1))))
                .toString());
    // Let us check the multiplicative properties
    System.out.println("Checking the multiplicative properties");
    // D(multiply(E(2),3))=6
    System.out.println(
        "6="
            + esystem.decrypt(
                esystem.multiply(
                    esystem.add(esystem.encrypt(BigInteger.ONE), esystem.encrypt(BigInteger.ONE)),
                    3)));
  }
 // To add/remove functions change evaluateOperator() and registration
 public double evaluateFunction(String fncnam, ArgParser fncargs) throws ArithmeticException {
   switch (Character.toLowerCase(fncnam.charAt(0))) {
     case 'a':
       {
         if (fncnam.equalsIgnoreCase("abs")) {
           return Math.abs(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("acos")) {
           return Math.acos(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("asin")) {
           return Math.asin(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("atan")) {
           return Math.atan(fncargs.next());
         }
       }
       break;
     case 'c':
       {
         if (fncnam.equalsIgnoreCase("cbrt")) {
           return Math.cbrt(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("ceil")) {
           return Math.ceil(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("cos")) {
           return Math.cos(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("cosh")) {
           return Math.cosh(fncargs.next());
         }
       }
       break;
     case 'e':
       {
         if (fncnam.equalsIgnoreCase("exp")) {
           return Math.exp(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("expm1")) {
           return Math.expm1(fncargs.next());
         }
       }
       break;
     case 'f':
       {
         if (fncnam.equalsIgnoreCase("floor")) {
           return Math.floor(fncargs.next());
         }
       }
       break;
     case 'g':
       {
         //              if(fncnam.equalsIgnoreCase("getExponent"   )) { return
         // Math.getExponent(fncargs.next());                } needs Java 6
       }
       break;
     case 'l':
       {
         if (fncnam.equalsIgnoreCase("log")) {
           return Math.log(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("log10")) {
           return Math.log10(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("log1p")) {
           return Math.log1p(fncargs.next());
         }
       }
       break;
     case 'm':
       {
         if (fncnam.equalsIgnoreCase("max")) {
           return Math.max(fncargs.next(), fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("min")) {
           return Math.min(fncargs.next(), fncargs.next());
         }
       }
       break;
     case 'n':
       {
         //              if(fncnam.equalsIgnoreCase("nextUp"        )) { return Math.nextUp
         // (fncargs.next());                } needs Java 6
       }
       break;
     case 'r':
       {
         if (fncnam.equalsIgnoreCase("random")) {
           return Math.random();
         } // impure
         if (fncnam.equalsIgnoreCase("round")) {
           return Math.round(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("roundHE")) {
           return Math.rint(fncargs.next());
         } // round half-even
       }
       break;
     case 's':
       {
         if (fncnam.equalsIgnoreCase("signum")) {
           return Math.signum(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sin")) {
           return Math.sin(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sinh")) {
           return Math.sinh(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sqrt")) {
           return Math.sqrt(fncargs.next());
         }
       }
       break;
     case 't':
       {
         if (fncnam.equalsIgnoreCase("tan")) {
           return Math.tan(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("tanh")) {
           return Math.tanh(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("toDegrees")) {
           return Math.toDegrees(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("toRadians")) {
           return Math.toRadians(fncargs.next());
         }
       }
       break;
     case 'u':
       {
         if (fncnam.equalsIgnoreCase("ulp")) {
           return Math.ulp(fncargs.next());
         }
       }
       break;
       // no default
   }
   throw new UnsupportedOperationException(
       "MathEval internal function setup is incorrect - internal function \""
           + fncnam
           + "\" not handled");
 }
Beispiel #27
0
 public static boolean epsEquals(double a, double b) {
   return Math.abs(a - b) < EPS;
 };
Beispiel #28
0
 /**
  * Checks if given <code>value</code> is a power of two.
  *
  * @param value any number
  * @return <code>true</code> when <code>value</code> is power of two, <code>false</code> otherwise
  */
 public static boolean isPowerOfTwo(int value) {
   value = Math.abs(value);
   // return (Math.abs(value) | (Math.abs(value) - 1)) == 0;
   return Integer.bitCount(value) == 1;
 }