@Override
  public default void addedStatement(Statement statement) {
    Model m = ModelFactory.createDefaultModel();
    m.add(statement);

    logAddChange(m);
  }
示例#2
0
  public static String RenderTemplatePage(Bindings b, String templateName) throws IOException {

    MediaType mt = MediaType.TEXT_HTML;
    Resource config = model.createResource("eh:/root");
    Mode prefixMode = Mode.PreferPrefixes;
    ShortnameService sns = new StandardShortnameService();

    List<Resource> noResults = CollectionUtils.list(root.inModel(model));
    Graph resultGraph = graphModel.getGraph();

    resultGraph.getPrefixMapping().setNsPrefix("api", API.NS);
    resultGraph.add(Triple.create(root.asNode(), API.items.asNode(), RDF.nil.asNode()));

    APIResultSet rs = new APIResultSet(resultGraph, noResults, true, true, "details", View.ALL);
    VelocityRenderer vr = new VelocityRenderer(mt, null, config, prefixMode, sns);

    VelocityRendering vx = new VelocityRendering(b, rs, vr);

    VelocityEngine ve = vx.createVelocityEngine();
    VelocityContext vc = vx.createVelocityContext(b);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Writer w = new OutputStreamWriter(bos, "UTF-8");
    Template t = ve.getTemplate(templateName);

    t.merge(vc, w);
    w.close();

    return bos.toString();
  }
示例#3
0
  private boolean checkDiagonalDescending(CellState player, int col, int row) { // diagonal-\

    // check winLength-in-a-row
    int winCounter = 0;
    int x = 0;
    int y = 0;

    for (int i = -model.getWinLength() - 1; i < model.getWinLength(); ++i) {

      x = col + i;
      // FIXME wtf?? i+1??
      y = row + i + 1;

      if (isInsideBoard(x, y)) {

        if (model.getCell(x, y) == player) {
          ++winCounter;
        } else {
          winCounter = 0;
        }

        if (winCounter == model.getWinLength()) {
          return true;
        }
      }
    }
    return false;
  }
示例#4
0
  private void computePreferredSize() {
    Model model = getModel();
    Selection sel = model.getSelection();
    int columns = sel.size();
    if (columns == 0) {
      setPreferredSize(new Dimension(0, 0));
      return;
    }

    Graphics g = getGraphics();
    if (g == null) {
      cellHeight = 16;
      cellWidth = 24;
    } else {
      FontMetrics fm = g.getFontMetrics(HEAD_FONT);
      cellHeight = fm.getHeight();
      cellWidth = 24;
      for (int i = 0; i < columns; i++) {
        String header = sel.get(i).toShortString();
        cellWidth = Math.max(cellWidth, fm.stringWidth(header));
      }
    }

    tableWidth = (cellWidth + COLUMN_SEP) * columns - COLUMN_SEP;
    tableHeight = cellHeight * (1 + rowCount) + HEADER_SEP;
    setPreferredSize(new Dimension(tableWidth, tableHeight));
    revalidate();
    repaint();
  }
示例#5
0
  public void Update(String event) {
    if (event.equals("time")) {
      MODEL.time =
          "<html>Elapsed Time: <font color =\"GREEN\">"
              + MODEL.watch.getElapsedTimeSecs()
              + "</font> Seconds</html>";
      timeLab.setText(MODEL.time);
    } else if (event.equals("invalid")) {
      MODEL.answerInvalid();
      msg.setText(MODEL.msg);
    } else if (event.equals("correct")) {
      MODEL.answerCorrect();

      score.setText(MODEL.str);
      msg.setText(MODEL.msg);
      problem.setText(MODEL.prb);
      entry.setText("");
      entry.requestFocus();
    } else if (event.equals("wrong")) {
      MODEL.answerWrong();
      msg.setText(MODEL.msg);
    } else if (event.equals("replay")) {
      MODEL.gameReplay();

      problem.setText(MODEL.prb);
      score.setText(MODEL.str);
      msg.setText(MODEL.msg);
      timeLab.setText(MODEL.time);
    } else System.out.println("Invalid Update Command");
  }
示例#6
0
  private Map<String, double[]> getGraphDatasFromDaily(
      Date start, Date end, Model model, Payload payload) {
    String domain = model.getDomain();
    String type = payload.getType();
    String name = payload.getName();
    String ip = model.getIpAddress();
    String queryIp = "All".equalsIgnoreCase(ip) == true ? "All" : ip;
    List<DailyGraph> graphs = new ArrayList<DailyGraph>();

    for (long startLong = start.getTime();
        startLong < end.getTime();
        startLong = startLong + TimeUtil.ONE_DAY) {
      try {
        DailyGraph graph =
            m_dailyGraphDao.findByDomainNameIpDate(
                new Date(startLong),
                queryIp,
                domain,
                EventAnalyzer.ID,
                DailyGraphEntity.READSET_FULL);
        graphs.add(graph);
      } catch (DalNotFoundException e) {
      } catch (Exception e) {
        Cat.logError(e);
      }
    }
    return buildGraphDatasForDaily(start, end, type, name, graphs);
  }
示例#7
0
 @Transient
 public ImageAnchor getLargeImageBean() {
   ImageAnchorBean bean = new ImageAnchorBean();
   bean.setTitle(getTitle());
   bean.setUrl(getUrl());
   bean.setSrc(getLargeImageUrl());
   Model model = getModel();
   if (model == null) {
     return bean;
   }
   ModelField mf = model.getField("largeImage");
   if (mf == null) {
     return bean;
   }
   Map<String, String> map = mf.getCustoms();
   String width = map.get(ModelField.IMAGE_WIDTH);
   if (StringUtils.isNotBlank(width)) {
     bean.setWidth(NumberUtils.createInteger(width));
   }
   String height = map.get(ModelField.IMAGE_HEIGHT);
   if (StringUtils.isNotBlank(height)) {
     bean.setHeight(NumberUtils.createInteger(height));
   }
   return bean;
 }
示例#8
0
 /*Execute each of the agent's yearly actions in turn*/
 public void step(SimState state) {
   if (Model.instance().generateLifeProb() == 101) {
     mode = LifeStage.DYING;
   }
   // earn
   if (mode == LifeStage.EARNING) {
     this.earnIncome();
     mode = LifeStage.TRADING;
     Model.instance().schedule.scheduleOnceIn(.1, this);
     // trade
   } else if (mode == LifeStage.TRADING) {
     // this.tradeWithRandomAgents();
     this.checkThreeProducers();
     mode = LifeStage.CONSUMING;
     Model.instance().schedule.scheduleOnceIn(.1, this);
     // consume
   } else if (mode == LifeStage.CONSUMING) {
     this.consume();
     // System.out.printf("food price: %f, id: %d, Make: %d\n",expPrice[1],myId,producedCommodity);
     // mode = LifeStage.BIRTHING;
     mode = LifeStage.EARNING;
     Model.instance().schedule.scheduleOnceIn(.8, this);
     age++;
     // child
   } /*else if(mode == LifeStage.BIRTHING){
        this.considerHavingAChild();
        mode = LifeStage.DYING;
        Model.instance().schedule.scheduleOnceIn(.1,this);
     //death
     }*/ else if (mode == LifeStage.DYING) {
     this.considerDeath();
     // mode = LifeStage.EARNING;
   }
 }
  @Test
  public void resolveInlineArrayModel() throws Exception {
    Swagger swagger = new Swagger();

    swagger.addDefinition(
        "User",
        new ArrayModel()
            .items(
                new ObjectProperty()
                    .title("title")
                    ._default("default")
                    .access("access")
                    .readOnly(false)
                    .required(true)
                    .description("description")
                    .name("name")
                    .property("street", new StringProperty())
                    .property("city", new StringProperty())));

    new InlineModelResolver().flatten(swagger);

    Model model = swagger.getDefinitions().get("User");
    assertTrue(model instanceof ArrayModel);

    Model user = swagger.getDefinitions().get("User_inner");
    assertNotNull(user);
    assertEquals("description", user.getDescription());
  }
示例#10
0
  public static void displayRealm(Realm r) {
    if (Logic.getPlayer() != null) {
      LAYER = BACKGROUND_LAYER;
      setCameraBackground();
      camera.setCameraBound(r.getCameraBound());
      Model background = r.getBackground();
      if (background != null) {
        background.draw(null, null, null);
      }
      camera.setPos(Logic.getPlayer().getPos());
      setCameraLevel();

      LAYER = STATIC_LAYER;
      for (Entity i : r.getEntities()) i.draw();
      for (Entity i : r.getWayPoints()) {
        i.draw();
      }

      LAYER = UNIT_LAYER;
      for (EntityUnit i : r.getUnits()) i.draw();
      LAYER = DYNAMIC_LAYER;
      for (EntityMissile i : r.getMissiles()) i.draw();

      GUI gui = Main.getGameState(STATE_SETTING_MENU).getGUI("GUI_CB_PARTICLES");
      if (gui != null && ((GUICheckBox) gui).getValue()) {
        LAYER = PARTICLE_LAYER;
        for (EntityParticle i : r.getParticles()) i.draw();
      }
    }
  }
示例#11
0
 public Set<Model> getSubModelsOld() {
   if (subModels == null) {
     subModels = new HashSet<Model>();
     Iterator<? extends ModelObject> iterator = getObjects().iterator();
     while (iterator.hasNext()) {
       ModelObject modelObject = iterator.next();
       if (subModels.isEmpty()) {
         SubModel subModel = new SubModel(this);
         subModels.add(subModel);
         addAll(modelObject, subModel);
       } else {
         boolean found = false;
         for (Model m : subModels) {
           if (m.contains(modelObject)) {
             found = true;
             break;
           }
         }
         if (!found) {
           SubModel subModel = new SubModel(this);
           subModels.add(subModel);
           addAll(modelObject, subModel);
         }
       }
     }
     for (Model subModel : subModels) {
       subModel.indexGuids();
     }
   }
   return subModels;
 }
示例#12
0
  @Test
  public void testUpdate() throws Exception {
    Resource rhmRes = model.getResource(FakeRDFModel.rhm);
    Property name = model.getProperty(foaf + "name");

    Statement nameSt = rhmRes.listProperties(name).nextStatement();
    String originalName = nameSt.getLiteral().getString();

    // assume update is always first remove and then add
    model.remove(nameSt);
    model.add(rhmRes, name, "TESTNAME");

    assert changes.size() == 2;
    assert rhmRes.listProperties(name).toList().size() == 1;
    assert rhmRes.listProperties(name).nextStatement().getLiteral().getString().equals("TESTNAME");

    changes.undo();

    assert changes.size() == 2;
    assert rhmRes.listProperties(name).toList().size() == 1;
    assert rhmRes
        .listProperties(name)
        .nextStatement()
        .getLiteral()
        .getString()
        .equals(originalName);

    changes.redo();

    assert changes.size() == 2;
    assert rhmRes.listProperties(name).toList().size() == 1;
    assert rhmRes.listProperties(name).nextStatement().getLiteral().getString().equals("TESTNAME");
  }
示例#13
0
 @Override
 protected void execImpl() {
   Vec va = null, vp = null, avp = null;
   try {
     if (classification) {
       // Create a new vectors - it is cheap since vector are only adaptation vectors
       va = vactual.toEnum(); // always returns TransfVec
       actual_domain = va._domain;
       vp = vpredict.toEnum(); // always returns TransfVec
       predicted_domain = vp._domain;
       if (!Arrays.equals(actual_domain, predicted_domain)) {
         domain = Utils.domainUnion(actual_domain, predicted_domain);
         int[][] vamap = Model.getDomainMapping(domain, actual_domain, true);
         va = TransfVec.compose((TransfVec) va, vamap, domain, false); // delete original va
         int[][] vpmap = Model.getDomainMapping(domain, predicted_domain, true);
         vp = TransfVec.compose((TransfVec) vp, vpmap, domain, false); // delete original vp
       } else domain = actual_domain;
       // The vectors are from different groups => align them, but properly delete it after
       // computation
       if (!va.group().equals(vp.group())) {
         avp = vp;
         vp = va.align(vp);
       }
       cm = new CM(domain.length).doAll(va, vp)._cm;
     } else {
       mse = new CM(1).doAll(vactual, vpredict).mse();
     }
     return;
   } finally { // Delete adaptation vectors
     if (va != null) UKV.remove(va._key);
     if (vp != null) UKV.remove(vp._key);
     if (avp != null) UKV.remove(avp._key);
   }
 }
示例#14
0
  // This function is used to load the list of selected media from internal storage
  // This should only be called from AlarmixActivity
  public void loadGlobalId(Context context) {
    try {
      m_model.gId = 0;

      FileInputStream is = context.openFileInput(FILE_NAME_GLOBAL_ID);
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      // read form the stream to build the media list
      String line;
      if ((line = br.readLine()) != null) {
        if (!line.isEmpty()) m_model.gId = Integer.parseInt(line);
      }

      // clean up
      br.close();
      isr.close();
      is.close();
    } catch (NumberFormatException e) {
      // the number you are parsing is wrong? check saveGlobalId just in case
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      // maybe the file hasn't been created yet
      // in that case, leave model.lstMediaPaths as an empty list
      e.printStackTrace();
    } catch (IOException e) {
      // something went wrong when reading from file?
      e.printStackTrace();
    }
  }
示例#15
0
 // test deletion
 @Test
 public void deleteTest1() {
   // if there's nothing and we do a deletion, nothing happens
   m.removeLastSignature();
   assertTrue(m.getTexts().isEmpty());
   assertEquals("", m.getCurrentSignature());
 }
 /**
  * This method manages a request from the user. Here, the decision of moving forward or staying
  * still is made. This depends on the users credentials and whether they check out or not.
  *
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // A few details that are relevant to checking.
   Model model = new Model();
   String username = request.getParameter("username");
   String password = request.getParameter("password");
   boolean result = model.login(username, password);
   RequestDispatcher dispatcher;
   HttpSession session = request.getSession();
   // If the user credentials are correct
   if (result) {
     String userIDKey = new String("userID");
     String userID = new String(username);
     // Session management
     session.setAttribute(userIDKey, userID);
     session.setAttribute("model", model);
     session.setAttribute("status", "");
     session.setMaxInactiveInterval(60);
     // Moving on to the next view.
     dispatcher = request.getRequestDispatcher("createMail.jsp");
   }
   // If the user credentials are incorrect
   else {
     model.close();
     // Session management and view control.
     session.setAttribute("statusLog", "Login failed. Could you please try again?");
     dispatcher = request.getRequestDispatcher("index.jsp");
   }
   dispatcher.forward(request, response);
 }
示例#17
0
 @Test
 public void inputTest2() {
   m.updateSignature(2);
   String expected = "2";
   String result = m.getCurrentSignature();
   assertEquals(expected, result);
 }
  /**
   * Tests deferred update behaviour of a replace instance submission.
   *
   * @throws Exception if any error occurred during the test.
   */
  public void testReplaceInstanceUpdateBehaviour() throws Exception {
    Model model = this.chibaBean.getContainer().getDefaultModel();
    UpdateHandler updateHandler = new UpdateHandler(model);
    updateHandler.doRebuild(true);
    updateHandler.doRecalculate(true);
    updateHandler.doRevalidate(true);
    updateHandler.doRefresh(true);
    model.setUpdateHandler(updateHandler);

    EventTarget target = model.getTarget();
    TestEventListener rebuildListener = new TestEventListener();
    TestEventListener recalculateListener = new TestEventListener();
    TestEventListener revalidateListener = new TestEventListener();
    TestEventListener refreshListener = new TestEventListener();
    target.addEventListener(XFormsEventNames.REBUILD, rebuildListener, false);
    target.addEventListener(XFormsEventNames.RECALCULATE, recalculateListener, false);
    target.addEventListener(XFormsEventNames.REVALIDATE, revalidateListener, false);
    target.addEventListener(XFormsEventNames.REFRESH, refreshListener, false);

    this.chibaBean.dispatch("submission-replace-instance", XFormsEventNames.SUBMIT);
    updateHandler.doUpdate();

    assertEquals("submission-replace-instance", this.submitDoneListener.getId());
    assertEquals(null, this.submitErrorListener.getId());

    assertEquals(null, rebuildListener.getId());
    assertEquals(null, recalculateListener.getId());
    assertEquals(null, revalidateListener.getId());
    assertEquals(null, refreshListener.getId());
  }
示例#19
0
  @Test
  public void testJitConstraintWithOperationOnBigDecimal() {
    // DROOLS-32
    String str =
        "import org.drools.integrationtests.MiscTest2.Model;\n"
            + "import java.math.BigDecimal;\n"
            + "\n"
            + "rule \"minCost\" dialect \"mvel\" \n"
            + "when\n"
            + "    $product : Model(price < (cost + 0.10B))\n"
            + "then\n"
            + "    modify ($product) { price = $product.cost + 0.10B }\n"
            + "end";

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);

    final Model model = new Model();
    model.setCost(new BigDecimal("2.43"));
    model.setPrice(new BigDecimal("2.43"));

    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    ksession.insert(model);

    int fired = ksession.fireAllRules(2);
    if (fired > 1) throw new RuntimeException("loop");
  }
 @Override
 @SuppressWarnings("unchecked")
 public Object bind(
     String name,
     @SuppressWarnings("rawtypes") Class clazz,
     java.lang.reflect.Type type,
     Annotation[] annotations,
     Map<String, String[]> params) {
   if (Model.class.isAssignableFrom(clazz)) {
     String keyName = modelFactory(clazz).keyName();
     String idKey = name + "." + keyName;
     if (params.containsKey(idKey)
         && params.get(idKey).length > 0
         && params.get(idKey)[0] != null
         && params.get(idKey)[0].trim().length() > 0) {
       String id = params.get(idKey)[0];
       try {
         Object o = ds().createQuery(clazz).filter(keyName, new ObjectId(id)).get();
         return Model.edit(o, name, params, annotations);
       } catch (Exception e) {
         return null;
       }
     }
     return Model.create(clazz, name, params, annotations);
   }
   return super.bind(name, clazz, type, annotations, params);
 }
  public static void main(String args[]) {

    // some definitions
    String personURI = "http://somewhere/JohnSmith";
    String givenName = "John";
    String familyName = "Smith";
    String fullName = givenName + " " + familyName;
    // create an empty model
    Model model = ModelFactory.createDefaultModel();

    // create the resource
    //   and add the properties cascading style
    Resource johnSmith =
        model
            .createResource(personURI)
            .addProperty(VCARD.FN, fullName)
            .addProperty(
                VCARD.N,
                model
                    .createResource()
                    .addProperty(VCARD.Given, givenName)
                    .addProperty(VCARD.Family, familyName));

    // now write the model in XML form to a file
    model.write(System.out);
  }
 @Test
 public void testExhaustedCharacterSet() {
   Assert.assertFalse(search.exhaustedCharset("wants"));
   Assert.assertFalse(search.exhaustedCharset(Model.getBlob()));
   Assert.assertTrue(search.exhaustedCharset("zippo"));
   Assert.assertTrue(search.exhaustedCharset(Model.getBlob() + "a"));
 }
示例#23
0
 private void updateUI() {
   final boolean running = model.isRunning();
   final boolean scriptRunning = model.isScriptRunning();
   startButton.setDisable(running || scriptRunning);
   stopButton.setDisable(!running && !scriptRunning);
   scriptsButton.setDisable(running || scriptRunning);
   final Settings settings = model.loadSettings();
   goldField.setText(settings.getGoldThreshold() + "");
   elixirField.setText(settings.getElixirThreshold() + "");
   deField.setText(settings.getDarkElixirThreshold() + "");
   maxThField.setText(settings.getMaxThThreshold() + "");
   detectEmptyCollectorsCheckBox.setSelected(settings.isDetectEmptyCollectors());
   isMatchAllConditionsCheckBox.setSelected(settings.isMatchAllConditions());
   collectResourcesCheckBox.setSelected(settings.isCollectResources());
   trainTroopsSlider.setValue(settings.getTrainMaxTroops());
   logLevelComboBox.getSelectionModel().select(settings.getLogLevel());
   autoAttackComboBox.getSelectionModel().select(settings.getAttackStrategy());
   rax1ComboBox.getSelectionModel().select(settings.getRaxInfo()[0]);
   rax2ComboBox.getSelectionModel().select(settings.getRaxInfo()[1]);
   rax3ComboBox.getSelectionModel().select(settings.getRaxInfo()[2]);
   rax4ComboBox.getSelectionModel().select(settings.getRaxInfo()[3]);
   rax5ComboBox.getSelectionModel().select(settings.getRaxInfo()[4]);
   rax6ComboBox.getSelectionModel().select(settings.getRaxInfo()[5]);
   extraFuncCheckBox.setSelected(settings.isExtraFunctions());
 }
示例#24
0
 public void changeItems() {
   if (model.getItems().contains("one")) {
     model.setItems(ImmutableList.of("two", "three", "four", "five", "six"));
   } else {
     model.setItems(ImmutableList.of("one", "two", "three", "four"));
   }
 }
示例#25
0
 public boolean train(DataIter trainData, boolean cachedLabels, boolean collectIds)
     throws Exception {
   // map the y-values in the training set.
   boolean labelsMapped = false;
   if (cachedLabels) {
     labelsMapped = stateMappings(trainData);
   }
   if (dict != null) dict.train(trainData, model.numStates());
   for (WordsInTrain d : otherDicts) {
     d.train(trainData, model.numStates());
   }
   boolean requiresTraining = false;
   for (int f = 0; f < features.size(); f++) {
     if (getFeature(f).requiresTraining()) {
       requiresTraining = true;
       break;
     }
   }
   if (requiresTraining) {
     for (trainData.startScan(); trainData.hasNext(); ) {
       DataSequence seq = trainData.next();
       for (int f = 0; f < features.size(); f++) {
         if (getFeature(f).requiresTraining()) {
           trainFeatureType(getFeature(f), seq);
         }
       }
     }
   }
   if (collectIds) totalFeatures = featureMap.collectFeatureIdentifiers(trainData, maxMemory());
   return labelsMapped;
 };
示例#26
0
  public void handleMoving(String[] fields) {
    String volunteerString = fields[1];
    String startString = fields[2];
    String destinationString = fields[3];
    int transitTime = Integer.parseInt(fields[4]);

    Log.i(
        "MOVING: volunteer=%s start=%s destination=%s transitTime=%d",
        volunteerString, startString, destinationString, transitTime);

    Volunteer volunteer = model.getVolunteerByName(volunteerString);
    if (volunteer == null) {
      Log.w("Haven't seen moving volunteer %s yet", volunteerString);
      return;
    }

    Location start = model.getLocationByName(startString);
    if (start == null) {
      Log.w("Haven't see start location %s yet", startString);
      return;
    }

    Location destination = model.getLocationByName(destinationString);
    if (destination == null) {
      Log.w("Haven't seen destination location %s yet", destinationString);
      return;
    }

    if (!start.getName().equals(startString))
      Log.w(
          "MOVING violation: %s not at %s but rather at %s",
          volunteerString, startString, start.getName());

    volunteer.startMoving(destination, transitTime);
  }
示例#27
0
  public static void main(String[] args) {
    // create an empty model
    Model model = ModelFactory.createDefaultModel();

    // use the FileManager to find the input file
    String inputFileName = "src/main/resources/lab-3.ttl";
    InputStream in = FileManager.get().open(inputFileName);
    if (in == null) {
      throw new IllegalArgumentException("File: " + inputFileName + " not found");
    }

    // read the Turtle file
    model.read(in, null, "TTL");

    // get the inferred mode
    /* The getDeductionsFunction somehow returns the incorrect answer, so I have to use the deprecated class 'Filter'. */
    InfModel infModel = ModelFactory.createRDFSModel(model);
    ExtendedIterator<Statement> stmts =
        infModel
            .listStatements()
            .filterDrop(
                new Filter<Statement>() {
                  @Override
                  public boolean accept(Statement o) {
                    return model.contains(o);
                  }
                });
    Model deductionsModel = ModelFactory.createDefaultModel().add(new StmtIteratorImpl(stmts));

    // list new RDFS-inferred triples about 'Museion'
    outputInfo(deductionsModel, "museion");

    // list new RDFS-inferred triples about 'Chicken Hut'
    outputInfo(deductionsModel, "chickenHut");
  }
示例#28
0
  public void handleRequest(String[] fields) {
    String requesterName = fields[1];
    String startString = fields[2];
    String destinationString = fields[3];
    int value = Integer.parseInt(fields[4]);

    Log.i(
        "REQUEST: requester=%s start=%s, destination=%s value=%d",
        requesterName, startString, destinationString, value);

    // Remove any old request with the same name...
    Request request = model.getRequestByName(requesterName);
    if (request != null) model.removeRequest(request);

    Location start = model.getLocationByName(startString);
    Location destination = model.getLocationByName(destinationString);

    if (start == null) {
      Log.w("Haven't see the request start location %s yet", startString);
      return;
    }

    if (destination == null) {
      Log.w("Haven't see the request destination location %s yet", destinationString);
      return;
    }

    new Request(model, requesterName, start, destination, value);
  }
示例#29
0
  private boolean checkHorizontal(CellState player, int col, int row) {

    int minCheck = col - (model.getWinLength() - 1);
    int maxCheck = col + (model.getWinLength() - 1);

    if (minCheck < 0) {
      minCheck = 0;
    }

    if (maxCheck > model.numOfColumns() - 1) {
      maxCheck = model.numOfColumns() - 1;
    }

    // check winLength-in-a-row
    int winCounter = 0;

    for (int i = minCheck; i <= maxCheck; ++i) {
      // FIXME warum row+1? problem: er erkentn die ganz oberste reihe
      // nicht mehr... weil -1
      if (model.getCell(i, row + 1) == player) {
        ++winCounter;
      } else {
        winCounter = 0;
      }

      if (winCounter == model.getWinLength()) {
        return true;
      }
    }

    return false;
  }
  @Override
  public default void removedStatements(StmtIterator stmtIterator) {
    Model m = ModelFactory.createDefaultModel();
    m.add(stmtIterator);

    logRemoveChange(m);
  }