/**
  * This is for debug only: print out training matrices in a CSV type format so that the matrices
  * can be examined in a spreadsheet program for debugging purposes.
  */
 private void WriteCSVfile(
     List<String> rowNames, List<String> colNames, float[][] buf, String fileName) {
   p("tagList.size()=" + tagList.size());
   try {
     FileWriter fw = new FileWriter(fileName + ".txt");
     PrintWriter bw = new PrintWriter(new BufferedWriter(fw));
     // write the first title row:
     StringBuffer sb = new StringBuffer(500);
     for (int i = 0, size = colNames.size(); i < size; i++) {
       sb.append("," + colNames.get(i));
     }
     bw.println(sb.toString());
     // loop on remaining rows:
     for (int i = 0, size = buf.length; i < size; i++) {
       sb.delete(0, sb.length());
       sb.append(rowNames.get(i));
       for (int j = 0, size2 = buf[i].length; j < size2; j++) {
         sb.append("," + buf[i][j]);
       }
       bw.println(sb.toString());
     }
     bw.close();
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
    @Override
    public void map(LongWritable key, Text value, Context context)
        throws IOException, InterruptedException {
      String line = ((Text) value).toString();

      List<String> tokens = new ArrayList<String>();
      StringTokenizer itr = new StringTokenizer(line);
      int numWords = 0;
      while (itr.hasMoreTokens() && numWords < 100) {
        String w = itr.nextToken().toLowerCase().replaceAll("(^[^a-z]+|[^a-z]+$)", "");
        if (w.length() == 0) continue;
        if (!tokens.contains(w)) {
          tokens.add(w);
        }
        numWords++;
      }

      for (int i = 0; i < tokens.size(); i++) {
        MAP.clear();
        for (int j = 0; j < tokens.size(); j++) {
          if (i == j) continue;

          MAP.increment(tokens.get(j));
        }
        KEY.set(tokens.get(i));
        context.write(KEY, MAP);
      }
    }
 /**
  * For a sequence of words, values of class variable indices[], and class variable possibleTags,
  * evaluate how well tags rate using equation 10.7 in [Manning/Schutze, 1999]
  */
 float score(List<String> words) { // uses global variables
   float s = 1.0f;
   int num = words.size();
   float prob_tag_i_given_tag_i_minus_1 = 1.0f;
   for (int i = 0; i < num; i++) {
     System.out.println("words[" + i + "]=" + words.get(i));
     // int tag_index = indices[i];
     if (i > 0) {
       List<String> v0 = possibleTags.get(i - 1);
       List<String> v1 = possibleTags.get(i);
       int index1 = uniqueTags.indexOf(v0.get(indices[i - 1]));
       int index2 = uniqueTags.indexOf(v1.get(indices[i]));
       System.out.println(
           "index1="
               + index1
               + "[tag: "
               + uniqueTags.get(index1)
               + "], index2="
               + index2
               + "[tag: "
               + uniqueTags.get(index2)
               + "]");
       prob_tag_i_given_tag_i_minus_1 = probabilityTag1ToTag2[index1][index2];
       int index3 = uniqueWords.indexOf("" + words.get(i));
       float p = probabilityWordGivenTag[index3][index2];
       System.out.println("word: " + words.get(i) + ", p=" + p);
       prob_tag_i_given_tag_i_minus_1 *= p;
     }
     s *= prob_tag_i_given_tag_i_minus_1;
   }
   return s;
 }
  private String getVendorNumberFromVendorAlias(
      OleInvoiceRecord oleInvoiceRecord, INVOrder invOrder) throws Exception {
    if (StringUtils.isNotBlank(oleInvoiceRecord.getVendorAlias())) {
      Map vendorAliasMap = new HashMap();
      vendorAliasMap.put(
          org.kuali.ole.sys.OLEConstants.VENDOR_ALIAS_NAME, oleInvoiceRecord.getVendorAlias());
      List<VendorAlias> vendorAliasList =
          (List<VendorAlias>)
              getLookupService()
                  .findCollectionBySearchHelper(VendorAlias.class, vendorAliasMap, true);
      if (vendorAliasList != null && vendorAliasList.size() > 0) {
        return vendorAliasList.get(0).getVendorHeaderGeneratedIdentifier()
            + "-"
            + vendorAliasList.get(0).getVendorDetailAssignedIdentifier();

      } else {
        if (oleInvoiceRecord.getVendorItemIdentifier() == null)
          throw new Exception(
              "The vendor alias in Edifact file doesn't match in database for invoice number:: "
                  + getInvoiceNumber(invOrder)
                  + " and invoice date:: "
                  + getInvoiceDate(invOrder));
      }
    }
    return null;
  }
  public IndTestFisherZPercentIndependent(List<DataSet> dataSets, double alpha) {
    this.dataSets = dataSets;
    this.variables = dataSets.get(0).getVariables();

    data = new ArrayList<TetradMatrix>();

    for (DataSet dataSet : dataSets) {
      dataSet = DataUtils.center(dataSet);
      TetradMatrix _data = dataSet.getDoubleData();
      data.add(_data);
    }

    ncov = new ArrayList<TetradMatrix>();
    for (TetradMatrix d : this.data) ncov.add(d.transpose().times(d).scalarMult(1.0 / d.rows()));

    setAlpha(alpha);
    rows = new int[dataSets.get(0).getNumRows()];
    for (int i = 0; i < getRows().length; i++) getRows()[i] = i;

    variablesMap = new HashMap<Node, Integer>();
    for (int i = 0; i < variables.size(); i++) {
      variablesMap.put(variables.get(i), i);
    }

    this.recursivePartialCorrelation = new ArrayList<RecursivePartialCorrelation>();
    for (TetradMatrix covMatrix : ncov) {
      recursivePartialCorrelation.add(new RecursivePartialCorrelation(getVariables(), covMatrix));
    }
  }
示例#6
0
  /**
   * Finds the index of the best solution in the list according to a comparator
   *
   * @param solutionList
   * @param comparator
   * @return The index of the best solution
   */
  public static <S extends Solution<?>> int findIndexOfBestSolution(
      List<S> solutionList, Comparator<S> comparator) {
    if (solutionList == null) {
      throw new JMetalException("The solution list is null");
    } else if (solutionList.isEmpty()) {
      throw new JMetalException("The solution list is empty");
    } else if (comparator == null) {
      throw new JMetalException("The comparator is null");
    }

    int index = 0;
    S bestKnown = solutionList.get(0);
    S candidateSolution;

    int flag;
    for (int i = 1; i < solutionList.size(); i++) {
      candidateSolution = solutionList.get(i);
      flag = comparator.compare(bestKnown, candidateSolution);
      if (flag == 1) {
        index = i;
        bestKnown = candidateSolution;
      }
    }

    return index;
  }
  public List<StockInfo> findStockInfoBtw(StockInfo stock, int previousDays, int followingDays) {
    LinkedList<StockInfo> selected = new LinkedList<>();
    int beginIndex = 0;
    List<StockInfo> stocks = getStocks(stock.getTicker());
    for (int i = 0; i < stocks.size(); i++) {
      if (stocks.get(i).getTradeDate().equals(stock.getTradeDate())) {
        beginIndex = i;
        selected.add(stocks.get(beginIndex));
        break;
      }
    }

    for (int i = 1; i <= previousDays; i++) {
      StockInfo addingStock = null;
      try {
        addingStock = stocks.get(beginIndex + i);
        selected.addFirst(addingStock);
      } catch (Exception e) {

      }
    }
    for (int i = 1; i <= followingDays; i++) {
      StockInfo addingStock = null;
      try {
        addingStock = stocks.get(beginIndex - i);
      } catch (Exception e) {

      }
      selected.addLast(addingStock);
    }
    return selected;
  }
示例#8
0
  public Result updateVitalsPost(int id) {

    CurrentUser currentUser = sessionService.getCurrentUserSession();

    ServiceResponse<IPatientEncounter> currentEncounterByPatientId =
        searchService.findCurrentEncounterByPatientId(id);

    UpdateVitalsModel updateVitalsModel = updateVitalsModelForm.bindFromRequest().get();

    List<? extends IPatientEncounterVital> patientEncounterVitals =
        medicalHelper.populatePatientVitals(
            updateVitalsModel,
            currentUser.getId(),
            currentEncounterByPatientId.getResponseObject().getId());
    ServiceResponse<IPatientEncounterVital> patientEncounterVitalServiceResponse;
    for (int i = 0; i < patientEncounterVitals.size(); i++) {
      if (patientEncounterVitals.get(i).getVitalValue() > 0) {
        patientEncounterVitalServiceResponse =
            triageService.createPatientEncounterVital(patientEncounterVitals.get(i));
        if (patientEncounterVitalServiceResponse.hasErrors()) {
          return internalServerError();
        }
      }
    }
    return ok("true");
  }
  SparkSubmitCommandBuilder(List<String> args) {
    this.allowsMixedArguments = false;

    boolean isExample = false;
    List<String> submitArgs = args;
    if (args.size() > 0 && args.get(0).equals(PYSPARK_SHELL)) {
      this.allowsMixedArguments = true;
      appResource = PYSPARK_SHELL_RESOURCE;
      submitArgs = args.subList(1, args.size());
    } else if (args.size() > 0 && args.get(0).equals(SPARKR_SHELL)) {
      this.allowsMixedArguments = true;
      appResource = SPARKR_SHELL_RESOURCE;
      submitArgs = args.subList(1, args.size());
    } else if (args.size() > 0 && args.get(0).equals(RUN_EXAMPLE)) {
      isExample = true;
      submitArgs = args.subList(1, args.size());
    }

    this.sparkArgs = new ArrayList<>();
    this.isExample = isExample;

    OptionParser parser = new OptionParser();
    parser.parse(submitArgs);
    this.printInfo = parser.infoRequested;
  }
  /**
   * Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings.
   * Paths are ordered from most to least specific match.
   *
   * @param site The hosted site.
   * @param pathInfo Path to be rewritten.
   * @param queryString
   * @return The rewritten path. May be either:
   *     <ul>
   *       <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code>
   *       <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code>
   *     </ul>
   *
   * @return The rewritten paths.
   * @throws URISyntaxException
   */
  private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString)
      throws URISyntaxException {
    final Map<String, List<String>> map = site.getMappings();
    final IPath originalPath = pathInfo;
    IPath path = originalPath.removeTrailingSeparator();

    List<URI> uris = new ArrayList<URI>();
    String rest = null;
    final int count = path.segmentCount();
    for (int i = 0; i <= count; i++) {
      List<String> base = map.get(path.toString());
      if (base != null) {
        rest = originalPath.removeFirstSegments(count - i).toString();
        for (int j = 0; j < base.size(); j++) {
          URI uri =
              rest.equals("") ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest);
          uris.add(
              new URI(
                  uri.getScheme(),
                  uri.getUserInfo(),
                  uri.getHost(),
                  uri.getPort(),
                  uri.getPath(),
                  queryString,
                  uri.getFragment()));
        }
      }
      path = path.removeLastSegments(1);
    }
    if (uris.size() == 0)
      // No mapping for /
      return null;
    else return uris.toArray(new URI[uris.size()]);
  }
  /**
   * Tests that the system.peers table is not updated after a node has been removed. (See
   * CASSANDRA-6053)
   */
  @Test
  public void testStateChangeOnRemovedNode() throws UnknownHostException {
    StorageService ss = StorageService.instance;
    VersionedValue.VersionedValueFactory valueFactory =
        new VersionedValue.VersionedValueFactory(partitioner);

    // create a ring of 2 nodes
    ArrayList<Token> endpointTokens = new ArrayList<>();
    List<InetAddress> hosts = new ArrayList<>();
    Util.createInitialRing(
        ss, partitioner, endpointTokens, new ArrayList<Token>(), hosts, new ArrayList<UUID>(), 2);

    InetAddress toRemove = hosts.get(1);
    SystemKeyspace.updatePeerInfo(toRemove, "data_center", "dc42");
    SystemKeyspace.updatePeerInfo(toRemove, "rack", "rack42");
    assertEquals("rack42", SystemKeyspace.loadDcRackInfo().get(toRemove).get("rack"));

    // mark the node as removed
    Gossiper.instance.injectApplicationState(
        toRemove,
        ApplicationState.STATUS,
        valueFactory.left(
            Collections.singleton(endpointTokens.get(1)), Gossiper.computeExpireTime()));
    assertTrue(
        Gossiper.instance.isDeadState(Gossiper.instance.getEndpointStateForEndpoint(hosts.get(1))));

    // state changes made after the endpoint has left should be ignored
    ss.onChange(hosts.get(1), ApplicationState.RACK, valueFactory.rack("rack9999"));
    assertEquals("rack42", SystemKeyspace.loadDcRackInfo().get(toRemove).get("rack"));
  }
  @Override
  public Set<Person> getSiblingsAll(Person thisPerson) {
    // return full and half siblings of thisPerson
    // exclude thisPerson from the set

    Set<Person> siblings = new HashSet<Person>();
    List<Person> parents = new ArrayList<Person>();

    em.getTransaction().begin();
    Query q =
        em.createQuery(
            "select b.parents from Birth b, IN(b.person) p WHERE p.id = :personId"
                + " or p.id = :parent2Id");
    q.setParameter("personId", thisPerson.getId());

    parents.addAll((Collection<? extends Person>) q.getResultList());

    if (!parents.isEmpty()) {
      if (parents.size() == 2) {
        siblings = getChildrenAll(parents.get(0), parents.get(1));
      } else if (parents.size() == 1) {
        siblings = getChildren(parents.get(0));
      }
    }
    em.getTransaction().commit();
    siblings.remove(thisPerson);
    return siblings;
  }
示例#13
0
  @Test
  public void testEnums() {
    sql2o
        .createQuery(
            "create table EnumTest(id int identity primary key, enum_val varchar(10), enum_val2 int) ")
        .executeUpdate();

    sql2o
        .createQuery("insert into EnumTest(enum_val, enum_val2) values (:val, :val2)")
        .addParameter("val", TestEnum.HELLO)
        .addParameter("val2", TestEnum.HELLO.ordinal())
        .addToBatch()
        .addParameter("val", TestEnum.WORLD)
        .addParameter("val2", TestEnum.WORLD.ordinal())
        .addToBatch()
        .executeBatch();

    List<EntityWithEnum> list =
        sql2o
            .createQuery("select id, enum_val val, enum_val2 val2 from EnumTest")
            .executeAndFetch(EntityWithEnum.class);

    assertThat(list.get(0).val, is(TestEnum.HELLO));
    assertThat(list.get(0).val2, is(TestEnum.HELLO));
    assertThat(list.get(1).val, is(TestEnum.WORLD));
    assertThat(list.get(1).val2, is(TestEnum.WORLD));

    TestEnum testEnum =
        sql2o.createQuery("select 'HELLO' from (values(0))").executeScalar(TestEnum.class);
    assertThat(testEnum, is(TestEnum.HELLO));

    TestEnum testEnum2 =
        sql2o.createQuery("select NULL from (values(0))").executeScalar(TestEnum.class);
    assertThat(testEnum2, is(nullValue()));
  }
示例#14
0
  private void outputVolumeIndex(
      String tagName,
      String titleName,
      String titleIntroduction,
      List<String> volumeTitleList,
      List<String> snsSysIDList) {
    String outputDirectory = getBaseOutputDirectory();
    String text = "";
    int count = volumeTitleList.size();
    text += "TITLE_NAME = '" + getOutputText(titleName) + "';\n";
    text += "TITLE_INTRODUCTION = '" + getOutputText(titleIntroduction) + "';\n";
    text += "VOLUME_LIST = new Array( ";
    for (int i = 0; i < count; i++) {
      if (i > 0) text += ", ";
      text +=
          "'"
              + getOutputText(volumeTitleList.get(i))
              + "', "
              + "'"
              + getVolumeID(snsSysIDList.get(i))
              + "'";
    }
    text += "\n);\n";

    Common.outputFile(text, outputDirectory, tagName + ".js");
  }
  private Notification.PathTokens getPathTokens(List<ServiceParameter> parameters) {

    Notification.PathTokens pathTokens = new Notification.PathTokens();
    pathTokens.setApplicationRef((SimpleEntityRef) em.getApplicationRef());

    // first parameter is always collection name, start parsing after that
    for (int i = 0; i < parameters.size() - 1; i += 2) {
      String collection = pluralize(parameters.get(i).getName());
      Identifier identifier = null;
      String ql = null;
      ServiceParameter sp = parameters.get(i + 1);

      // if the next param is a query, add a token with the query
      if (sp.isQuery()) {
        ql = sp.getQuery().getQl().get();
        pathTokens.getPathTokens().add(new Notification.PathToken(collection, ql));
      } else {
        // if the next param is "notifications", it's the end let identifier be null
        if (sp.isName() && !sp.getName().equalsIgnoreCase("notifications") || sp.isId()) {
          identifier = sp.getIdentifier();
        }
        pathTokens.getPathTokens().add(new Notification.PathToken(collection, identifier));
      }
    }
    return pathTokens;
  }
示例#16
0
  public void drawOn(Page page) throws Exception {
    if (fill_shape) {
      page.setBrushColor(color[0], color[1], color[2]);
    } else {
      page.setPenColor(color[0], color[1], color[2]);
    }
    page.setPenWidth(width);
    page.setLinePattern(pattern);

    for (int i = 0; i < points.size(); i++) {
      Point point = points.get(i);
      point.x += box_x;
      point.y += box_y;
    }

    if (fill_shape) {
      page.drawPath(points, 'f');
    } else {
      if (close_path) {
        page.drawPath(points, 's');
      } else {
        page.drawPath(points, 'S');
      }
    }

    for (int i = 0; i < points.size(); i++) {
      Point point = points.get(i);
      point.x -= box_x;
      point.y -= box_y;
    }
  }
示例#17
0
  /**
   * This method receives a normalized list of non-dominated solutions and return the inverted one.
   * This operation is needed for minimization problem
   *
   * @param solutionList The front to invert
   * @return The inverted front
   */
  public static <S extends Solution<?>> List<S> selectNRandomDifferentSolutions(
      int numberOfSolutionsToBeReturned, List<S> solutionList) {
    if (null == solutionList) {
      throw new JMetalException("The solution list is null");
    } else if (solutionList.size() == 0) {
      throw new JMetalException("The solution list is empty");
    } else if (solutionList.size() < numberOfSolutionsToBeReturned) {
      throw new JMetalException(
          "The solution list size ("
              + solutionList.size()
              + ") is less than "
              + "the number of requested solutions ("
              + numberOfSolutionsToBeReturned
              + ")");
    }

    JMetalRandom randomGenerator = JMetalRandom.getInstance();
    List<S> resultList = new ArrayList<>(numberOfSolutionsToBeReturned);

    if (solutionList.size() == 1) {
      resultList.add(solutionList.get(0));
    } else {
      Collection<Integer> positions = new HashSet<>(numberOfSolutionsToBeReturned);
      while (positions.size() < numberOfSolutionsToBeReturned) {
        int nextPosition = randomGenerator.nextInt(0, solutionList.size() - 1);
        if (!positions.contains(nextPosition)) {
          positions.add(nextPosition);
          resultList.add(solutionList.get(nextPosition));
        }
      }
    }

    return resultList;
  }
  public List<Interval> merge(List<Interval> intervals) {
    if (intervals.size() <= 1) return intervals;

    // Sort by ascending starting point using an anonymous Comparator
    Collections.sort(
        intervals,
        new Comparator<Interval>() {
          @Override
          public int compare(Interval i1, Interval i2) {
            return Integer.compare(i1.start, i2.start);
          }
        });

    List<Interval> result = new LinkedList<Interval>();
    int start = intervals.get(0).start;
    int end = intervals.get(0).end;

    for (Interval interval : intervals) {
      if (interval.start <= end) // Overlapping intervals, move the end if needed
      end = Math.max(end, interval.end);
      else { // Disjoint intervals, add the previous one and reset bounds
        result.add(new Interval(start, end));
        start = interval.start;
        end = interval.end;
      }
    }

    // Add the last interval
    result.add(new Interval(start, end));
    return result;
  }
示例#19
0
文件: Job.java 项目: eguller/mujobo
 public String getFirstLatLng() {
   if (mapLocationList.size() == 0) {
     return "0,0";
   } else {
     return mapLocationList.get(0).getLatitude() + ", " + mapLocationList.get(0).getLatitude();
   }
 }
示例#20
0
  public void marshal(DataOutputStream dos) {
    super.marshal(dos);
    try {
      minefieldID.marshal(dos);
      requestingEntityID.marshal(dos);
      dos.writeShort((short) minefieldSequenceNumbeer);
      dos.writeByte((byte) requestID);
      dos.writeByte((byte) pduSequenceNumber);
      dos.writeByte((byte) numberOfPdus);
      dos.writeByte((byte) mineLocation.size());
      dos.writeByte((byte) sensorTypes.size());
      dos.writeByte((byte) pad2);
      dos.writeInt((int) dataFilter);
      mineType.marshal(dos);

      for (int idx = 0; idx < sensorTypes.size(); idx++) {
        TwoByteChunk aTwoByteChunk = sensorTypes.get(idx);
        aTwoByteChunk.marshal(dos);
      } // end of list marshalling

      dos.writeByte((byte) pad3);

      for (int idx = 0; idx < mineLocation.size(); idx++) {
        Vector3Float aVector3Float = mineLocation.get(idx);
        aVector3Float.marshal(dos);
      } // end of list marshalling

    } // end try
    catch (Exception e) {
      System.out.println(e);
    }
  } // end of marshal method
  protected List<List<Statement>> buildContext(
      InputContext inputContext, List<Statement> stmts, int targetIndex) {
    VarCartesianProduct varCartesianProduct = new VarCartesianProduct();
    Statement statement = stmts.get(targetIndex);

    for (CtVariableReference var : statement.getInputContext().getVar()) {

      varCartesianProduct.addReplaceVar(var, valueCreator.createNull(var.getType()));

      List<CtVariableReference> candidates = inputContext.allCandidate(var.getType(), true, false);
      if (!candidates.isEmpty()) {
        varCartesianProduct.addReplaceVar(
            var, candidates.get(AmplificationHelper.getRandom().nextInt(candidates.size())));
      }

      Statement cfLocalVar = getLocalVar(var.getType(), inputContext);
      if (cfLocalVar != null) {
        varCartesianProduct.addReplaceVar(var, cfLocalVar);
      }

      CtLocalVariable localVariable =
          createLocalVarFromMethodLiterals(currentMethod, var.getType());
      if (localVariable != null) {
        varCartesianProduct.addReplaceVar(var, localVariable);
      }

      CtLocalVariable randomVar = valueCreator.createRandomLocalVar(var.getType());
      if (randomVar != null) {
        varCartesianProduct.addReplaceVar(var, randomVar);
      }
    }

    return varCartesianProduct.apply(stmts, targetIndex);
  }
示例#22
0
  /**
   * Packs a Pdu into the ByteBuffer.
   *
   * @throws java.nio.BufferOverflowException if buff is too small
   * @throws java.nio.ReadOnlyBufferException if buff is read only
   * @see java.nio.ByteBuffer
   * @param buff The ByteBuffer at the position to begin writing
   * @since ??
   */
  public void marshal(java.nio.ByteBuffer buff) {
    super.marshal(buff);
    minefieldID.marshal(buff);
    requestingEntityID.marshal(buff);
    buff.putShort((short) minefieldSequenceNumbeer);
    buff.put((byte) requestID);
    buff.put((byte) pduSequenceNumber);
    buff.put((byte) numberOfPdus);
    buff.put((byte) mineLocation.size());
    buff.put((byte) sensorTypes.size());
    buff.put((byte) pad2);
    buff.putInt((int) dataFilter);
    mineType.marshal(buff);

    for (int idx = 0; idx < sensorTypes.size(); idx++) {
      TwoByteChunk aTwoByteChunk = (TwoByteChunk) sensorTypes.get(idx);
      aTwoByteChunk.marshal(buff);
    } // end of list marshalling

    buff.put((byte) pad3);

    for (int idx = 0; idx < mineLocation.size(); idx++) {
      Vector3Float aVector3Float = (Vector3Float) mineLocation.get(idx);
      aVector3Float.marshal(buff);
    } // end of list marshalling
  } // end of marshal method
 private void setCurrencyDetails(INVOrder invOrder, OleInvoiceRecord oleInvoiceRecord) {
   if (invOrder.getMessage() != null
       && invOrder.getMessage().getCurrencyDetails() != null
       && invOrder.getMessage().getCurrencyDetails().getCurrencyDetailsSupplierInformation()
           != null) {
     if (!StringUtils.isBlank(
         invOrder
             .getMessage()
             .getCurrencyDetails()
             .getCurrencyDetailsSupplierInformation()
             .getCurrencyType())) {
       Map<String, String> currencyTypeMap = new HashMap<>();
       currencyTypeMap.put(
           OLEConstants.CURR_ALPHA_CD,
           invOrder
               .getMessage()
               .getCurrencyDetails()
               .getCurrencyDetailsSupplierInformation()
               .getCurrencyType());
       List<OleCurrencyType> currencyTypeList =
           (List) getBusinessObjectService().findMatching(OleCurrencyType.class, currencyTypeMap);
       if (currencyTypeList != null && currencyTypeList.size() > 0) {
         oleInvoiceRecord.setCurrencyTypeId(
             currencyTypeList.get(0).getCurrencyTypeId().toString());
         oleInvoiceRecord.setCurrencyType(currencyTypeList.get(0).getCurrencyType());
         if (!oleInvoiceRecord
             .getCurrencyType()
             .equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
           oleInvoiceRecord.setForeignListPrice(oleInvoiceRecord.getListPrice());
         }
       }
     }
   }
 }
示例#24
0
  @Override
  public boolean equalsImpl(Object obj) {
    boolean ivarsEqual = true;

    if (!(obj instanceof MinefieldDataPdu)) return false;

    final MinefieldDataPdu rhs = (MinefieldDataPdu) obj;

    if (!(minefieldID.equals(rhs.minefieldID))) ivarsEqual = false;
    if (!(requestingEntityID.equals(rhs.requestingEntityID))) ivarsEqual = false;
    if (!(minefieldSequenceNumbeer == rhs.minefieldSequenceNumbeer)) ivarsEqual = false;
    if (!(requestID == rhs.requestID)) ivarsEqual = false;
    if (!(pduSequenceNumber == rhs.pduSequenceNumber)) ivarsEqual = false;
    if (!(numberOfPdus == rhs.numberOfPdus)) ivarsEqual = false;
    if (!(numberOfMinesInThisPdu == rhs.numberOfMinesInThisPdu)) ivarsEqual = false;
    if (!(numberOfSensorTypes == rhs.numberOfSensorTypes)) ivarsEqual = false;
    if (!(pad2 == rhs.pad2)) ivarsEqual = false;
    if (!(dataFilter == rhs.dataFilter)) ivarsEqual = false;
    if (!(mineType.equals(rhs.mineType))) ivarsEqual = false;

    for (int idx = 0; idx < sensorTypes.size(); idx++) {
      if (!(sensorTypes.get(idx).equals(rhs.sensorTypes.get(idx)))) ivarsEqual = false;
    }

    if (!(pad3 == rhs.pad3)) ivarsEqual = false;

    for (int idx = 0; idx < mineLocation.size(); idx++) {
      if (!(mineLocation.get(idx).equals(rhs.mineLocation.get(idx)))) ivarsEqual = false;
    }

    return ivarsEqual && super.equalsImpl(rhs);
  }
示例#25
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    String line;
    StringBuilder sb = new StringBuilder();
    while ((line = in.readLine()) != null) {
      int k = Integer.parseInt(line);
      List<Integer> xd = new ArrayList<Integer>();
      List<Integer> yd = new ArrayList<Integer>();

      for (int y = k + 1; y <= 2 * k; ++y) {
        if (k * y % (y - k) == 0) {
          int x = k * y / (y - k);
          xd.add(x);
          yd.add(y);
        }
      }

      sb.append(xd.size() + "\n");
      for (int i = 0; i < xd.size(); ++i)
        sb.append(String.format("1/%d = 1/%d + 1/%d\n", k, xd.get(i), yd.get(i)));
    }

    System.out.print(sb);

    in.close();
    System.exit(0);
  }
示例#26
0
  public int getMarshalledSize() {
    int marshalSize = 0;

    marshalSize = super.getMarshalledSize();
    marshalSize = marshalSize + minefieldID.getMarshalledSize(); // minefieldID
    marshalSize = marshalSize + requestingEntityID.getMarshalledSize(); // requestingEntityID
    marshalSize = marshalSize + 2; // minefieldSequenceNumbeer
    marshalSize = marshalSize + 1; // requestID
    marshalSize = marshalSize + 1; // pduSequenceNumber
    marshalSize = marshalSize + 1; // numberOfPdus
    marshalSize = marshalSize + 1; // numberOfMinesInThisPdu
    marshalSize = marshalSize + 1; // numberOfSensorTypes
    marshalSize = marshalSize + 1; // pad2
    marshalSize = marshalSize + 4; // dataFilter
    marshalSize = marshalSize + mineType.getMarshalledSize(); // mineType
    for (int idx = 0; idx < sensorTypes.size(); idx++) {
      TwoByteChunk listElement = sensorTypes.get(idx);
      marshalSize = marshalSize + listElement.getMarshalledSize();
    }
    marshalSize = marshalSize + 1; // pad3
    for (int idx = 0; idx < mineLocation.size(); idx++) {
      Vector3Float listElement = mineLocation.get(idx);
      marshalSize = marshalSize + listElement.getMarshalledSize();
    }

    return marshalSize;
  }
示例#27
0
  /**
   * This is for book production only: print out training matrices in a Latex type format so that
   * the matrices can be inserted into my manuscript:
   *
   * <p>\begin{table}[htdp] \caption{Runtimes by Method} \centering
   *
   * <p>\begin{tabular}{|l|l|l|} \hline \textbf{Class.method name}&\textbf{Percent of total
   * runtime}&\textbf{Percent in this method}\\ \hline Chess.main&97.7&0.0\\
   * GameSearch.playGame&96.5&0.0\\
   *
   * <p>Chess.calcPieceMoves&1.7&0.8\\ \hline \end{tabular}
   *
   * <p>\label{tab:runtimes_by_method} \end{table}
   */
  private void WriteLatexFile(
      List<String> rowNames, List<String> colNames, float[][] buf, String fileName) {
    p("tagList.size()=" + tagList.size());
    int SKIP = 6;
    try {
      FileWriter fw = new FileWriter(fileName + ".latex");
      PrintWriter bw = new PrintWriter(new BufferedWriter(fw));
      int size = colNames.size() - SKIP;
      bw.print("\\begin{table*}[htdp]\n\\caption{ADD CAPTION}\\centering\\begin{tabular}{|");
      for (int i = 0; i < size + 1; i++) bw.print("l|");
      bw.println("}\n\\hline");
      bw.print(" &");
      for (int i = 0; i < size; i++) {
        bw.print("\\emph{" + colNames.get(i) + "}");
        if (i < (size - 1)) bw.print("&");
      }
      bw.println("\\\\\n\\hline");

      // bw.printf(format, args)
      // loop on remaining rows:
      for (int i = 0, size3 = buf.length - SKIP; i < size3; i++) {
        bw.print(rowNames.get(i) + "&");
        for (int j = 0, size2 = buf[i].length - SKIP; j < size2; j++) {
          bw.printf("%.2f", buf[i][j]);
          if (j < (size2 - 1)) bw.print("&");
        }
        bw.println("\\\\");
      }
      bw.println("\\hline\n\\end{tabular}\n\\label{tab:CHANGE_THIS_LABEL}\n\\end{table*}");
      bw.close();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
示例#28
0
 private void updlayout() {
   synchronized (ui.sess.glob.paginae) {
     List<Pagina> cur = new ArrayList<Pagina>();
     loading = !cons(this.cur, cur);
     Collections.sort(cur, sorter);
     int i = curoff;
     hotmap.clear();
     for (int y = 0; y < gsz.y; y++) {
       for (int x = 0; x < gsz.x; x++) {
         Pagina btn = null;
         if ((this.cur != null) && (x == gsz.x - 1) && (y == gsz.y - 1)) {
           btn = bk;
         } else if ((cur.size() > ((gsz.x * gsz.y) - 1)) && (x == gsz.x - 2) && (y == gsz.y - 1)) {
           btn = next;
         } else if (i < cur.size()) {
           Resource.AButton ad = cur.get(i).act();
           if (ad.hk != 0) hotmap.put(Character.toUpperCase(ad.hk), cur.get(i));
           btn = cur.get(i++);
         }
         layout[x][y] = btn;
       }
     }
     pagseq = ui.sess.glob.pagseq;
   }
 }
示例#29
0
 /** Throw away test method. */
 public void test_model() {
   List<String> words = new ArrayList<String>();
   words.add(".");
   words.add("the");
   words.add("dog");
   words.add("chased");
   words.add("the");
   words.add("cat");
   words.add(".");
   words.add("mary");
   words.add("went");
   words.add("to");
   words.add("the");
   words.add("river");
   words.add(".");
   words.add("john");
   words.add("saw");
   words.add("mary");
   words.add("bank");
   words.add("the");
   words.add("airplane");
   words.add(".");
   List<String> tags = exponential_tagging_algorithm(words);
   p("");
   for (int i = 0; i < words.size() - 1; i++) {
     p("" + words.get(i) + "\t: " + tags.get(i));
   }
 }
示例#30
0
  @Test
  public void postComments() {
    // Create a new user and save it
    User bob = new User("*****@*****.**", "secret", "Bob").save();

    // Create a new post
    Post bobPost = new Post(bob, "My first post", "Hello world").save();

    // Post a first comment
    new Comment(bobPost, "Jeff", "Nice Post").save();
    new Comment(bobPost, "Tom", "I knew that !").save();

    // Retrieve all comments
    List<Comment> bobPostComments = Comment.find("byPost", bobPost).fetch();

    // Tests
    assertEquals(2, bobPostComments.size());

    Comment firstComment = bobPostComments.get(0);
    assertNotNull(firstComment);
    assertEquals("Jeff", firstComment.author);
    assertEquals("Nice Post", firstComment.content);
    assertNotNull(firstComment.postedAt);

    Comment secondComment = bobPostComments.get(1);
    assertNotNull(secondComment);
    assertEquals("Tom", secondComment.author);
    assertEquals("I knew that !", secondComment.content);
    assertNotNull(secondComment.postedAt);
  }