Example #1
0
 public CoverVertex(L vertex, BipartiteGraph<L, R> graph) {
   this.vertex = vertex;
   Set<R> adjR = graph.getAdjacentSetL(vertex);
   adjRLabels = new HashSet<String>(adjR.size());
   for (R adj : adjR) adjRLabels.add(adj.getLabel());
   origAdjCount = getAdjacentCount();
 }
Example #2
0
  /**
   * Execute this test. Takes the model sources, parses, type checks them then takes the AST and
   * applies whatever analysis is implemented in {@link #processModel(List)}. Afterwards, results
   * are compared with {@link #compareResults(Object, Object)}. <br>
   * <br>
   * If the test is running in update mode, testUpdate(Object) is executed instead of the
   * comparison.
   *
   * @param exSource holding the example data. Provided by {@link #testData()}
   * @throws FileNotFoundException
   * @throws IOException
   * @throws ParserException
   * @throws LexException
   */
  @Test
  @Parameters(method = "testData")
  public void testCase(ExampleSourceData exSource)
      throws FileNotFoundException, IOException, ParserException, LexException {

    ExampleAstData exData = ExamplesUtility.parseTcExample(exSource);

    this.testName = exData.getExampleName();
    this.model = exData.getModel();
    this.resultPath = RESULTS_EXAMPLES + exData.getExampleName() + PathsProvider.RESULT_EXTENSION;
    this.updateResult = updateCheck();

    R actual = processModel(model);
    if (updateResult) {
      testUpdate(actual);
    } else {
      R expected = null;
      try {
        expected = deSerializeResult(resultPath);
      } catch (FileNotFoundException e) {
        Assert.fail(
            "Test "
                + testName
                + " failed. No result file found. Use \"-D"
                + getUpdatePropertyString()
                + "."
                + testName
                + "\" to create an initial one."
                + "\n The test result was: "
                + actual.toString());
      }
      this.compareResults(actual, expected);
    }
  }
Example #3
0
  /**
   * Run consistency checks against the object database.
   *
   * <p>This method completes silently if the checks pass. A temporary revision pool is constructed
   * during the checking.
   *
   * @param tips the tips to start checking from; if not supplied the refs of the repository are
   *     used instead.
   * @throws MissingObjectException
   * @throws IncorrectObjectTypeException
   * @throws IOException
   */
  public void fsck(RevObject... tips)
      throws MissingObjectException, IncorrectObjectTypeException, IOException {
    ObjectWalk ow = new ObjectWalk(db);
    if (tips.length != 0) {
      for (RevObject o : tips) ow.markStart(ow.parseAny(o));
    } else {
      for (Ref r : db.getAllRefs().values()) ow.markStart(ow.parseAny(r.getObjectId()));
    }

    ObjectChecker oc = new ObjectChecker();
    for (; ; ) {
      final RevCommit o = ow.next();
      if (o == null) break;

      final byte[] bin = db.open(o, o.getType()).getCachedBytes();
      oc.checkCommit(bin);
      assertHash(o, bin);
    }

    for (; ; ) {
      final RevObject o = ow.nextObject();
      if (o == null) break;

      final byte[] bin = db.open(o, o.getType()).getCachedBytes();
      oc.check(o.getType(), bin);
      assertHash(o, bin);
    }
  }
  public <R> R check(Call instance) {
    R r1 = null;
    R r2 = null;
    for (int i = 0; i < 50; i++) {
      r1 = (R) instance.method(map1);
      r2 = (R) instance.method(map2);

      if (r1 != null && r1.equals(r2)) return r1;

      if (i > 30) {
        try {
          Thread.sleep(i);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      } else Thread.yield();
    }

    Assert.assertEquals(map1, map2);
    System.out.print(map1);
    System.out.print(map2);

    if (r1 != null) Assert.assertEquals(r1.toString(), r2.toString());

    return (R) r1;
  }
Example #5
0
    // sorta called by HU_Erase and just better darn get things straight
    public void eraseTextLine() {
      int lh;

      // Only erases when NOT in automap and the screen is reduced,
      // and the text must either need updating or refreshing
      // (because of a recent change back from the automap)

      if (!DM.automapactive && (R.view.windowx != 0) && (this.needsupdate > 0)) {
        lh = this.f[0].height + 1;

        for (int y = this.y, yoffset = y * SCREENWIDTH;
            y < this.y + lh;
            y++, yoffset += SCREENWIDTH) {
          // Stuff is probably in am_map??
          if (y < R.view.windowy || y >= R.view.windowy + R.view.height)
            R.VideoErase(yoffset, SCREENWIDTH); // erase entire
          // line
          else {
            R.VideoErase(yoffset, R.view.windowx); // erase left
            // border
            R.VideoErase(yoffset + R.view.windowx + R.view.width, R.view.windowx);
            // erase right border
          }
        }
      }

      lastautomapactive = DM.automapactive;
      if (this.needsupdate != 0) this.needsupdate--;
    }
  @Override
  public RQ factor(DenseMatrix A) {

    if (Q.numRows() != A.numRows())
      throw new IllegalArgumentException("Q.numRows() != A.numRows()");
    else if (Q.numColumns() != A.numColumns())
      throw new IllegalArgumentException("Q.numColumns() != A.numColumns()");
    else if (R == null) throw new IllegalArgumentException("R == null");

    /*
     * Calculate factorisation, and extract the triangular factor
     */
    intW info = new intW(0);
    LAPACK.getInstance().dgerqf(m, n, A.getData(), Matrices.ld(m), tau, work, work.length, info);

    if (info.val < 0) throw new IllegalArgumentException();

    R.zero();
    for (MatrixEntry e : A)
      if (e.column() >= (n - m) + e.row()) R.set(e.row(), e.column() - (n - m), e.get());

    /*
     * Generate the orthogonal matrix
     */
    info.val = 0;
    LAPACK
        .getInstance()
        .dorgrq(m, n, k, A.getData(), Matrices.ld(m), tau, workGen, workGen.length, info);

    if (info.val < 0) throw new IllegalArgumentException();

    Q.set(A);

    return this;
  }
  @Transactional
  public boolean importData(UserInfo userInfo, List<F> list) {
    logger.infoCode("I0001");
    try {

      for (int i = 0; i < list.size(); i++) {
        F form = list.get(i);

        T entity = (T) form.getNewTbl();
        entity = this.getPortfolioTbl(form, entity);

        entity.setPublicFlag(form.getPublicFlag());

        UsUserTbl usUserTbl = new UsUserTbl();
        usUserTbl.setUserKey(userInfo.getTargetUserKey());
        entity.setUsUserTbl(usUserTbl);
        entity.setUpdUserKey(userInfo.getLoginUserKey());
        entity.setUpdDate(DateUtil.getNowTimestamp());

        repository.save(entity);
      }

      repository.flush();
      logger.infoCode("I0002");
      return true;
    } catch (Exception e) {
      logger.errorCode("E1007", e); // E1007=登録に失敗しました。{0}
    }
    return false;
  }
  @Transactional
  public boolean updateAll(UserInfo userInfo, F form) {
    logger.infoCode("I0001");
    try {

      List<T> list = findAll(userInfo, form);

      for (int i = 0; i < list.size(); i++) {
        T entity = list.get(i);

        entity.setPublicFlag(form.getPublicFlag());

        UsUserTbl usUserTbl = new UsUserTbl();
        usUserTbl.setUserKey(userInfo.getTargetUserKey());
        entity.setUsUserTbl(usUserTbl);
        entity.setUpdUserKey(userInfo.getLoginUserKey());
        entity.setUpdDate(DateUtil.getNowTimestamp());

        repository.save(entity);
      }
      repository.flush();
      logger.infoCode("I0002");
      return true;
    } catch (Exception e) {
      logger.errorCode("E1007", e); // E1007=登録に失敗しました。{0}
    }
    return false;
  }
 // This can be called after any step
 @Override
 protected void sequenceFailed(SocietyCompletionEvent<ExperimentStep, R> evt) {
   StringBuffer msg = new StringBuffer();
   msg.append("Experiment ").append(suiteName).append(" FAILED at step ").append(evt.getStep());
   Map<String, Set<R>> reportsMap = evt.getReports();
   if (!reportsMap.isEmpty()) {
     String seperator = " ";
     msg.append(" because");
     for (Map.Entry<String, Set<R>> entry : reportsMap.entrySet()) {
       String nodeId = entry.getKey();
       for (R report : entry.getValue()) {
         if (!report.isSuccessful()) {
           msg.append(seperator).append("worker ").append(report.getWorker());
           msg.append(" on node ").append(nodeId);
           msg.append(" said: \"").append(report.getReason()).append("\"");
           seperator = ", ";
         }
       }
     }
   }
   log.shout(msg.toString());
   // Submit a request to perform the Shutdown step....
   // All bets are off if this will actually complete, because there is some
   // failure out there
   // but we do not know what it is.
   if (hasAttemptedToShutdown) {
     log.warn("Already Attempted to Shutdown, so doing nothing more");
   } else {
     log.warn("Attempting to shutdown the experiment society by skipping to Shutdown step");
     hasAttemptedToShutdown = true;
     publishNodeRequestStep(ExperimentSteps.SHUTDOWN);
   }
 }
  public T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken token = jp.getCurrentToken();
    if (token == JsonToken.START_OBJECT) {
      token = jp.nextToken();
    }

    R reader = readerSupplier.get();
    while (token != null && token != JsonToken.END_OBJECT) {
      if (token != JsonToken.FIELD_NAME) {
        APIParsingException.raise(
            "Parsing of json failed.  Expected to be at field name token but was " + token.name(),
            jp);
      }

      String name = jp.getCurrentName();
      jp.nextToken();

      Optional<FieldParser<R>> fieldParser = registry.getFieldParser(name);
      if (fieldParser.isPresent()) {
        fieldParser.get().parse(reader, jp, ctxt);
      } else {
        jp.skipChildren();
      }

      token = jp.nextToken();
    }

    return reader.validateAndBuild();
  }
 private final <T> Response fetchCreatedEntity(
     IResolver<T, Q> entityResolver,
     boolean block,
     Class<? extends BaseResource> suggestedParentType,
     VdcReturnValueBase createResult) {
   Q created = resolveCreated(createResult, entityResolver);
   R model = mapEntity(suggestedParentType, created);
   Response response = null;
   if (createResult.getHasAsyncTasks()) {
     if (block) {
       awaitCompletion(createResult);
       // refresh model state
       created = resolveCreated(createResult, entityResolver);
       model = mapEntity(suggestedParentType, created);
       response = Response.created(URI.create(model.getHref())).entity(model).build();
     } else {
       if (model == null) {
         response = Response.status(ACCEPTED_STATUS).build();
       } else {
         handleAsynchrony(createResult, model);
         response = Response.status(ACCEPTED_STATUS).entity(model).build();
       }
     }
   } else {
     if (model == null) {
       response = Response.status(ACCEPTED_STATUS).build();
     } else {
       response = Response.created(URI.create(model.getHref())).entity(model).build();
     }
   }
   return response;
 }
  private int silentAdd(R record) {
    if (record == null) {
      throw new NullPointerException("Record is null passed into add() to store");
    }

    Long id = record.getRecordId();

    if (id == null) {
      id = ID_GENERATOR.next();
      try {
        record.setRecordId(id);
      } catch (Exception e) {
        // this can't happen if we have exclusive access to the object (2 threads?)
      }
    }

    R existing = data.get(id);
    if (existing != null) {
      throw new RuntimeException("The store already contains this");
    }

    // add it to our internal memory
    int index = data.add(id, record);

    // listen for change events. (null safe version)
    record.onChange().addObserver(this.onValueChanged);

    return index;
  }
Example #13
0
    @Override
    public final E map(R record) {
      try {
        for (int i = 0; i < fields.length; i++) {
          if (propertyIndexes[i] != null) {
            parameterValues[propertyIndexes[i]] = record.getValue(i);
          } else {
            for (java.lang.reflect.Field member : members[i]) {
              int index = propertyNames.indexOf(member.getName());

              if (index >= 0) {
                parameterValues[index] = record.getValue(i);
              }
            }

            if (methods[i] != null) {
              String name = getPropertyName(methods[i].getName());
              int index = propertyNames.indexOf(name);

              if (index >= 0) {
                parameterValues[index] = record.getValue(i);
              }
            }
          }
        }

        Object[] converted = Convert.convert(parameterValues, parameterTypes);
        return accessible(constructor).newInstance(converted);
      } catch (Exception e) {
        throw new MappingException("An error ocurred when mapping record to " + type, e);
      }
    }
Example #14
0
    @SuppressWarnings("rawtypes")
    @Override
    public final E map(R record) {
      try {
        E result = instance != null ? instance : constructor.newInstance();

        for (int i = 0; i < fields.length; i++) {
          for (java.lang.reflect.Field member : members[i]) {

            // [#935] Avoid setting final fields
            if ((member.getModifiers() & Modifier.FINAL) == 0) {
              map(record, result, member, i);
            }
          }

          for (java.lang.reflect.Method method : methods[i]) {
            Class<?> mType = method.getParameterTypes()[0];
            Object value = record.getValue(i, mType);

            // [#3082] Map nested collection types
            if (value instanceof Collection && List.class.isAssignableFrom(mType)) {
              Class componentType =
                  (Class)
                      ((ParameterizedType) method.getGenericParameterTypes()[0])
                          .getActualTypeArguments()[0];
              method.invoke(result, Convert.convert((Collection) value, componentType));
            }

            // Default reference types (including arrays)
            else {
              method.invoke(result, record.getValue(i, mType));
            }
          }
        }

        for (Entry<String, List<RecordMapper<R, Object>>> entry : nested.entrySet()) {
          String prefix = entry.getKey();

          for (RecordMapper<R, Object> mapper : entry.getValue()) {
            Object value = mapper.map(record);

            for (java.lang.reflect.Field member : getMatchingMembers(configuration, type, prefix)) {

              // [#935] Avoid setting final fields
              if ((member.getModifiers() & Modifier.FINAL) == 0) {
                map(value, result, member);
              }
            }

            for (Method method : getMatchingSetters(configuration, type, prefix)) {
              method.invoke(result, value);
            }
          }
        }

        return result;
      } catch (Exception e) {
        throw new MappingException("An error ocurred when mapping record to " + type, e);
      }
    }
Example #15
0
 private String[] formatRow(R report, int rowIdx, ReportOutputFormat format) {
   String[] tableRow = new String[report.getColumnCount()];
   for (int colIdx = 0; colIdx < report.getColumnCount(); colIdx++) {
     tableRow[colIdx] = formatData(report, rowIdx, colIdx, format);
   }
   return tableRow;
 }
Example #16
0
  @Override
  public final <E> Map<Record, List<E>> intoGroups(Field<?>[] keys, Class<? extends E> type) {
    if (keys == null) {
      keys = new Field[0];
    }

    Map<Record, List<E>> map = new LinkedHashMap<Record, List<E>>();
    FieldList keyList = new FieldList(keys);

    for (R record : this) {

      @SuppressWarnings("rawtypes")
      Record key = new RecordImpl(keyList);

      for (Field<?> field : keys) {
        Utils.setValue(key, field, record, field);
      }

      List<E> list = map.get(key);
      if (list == null) {
        list = new ArrayList<E>();
        map.put(key, list);
      }

      list.add(record.into(type));
    }

    return map;
  }
  @Override
  protected <R extends XMLRenderer<T>, D extends T> ModelAndView update(
      String xmlCrudParameters, Class<R> renderedType, Class<D> delegatedType) {
    logger.trace(
        "Request for update " + getModelName() + " with parameters " + xmlCrudParameters + "!!!");

    try {
      R rendered = read(xmlCrudParameters, renderedType, delegatedType);

      getCrudService().update(beforeUpdate(rendered.getDelegated()));

      return getXMLViewer(
          getInfo(
              getMessages()
                  .getMessage(
                      GeneralProperties.class.getName()
                          + "."
                          + GeneralProperties.INFO_TITLE.name()),
              getMessages()
                  .getMessage(
                      GeneralProperties.class.getName()
                          + "."
                          + GeneralProperties.UPDATE_SUCCEED.name(),
                      getModelName())));
    } catch (Exception e) {
      return handleException(
          e, GeneralProperties.class.getName() + "." + GeneralProperties.UPDATE_FAILED.name());
    }
  }
Example #18
0
 // Constructors
 public Astronaut(GameWorld gw) {
   super(gw);
   this.setSize(R.nextInt(MIN_SIZE, MAX_SIZE));
   this.setDirection(R.nextInt(MIN_DIRECTION, MAX_DIRECTION));
   this.setSpeed(MIN_SPEED);
   this.setColor(DEFAULT_COLOR);
   this.setHealth(DEFAULT_HEALTH);
 }
 /**
  * Deletes the metric from the repository
  *
  * @param name the name of the metric to delete
  */
 @RequestMapping(value = "/{name}", method = RequestMethod.DELETE)
 @ResponseStatus(HttpStatus.OK)
 protected void delete(@PathVariable("name") String name) {
   if (!repository.exists(name)) {
     throw new NoSuchMetricException(name, "Can't delete metric '%s' because it does not exist");
   }
   repository.delete(name);
 }
 private Iterable<CompletionHandler<Void, K>> remove(K key) {
   R actualRequest = requests.remove(key);
   if (actualRequest == null) {
     return Collections.emptyList();
   }
   state.decrement();
   return actualRequest.callbacks();
 }
Example #21
0
 protected final <R extends ValidationRule> void performValidation(
     Class<R> validationRuleClass, ValidationReport report) {
   R rule = (R) getRule(validationRuleClass);
   ValidationIssue issue = rule.applyValidation(this);
   if (issue != null) {
     report.addToValidationIssues(issue);
   }
 }
 /** Cancels requests whose deadline has past. */
 public void cancelExpiredRequests() {
   long now = System.currentTimeMillis();
   for (R request : requests.values()) {
     if (request.getDeadline() <= now) {
       request.cancel();
     }
   }
 }
 public ArrayList<FileRegion> getFileRegions() {
   ArrayList<FileRegion> regions = new ArrayList<FileRegion>();
   for (OpenDefinitionsDocument odd : _documents) {
     File f = odd.getRawFile();
     for (R r : _regions.get(odd))
       regions.add(new DummyDocumentRegion(f, r.getStartOffset(), r.getEndOffset()));
   }
   return regions;
 }
Example #24
0
    @Override
    public final E map(R record) {
      int size = record.size();
      if (size != 1)
        throw new MappingException(
            "Cannot map multi-column record of degree " + size + " to value type " + type);

      return record.getValue(0, type);
    }
 @Override
 public R apply(final T inputMap, final F function) {
   final R result = mapCreator.createMap();
   for (final Entry<? extends K, ? extends E> entry : inputMap.entrySet()) {
     final Pair<NK, NE> mappedKeyValuepPair = function.apply(entry.getKey(), entry.getValue());
     result.put(mappedKeyValuepPair.getValue1(), mappedKeyValuepPair.getValue2());
   }
   return result;
 }
Example #26
0
 /**
  * Outputs the report table in CSV format.
  *
  * @param report the report
  * @param out the output stream to write to
  */
 @SuppressWarnings("resource")
 public void writeCsv(R report, OutputStream out) {
   OutputStreamWriter outputWriter = new OutputStreamWriter(out);
   CsvOutput csvOut = new CsvOutput(outputWriter);
   csvOut.writeLine(Arrays.asList(report.getColumnHeaders()));
   IntStream.range(0, report.getRowCount())
       .mapToObj(rowIdx -> Arrays.asList(formatRow(report, rowIdx, ReportOutputFormat.CSV)))
       .forEachOrdered(csvOut::writeLine);
   Unchecked.wrap(() -> outputWriter.flush());
 }
Example #27
0
  @Override
  public final List<Map<String, Object>> intoMaps() {
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

    for (R record : this) {
      list.add(record.intoMap());
    }

    return list;
  }
Example #28
0
  @Override
  public final <Z extends Record> Result<Z> into(Table<Z> table) {
    Result<Z> list = new ResultImpl<Z>(getConfiguration(), table.fields());

    for (R record : this) {
      list.add(record.into(table));
    }

    return list;
  }
Example #29
0
  /** Extract a list of values from a set of records given some fields */
  private static <R extends Record> List<Object> extractValues(
      Collection<? extends R> records, TableField<R, ?> field2) {
    List<Object> result = new ArrayList<Object>();

    for (R record : records) {
      result.add(record.getValue(field2));
    }

    return result;
  }
  /**
   * {@inheritDoc}
   *
   * @see
   *     ch.entwine.weblounge.common.repository.ContentRepositoryResourceOperation#apply(ResourceURI,
   *     Resource)
   */
  public <C extends ResourceContent, R extends Resource<C>> R apply(ResourceURI uri, R resource) {
    if (resource == null) return null;

    // Is it a different resource? We care about id and path, but not about
    // version
    if (!ResourceUtils.equalsByIdOrPath(this.uri, resource.getURI())) return resource;

    resource.lock(user);
    return resource;
  }