예제 #1
0
  /**
   * Compares this LTS to another for debugging purposes.
   *
   * @param other the other LTS to compare to
   * @return <code>true</code> if these are equivalent
   */
  public boolean compare(LetterToSound other) {

    // compare letter index table
    //
    for (Iterator i = letterIndex.keySet().iterator(); i.hasNext(); ) {
      String key = (String) i.next();
      Integer thisIndex = (Integer) letterIndex.get(key);
      Integer otherIndex = (Integer) other.letterIndex.get(key);
      if (!thisIndex.equals(otherIndex)) {
        if (RiTa.PRINT_LTS_INFO) System.err.println("[WARN] LTSengine -> Bad index: " + key);
        return false;
      }
    }

    // compare states
    //
    for (int i = 0; i < stateMachine.length; i++) {
      State state = getState(i);
      State otherState = other.getState(i);
      if (!state.compare(otherState)) {
        if (RiTa.PRINT_LTS_INFO) System.err.println("[WARN] LTSengine -> Bad state: " + i);
        return false;
      }
    }

    return true;
  }
예제 #2
0
 /**
  * I think in the basic framework this method is never called explicitely, because processing is
  * done implicitly by the render
  */
 @Override
 public void process(
     Processor processor, Parameters blockParameters, Parameters frameworkParameters)
     throws FrameworkException {
   HttpServletRequest request = frameworkParameters.get(Parameter.REQUEST);
   State state = State.getState(request);
   state.startBlock(frameworkParameters, null);
   setBlockParametersForProcess(state, blockParameters);
   processor.process(blockParameters);
 }
예제 #3
0
 @Override
 public Block getRenderingBlock(Parameters frameworkParameters) {
   HttpServletRequest request = frameworkParameters.get(Parameter.REQUEST);
   State state = State.getState(request);
   if (state.isRendering()) {
     return state.getBlock();
   } else {
     return null;
   }
 }
 public void loadState(final State state) {
   synchronized (myStateLock) {
     myState = state;
     if (myState.lastPath != null && !new File(myState.lastPath).exists()) {
       myState.lastPath = null;
     }
     if (myState.lastPath != null) {
       File lastFile = new File(myState.lastPath);
       if (lastFile.isDirectory()
           && !new File(lastFile, Project.DIRECTORY_STORE_FOLDER).exists()) {
         myState.lastPath = null;
       }
     }
   }
 }
 private void markPathRecent(String path) {
   synchronized (myStateLock) {
     myState.lastPath = path;
     removePath(path);
     myState.recentPaths.add(0, path);
   }
 }
 public static void main(String[] args) throws IOException {
   int simulation = 1000;
   Event actEvent;
   EventList myEventList = new EventList();
   State actState = new State(myEventList);
   myEventList.InsertEvent(ARRIVAL, 0);
   myEventList.InsertEvent(MEASURE, 5);
   while (actState.noMeasurements < simulation) {
     actEvent = myEventList.FetchEvent();
     time = actEvent.eventTime;
     actState.TreatEvent(actEvent);
   }
   System.out.println(
       "Mean number of customers: " + 1.0 * actState.accumulated / actState.noMeasurements);
   System.out.println("Number of measurements done: " + actState.noMeasurements);
 }
 public void updateLastProjectPath() {
   final Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
   synchronized (myStateLock) {
     if (openProjects.length == 0) {
       myState.lastPath = null;
       myState.openPaths = Collections.emptyList();
     } else {
       myState.lastPath = getProjectPath(openProjects[openProjects.length - 1]);
       myState.openPaths = new ArrayList<String>();
       for (Project openProject : openProjects) {
         final String path = getProjectPath(openProject);
         ContainerUtil.addIfNotNull(myState.openPaths, path);
         myState.names.put(path, getProjectDisplayName(openProject));
       }
     }
   }
 }
예제 #8
0
 @Override
 public String getProcessUrl(
     String path, Map<String, ?> parameters, Parameters frameworkParameters, boolean escapeAmps)
     throws FrameworkException {
   HttpServletRequest request =
       BasicUrlConverter.getUserRequest(frameworkParameters.get(Parameter.REQUEST));
   State state = State.getState(request);
   frameworkParameters.set(ACTION, state.getId());
   Url url = urlConverter.getProcessUrl(path, parameters, frameworkParameters, escapeAmps);
   if (url == Url.NOT) {
     log.debug("Fall back url");
     return fallbackConverter
         .getProcessUrl(path, parameters, frameworkParameters, escapeAmps)
         .getUrl();
   } else {
     log.debug("Url converter url " + url);
     return url.getUrl();
   }
 }
예제 #9
0
  private void recordNewState(State state) {
    Object[] keyTable = this.binaryLocationsPerProject.keyTable;
    for (int i = 0, l = keyTable.length; i < l; i++) {
      IProject prereqProject = (IProject) keyTable[i];
      if (prereqProject != null && prereqProject != this.currentProject)
        state.recordStructuralDependency(prereqProject, getLastState(prereqProject));
    }

    if (DEBUG) System.out.println("JavaBuilder: Recording new state : " + state); // $NON-NLS-1$
    // state.dump();
    JavaModelManager.getJavaModelManager().setLastBuiltState(this.currentProject, state);
  }
예제 #10
0
 @SuppressWarnings("unchecked")
 protected void setBlockParametersForRender(State state, Parameters blockParameters) {
   ServletRequest request = state.getRequest();
   String prefix = getPrefix(state);
   log.debug("prefix " + prefix);
   blockParameters.setAutoCasting(true);
   for (Map.Entry<String, String[]> entry :
       ((Map<String, String[]>) request.getParameterMap()).entrySet()) {
     String key = entry.getKey();
     if (key.startsWith(prefix)) {
       log.trace("setting" + entry);
       blockParameters.setIfDefined(key.substring(prefix.length()), entry.getValue());
     }
   }
   if (log.isDebugEnabled()) {
     log.debug("Set " + blockParameters);
   }
 }
예제 #11
0
  public static void main(String argv[]) {

    // argv[0]: input file containing source code using tokens defined above
    // argv[1]: output file to display a list of the tokens

    setLex(argv[0], argv[1]);

    int i;

    while (a != -1) // while "a" is not end-of-stream
    {
      i = driver(); // extract the next token
      if (i == 1) displayln(t + "   : " + state.toString());
      else if (i == 0) displayln(t + "  -- Invalid Token");
    }

    closeIO();
  }
예제 #12
0
  private static int driver()

        // This is the driver of the FA.
        // If a valid token is found, assigns it to "t" and returns 1.
        // If an invalid token is found, assigns it to "t" and returns 0.
        // If end-of-stream is reached without finding any non-whitespace character, returns -1.

      {
    State nextSt; // the next state of the FA

    t = "";
    state = State.Start;

    if (Character.isWhitespace((char) a)) a = getChar(); // get the next non-whitespace character
    if (a == -1) // end-of-stream is reached
    return -1;

    while (a != -1) // do the body if "a" is not end-of-stream
    {
      c = (char) a;
      nextSt = nextState[state.ordinal()][a];
      if (nextSt == State.UNDEF) // The FA will halt.
      {
        if (isFinal(state)) return 1; // valid token extracted
        else // "c" is an unexpected character
        {
          t = t + c;
          a = getNextChar();
          return 0; // invalid token found
        }
      } else // The FA will go on.
      {
        state = nextSt;
        t = t + c;
        a = getNextChar();
      }
    }

    // end-of-stream is reached while a token is being extracted

    if (isFinal(state)) return 1; // valid token extracted
    else return 0; // invalid token found
  } // end driver
예제 #13
0
 public static State readState(IProject project, DataInputStream in) throws IOException {
   return State.read(project, in);
 }
예제 #14
0
 private static boolean isFinal(State state) {
   return (state.compareTo(State.Id) >= 0);
 }
예제 #15
0
 @Override
 public void update(Observable o, Object arg) {
   if (o != pokerMachine) return;
   State state = ((PokerMachine) o).state();
   this.state = state;
   String s = "";
   if (state.pokerHand() == null || state.subState() == state.betMade) s += "XXXXX";
   else s += state.pokerHand().toCharacters() + " " + info(state.pokerHand(), state.handNumber());
   s = s + CommandLineController.lineSeparator;
   if (!(state.pokerHand() == null || state.subState() == state.betMade)) {
     for (int i = 0; i < 5; i++) s += " " + (state.holds[i] ? 'H' : 'T');
     s += CommandLineController.lineSeparator;
   }
   if (state.subState() == state.afterDraw && state.payoff() > 0)
     s += "payoff " + state.payoff() + CommandLineController.lineSeparator;
   s +=
       ("hand "
           + state.hands()
           + ", "
           + state.coins()
           + " Coins, "
           + state.credits()
           + " credits");
   if (/* true|| */ !automatic || state.hands() % 250 == 0) System.out.println(s);
   this.state = state;
 }
예제 #16
0
  private SimpleLookupTable findDeltas() {
    this.notifier.subTask(
        Messages.bind(Messages.build_readingDelta, this.currentProject.getName()));
    IResourceDelta delta = getDelta(this.currentProject);
    SimpleLookupTable deltas = new SimpleLookupTable(3);
    if (delta != null) {
      if (delta.getKind() != IResourceDelta.NO_CHANGE) {
        if (DEBUG)
          System.out.println(
              "JavaBuilder: Found source delta for: "
                  + this.currentProject.getName()); // $NON-NLS-1$
        deltas.put(this.currentProject, delta);
      }
    } else {
      if (DEBUG)
        System.out.println(
            "JavaBuilder: Missing delta for: " + this.currentProject.getName()); // $NON-NLS-1$
      this.notifier.subTask(""); // $NON-NLS-1$
      return null;
    }

    Object[] keyTable = this.binaryLocationsPerProject.keyTable;
    Object[] valueTable = this.binaryLocationsPerProject.valueTable;
    nextProject:
    for (int i = 0, l = keyTable.length; i < l; i++) {
      IProject p = (IProject) keyTable[i];
      if (p != null && p != this.currentProject) {
        State s = getLastState(p);
        if (!this.lastState.wasStructurallyChanged(p, s)) { // see if we can skip its delta
          if (s.wasNoopBuild())
            continue nextProject; // project has no source folders and can be skipped
          ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) valueTable[i];
          boolean canSkip = true;
          for (int j = 0, m = classFoldersAndJars.length; j < m; j++) {
            if (classFoldersAndJars[j].isOutputFolder())
              classFoldersAndJars[j] =
                  null; // can ignore output folder since project was not structurally changed
            else canSkip = false;
          }
          if (canSkip)
            continue nextProject; // project has no structural changes in its output folders
        }

        this.notifier.subTask(Messages.bind(Messages.build_readingDelta, p.getName()));
        delta = getDelta(p);
        if (delta != null) {
          if (delta.getKind() != IResourceDelta.NO_CHANGE) {
            if (DEBUG)
              System.out.println(
                  "JavaBuilder: Found binary delta for: " + p.getName()); // $NON-NLS-1$
            deltas.put(p, delta);
          }
        } else {
          if (DEBUG)
            System.out.println("JavaBuilder: Missing delta for: " + p.getName()); // $NON-NLS-1$
          this.notifier.subTask(""); // $NON-NLS-1$
          return null;
        }
      }
    }
    this.notifier.subTask(""); // $NON-NLS-1$
    return deltas;
  }
예제 #17
0
 /** @todo */
 protected void setBlockParametersForProcess(State state, Parameters blockParameters) {
   ServletRequest request = state.getRequest();
   for (Map.Entry<String, ?> entry : blockParameters.toMap().entrySet()) {
     request.setAttribute(entry.getKey(), entry.getValue());
   }
 }
예제 #18
0
 /**
  * Construct an NFA that will recognize a string matching this regular expression and then
  * transition to a state that will accept with the given integer code.
  */
 public State toNFA(int accept) {
   State s = new State(); // Build a new state
   s.accept = accept; // with specified accept code
   s.trans = new Transition[0]; // and no outgoing transitions.
   return this.toNFA(s); // Generate recognizer.
 }
예제 #19
0
  /**
   * Basic Framework implicitely also processes, i'm not sure if we should require any framework to
   * do that (perhaps we could say, that the render method must process, if that is necessary, and
   * not yet done).
   */
  @Override
  public void render(
      Renderer renderer,
      Parameters blockParameters,
      Parameters frameworkParameters,
      Writer w,
      WindowState windowState)
      throws FrameworkException {
    ServletRequest request = frameworkParameters.get(Parameter.REQUEST);
    if (request == null) {
      throw new IllegalArgumentException("No request object given");
    }

    State state = State.getState(request);
    if (state
        .isRendering()) { // mm:component used during rending of a component, that's fine, but use a
                          // new State.
      state = new State(request);
      log.debug("Alreadying rendering, taking a new state for sub-block-rendering: " + state);
    }

    log.debug("Rendering " + renderer.getBlock() + " " + renderer);
    Object prevHints = request.getAttribute(RenderHints.KEY);
    try {

      request.setAttribute(COMPONENT_CLASS_KEY, getComponentClass());
      request.setAttribute(COMPONENT_CURRENTUSER_KEY, getUserNode(frameworkParameters));

      Renderer actualRenderer = state.startBlock(frameworkParameters, renderer);
      if (!actualRenderer.equals(renderer)) {
        Parameters newBlockParameters = actualRenderer.getBlock().createParameters();
        newBlockParameters.setAllIfDefined(blockParameters);
        blockParameters = newBlockParameters;
      }
      state.setAction(request.getParameter(ACTION.getName()));
      if (state.needsProcess()) {
        log.service("Performing action on " + actualRenderer.getBlock());
        Processor processor = actualRenderer.getBlock().getProcessor();
        state.process(processor);
        log.service("Processing " + actualRenderer.getBlock() + " " + processor);
        setBlockParametersForProcess(state, blockParameters);
        processor.process(blockParameters);
        state.endProcess();
      }

      state.render(actualRenderer);

      setBlockParametersForRender(state, blockParameters);

      RenderHints hints =
          new RenderHints(
              actualRenderer,
              windowState,
              state.getId(),
              getComponentClass(),
              RenderHints.Mode.NORMAL);
      request.setAttribute(RenderHints.KEY, hints);
      actualRenderer.render(blockParameters, w, hints);
      request.setAttribute("org.mmbase.framework.hints", hints);
    } catch (FrameworkException fe) {
      log.debug(fe);
      URI uri = renderer.getUri();
      Renderer error =
          new ErrorRenderer(
              renderer.getType(),
              renderer.getBlock(),
              (uri != null) ? uri.toString() : null,
              500,
              fe);
      RenderHints hints =
          new RenderHints(
              error, windowState, state.getId(), getComponentClass(), RenderHints.Mode.NORMAL);
      error.render(blockParameters, w, hints);
    } finally {
      request.setAttribute(RenderHints.KEY, prevHints);
      state.endBlock();
    }
  }
예제 #20
0
 protected String getPrefix(final State state) {
   // return "_" + renderer.getBlock().getComponent().getName() + "_" +
   // renderer.getBlock().getName() + "_" + count + "_";
   return state.getId() + ":";
 }
예제 #21
0
파일: FileGen.java 프로젝트: asanian/GenNet
  public void treatmentGenStateGraph() {
    try {
      PrintWriter file = new PrintWriter(new FileWriter(destination));
      // We want color wells in red
      ArrayList<String> lesPuits = new ArrayList<String>();
      file.println("digraph G {");
      file.println();

      // Prepare a bubble giving all genes
      file.println("/* Order of genes */");
      file.print("/*$g*/" + "\"");
      for (int j = 0; j < autoGraphState.vGeneNames.size(); j++) {
        file.print(autoGraphState.vGeneNames.get(j));
        file.print(" ; ");
      }
      file.println("\"" + "/*$fg*/" + " [color=green,fontcolor=black];");
      file.println();

      // List potential and their position statements
      file.println("/* States and their transitions */");
      for (int j = 0; j < autoGraphState.vStates.size(); j++) {
        file.print("/*$e*/" + "\"");
        file.print(autoGraphState.vStates.get(j).getEtiquette());
        file.print("\"");
        // x et y
        file.print(
            "/*x:"
                + autoGraphState.vStates.get(j).getX()
                + ";y:"
                + autoGraphState.vStates.get(j).getY()
                + " $fe*/");
        file.println(";");
      }
      file.println();

      // Recherche des transitions

      /*
       * A faire : les clous !
       */

      file.println("/* Transitions */");
      for (int i = 0; i < autoGraphState.vTranStates.size(); i++) {
        TransState trans = (TransState) autoGraphState.vTranStates.get(i);

        file.print("/*$t*/" + "\"");
        for (int j = 0; j < autoGraphState.vStates.size(); j++) {
          State state = (State) autoGraphState.vStates.get(j);
          if (state.getNum() == trans.getNumInitialState()) {
            /*
             * L'�tiquette est de la forme "[0, 1, 2]"
             * On la veut sous la forme "0,1,2" dans le .gen
             */
            String labelGen = state.getEtiquette();
            labelGen = labelGen.replace("[", "");
            labelGen = labelGen.replace("]", "");
            labelGen = labelGen.replace(" ", "");
            file.print(labelGen);
          }
        }
        file.print("\"");

        file.print("->");

        file.print("\"");
        for (int j = 0; j < autoGraphState.vStates.size(); j++) {
          State state = (State) autoGraphState.vStates.get(j);
          if (state.getNum() == trans.getNumFinalState()) {
            /*
             * The label is of the form "[0, 1, 2]"
             * We want it in the form "0,1,2" in the .gen
             */
            String labelGen = state.getEtiquette();
            labelGen = labelGen.replace("[", "");
            labelGen = labelGen.replace("]", "");
            labelGen = labelGen.replace(" ", "");
            file.print(labelGen);

            if (state.couleurPuit.equals(Color.red)) {
              lesPuits.add("\"" + labelGen + "\"");
            }
          }
        }
        file.print("\"" + "/*$ft*/");
        file.println(";");
      }
      file.println();

      // Ecrire dans le .gen les puits, et dire qu'il faudra afficher leur police en rouge
      file.println("/* Stable states */");
      while (lesPuits.isEmpty() == false) {
        String lePuit = lesPuits.get(0);
        file.println("/*$p*/" + lePuit + "/*$fp*/" + " [fontcolor=red];");
        while (lesPuits.contains(lePuit)) {
          lesPuits.remove(lePuit);
        }
      }
      file.println();
      file.println("}");
      file.println("");
      file.println(autoGraphState.comment);
      file.println("");
      // uncomment
      file.println("$ed");
      file.println("gene x");
      file.println("equation : 2 + 3 * s(p,y,theta(x,x))  * s(n,x,theta(x,y)) ;");
      file.println("thetas : theta(x,x) < theta(x,y) ;");
      file.println("gene y");
      file.println("equation : 1 + 2 * s(p,y,theta(y,x)) ;");
      file.println("thetas : theta(y,x) ;");
      file.println("$fed");
      file.println("");

      /* Le systeme d'equation ci-dessous sert pour les tests
       * Il sera a supprimer
       */
      // fichier.println("$ed");
      // fichier.println("gene x");
      // fichier.println("equation : 2 + 3 * s(p,y,theta(x,x))  * s(n,x,theta(x,y)) ;");
      // fichier.println("thetas : theta(x,x) < theta(x,y) ;");
      // fichier.println("gene y");
      // fichier.println("equation : 1 + 2 * s(p,y,theta(y,x)) ;");
      // fichier.println("thetas : theta(y,x) ;");
      // fichier.println("$fed");
      // fichier.println("");

      file.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
        @Override
        public Counter<String> apply(Triple<State, Action, State> triple) {
          // Variables
          State from = triple.first;
          Action action = triple.second;
          State to = triple.third;
          String signature = action.signature();
          String edgeRelTaken = to.edge == null ? "root" : to.edge.getRelation().toString();
          String edgeRelShort = to.edge == null ? "root" : to.edge.getRelation().getShortName();
          if (edgeRelShort.contains("_")) {
            edgeRelShort = edgeRelShort.substring(0, edgeRelShort.indexOf("_"));
          }

          // -- Featurize --
          // Variables to aggregate
          boolean parentHasSubj = false;
          boolean parentHasObj = false;
          boolean childHasSubj = false;
          boolean childHasObj = false;
          Counter<String> feats = new ClassicCounter<>();

          // 1. edge taken
          feats.incrementCount(signature + "&edge:" + edgeRelTaken);
          feats.incrementCount(signature + "&edge_type:" + edgeRelShort);

          // 2. last edge taken
          if (from.edge == null) {
            assert to.edge == null || to.originalTree().getRoots().contains(to.edge.getGovernor());
            feats.incrementCount(signature + "&at_root");
            feats.incrementCount(
                signature + "&at_root&root_pos:" + to.originalTree().getFirstRoot().tag());
          } else {
            feats.incrementCount(signature + "&not_root");
            String lastRelShort = from.edge.getRelation().getShortName();
            if (lastRelShort.contains("_")) {
              lastRelShort = lastRelShort.substring(0, lastRelShort.indexOf("_"));
            }
            feats.incrementCount(signature + "&last_edge:" + lastRelShort);
          }

          if (to.edge != null) {
            // 3. other edges at parent
            for (SemanticGraphEdge parentNeighbor :
                from.originalTree().outgoingEdgeIterable(to.edge.getGovernor())) {
              if (parentNeighbor != to.edge) {
                String parentNeighborRel = parentNeighbor.getRelation().toString();
                if (parentNeighborRel.contains("subj")) {
                  parentHasSubj = true;
                }
                if (parentNeighborRel.contains("obj")) {
                  parentHasObj = true;
                }
                // (add feature)
                feats.incrementCount(signature + "&parent_neighbor:" + parentNeighborRel);
                feats.incrementCount(
                    signature
                        + "&edge_type:"
                        + edgeRelShort
                        + "&parent_neighbor:"
                        + parentNeighborRel);
              }
            }

            // 4. Other edges at child
            int childNeighborCount = 0;
            for (SemanticGraphEdge childNeighbor :
                from.originalTree().outgoingEdgeIterable(to.edge.getDependent())) {
              String childNeighborRel = childNeighbor.getRelation().toString();
              if (childNeighborRel.contains("subj")) {
                childHasSubj = true;
              }
              if (childNeighborRel.contains("obj")) {
                childHasObj = true;
              }
              childNeighborCount += 1;
              // (add feature)
              feats.incrementCount(signature + "&child_neighbor:" + childNeighborRel);
              feats.incrementCount(
                  signature + "&edge_type:" + edgeRelShort + "&child_neighbor:" + childNeighborRel);
            }
            // 4.1 Number of other edges at child
            feats.incrementCount(
                signature
                    + "&child_neighbor_count:"
                    + (childNeighborCount < 3 ? childNeighborCount : ">2"));
            feats.incrementCount(
                signature
                    + "&edge_type:"
                    + edgeRelShort
                    + "&child_neighbor_count:"
                    + (childNeighborCount < 3 ? childNeighborCount : ">2"));

            // 5. Subject/Object stats
            feats.incrementCount(signature + "&parent_neighbor_subj:" + parentHasSubj);
            feats.incrementCount(signature + "&parent_neighbor_obj:" + parentHasObj);
            feats.incrementCount(signature + "&child_neighbor_subj:" + childHasSubj);
            feats.incrementCount(signature + "&child_neighbor_obj:" + childHasObj);

            // 6. POS tag info
            feats.incrementCount(signature + "&parent_pos:" + to.edge.getGovernor().tag());
            feats.incrementCount(signature + "&child_pos:" + to.edge.getDependent().tag());
            feats.incrementCount(
                signature
                    + "&pos_signature:"
                    + to.edge.getGovernor().tag()
                    + "_"
                    + to.edge.getDependent().tag());
            feats.incrementCount(
                signature
                    + "&edge_type:"
                    + edgeRelShort
                    + "&pos_signature:"
                    + to.edge.getGovernor().tag()
                    + "_"
                    + to.edge.getDependent().tag());
          }
          return feats;
        }
예제 #23
0
 public static void writeState(Object state, DataOutputStream out) throws IOException {
   ((State) state).write(out);
 }