Пример #1
1
  public static Hashtable findConfidence(Hashtable table) {
    Hashtable confidences = new Hashtable();
    Iterator key_iter = table.keySet().iterator();
    while (key_iter.hasNext()) {
      // System.out.println("here");
      ArrayList<Integer> combo = (ArrayList<Integer>) key_iter.next();
      // System.out.println("current combo"+combo);
      if (combo.size() >= 2) {
        ArrayList<Integer> current_combo =
            new ArrayList<Integer>(combo.subList(0, combo.size() - 1));
        ArrayList<Integer> last_combo =
            new ArrayList<Integer>(combo.subList(combo.size() - 1, combo.size()));
        /*System.out.println(combo);
        System.out.println(current_combo);
        System.out.println(last_combo);
        System.out.println(table.get(current_combo));*/

        if (table.get(current_combo) != null) {
          // System.out.println("it contains!");
          int first = (Integer) table.get(current_combo);
          int second = (Integer) table.get(combo);
          double dub_first = (double) first;
          double dub_second = (double) second;
          double combo_conf = dub_second / dub_first;
          confidences.put(combo, combo_conf);
          // System.out.println("combo:"+combo+" has the confience: "+combo_conf);
        }
      }
    }
    // System.out.println(confidences+"O");

    return confidences;
  }
Пример #2
1
    @Override
    public void run() {
      while (true) {
        if (istWindows()) aktuell = holeLaufwerkeWindows();
        else aktuell = holeLaufwerkeUnix();

        if (initial.size() != aktuell.size()) {
          if (!initial.containsAll(aktuell)) {
            neuesLaufwerk = holePathVonNeuemLaufwerk(initial, aktuell);
            textArea.append("Neues Laufwerk endeckt:  " + neuesLaufwerk + System.lineSeparator());
            this.initial = (ArrayList<Path>) aktuell.clone();
            neuesLaufwerkDialog();

          } else {
            this.initial = (ArrayList<Path>) aktuell.clone();
            textArea.append("Laufwerk wurde entfernt" + System.lineSeparator());
          }
        }

        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          System.out.println("Laufwerksprüfung wird abgebrochen");
        }
      }
    }
Пример #3
0
 /** generate mention annotations (with entity numbers) based on the ACE entities and mentions. */
 static void addMentionTags(Document doc, AceDocument aceDoc) {
   ArrayList<AceEntity> entities = aceDoc.entities;
   for (int i = 0; i < entities.size(); i++) {
     AceEntity entity = entities.get(i);
     ArrayList<AceEntityMention> mentions = entity.mentions;
     for (int j = 0; j < mentions.size(); j++) {
       AceEntityMention mention = (AceEntityMention) mentions.get(j);
       // we compute a jetSpan not including trailing whitespace
       Span aceSpan = mention.head;
       // skip mentions in ChEnglish APF not aligned to any English text
       if (aceSpan.start() < 0) continue;
       Span jetSpan = new Span(aceSpan.start(), aceSpan.end() + 1);
       FeatureSet features = new FeatureSet("entity", new Integer(i));
       if (flags.contains("types")) {
         features.put("type", entity.type.substring(0, 3));
         if (entity.subtype != null) features.put("subtype", entity.subtype);
       }
       if (flags.contains("extents")) {
         String cleanExtent = mention.text.replaceAll("\n", " ");
         features.put("extent", AceEntityMention.addXmlEscapes(cleanExtent));
       }
       doc.annotate("mention", jetSpan, features);
     }
   }
 }
Пример #4
0
 public static void findMaxCut() {
   int arrayCut = Integer.MAX_VALUE;
   int indexCut = Integer.MAX_VALUE;
   int max = Integer.MIN_VALUE;
   int numArrays = occupied.size();
   for (int i = 0; i < numArrays; i++) {
     ArrayList<Integer> arr = occupied.get(i);
     int len = arr.size();
     for (int j = 0; j < len - 1; j++) {
       if (arr.get(j + 1) - arr.get(j) > max) {
         max = arr.get(j + 1) - arr.get(j);
         indexCut = j;
         arrayCut = i;
       }
     }
   }
   ArrayList<Integer> arr1 = new ArrayList<Integer>();
   ArrayList<Integer> arr2 = new ArrayList<Integer>();
   ArrayList<Integer> arr = occupied.get(arrayCut);
   for (int i = 0; i <= indexCut; i++) {
     arr1.add(arr.get(i));
   }
   for (int i = indexCut + 1; i < arr.size(); i++) {
     arr2.add(arr.get(i));
   }
   occupied.remove(arrayCut);
   occupied.add(arr1);
   occupied.add(arr2);
 }
  public static void main(String[] args) {
    ArrayList<Pattern> patterns = new ArrayList<Pattern>();
    ArrayList<Cut> cuts;
    ArrayList<Garment> garments;

    patterns.add(new Pattern(2, 2, 1, "Tie"));
    patterns.add(new Pattern(2, 6, 4, "Skirt"));
    patterns.add(new Pattern(4, 2, 3, "Blouse"));
    patterns.add(new Pattern(5, 3, 5, "Dress"));
    int width = 30;
    int height = 15;
    ClothCutter cutter = new ClothCutter(width, height, patterns);
    System.out.println("Optimized value: " + cutter.optimize());
    cuts = cutter.getCuts();
    garments = cutter.getGarments();

    ClothPanel panel = new ClothPanel(width, height);
    JFrame frame = new JFrame("A luxurious bolt of fabric");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
    sleep(1000);
    for (int i = 0; i < cuts.size(); i++) {
      panel.drawCut(cuts.get(i));
      sleep(100);
    }
    for (int i = 0; i < garments.size(); i++) {
      System.out.println(garments.get(i));
      panel.drawGarment(garments.get(i));
      sleep(100);
    }
  }
 /**
  * Return certificates for signed bundle, otherwise null.
  *
  * @return An array of certificates or null.
  */
 public ArrayList getCertificateChains(boolean onlyTrusted) {
   if (checkCerts) {
     Certificate[] c = archive.getCertificates();
     checkCerts = false;
     if (c != null) {
       ArrayList failed = new ArrayList();
       untrustedCerts = Util.getCertificateChains(c, failed);
       if (!failed.isEmpty()) {
         // NYI, log Bundle archive has invalid certificates
         untrustedCerts = null;
       }
     }
   }
   ArrayList res = trustedCerts;
   if (!onlyTrusted && untrustedCerts != null) {
     if (res == null) {
       res = untrustedCerts;
     } else {
       res = new ArrayList(trustedCerts.size() + untrustedCerts.size());
       res.addAll(trustedCerts);
       res.addAll(untrustedCerts);
     }
   }
   return res;
 }
Пример #7
0
 private boolean processURL(URL url, String baseDir, StatusWindow status) throws IOException {
   if (processedLinks.contains(url)) {
     return false;
   } else {
     processedLinks.add(url);
   }
   URLConnection connection = url.openConnection();
   InputStream in = new BufferedInputStream(connection.getInputStream());
   ArrayList list = processPage(in, baseDir, url);
   if ((status != null) && (list.size() > 0)) {
     status.setMaximum(list.size());
   }
   for (int i = 0; i < list.size(); i++) {
     if (status != null) {
       status.setMessage(Utils.trimFileName(list.get(i).toString(), 40), i);
     }
     if ((!((String) list.get(i)).startsWith("RUN"))
         && (!((String) list.get(i)).startsWith("SAVE"))
         && (!((String) list.get(i)).startsWith("LOAD"))) {
       processURL(
           new URL(url.getProtocol(), url.getHost(), url.getPort(), (String) list.get(i)),
           baseDir,
           status);
     }
   }
   in.close();
   return true;
 }
Пример #8
0
  private static void getTopDocuments(int num, HashMap<String, Float> scoremap, String filename)
      throws FileNotFoundException {
    PrintWriter out = new PrintWriter(filename);
    Iterator<String> itr = scoremap.keySet().iterator();
    ArrayList<String> urls = new ArrayList<String>();
    ArrayList<Float> scores = new ArrayList<Float>();

    while (itr.hasNext()) {
      String key = itr.next();
      if (scores.size() < num) {
        scores.add(scoremap.get(key));
        urls.add(key);
      } else {
        int index = scores.indexOf(Collections.min(scores));
        if (scores.get(index) < scoremap.get(key)) {
          scores.set(index, scoremap.get(key));
          urls.set(index, key);
        }
      }
    }

    while (scores.size() > 0) {
      int index = scores.indexOf(Collections.max(scores));
      out.println(urls.get(index) + "\t" + scores.get(index));
      urls.remove(index);
      scores.remove(index);
    }
    out.close();
  }
Пример #9
0
  // returns the stream of final pig script to be passed to Grunt
  private static BufferedReader runParamPreprocessor(
      BufferedReader origPigScript,
      ArrayList<String> params,
      ArrayList<String> paramFiles,
      String scriptFile,
      boolean createFile)
      throws org.apache.pig.tools.parameters.ParseException, IOException {
    ParameterSubstitutionPreprocessor psp = new ParameterSubstitutionPreprocessor(50);
    String[] type1 = new String[1];
    String[] type2 = new String[1];

    if (createFile) {
      BufferedWriter fw = new BufferedWriter(new FileWriter(scriptFile));
      psp.genSubstitutedFile(
          origPigScript,
          fw,
          params.size() > 0 ? params.toArray(type1) : null,
          paramFiles.size() > 0 ? paramFiles.toArray(type2) : null);
      return new BufferedReader(new FileReader(scriptFile));

    } else {
      StringWriter writer = new StringWriter();
      psp.genSubstitutedFile(
          origPigScript,
          writer,
          params.size() > 0 ? params.toArray(type1) : null,
          paramFiles.size() > 0 ? paramFiles.toArray(type2) : null);
      return new BufferedReader(new StringReader(writer.toString()));
    }
  }
Пример #10
0
 public void execute(ArrayList<String> array) {
   String[] args = new String[array.size()];
   for (int i = 0; i < array.size(); i++) {
     args[i] = array.get(i);
   }
   main(args);
 }
  // read data from text files
  private String[] readFileText(String file_name) {
    ArrayList<String> data_out = new ArrayList<String>();
    String[] output;
    String current_line = null;

    System.out.println("readFileText: About to read file");
    try {
      InputStream file = new FileInputStream(file_name);
      BufferedReader buffer = new BufferedReader(new InputStreamReader(file));

      // read file data line by line & add to temporary storage
      while ((current_line = buffer.readLine()) != null) {
        data_out.add(new String(current_line));
      }
    } catch (Exception e) {
      System.out.println("readFileText: Failed to read file " + file_name);
    }

    System.out.println("readFileText: About to convert to array");
    output = new String[data_out.size()];
    data_out.toArray(output); // convert collected data to array

    System.out.println("readFileText: data_out size = " + data_out.size());

    for (String line : output) {
      System.out.println("readFileText: Returning = '" + line + "'");
    }

    return output;
  }
Пример #12
0
 public void drawOrbits(ArrayList alObjectsArchive) {
   //  println("SIZE:" + alObjectsArchive.size());
   //  ArrayList alObjectsArchive = timeline.getObjectStateArchive();
   ArrayList alPrevPos = new ArrayList();
   ArrayList alColors = new ArrayList();
   alColors.add(color(255, 0, 0));
   alColors.add(color(255, 255, 0));
   alColors.add(color(255, 0, 255));
   //  for (int i = timeline.getTimeIdx(); i >= 0 && i > (timeline.getTimeIdx() - 1 - 100); i--)
   for (int i = 0; i < alObjectsArchive.size(); i++) {
     ArrayList objects = (ArrayList) alObjectsArchive.get(i);
     for (int j = 0; j < objects.size(); j++) {
       CelestialObject obj = (CelestialObject) objects.get(j);
       //      CelestialObject obj = (CelestialObject)objects.get(1);
       PVector pos = obj.getPosition();
       //      stroke(0, 0, 255);
       stroke((Integer) alColors.get(j));
       if (alPrevPos.size() == objects.size()) {
         PVector prevPos = (PVector) alPrevPos.get(j);
         line(prevPos.x, prevPos.y, pos.x, pos.y);
         alPrevPos.set(j, pos);
       } else alPrevPos.add(pos);
     }
   }
 }
Пример #13
0
  public static void doIt() throws Exception {
    Scanner scanner = new Scanner(System.in);
    Integer currentBalance = scanner.nextInt();
    int removeLast, removePenultimate;
    StringBuffer buf = new StringBuffer();

    ArrayList<Character> chars = new ArrayList<Character>();
    for (Character c : currentBalance.toString().toCharArray()) chars.add(c);

    ArrayList<Character> c1 = (ArrayList<Character>) chars.clone();
    c1.remove(c1.size() - 1);

    for (Character cc : c1) buf.append(cc);

    removeLast = new Integer(buf.toString());
    buf = new StringBuffer();

    ArrayList<Character> c2 = (ArrayList<Character>) chars.clone();
    c2.remove(c2.size() - 2);

    for (Character cc : c2) buf.append(cc);
    removePenultimate = new Integer(buf.toString());

    System.out.println(Math.max(currentBalance, Math.max(removeLast, removePenultimate)));
  }
Пример #14
0
 private static ArrayList<Long> findPrimes(long n) {
   ArrayList<Long> ret = new ArrayList<Long>();
   if (n == 1) {
     return ret;
   }
   while (n % 2 == 0) {
     ret.add(2l);
     n = n / 2;
   }
   if (ret.size() > 1) {
     return ret;
   }
   for (long i = 3; i * i <= n; i += 2) {
     if (n % i == 0) {
       ret.add(i);
       n = n / i;
     }
     if (ret.size() > 1) {
       return ret;
     }
   }
   if (ret.size() > 1) {
     return ret;
   }
   if (n > 2) {
     ret.add(n);
   }
   return ret;
 }
  /**
   * Returns the index of the piece that could be downloaded by the peer in parameter
   *
   * @param id The id of the peer that wants to download
   * @return int The index of the piece to request
   */
  private synchronized int choosePiece2Download(String id) {
    synchronized (this.isComplete) {
      int index = 0;
      ArrayList<Integer> possible = new ArrayList<Integer>(this.nbPieces);
      for (int i = 0; i < this.nbPieces; i++) {
        if ((!this.isPieceRequested(i) || (this.isComplete.cardinality() > this.nbPieces - 3))
            &&
            // (this.isRequested.cardinality() == this.nbPieces)) &&
            (!this.isPieceComplete(i))
            && this.peerAvailabilies.get(id) != null) {

          if (this.peerAvailabilies.get(id).get(i)) possible.add(i);
        }
      }
      // System.out.println(this.isRequested.cardinality()+" "+this.isComplete.cardinality()+" " +
      // possible.size());
      if (possible.size() > 0) {
        Random r = new Random(System.currentTimeMillis());
        index = possible.get(r.nextInt(possible.size()));
        this.setRequested(index, true);
        return (index);
      }
      return -1;
    }
  }
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();

    sb.append("GeneratedElecInputs with " + this.getNumberSingleInputs() + " inputs in total\n");

    Enumeration keys = this.myElecInputs.keys();

    while (keys.hasMoreElements()) {
      String input = (String) keys.nextElement();
      ArrayList<SingleElectricalInput> singleInputList = myElecInputs.get(input);
      StimulationSettings ss = project.elecInputInfo.getStim(input);
      sb.append(
          input + " (" + ss.toLongString() + ") has " + singleInputList.size() + " entries.\n");
      for (int i = 0; (i < singleInputList.size() && i < 9); i++) {
        SingleElectricalInput sei = singleInputList.get(i);
        sb.append("   Input " + i + ": " + sei.toString());
        if (sei.getInstanceProps() != null)
          sb.append(" (" + sei.getInstanceProps().details(false) + ")");

        sb.append("\n");
      }
    }
    return sb.toString();
  }
  /* Scan the files in the new directory, and store them in the filelist.
   * Update the UI by refreshing the list adapter.
   */
  private void loadDirectory(String newdirectory) {
    if (newdirectory.equals("../")) {
      try {
        directory = new File(directory).getParent();
      } catch (Exception e) {
      }
    } else {
      directory = newdirectory;
    }
    SharedPreferences.Editor editor = getPreferences(0).edit();
    editor.putString("lastBrowsedDirectory", directory);
    editor.commit();
    directoryView.setText(directory);

    filelist = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedDirs = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedFiles = new ArrayList<FileUri>();
    if (!newdirectory.equals(rootdir)) {
      String parentDirectory = new File(directory).getParent() + "/";
      Uri uri = Uri.parse("file://" + parentDirectory);
      sortedDirs.add(new FileUri(uri, parentDirectory));
    }
    try {
      File dir = new File(directory);
      File[] files = dir.listFiles();
      if (files != null) {
        for (File file : files) {
          if (file == null) {
            continue;
          }
          String filename = file.getName();
          if (file.isDirectory()) {
            Uri uri = Uri.parse("file://" + file.getAbsolutePath() + "/");
            FileUri fileuri = new FileUri(uri, uri.getPath());
            sortedDirs.add(fileuri);
          } else if (filename.endsWith(".mid")
              || filename.endsWith(".MID")
              || filename.endsWith(".midi")
              || filename.endsWith(".MIDI")) {

            Uri uri = Uri.parse("file://" + file.getAbsolutePath());
            FileUri fileuri = new FileUri(uri, uri.getLastPathSegment());
            sortedFiles.add(fileuri);
          }
        }
      }
    } catch (Exception e) {
    }

    if (sortedDirs.size() > 0) {
      Collections.sort(sortedDirs, sortedDirs.get(0));
    }
    if (sortedFiles.size() > 0) {
      Collections.sort(sortedFiles, sortedFiles.get(0));
    }
    filelist.addAll(sortedDirs);
    filelist.addAll(sortedFiles);
    adapter = new IconArrayAdapter<FileUri>(this, android.R.layout.simple_list_item_1, filelist);
    this.setListAdapter(adapter);
  }
Пример #18
0
  /**
   * Return top K authorities (result from SALSA), but do not include users in the removeList
   *
   * @param K
   * @param removeList
   * @return
   */
  public ArrayList<SalsaVertex> topAuthorities(int K, HashSet<Integer> removeList) {
    // TODO: faster top-K implementation
    ArrayList<SalsaVertex> all = new ArrayList<SalsaVertex>(authorities.size());
    all.addAll(authorities.values());
    Collections.sort(
        all,
        new Comparator<SalsaVertex>() {
          @Override
          public int compare(SalsaVertex salsaVertex, SalsaVertex salsaVertex1) {
            if (salsaVertex.value < salsaVertex1.value) return 1;
            else return (salsaVertex.value > salsaVertex1.value ? -1 : 0);
          }
        });

    ArrayList<SalsaVertex> result = new ArrayList<SalsaVertex>(K);
    int i = 0;
    while (result.size() < K) {
      if (i < all.size()) {
        SalsaVertex x = all.get(i);
        if (!removeList.contains(x.id)) result.add(x);
      } else {
        break;
      }
      i++;
    }
    return result;
  }
Пример #19
0
  public int[] solve(String[] edgeStrings) {

    ArrayList<Integer> oddPoints = new ArrayList<Integer>();

    int min = Integer.MAX_VALUE;
    for (String s : edgeStrings) {
      StringTokenizer st = new StringTokenizer(s);
      int from = Integer.parseInt(st.nextToken());
      int to = Integer.parseInt(st.nextToken());
      edges.add(new Edge(from, to));

      min = Math.min(min, from);
      min = Math.min(min, to);
      oddPoint(oddPoints, from);
      oddPoint(oddPoints, to);
    }

    assert (oddPoints.size() < 3);

    if (oddPoints.size() > 0) {
      dfs(min(oddPoints));
      return toArray(circuit);
    } else {
      dfs(min);
      return toArray(circuit);
    }
  }
Пример #20
0
 public static void main(String[] args) throws IOException {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   String[] temp = in.readLine().split(" ");
   int n = Integer.parseInt(temp[0]);
   int s = Integer.parseInt(temp[1]);
   HashMap<Integer, Integer> buy = new HashMap<>();
   HashMap<Integer, Integer> sell = new HashMap<>();
   for (int i = 1; i <= n; i++) {
     temp = in.readLine().split(" ");
     int p = Integer.parseInt(temp[1]);
     int q = Integer.parseInt(temp[2]);
     if (temp[0].charAt(0) == 'B') {
       if (buy.containsKey(p)) buy.put(p, buy.get(p) + q);
       else buy.put(p, q);
     } else {
       if (sell.containsKey(p)) sell.put(p, sell.get(p) + q);
       else sell.put(p, q);
     }
   }
   ArrayList<Integer> buyArr = new ArrayList<>();
   ArrayList<Integer> sellArr = new ArrayList<>();
   for (Integer i : buy.keySet()) buyArr.add(i);
   for (Integer i : sell.keySet()) sellArr.add(i);
   Collections.sort(buyArr, Comparator.reverseOrder());
   Collections.sort(sellArr);
   for (int i = Math.min(s, sellArr.size()) - 1; i >= 0; i--)
     System.out.println("S " + sellArr.get(i) + " " + sell.get(sellArr.get(i)));
   for (int i = 0; i < s && i < buyArr.size(); i++)
     System.out.println("B " + buyArr.get(i) + " " + buy.get(buyArr.get(i)));
 }
  public static ArrayList<ArrayList<TaggedWord>> getPhrasesNaive(
      String sentence, LexicalizedParser lp, AbstractSequenceClassifier<CoreLabel> classifier) {
    ArrayList<ArrayList<TaggedWord>> newList = new ArrayList<ArrayList<TaggedWord>>();
    ArrayList<TaggedWord> taggedWords = StanfordNER.parse(sentence, lp, classifier);
    HashMap<String, String> phraseBoundaries = new HashMap<String, String>();
    phraseBoundaries.put(",", ",");
    phraseBoundaries.put("\"", "\"");
    phraseBoundaries.put("''", "''");
    phraseBoundaries.put("``", "``");
    phraseBoundaries.put("--", "--");
    // List<Tree> leaves = parse.getLeaves();
    ArrayList<TaggedWord> temp = new ArrayList<TaggedWord>();
    int index = 0;
    while (index < taggedWords.size()) {
      if ((phraseBoundaries.containsKey(taggedWords.get(index).word()))) {
        if (temp.size() > 0) {
          // System.out.println(temp);
          ArrayList<TaggedWord> tempCopy = new ArrayList<TaggedWord>(temp);
          newList.add(Preprocess(tempCopy));
        }
        temp.clear();
      } else {
        // System.out.println(taggedWords.get(index).toString());
        temp.add(taggedWords.get(index));
      }
      index += 1;
    }
    if (temp.size() > 0) {
      ArrayList<TaggedWord> tempCopy = new ArrayList<TaggedWord>(temp);
      newList.add(Preprocess(tempCopy));
    }

    // System.out.println(newList);
    return newList;
  }
Пример #22
0
  /** Normalizes the copy number signal, allele A signal and allele B signal globally. */
  public void globalNormalization(ArrayList<Integer> index, ArrayList<Integer> indexSNP) {

    double globalMean = 0;
    double globalMeanA = 0;
    double globalMeanB = 0;
    double[] copyNumberOneChip = new double[index.size()];
    double[] alleleAOneChip = new double[indexSNP.size()];
    double[] alleleBOneChip = new double[indexSNP.size()];

    for (int i = 0; i < index.size(); i++) {
      copyNumberOneChip[i] = copyNumber[index.get(i)];
    }

    for (int i = 0; i < indexSNP.size(); i++) {
      alleleAOneChip[i] = alleleA[indexSNP.get(i)];
      alleleBOneChip[i] = alleleB[indexSNP.get(i)];
    }

    globalMean = robustMu(copyNumberOneChip);
    globalMeanA = robustMu(alleleAOneChip);
    globalMeanB = robustMu(alleleBOneChip);

    for (int i = 0; i < index.size(); i++) {
      copyNumber[index.get(i)] = copyNumber[index.get(i)] / globalMean * 2;
      alleleA[index.get(i)] = alleleA[index.get(i)] / globalMeanA;
      alleleB[index.get(i)] = alleleB[index.get(i)] / globalMeanB;
    }
  }
Пример #23
0
  public void calcSigma() {

    Double summation = new Double(0);

    // Take the sum of gdplist and divide by n

    for (Double x1 : gdplist) summation += x1;

    average = summation / gdplist.size();

    // Now we have the mean

    // Take the difference of the GDP by year and the mean
    // Sum all of the squares of the differences
    // Take the square root of the sum == std deviation

    summation = new Double(0);

    for (Double x1 : gdplist) { // look at each year GDP
      Double x2 = x1 - average; // subtract the average from that year GDP

      summation += (x2 * x2); // square the result and add it to a total sum
    }

    summation = summation / gdplist.size();

    stdev = Math.sqrt(summation);
  }
Пример #24
0
  /**
   * Estimates the mean of array <code>y</code>. <code>robustMu</code> uses a Gaussian model to
   * remove outliers iteratively.
   *
   * @param y an array
   * @return the estimated mean of <code>y</code>
   */
  private double robustMu(double[] y) {

    ArrayList<Double> x = new ArrayList<Double>(y.length);

    for (int i = 0; i < y.length; i++) {
      x.add(y[i]);
    }

    double sigma = 0;
    NormalDist gaussian = new NormalDist();
    double cutoff = 0;
    double cutoff1 = 0;
    double cutoff2 = 0;

    int xSize = x.size();

    sigma = std(x);
    double areaRemoved = 0.5 / xSize;

    cutoff = abs(gaussian.inverseF(areaRemoved));

    cutoff1 = -cutoff * sigma + mean(x);
    cutoff2 = cutoff * sigma + mean(x);

    while (true) {

      Iterator<Double> iter = x.iterator();

      int numRemoved = 0;
      while (iter.hasNext()) {

        double cn = iter.next();
        if (cn < cutoff1 || cn > cutoff2) {
          numRemoved++;
          iter.remove();
        }
      }

      if (numRemoved == 0) {
        break;
      }

      sigma = std(x);
      sigma =
          sigma
              / sqrt(
                  (1 - 2 * areaRemoved - 2 * cutoff * exp(-pow(cutoff, 2) / 2) / sqrt(2 * PI))
                      / (1 - 2 * areaRemoved));

      xSize = x.size();
      areaRemoved = 0.5 / xSize;

      cutoff = abs(gaussian.inverseF(areaRemoved));

      cutoff1 = -cutoff * sigma + mean(x);
      cutoff2 = cutoff * sigma + mean(x);
    }

    return mean(x);
  }
Пример #25
0
  /**
   * Parse a method declaration. The declaration should be in the following format:
   *
   * <p>fully-qualified-method-name (args)
   *
   * <p>where the arguments are comma separated and all arguments other than primitives should have
   * fully qualified names. Arrays are indicating by trailing brackets. For example:
   *
   * <p>int int[] int[][] java.lang.String java.util.Date[]
   *
   * <p>The arguments are translated into BCEL types and a MethodDef is returned.
   */
  private MethodDef parse_method(StrTok st) {

    // Get the method name
    String method_name = st.need_word();

    // Get the opening paren
    st.need("(");

    // Read the arguments
    ArrayList<String> args = new ArrayList<String>();
    String tok = st.nextToken();
    if (tok != ")") {
      st.pushBack();
      do {
        tok = st.need_word();
        args.add(tok);
      } while (st.nextToken() == ",");
      st.pushBack();
      st.need(")");
    }

    // Convert the arguments to Type
    Type[] targs = new Type[args.size()];
    for (int ii = 0; ii < args.size(); ii++) {
      targs[ii] = BCELUtil.classname_to_type(args.get(ii));
    }

    return new MethodDef(method_name, targs);
  }
Пример #26
0
 public boolean convertMapFormat(String s, IProgressUpdate iprogressupdate) {
   iprogressupdate.setLoadingProgress(0);
   ArrayList arraylist = new ArrayList();
   ArrayList arraylist1 = new ArrayList();
   ArrayList arraylist2 = new ArrayList();
   ArrayList arraylist3 = new ArrayList();
   File file = new File(field_22180_a, s);
   File file1 = new File(file, "DIM-1");
   System.out.println("Scanning folders...");
   func_22183_a(file, arraylist, arraylist1);
   if (file1.exists()) {
     func_22183_a(file1, arraylist2, arraylist3);
   }
   int i = arraylist.size() + arraylist2.size() + arraylist1.size() + arraylist3.size();
   System.out.println(
       (new StringBuilder()).append("Total conversion count is ").append(i).toString());
   func_22181_a(file, arraylist, 0, i, iprogressupdate);
   func_22181_a(file1, arraylist2, arraylist.size(), i, iprogressupdate);
   WorldInfo worldinfo = func_22173_b(s);
   worldinfo.setSaveVersion(19132);
   ISaveHandler isavehandler = getSaveLoader(s, false);
   isavehandler.saveWorldInfo(worldinfo);
   func_22182_a(arraylist1, arraylist.size() + arraylist2.size(), i, iprogressupdate);
   if (file1.exists()) {
     func_22182_a(
         arraylist3, arraylist.size() + arraylist2.size() + arraylist1.size(), i, iprogressupdate);
   }
   return true;
 }
Пример #27
0
     public void sortFrontbyR(){
    
        sortByR = new ArrayList();
    
        for (int i = 0 ; i < Fronts.size() ; i++){
            
       
            ArrayList tempfront = (ArrayList) Fronts.get(i);
			
			for (int j = 0 ; j < tempfront.size() ; j++){
				
				for (int a = 0 ; a <  tempfront.size() ; a++){
			
					if (a > j){
						
						NSGAII.Solutions.QRTPSolution.OneSolution first = (NSGAII.Solutions.QRTPSolution.OneSolution) tempfront.get(j);
						double x  = first.getRecall();
						NSGAII.Solutions.QRTPSolution.OneSolution second = (NSGAII.Solutions.QRTPSolution.OneSolution) tempfront.get(a);
						double y  = second.getRecall();
						
						if (y > x){
						
							tempfront.set(j, second);
							tempfront.set(a, first);
						
						}else{}
					}        
				}      
			}   
			
			sortByR.add(tempfront);
		}
    

    }
Пример #28
0
  /** Generates array of XContour from local contours and modules. Used for TTF building. */
  private XContour[] toContours() {
    XContour[] retval;
    ArrayList<XContour> list = new ArrayList<>();
    XContour[] contours = m_glyph.getBody().getContour();
    for (int i = 0; i < contours.length; i++) {
      EContour contour = (EContour) contours[i];
      list.add(contour.toQuadratic());
    } // for i

    XModule[] modules = m_glyph.getBody().getModule();
    for (int i = 0; i < modules.length; i++) {
      EModuleInvoke module = (EModuleInvoke) modules[i];

      // push and pop happens inside toContour
      list.add(module.toContour(new AffineTransform()));
    } // for i

    if (list.size() == 0) return null;

    retval = new XContour[list.size()];
    for (int i = 0; i < list.size(); i++) {
      retval[i] = list.get(i);
    } // for i

    return retval;
  }
  protected void finishedWith(
      String sourceLocator,
      CompilationResult result,
      char[] mainTypeName,
      ArrayList definedTypeNames,
      ArrayList duplicateTypeNames) {
    char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(sourceLocator);
    if (previousTypeNames == null) previousTypeNames = new char[][] {mainTypeName};
    IPath packagePath = null;
    next:
    for (int i = 0, l = previousTypeNames.length; i < l; i++) {
      char[] previous = previousTypeNames[i];
      for (int j = 0, m = definedTypeNames.size(); j < m; j++)
        if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j))) continue next;

      SourceFile sourceFile = (SourceFile) result.getCompilationUnit();
      if (packagePath == null) {
        int count = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
        packagePath =
            sourceFile.resource.getFullPath().removeFirstSegments(count).removeLastSegments(1);
      }
      if (this.secondaryTypesToRemove == null)
        this.secondaryTypesToRemove = new SimpleLookupTable();
      ArrayList types =
          (ArrayList) this.secondaryTypesToRemove.get(sourceFile.sourceLocation.binaryFolder);
      if (types == null) types = new ArrayList(definedTypeNames.size());
      types.add(packagePath.append(new String(previous)));
      this.secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, types);
    }
    super.finishedWith(sourceLocator, result, mainTypeName, definedTypeNames, duplicateTypeNames);
  }
  public void draw() {
    background(255);

    // Turn off highlighting for all obstalces
    for (int i = 0; i < obstacles.size(); i++) {
      Obstacle o = (Obstacle) obstacles.get(i);
      o.highlight(false);
    }

    // Act on all boids
    for (int i = 0; i < boids.size(); i++) {
      Boid b = (Boid) boids.get(i);
      b.avoid(obstacles);
      b.run();
    }

    // Display the obstacles
    for (int i = 0; i < obstacles.size(); i++) {
      Obstacle o = (Obstacle) obstacles.get(i);
      o.display();
    }

    // Instructions
    textFont(f);
    fill(0);
    text(
        "Hit space bar to toggle debugging lines.\nClick the mouse to generate a new boids.",
        10,
        height - 30);
  }