コード例 #1
1
ファイル: Util.java プロジェクト: subxiang/jdk-source-code
 /**
  * Given a string, return an array of tokens. The separator can be escaped with the '\' character.
  * The '\' character may also be escaped by the '\' character.
  *
  * @param s the string to tokenize.
  * @param separator the separator char.
  * @param maxTokens the maxmimum number of tokens returned. If the max is reached, the remaining
  *     part of s is appended to the end of the last token.
  * @return an array of tokens.
  */
 public static String[] tokenize(String s, char separator, int maxTokens) {
   List tokens = new ArrayList();
   StringBuilder token = new StringBuilder();
   boolean prevIsEscapeChar = false;
   for (int i = 0; i < s.length(); i += Character.charCount(i)) {
     int currentChar = s.codePointAt(i);
     if (prevIsEscapeChar) {
       // Case 1:  escaped character
       token.appendCodePoint(currentChar);
       prevIsEscapeChar = false;
     } else if (currentChar == separator && tokens.size() < maxTokens - 1) {
       // Case 2:  separator
       tokens.add(token.toString());
       token = new StringBuilder();
     } else if (currentChar == '\\') {
       // Case 3:  escape character
       prevIsEscapeChar = true;
     } else {
       // Case 4:  regular character
       token.appendCodePoint(currentChar);
     }
   }
   if (token.length() > 0) {
     tokens.add(token.toString());
   }
   return (String[]) tokens.toArray(new String[] {});
 }
コード例 #2
0
    public void write(final BufferedWriter w) {
      RW.writeln(w, "Module:" + myName);

      RW.writeln(w, "SourceProperties:");
      mySource.write(w);

      RW.writeln(w, "TestProperties:");
      myTest.write(w);

      RW.writeln(w, "Excludes:");
      RW.writeln(w, myExcludes, RW.fromString);

      RW.writeln(w, "Libraries:");
      RW.writeln(w, myLibraries);

      RW.writeln(w, "Dependencies:");

      final List<ClasspathItemWrapper> weakened = new ArrayList<ClasspathItemWrapper>();

      for (ClasspathItemWrapper cpiw : dependsOn(false)) {
        weakened.add(weaken(cpiw));
      }

      RW.writeln(w, weakened);

      weakened.clear();

      for (ClasspathItemWrapper cpiw : dependsOn(true)) {
        weakened.add(weaken(cpiw));
      }

      RW.writeln(w, weakened);
    }
コード例 #3
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);
  }
コード例 #4
0
ファイル: Graph.java プロジェクト: karthikrk1/IADSA
 /**
  * Constructor for Graph
  *
  * @param size : int - number of vertices
  */
 Graph(int size) {
   numNodes = size;
   verts = new ArrayList<>(size + 1);
   verts.add(0, null);
   // create an array of Vertex objects
   for (int i = 1; i <= size; i++) verts.add(i, new Vertex(i));
 }
コード例 #5
0
  static void logPlugins() {
    List<String> loadedBundled = new ArrayList<String>();
    List<String> disabled = new ArrayList<String>();
    List<String> loadedCustom = new ArrayList<String>();

    for (IdeaPluginDescriptor descriptor : ourPlugins) {
      final String version = descriptor.getVersion();
      String s = descriptor.getName() + (version != null ? " (" + version + ")" : "");
      if (descriptor.isEnabled()) {
        if (descriptor.isBundled() || SPECIAL_IDEA_PLUGIN.equals(descriptor.getName()))
          loadedBundled.add(s);
        else loadedCustom.add(s);
      } else {
        disabled.add(s);
      }
    }

    Collections.sort(loadedBundled);
    Collections.sort(loadedCustom);
    Collections.sort(disabled);

    getLogger().info("Loaded bundled plugins: " + StringUtil.join(loadedBundled, ", "));
    if (!loadedCustom.isEmpty()) {
      getLogger().info("Loaded custom plugins: " + StringUtil.join(loadedCustom, ", "));
    }
    if (!disabled.isEmpty()) {
      getLogger().info("Disabled plugins: " + StringUtil.join(disabled, ", "));
    }
  }
コード例 #6
0
  /** {@inheritDoc} */
  @SuppressWarnings("TypeMayBeWeakened")
  @Nullable
  private Collection<byte[]> marshalFieldsCollection(
      @Nullable Collection<Object> col, GridCacheContext<K, V> ctx) throws GridException {
    assert ctx != null;

    if (col == null) return null;

    Collection<List<Object>> col0 = new ArrayList<>(col.size());

    for (Object o : col) {
      List<GridIndexingEntity<?>> list = (List<GridIndexingEntity<?>>) o;
      List<Object> list0 = new ArrayList<>(list.size());

      for (GridIndexingEntity<?> ent : list) {
        if (ent.bytes() != null) list0.add(ent.bytes());
        else {
          if (ctx.deploymentEnabled()) prepareObject(ent.value(), ctx);

          list0.add(CU.marshal(ctx, ent.value()));
        }
      }

      col0.add(list0);
    }

    return marshalCollection(col0, ctx);
  }
コード例 #7
0
  public void unmarshal(DataInputStream dis) {
    super.unmarshal(dis);

    try {
      minefieldID.unmarshal(dis);
      requestingEntityID.unmarshal(dis);
      minefieldSequenceNumbeer = (int) dis.readUnsignedShort();
      requestID = (short) dis.readUnsignedByte();
      pduSequenceNumber = (short) dis.readUnsignedByte();
      numberOfPdus = (short) dis.readUnsignedByte();
      numberOfMinesInThisPdu = (short) dis.readUnsignedByte();
      numberOfSensorTypes = (short) dis.readUnsignedByte();
      pad2 = (short) dis.readUnsignedByte();
      dataFilter = dis.readInt();
      mineType.unmarshal(dis);
      for (int idx = 0; idx < numberOfSensorTypes; idx++) {
        TwoByteChunk anX = new TwoByteChunk();
        anX.unmarshal(dis);
        sensorTypes.add(anX);
      }

      pad3 = (short) dis.readUnsignedByte();
      for (int idx = 0; idx < numberOfMinesInThisPdu; idx++) {
        Vector3Float anX = new Vector3Float();
        anX.unmarshal(dis);
        mineLocation.add(anX);
      }

    } // end try
    catch (Exception e) {
      System.out.println(e);
    }
  } // end of unmarshal method
コード例 #8
0
ファイル: Compiler.java プロジェクト: CM-9xx/cm9xx
  static private List getCommandCompilerCPP(String avrBasePath,
    List includePaths, String sourceName, String objectName,
    Map<String, String> boardPreferences) {
    
    List baseCommandCompilerCPP = new ArrayList(Arrays.asList(new String[] {
      avrBasePath + "avr-g++",
      "-c", // compile, don't link
      "-g", // include debugging info (so errors include line numbers)
      "-Os", // optimize for size
      Preferences.getBoolean("build.verbose") ? "-Wall" : "-w", // show warnings if verbose
      "-fno-exceptions",
      "-ffunction-sections", // place each function in its own section
      "-fdata-sections",
      "-mmcu=" + boardPreferences.get("build.mcu"),
      "-DF_CPU=" + boardPreferences.get("build.f_cpu"),
      "-MMD", // output dependancy info
      "-DUSB_VID=" + boardPreferences.get("build.vid"),
      "-DUSB_PID=" + boardPreferences.get("build.pid"),      
      "-DARDUINO=" + Base.REVISION,
    }));

    for (int i = 0; i < includePaths.size(); i++) {
      baseCommandCompilerCPP.add("-I" + (String) includePaths.get(i));
    }

    baseCommandCompilerCPP.add(sourceName);
    baseCommandCompilerCPP.add("-o");
    baseCommandCompilerCPP.add(objectName);

    return baseCommandCompilerCPP;
  }
コード例 #9
0
 public static String[] generateFileNamesFromOptions(CommandLine cli) {
   String[] filenames = cli.getArgs();
   List<String> fileList = new ArrayList<String>(filenames.length);
   boolean errors = false;
   for (String filename : filenames) {
     if (filename.startsWith("@")) {
       try {
         BufferedReader br = new BufferedReader(new FileReader(filename.substring(1)));
         String file;
         while ((file = br.readLine()) != null) {
           fileList.add(file);
         }
       } catch (IOException ioe) {
         System.err.println("error: file not readable: " + filename.substring(1));
         errors = true;
       }
     } else {
       fileList.add(filename);
     }
   }
   if (errors) {
     return null;
   } else {
     return fileList.toArray(new String[fileList.size()]);
   }
 }
コード例 #10
0
ファイル: TestCase.java プロジェクト: jacovino/JFlex
 public void init(File testDir) {
   // get files to process
   List<InputOutput> temp = new ArrayList<InputOutput>();
   String name;
   for (String file : testDir.list()) {
     if (null != commonInputFile) {
       if (file.equals(testName + ".output")) {
         temp.add(new InputOutput((new File(testDir, testName)).toString(), true));
         commonInputFile = (new File(testDir, commonInputFile)).toString();
       }
     } else {
       if (file.endsWith(".input") && file.startsWith(testName + "-")) {
         name = file.substring(0, file.length() - 6);
         temp.add(
             new InputOutput(
                 (new File(testDir, name)).toString(),
                 new File(testDir, name + ".output").exists()));
       }
     }
   }
   // When a common input file is specified, but no output file exists, add
   // a single InputOutput for the common input file.
   if (null != commonInputFile && 0 == temp.size()) {
     temp.add(new InputOutput(null, false));
   }
   setInputOutput(temp);
   testPath = testDir;
 }
コード例 #11
0
  public static void reconstructHeaders(Iterable<NativeLibrary> libraries, PrintWriter out) {
    List<MemberRef> orphanMembers = new ArrayList<MemberRef>();
    Map<TypeRef, List<MemberRef>> membersByClass = new HashMap<TypeRef, List<MemberRef>>();
    for (NativeLibrary library : libraries) {
      for (Symbol symbol : library.getSymbols()) {
        MemberRef mr = symbol.getParsedRef();
        if (mr == null) continue;

        TypeRef et = mr.getEnclosingType();
        if (et == null) orphanMembers.add(mr);
        else {
          List<MemberRef> mrs = membersByClass.get(et);
          if (mrs == null) membersByClass.put(et, mrs = new ArrayList<MemberRef>());
          mrs.add(mr);
        }
      }
    }
    for (TypeRef tr : membersByClass.keySet()) out.println("class " + tr + ";");

    for (MemberRef mr : orphanMembers) out.println(mr + ";");

    for (Map.Entry<TypeRef, List<MemberRef>> e : membersByClass.entrySet()) {
      TypeRef tr = e.getKey();
      List<MemberRef> mrs = e.getValue();
      out.println("class " + tr + " \n{");
      for (MemberRef mr : mrs) {
        out.println("\t" + mr + ";");
      }
      out.println("}");
    }
  }
コード例 #12
0
ファイル: Tool.java プロジェクト: laiello/perseph
 public void sortGrammarFiles() throws IOException {
   // System.out.println("Grammar names "+getGrammarFileNames());
   Graph g = new Graph();
   List<String> missingFiles = new ArrayList<String>();
   for (String gfile : grammarFileNames) {
     try {
       GrammarSpelunker grammar = new GrammarSpelunker(inputDirectory, gfile);
       grammar.parse();
       String vocabName = grammar.getTokenVocab();
       String grammarName = grammar.getGrammarName();
       // Make all grammars depend on any tokenVocab options
       if (vocabName != null) g.addEdge(gfile, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION);
       // Make all generated tokens files depend on their grammars
       g.addEdge(grammarName + CodeGenerator.VOCAB_FILE_EXTENSION, gfile);
     } catch (FileNotFoundException fnfe) {
       ErrorManager.error(ErrorManager.MSG_CANNOT_OPEN_FILE, gfile);
       missingFiles.add(gfile);
     }
   }
   List<Object> sorted = g.sort();
   // System.out.println("sorted="+sorted);
   grammarFileNames.clear(); // wipe so we can give new ordered list
   for (int i = 0; i < sorted.size(); i++) {
     String f = (String) sorted.get(i);
     if (missingFiles.contains(f)) continue;
     if (!(f.endsWith(".g") || f.endsWith(".g3"))) continue;
     grammarFileNames.add(f);
   }
   // System.out.println("new grammars="+grammarFileNames);
 }
コード例 #13
0
ファイル: MemoryStudy.java プロジェクト: ePADD/muse
 public static List<ClueEvaluator> getDefaultEvals() {
   List<ClueEvaluator> evals = new ArrayList<>();
   // default tuned params
   evals.add(new ClueEvaluator.LengthEvaluator(new float[] {-100.0f, -20.0f, 0f}));
   evals.add(new ClueEvaluator.EmotionEvaluator(new float[] {20.0f, 10.0f, 20.0f}));
   evals.add(new ClueEvaluator.NamesEvaluator(new float[] {10.0f}));
   float[] params = new float[] {10.0f, 0.0f, 10.0f, 0.0f, 10f, 10f, 5f};
   List<String[]> lists = new ArrayList<>();
   lists.add(
       "flight, travel, city, town, visit, arrive, arriving, land, landing, reach, reaching, train, road, bus, college, theatre, restaurant, book, film, movie, play, song, writer, artist, author, singer, actor, school"
           .split("\\s*,\\s*"));
   lists.add(
       "from, to, in, at, as, by, inside, like, of, towards, toward, via, such as, called, named, name"
           .split("\\s*,\\s*"));
   lists.add(
       "absorb, accept, admit, affirm, analyze, appreciate, assume, convinced of, believe, consider, decide, dislike, doubt, dream, dream up, expect, fail, fall for, fancy, fathom, feature, feel, find, foresee, forget, forgive, gather, get the idea, get the picture, grasp, hate, have a hunch, have faith in, have no doubt, hypothesize, ignore, image, imagine, infer, invent, judge, keep the faith, lap up, leave, lose, maintain, make rough guess, misunderstand, neglect, notice, overlook, perceive, place, place confidence in, plan, plan for, ponder, predict, presume, put heads together, rack brains, realise, realize, reckon, recognize, regard, reject, rely on, remember, rest assured, sense, share, suppose, suspect, swear by, take at one's word, take for granted, trust, understand, vision, visualize, wonder"
           .split("\\s*,\\s*"));
   lists.add("he,she,i,me,you".split("\\s*,\\s*"));
   lists.add(
       "husband, wife, partner, spouse, sister-in-law, brother-in-law, mother-in-law, father-in-law, daughter-in-law, son-in-law, fiancé, fiancée, aunt, brother, cousin, daughter, parent, father, dad, grandparent, granddaughter, grandmother, grandfather, grandpa, grandma, grandchild, grandson, mother, mom, nephew, niece, sister, children, child, baby, son, stepdaughter, stepmother, stepson, uncle, boyfriend, girlfriend, batchmate, buddy, colleague, mentor, co-worker, family, flatmate, folks, house-mate, junior, senior, neighbour, neighbor, relative, roommate"
           .split("\\s*,\\s*"));
   lists.add(
       "happy, alive, understanding, playful, calm, confident, gay, courageous, peaceful, reliable, joyous, energetic, at ease, easy, lucky, liberated, comfortable, amazed, fortunate, optimistic, pleased, free, delighted, provocative, sympathetic, overjoyed, impulsive, clever, gleeful, surprised, satisfied, thankful, frisky, receptive, animated, quiet, accepting, festive, spirited, certain, ecstatic, thrilled, enjoy, enjoyed, relaxed,  satisfied, wonderful, serene, cheerful, bright, sunny, blessed, reassured, elated, jubilant, love, loving, loved, concerned, eager, impulsive, considerate, affected, keen, affectionate, fascinated, earnest, sensitive,  intrigued, intent, anxious, rebellious, devoted, inquisitive, inspired, unique, attracted, determined, dynamic, passionate, excited, tenacious, admiration, engrossed, enthusiastic, hardy, curious, bold, brave, sympathy, daring, optimistic, comforted, drawn, confident, hopeful, amazing, fantastic, wow"
           .split("\\s*,\\s*"));
   lists.add(
       "angry, depressed, sad, sadly, unfortunate, unfortunately, confused, irritated, lousy, upset, incapable, enraged, disappointed, doubtful, alone, hostile, discouraged, uncertain, paralyzed, insulting, ashamed, indecisive, fatigued, sore, powerless, perplexed, useless, annoyed, embarrassed, inferior, guilty, hesitant, vulnerable, hateful, dissatisfied, shy, unpleasant, miserable, stupefied, offensive, detestable, disillusioned, bitter, unbelieving, despair, aggressive, despicable, skeptical, frustrated, resentful, disgusting, distrustful, distressed, inflamed, abominable, misgiving, woeful, provoked, terrible, pathetic, incensed, tragic, infuriated, sulky, uneasy, pessimistic, tense, fuming, indignant, indifferent, afraid, hurt, fearful, tearful, dull, terrified, tormented, sorrowful, nonchalant, suspicious, deprived, pained, neutral, pained,  grief, alarmed, tortured, anguish, weary, panic, dejected, desolate, bored, nervous, rejected, desperate, preoccupied, scared, injured, worried, offended, unhappy, disinterested, frightened, afflicted, lonely, lifeless, timid, aching, grieved, shaky, victimized, mournful, restless, heartbroken, dismayed, doubtful, agonized, threatened, appalled, cowardly, humiliated, wronged, menaced, alienated, wary"
           .split("\\s*,\\s*"));
   return evals;
 }
コード例 #14
0
    public List<ClasspathItemWrapper> dependsOn(final boolean tests) {
      if (tests) {
        if (myTestDependsOn != null) {
          return myTestDependsOn;
        }
      } else if (myDependsOn != null) {
        return myDependsOn;
      }

      final List<ClasspathItemWrapper> result = new ArrayList<ClasspathItemWrapper>();

      for (ClasspathItem cpi : myModule.getClasspath(ClasspathKind.compile(tests))) {
        if (cpi instanceof Module) {
          result.add(getModule(((Module) cpi).getName()));
        } else if (cpi instanceof Library) {
          result.add(new LibraryWrapper((Library) cpi));
        } else {
          result.add(new GenericClasspathItemWrapper(cpi));
        }
      }

      if (tests) {
        myTestDependsOn = result;
      } else {
        myDependsOn = result;
      }

      return result;
    }
コード例 #15
0
ファイル: Walker.java プロジェクト: safdariqbal/soot
  public void outALookupswitchStatement(ALookupswitchStatement node) {
    List lookupValues = new ArrayList();
    List targets = new ArrayList();
    UnitBox defaultTarget = null;

    if (node.getCaseStmt() != null) {
      int size = node.getCaseStmt().size();

      for (int i = 0; i < size; i++) {
        Object valueTargetPair = mProductions.removeLast();
        if (valueTargetPair instanceof UnitBox) {
          if (defaultTarget != null)
            throw new RuntimeException("error: can't ;have more than 1 default stmt");

          defaultTarget = (UnitBox) valueTargetPair;
        } else {
          Object[] pair = (Object[]) valueTargetPair;

          lookupValues.add(0, pair[0]);
          targets.add(0, pair[1]);
        }
      }
    } else {
      throw new RuntimeException("error: switch stmt has no case stmts");
    }

    Value key = (Value) mProductions.removeLast();
    Unit switchStmt = Jimple.v().newLookupSwitchStmt(key, lookupValues, targets, defaultTarget);

    mProductions.addLast(switchStmt);
  }
コード例 #16
0
  public static List<Library> list(File folder) {
    List<Library> libraries = new ArrayList<Library>();
    List<File> librariesFolders = new ArrayList<File>();
    librariesFolders.addAll(discover(folder));

    for (File baseFolder : librariesFolders) {
      libraries.add(new Library(baseFolder));
    }

    // Support libraries inside of one level of subfolders? I believe this was
    // the compromise for supporting library groups, but probably a bad idea
    // because it's not compatible with the Manager.
    String[] folderNames = folder.list(junkFolderFilter);
    if (folderNames != null) {
      for (String subfolderName : folderNames) {
        File subfolder = new File(folder, subfolderName);

        if (!librariesFolders.contains(subfolder)) {
          List<File> discoveredLibFolders = discover(subfolder);
          for (File discoveredFolder : discoveredLibFolders) {
            libraries.add(new Library(discoveredFolder, subfolderName));
          }
        }
      }
    }
    return libraries;
  }
コード例 #17
0
  /**
   * Reads the file that specifies method calls that should be replaced by other method calls. The
   * file is of the form:
   *
   * <p>[regex] [orig-method-def] [new-method-name]
   *
   * <p>where the orig_method-def is of the form:
   *
   * <p>fully-qualified-method-name (args)
   *
   * <p>Blank lines and // comments are ignored. The orig-method-def is replaced by a call to
   * new-method-name with the same arguments in any classfile that matches the regular expressions.
   * All method names and argument types should be fully qualified.
   */
  public void read_map_file(File map_file) throws IOException {

    LineNumberReader lr = new LineNumberReader(new FileReader(map_file));
    MapFileError mfe = new MapFileError(lr, map_file);
    Pattern current_regex = null;
    Map<MethodDef, MethodInfo> map = new LinkedHashMap<MethodDef, MethodInfo>();
    for (String line = lr.readLine(); line != null; line = lr.readLine()) {
      line = line.replaceFirst("//.*$", "");
      if (line.trim().length() == 0) continue;
      if (line.startsWith(" ")) {
        if (current_regex == null)
          throw new IOException("No current class regex on line " + lr.getLineNumber());
        StrTok st = new StrTok(line, mfe);
        st.stok.wordChars('.', '.');
        MethodDef md = parse_method(st);
        String new_method = st.need_word();
        map.put(md, new MethodInfo(new_method));
      } else {
        if (current_regex != null) {
          MethodMapInfo mmi = new MethodMapInfo(current_regex, map);
          map_list.add(mmi);
          map = new LinkedHashMap<MethodDef, MethodInfo>();
        }
        current_regex = Pattern.compile(line);
      }
    }
    if (current_regex != null) {
      MethodMapInfo mmi = new MethodMapInfo(current_regex, map);
      map_list.add(mmi);
    }

    dump_map_list();
  }
コード例 #18
0
    public ProxiedMethod(Method method) {
      this.method = method;
      this.name = // method instanceof Constructor ? "<init>" :
          method.getName();
      this.owner = method.getDeclaringClass();

      StringBuffer jni_sig = new StringBuffer("("), c_sig = new StringBuffer();

      retCapitalized = jni_capitalized(method.getReturnType());
      String[] sigArg = c_signature(method.getReturnType(), "?");
      c_sig.append(retType = sigArg[0]).append(" ").append(name).append("(");
      int i = 0;
      for (Class c : method.getParameterTypes()) {
        jni_sig.append(jni_signature(c));
        if (i > 0) c_sig.append(", ");

        String argName = "arg" + (i + 1);
        sigArg = c_signature(c, argName);
        String argType = sigArg[0];

        argTypes.add(argType);
        argNames.add(argName);
        argValues.add(sigArg[1]);

        c_sig.append(argType).append(" ").append(argName);
        i++;
      }
      c_sig.append(")");
      jni_sig.append(")").append(jni_signature(method.getReturnType()));
      this.jni_signature = jni_sig.toString();
      this.c_signature = c_sig.toString();
    }
コード例 #19
0
ファイル: Solution.java プロジェクト: hustbill/java-code
  static String[] animate(int speed, String init) {
    List<List<Particle>> lists = new ArrayList<>();
    List<String> res = new ArrayList<>();

    for (int i = 0; i < init.length(); i++) {
      lists.add(new ArrayList<>());
      char c = init.charAt(i);
      if (c == 'R') {
        lists.get(i).add(new Particle(speed));
      } else if (c == 'L') {
        lists.get(i).add(new Particle(-speed));
      }
    }

    while (checkRemain(lists)) {
      res.add(convert(lists));
      lists = nextStep(lists);
    }
    res.add(convert(lists));
    String[] result = new String[res.size()];
    int index = 0;
    for (String s : res) {
      result[index++] = s;
    }
    return result;
  }
コード例 #20
0
ファイル: UtilTest.java プロジェクト: Sk464036801/JGroups
  public static void testWriteView() throws Exception {
    List<Address> members = new ArrayList<>();
    View v;
    Address a1 = Util.createRandomAddress();
    Address a2 = Util.createRandomAddress();
    Address a4 = Util.createRandomAddress();
    ViewId vid = new ViewId(a1, 12345);
    members.add(a1);
    members.add(a2);
    members.add(a4);
    v = new View(vid, members);

    ByteArrayOutputStream outstream = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(outstream);
    Util.writeGenericStreamable(v, dos);
    Util.writeStreamable(v, dos);
    dos.close();
    byte[] buf = outstream.toByteArray();
    ByteArrayInputStream instream = new ByteArrayInputStream(buf);
    DataInputStream dis = new DataInputStream(instream);
    View v2 = (View) Util.readGenericStreamable(dis);
    Assert.assertEquals(v, v2);
    v2 = (View) Util.readStreamable(View.class, dis);
    Assert.assertEquals(v, v2);
  }
コード例 #21
0
  /**
   * Unpacks a Pdu from the underlying data.
   *
   * @throws java.nio.BufferUnderflowException if buff is too small
   * @see java.nio.ByteBuffer
   * @param buff The ByteBuffer at the position to begin reading
   * @since ??
   */
  public void unmarshal(java.nio.ByteBuffer buff) {
    super.unmarshal(buff);

    minefieldID.unmarshal(buff);
    requestingEntityID.unmarshal(buff);
    minefieldSequenceNumbeer = (int) (buff.getShort() & 0xFFFF);
    requestID = (short) (buff.get() & 0xFF);
    pduSequenceNumber = (short) (buff.get() & 0xFF);
    numberOfPdus = (short) (buff.get() & 0xFF);
    numberOfMinesInThisPdu = (short) (buff.get() & 0xFF);
    numberOfSensorTypes = (short) (buff.get() & 0xFF);
    pad2 = (short) (buff.get() & 0xFF);
    dataFilter = buff.getInt();
    mineType.unmarshal(buff);
    for (int idx = 0; idx < numberOfSensorTypes; idx++) {
      TwoByteChunk anX = new TwoByteChunk();
      anX.unmarshal(buff);
      sensorTypes.add(anX);
    }

    pad3 = (short) (buff.get() & 0xFF);
    for (int idx = 0; idx < numberOfMinesInThisPdu; idx++) {
      Vector3Float anX = new Vector3Float();
      anX.unmarshal(buff);
      mineLocation.add(anX);
    }
  } // end of unmarshal method
コード例 #22
0
ファイル: UtilTest.java プロジェクト: Sk464036801/JGroups
  public static void testNewMembers() {
    final Address a = Util.createRandomAddress(),
        b = Util.createRandomAddress(),
        c = Util.createRandomAddress(),
        d = Util.createRandomAddress(),
        e = Util.createRandomAddress();
    List<Address> old = new ArrayList<>();
    List<Address> new_list = new ArrayList<>();

    old.add(a);
    old.add(b);
    old.add(c);
    new_list.add(b);
    new_list.add(a);
    new_list.add(c);
    new_list.add(d);
    new_list.add(e);

    System.out.println("old: " + old);
    System.out.println("new: " + new_list);

    List<Address> new_nodes = Util.newMembers(old, new_list);
    System.out.println("new_nodes = " + new_nodes);
    assert new_nodes.size() == 2 : "list should have d and e";
    assert new_nodes.contains(d);
    assert new_nodes.contains(e);
  }
コード例 #23
0
ファイル: MakeEngine.java プロジェクト: brianhks/tablesaw
  // ---------------------------------------------------------------------------
  private void printDependencies(String target, PrintWriter pw, int spacing)
      throws TablesawException {
    Rule tr = findTargetRule(target);
    String[] pre;

    for (int I = 0; I < spacing; I++) pw.print("\t");

    List<String> targetList = new ArrayList<String>();
    if (tr != null) {
      for (String name : tr.getDependNames()) {
        targetList.add(name);
      }

      for (Rule r : tr.getDependRules()) {
        if ((r.getName() != null) && (!r.getName().startsWith(NAMED_RULE_PREFIX))) {
          targetList.add(r.getName());
        } else {
          for (String t : r.getTargets()) {
            targetList.add(t);
          }
        }
      }
    }

    if (!m_printedDependencies.add(target) && (targetList.size() != 0)) {
      pw.println(target + "*");
      return;
    }

    pw.println(target);

    for (String t : targetList) printDependencies(t, pw, spacing + 1);
  }
コード例 #24
0
 @Override
 public synchronized List<Action> getActions() {
   List<Action> actions = new ArrayList<Action>();
   actions.add(new GitFeedAction());
   actions.add(new ClearCaseUCMFeedAction());
   return actions;
 }
コード例 #25
0
ファイル: Utils.java プロジェクト: Fastest/FastestMBT
  /**
   * This function obtains a list with the subexpressions of a given expressions
   *
   * @param expr The original expresion
   * @return the list with all the subexpressions
   */
  public static List<Expr> getListExpr(Expr expr) throws IllegalArgumentException {

    List<Expr> list = new ArrayList<Expr>();

    if (expr instanceof NumExpr) {
      list.add(expr);
    } else if (expr instanceof RefExpr) {
      RefExpr refExpr = (RefExpr) expr;
      String strRefExpr = refExpr.getZName().getWord();
      // The \emptyset expression will be ignored
      if (!strRefExpr.equals(UtilSymbols.emptySetSymbol())) list.add(expr);
    } else if (expr instanceof SetExpr) {
      list = ((SetExpr) expr).getZExprList();
    } else if (expr instanceof TupleExpr) {
      list = ((TupleExpr) expr).getZExprList();
    } else if (expr instanceof ApplExpr) {
      if (((ApplExpr) expr).getMixfix()) { // es una secuencia
        ZExprListImpl applList =
            (ZExprListImpl) ((SetExpr) (((ApplExpr) expr).getRightExpr())).getZExprList();
        for (int i = 0; i < applList.size(); i++) {
          Expr elem = (((TupleExpr) (applList.get(i))).getZExprList()).get(1);
          list.add(elem);
        }
      } else { // es un valor negativo
        list.add(expr);
      }
    } else {
      throw new IllegalArgumentException();
    }
    return list;
  }
コード例 #26
0
ファイル: FileUtil.java プロジェクト: AppChecker/core
  public static File[] listFileHandles(File dir, Boolean includeSubDirs) throws IOException {

    if (!dir.exists() || !dir.isDirectory()) {
      return new File[0];
    }

    FileFilter fileFilter =
        new FileFilter() {
          public boolean accept(File file) {
            return file.isDirectory();
          }
        };

    File[] subFolders = dir.listFiles(fileFilter);

    List<File> files = new ArrayList<File>();

    List<File> fileArray =
        new ArrayList<File>(
            FileUtils.listFiles(
                dir, TrueFileFilter.INSTANCE, includeSubDirs ? TrueFileFilter.INSTANCE : null));

    for (File file : fileArray) {
      if (file.isFile()) {
        if (includeSubDirs && containsParentFolder(file, subFolders)) {
          files.add(file);
        } else {
          files.add(file);
        }
      }
    }

    return (File[]) files.toArray(new File[0]);
  }
コード例 #27
0
 @NotNull
 public static IpnbFile parseIpnbFile(
     @NotNull final CharSequence fileText, @NotNull final VirtualFile virtualFile)
     throws IOException {
   final String path = virtualFile.getPath();
   IpnbFileRaw rawFile = gson.fromJson(fileText.toString(), IpnbFileRaw.class);
   if (rawFile == null) {
     int nbformat = isIpythonNewFormat(virtualFile) ? 4 : 3;
     return new IpnbFile(Collections.emptyMap(), nbformat, Lists.newArrayList(), path);
   }
   List<IpnbCell> cells = new ArrayList<IpnbCell>();
   final IpnbWorksheet[] worksheets = rawFile.worksheets;
   if (worksheets == null) {
     for (IpnbCellRaw rawCell : rawFile.cells) {
       cells.add(rawCell.createCell());
     }
   } else {
     for (IpnbWorksheet worksheet : worksheets) {
       final List<IpnbCellRaw> rawCells = worksheet.cells;
       for (IpnbCellRaw rawCell : rawCells) {
         cells.add(rawCell.createCell());
       }
     }
   }
   return new IpnbFile(rawFile.metadata, rawFile.nbformat, cells, path);
 }
コード例 #28
0
ファイル: FileUtil.java プロジェクト: AppChecker/core
  public static String[] listFiles(File dir, Boolean includeSubDirs) throws IOException {
    FileFilter fileFilter =
        new FileFilter() {
          public boolean accept(File file) {
            return file.isDirectory();
          }
        };
    File[] subFolders = dir.listFiles(fileFilter);

    List<String> files = new ArrayList<String>();

    List<File> fileArray =
        new ArrayList<File>(
            FileUtils.listFiles(
                dir, TrueFileFilter.INSTANCE, includeSubDirs ? TrueFileFilter.INSTANCE : null));

    for (File file : fileArray) {
      if (file.isFile()) {
        if (includeSubDirs && containsParentFolder(file, subFolders)) {
          files.add(file.getParentFile().getName() + File.separator + file.getName());
        } else {
          files.add(file.getName());
        }
      }
    }

    return (String[]) files.toArray(new String[0]);
  }
コード例 #29
0
ファイル: MoquiStart.java プロジェクト: emer3/moqui
 /** @see java.lang.ClassLoader#findResources(java.lang.String) */
 @Override
 public Enumeration<URL> findResources(String resourceName) throws IOException {
   String webInfResourceName = "WEB-INF/classes/" + resourceName;
   List<URL> urlList = new ArrayList<URL>();
   int jarFileListSize = jarFileList.size();
   for (int i = 0; i < jarFileListSize; i++) {
     JarFile jarFile = jarFileList.get(i);
     JarEntry jarEntry = jarFile.getJarEntry(resourceName);
     // to better support war format, look for the resourceName in the WEB-INF/classes directory
     if (loadWebInf && jarEntry == null) jarEntry = jarFile.getJarEntry(webInfResourceName);
     if (jarEntry != null) {
       try {
         String jarFileName = jarFile.getName();
         if (jarFileName.contains("\\")) jarFileName = jarFileName.replace('\\', '/');
         urlList.add(new URL("jar:file:" + jarFileName + "!/" + jarEntry));
       } catch (MalformedURLException e) {
         System.out.println(
             "Error making URL for ["
                 + resourceName
                 + "] in jar ["
                 + jarFile
                 + "] in war file ["
                 + outerFile
                 + "]: "
                 + e.toString());
       }
     }
   }
   // add all resources found in parent loader too
   Enumeration<URL> superResources = super.findResources(resourceName);
   while (superResources.hasMoreElements()) urlList.add(superResources.nextElement());
   return Collections.enumeration(urlList);
 }
コード例 #30
0
  // Deze method leest alle zalen in en bepaald hun capaciteit
  public void getRooms() {
    try {
      BufferedReader csvZaalGegevens =
          new BufferedReader(new FileReader("resources/zalen_roostering.csv"));
      String room;
      csvZaalGegevens.readLine();

      while ((room = csvZaalGegevens.readLine()) != null) {
        List<String> gegevensZaal = Arrays.asList(room.split(";"));
        String roomName = gegevensZaal.get(0);
        int capacity = Integer.parseInt(gegevensZaal.get(1));
        if (capacity > 100) {
          List<Activity> list = new ArrayList<>(25);
          for (int i = 0; i < 25; i++) {
            list.add(null);
          }
          Room newRoom = new Room(roomName, capacity, true, list);
          rooms.add(newRoom);
        } else {
          List<Activity> list = new ArrayList<>(2);
          for (int i = 0; i < 20; i++) {
            list.add(null);
          }
          Room newRoom = new Room(roomName, capacity, false, list);
          rooms.add(newRoom);
        }
      }
      csvZaalGegevens.close();
    } catch (IOException e) {
      System.out.println("File Read Error Rooms");
    }
  }