static int doTest(BufferedReader in, PrintWriter out, boolean writeNewFile) throws Exception {
    int errorCount = 0;

    String key = null;
    String expectedValue = null;
    String line = in.readLine();
    while (line != null) {
      if (line.startsWith("#") || line.length() == 0) {
        if (writeNewFile) out.println(line);
      } else {
        int index = line.indexOf("=");
        if (index == -1) {
          key = line;
          expectedValue = "";
        } else {
          key = line.substring(0, index);
          if (index + 1 == line.length()) expectedValue = "";
          else expectedValue = line.substring(index + 1);
        }
        if (!processLine(key, expectedValue, out, writeNewFile)) ++errorCount;
      }
      line = in.readLine();
    }
    return errorCount;
  }
예제 #2
0
파일: Chart.java 프로젝트: feihugis/NetCDF
  public Chart(String filename) {
    try {
      // Get Stock Symbol
      this.stockSymbol = filename.substring(0, filename.indexOf('.'));

      // Create time series
      TimeSeries open = new TimeSeries("Open Price", Day.class);
      TimeSeries close = new TimeSeries("Close Price", Day.class);
      TimeSeries high = new TimeSeries("High", Day.class);
      TimeSeries low = new TimeSeries("Low", Day.class);
      TimeSeries volume = new TimeSeries("Volume", Day.class);

      BufferedReader br = new BufferedReader(new FileReader(filename));
      String key = br.readLine();
      String line = br.readLine();
      while (line != null && !line.startsWith("<!--")) {
        StringTokenizer st = new StringTokenizer(line, ",", false);
        Day day = getDay(st.nextToken());
        double openValue = Double.parseDouble(st.nextToken());
        double highValue = Double.parseDouble(st.nextToken());
        double lowValue = Double.parseDouble(st.nextToken());
        double closeValue = Double.parseDouble(st.nextToken());
        long volumeValue = Long.parseLong(st.nextToken());

        // Add this value to our series'
        open.add(day, openValue);
        close.add(day, closeValue);
        high.add(day, highValue);
        low.add(day, lowValue);

        // Read the next day
        line = br.readLine();
      }

      // Build the datasets
      dataset.addSeries(open);
      dataset.addSeries(close);
      dataset.addSeries(low);
      dataset.addSeries(high);
      datasetOpenClose.addSeries(open);
      datasetOpenClose.addSeries(close);
      datasetHighLow.addSeries(high);
      datasetHighLow.addSeries(low);

      JFreeChart summaryChart = buildChart(dataset, "Summary", true);
      JFreeChart openCloseChart = buildChart(datasetOpenClose, "Open/Close Data", false);
      JFreeChart highLowChart = buildChart(datasetHighLow, "High/Low Data", true);
      JFreeChart highLowDifChart =
          buildDifferenceChart(datasetHighLow, "High/Low Difference Chart");

      // Create this panel
      this.setLayout(new GridLayout(2, 2));
      this.add(new ChartPanel(summaryChart));
      this.add(new ChartPanel(openCloseChart));
      this.add(new ChartPanel(highLowChart));
      this.add(new ChartPanel(highLowDifChart));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #3
0
  public static void main(String[] args) throws IOException {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(br.readLine());
    int a[] = new int[n];
    int c[] = new int[n];
    for (int i = 0; i < n; i++) {
      a[i] = Integer.parseInt(br.readLine());
    }

    for (int i = 0; i < n; i++) {
      c[i] = 1;
    }

    for (int j = 1; j < n; j++) {
      if (a[j] > a[j - 1]) c[j] = c[j - 1] + 1;
    }

    for (int k = n - 2; k >= 0; k--) {
      if (a[k] > a[k + 1]) c[k] = Math.max(c[k + 1] + 1, c[k]);
    }
    int count = 0;
    for (int i = 0; i < n; i++) {
      count += c[i];
    }

    System.out.println(count);
  }
예제 #4
0
  // **********************************************************************************
  //
  // Theoretically, you shouldn't have to alter anything below this point in this file
  //      unless you want to change the color of your agent
  //
  // **********************************************************************************
  public void getConnected(String args[]) {
    try {
      // initial connection
      int port = 3000 + Integer.parseInt(args[1]);
      s = new Socket(args[0], port);
      sout = new PrintWriter(s.getOutputStream(), true);
      sin = new BufferedReader(new InputStreamReader(s.getInputStream()));

      // read in the map of the world
      numNodes = Integer.parseInt(sin.readLine());
      int i, j;
      for (i = 0; i < numNodes; i++) {
        world[i] = new node();
        String[] buf = sin.readLine().split(" ");
        world[i].posx = Double.valueOf(buf[0]);
        world[i].posy = Double.valueOf(buf[1]);
        world[i].numLinks = Integer.parseInt(buf[2]);
        // System.out.println(world[i].posx + ", " + world[i].posy);
        for (j = 0; j < 4; j++) {
          if (j < world[i].numLinks) {
            world[i].links[j] = Integer.parseInt(buf[3 + j]);
            // System.out.println("Linked to: " + world[i].links[j]);
          } else world[i].links[j] = -1;
        }
      }
      currentNode = Integer.parseInt(sin.readLine());

      String myinfo =
          args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink
      // send the agents name and color
      sout.println(myinfo);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
예제 #5
0
  public Main() {
    try {
      BufferedReader in;
      in = new BufferedReader(new InputStreamReader(System.in)); // Used for CCC
      int numLights = Integer.parseInt(in.readLine());
      int[] states = new int[numLights];
      for (int i = 0; i < numLights; i++) {
        states[i] = Integer.parseInt(in.readLine());
      }
      ArrayDeque<Scenario> Q = new ArrayDeque<Scenario>();
      HashMap<String, Integer> dp = new HashMap<String, Integer>();

      int moves = 0;
      Q.addLast(new Scenario(states));
      while (!Q.isEmpty()) {
        int size = Q.size();
        for (int q = 0; q < size; q++) {
          Scenario temp = Q.removeFirst();
          if (isEmpty(temp.states)) {
            System.out.println(moves);
            return;
          } else {
            for (int i = 0; i < temp.states.length; i++) {
              if (temp.states[i] == 0) {
                int[] newArr = Arrays.copyOf(temp.states, temp.states.length);
                newArr[i] = 1;
                newArr = fixArray(newArr);
                String arr = "";
                for (int p = 0; p < newArr.length; p++) arr += newArr[p];
                if (dp.get(arr) == null) {
                  dp.put(arr, moves);
                  Q.addLast(new Scenario(newArr));
                } else {
                  int val = dp.get(arr);
                  if (val != 0 && moves < val) {
                    dp.put(arr, moves);
                    Q.addLast(new Scenario(newArr));
                  }
                }

                // outputArr(newArr);
              }
            }
          }
        }
        moves++;
      }

    } catch (IOException e) {
      System.out.println("IO: General");
    }
  }
예제 #6
0
  /**
   * @return the clipboard content as a String (DataFlavor.stringFlavor) Code snippet adapted from
   *     jEdit (Registers.java), http://www.jedit.org. Returns null if clipboard is empty.
   */
  public static String getClipboardStringContent(Clipboard clipboard) {
    // Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    try {
      String selection =
          (String) (clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor));
      if (selection == null) return null;

      boolean trailingEOL =
          (selection.endsWith("\n") || selection.endsWith(System.getProperty("line.separator")));

      // Some Java versions return the clipboard contents using the native line separator,
      // so have to convert it here , see jEdit's "registers.java"
      BufferedReader in = new BufferedReader(new StringReader(selection));
      StringBuffer buf = new StringBuffer();
      String line;
      while ((line = in.readLine()) != null) {
        buf.append(line);
        buf.append('\n');
      }
      // remove trailing \n
      if (!trailingEOL) buf.setLength(buf.length() - 1);
      return buf.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
예제 #7
0
  // trained data
  void trainedWeights() {

    weightUpdate.clear();

    try {

      String line;

      FileReader fileReader = new FileReader("WeightFile.txt");

      BufferedReader bufferedReader = new BufferedReader(fileReader);

      while ((line = bufferedReader.readLine()) != null) {

        String[] lineSplit = line.split(" ");

        weightUpdate.put(
            weightKey(Integer.parseInt(lineSplit[0]), Integer.parseInt(lineSplit[1])),
            Double.parseDouble(lineSplit[2]));
      }

      bufferedReader.close();

    } catch (FileNotFoundException ex) {
      System.out.println("File Reading Error");
    } catch (IOException ex) {

      System.out.println("Error reading to file ");
    }
  }
예제 #8
0
  public void getSavedLocations() {
    // System.out.println("inside getSavedLocations");				//CONSOLE * * * * * * * * * * * * *
    loc.clear(); // clear locations.  helps refresh the list when reprinting all the locations
    BufferedWriter f = null; // just in case file has not been created yet
    BufferedReader br = null;
    try {
      // attempt to open the locations file if it doesn't exist, create it
      f =
          new BufferedWriter(
              new FileWriter("savedLocations.txt", true)); // evaluated true if file does not exist
      br = new BufferedReader(new FileReader("savedLocations.txt"));

      String line; // each line is one index of the list
      loc.add("Saved Locations");
      // loop and read a line from the file as long as we don't get null
      while ((line = br.readLine()) != null)
        // add the read word to the wordList
        loc.add(line);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        // attempt the close the file

        br.close(); // close bufferedwriter
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
예제 #9
0
  public CryoBay reconnectServer(ORB o, ReconnectThread rct) {

    BufferedReader reader;
    File file;
    ORB orb;
    org.omg.CORBA.Object obj;

    orb = o;

    obj = null;
    cryoB = null;

    try {
      // instantiate ModuleAccessor
      file = new File("/vnmr/acqqueue/cryoBay.CORBAref");
      if (file.exists()) {
        reader = new BufferedReader(new FileReader(file));
        obj = orb.string_to_object(reader.readLine());
      }

      if (obj != null) {
        cryoB = CryoBayHelper.narrow(obj);
      }

      if (cryoB != null) {
        if (!(cryoB._non_existent())) {
          // System.out.println("reconnected!!!!");
          rct.reconnected = true;
        }
      }
    } catch (Exception e) {
      // System.out.println("Got error: " + e);
    }
    return cryoB;
  }
예제 #10
0
  // You shouldn't modify this function
  // This function gets an update from the server each time your car reaches a new node
  // The server supplies you with the following information:
  //      1. Reward/cost information: travelCost: the cost (measured in happiness units) you
  // incurred for traveling over the last link
  //                               payout: the number of happiness units you got for arriving at the
  // current node
  //                               tollCharge: the amount of toll charge you incurred for traveling
  // the latest link
  //      2. currentNode: the current node position your car is at in the world (value between 0-3)
  //      3. currentUtilitiesforVisitingNode [array of 4]: The number of happiness units you will
  // get in the future for arriving at each of the 4 nodes
  public boolean readStatusMessage() {
    try {
      //            System.out.println(sin.readLine());
      String[] buf = sin.readLine().split(" ");

      if (buf[0].equals("quit")) return false;

      travelCost = Double.valueOf(buf[1]);
      payout = Double.valueOf(buf[2]);
      tollCharge = Double.valueOf(buf[3]);
      System.out.println("Results: " + travelCost + " " + payout + " " + tollCharge);

      // parse my current position in the world
      String[] buf2 = sin.readLine().split(" ");
      currentNode = Integer.valueOf(buf2[1]);
      System.out.println("Position: " + currentNode);

      // parse my utilities for visiting each node
      String[] buf3 = sin.readLine().split(" ");
      int i;
      for (i = 0; i < numNodes; i++)
        currentUtilitiesforVisitingNodes[i] = Double.valueOf(buf3[i + 1]);
      System.out.println(
          "Utilities: "
              + currentUtilitiesforVisitingNodes[0]
              + " "
              + currentUtilitiesforVisitingNodes[1]
              + " "
              + currentUtilitiesforVisitingNodes[2]
              + " "
              + currentUtilitiesforVisitingNodes[3]);

      // parse linkState stuff
      String[] buf4 = sin.readLine().split(" ");
      aveOnLink = Double.valueOf(buf4[1]);
      capacity = Integer.parseInt(buf4[2]);
      System.out.println("linkState: " + aveOnLink + " " + capacity);
    } catch (IOException e) {
      System.out.println(e);
      return false;
    }

    return true;
  }
예제 #11
0
파일: Model.java 프로젝트: Jankish/GRAB
 private void extractInfo(File filename) {
   checkpoint = false;
   String line;
   try {
     ArrayList<String> order = new ArrayList<String>();
     BufferedReader input =
         new BufferedReader(new InputStreamReader(new FileInputStream(filename), "iso-8859-1"));
     while ((line = input.readLine()) != null) {
       if (line.equalsIgnoreCase("hämtas")) checkpoint = true;
       if (checkpoint) order.add(new String(line));
     }
     //	printList(order);
     int quant = Integer.parseInt(order.get(2));
     int rows = 9;
     int outer = (quant * rows);
     double price;
     double total;
     // DecimalFormat decimal = (DecimalFormat) format;
     Number number;
     for (int i = 4; i <= outer; i += 9) {
       Data d =
           new Data(
               order.get(i + 1),
               order.get(i + 3),
               order.get(i + 4),
               order.get(i + 5),
               order.get(i + 7));
       dataList.add(d);
       /*	try {
       System.out.println(order.get(i+5));
       number = format.parse(order.get(i+5));
       System.out.println("Number is " + number);
       price = number.doubleValue();
       System.out.println("Price is " + price);
       number = format.parse(order.get(i+7));
       total = number.doubleValue();
       Data d = new Data(order.get(i), Integer.parseInt(order.get(i+1)), Integer.parseInt(order.get(i+2)), order.get(i+3), order.get(i+4), price, total);
       dataList.add(d);
       } catch (ParseException numExcep) {
       numExcep.printStackTrace();
       System.exit(1);
       }
       **/
     }
     //	printDataList(dataList);
   } catch (FileNotFoundException found) {
     found.printStackTrace();
     System.exit(1);
   } catch (UnsupportedEncodingException encode) {
     encode.printStackTrace();
     System.exit(1);
   } catch (IOException ioexcep) {
     ioexcep.printStackTrace();
     System.exit(1);
   }
 }
  public List<MarketSnapshot> load(ProgressListener progressListener) throws JBookTraderException {
    String line = "";
    int lineSeparatorSize = System.getProperty("line.separator").length();
    long sizeRead = 0, lineNumber = 0;

    List<MarketSnapshot> snapshots = new ArrayList<MarketSnapshot>();

    try {
      while ((line = reader.readLine()) != null) {
        if (lineNumber % 50000 == 0) {
          progressListener.setProgress(sizeRead, fileSize, "Loading historical data file");
          if (progressListener.isCancelled()) {
            break;
          }
        }
        lineNumber++;
        sizeRead += line.length() + lineSeparatorSize;
        boolean isComment = line.startsWith("#");
        boolean isProperty = line.contains("=");
        boolean isBlankLine = (line.trim().length() == 0);
        boolean isMarketDepthLine = !(isComment || isProperty || isBlankLine);
        if (isMarketDepthLine) {
          MarketSnapshot marketSnapshot = toMarketDepth(line);
          if (filter == null || filter.contains(time)) {
            snapshots.add(marketSnapshot);
          }
          previousTime = time;
        } else if (isProperty) {
          if (line.startsWith("timeZone")) {
            setTimeZone(line);
          }
        }
      }

      if (sdf == null) {
        String msg = "Property " + "\"timeZone\"" + " is not defined in the data file." + LINE_SEP;
        throw new JBookTraderException(msg);
      }

    } catch (IOException ioe) {
      throw new JBookTraderException("Could not read data file");
    } catch (Exception e) {
      String errorMsg = "Problem parsing line #" + lineNumber + ": " + line + LINE_SEP;
      String description = e.getMessage();
      if (description == null) {
        description = e.toString();
      }
      errorMsg += description;
      throw new RuntimeException(errorMsg);
    }

    return snapshots;
  }
예제 #13
0
  public static void main(String[] args) throws IOException {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    int T = 0;
    int N = 0;
    int answer = 1;
    int temp = 0;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String s;
    s = in.readLine();
    while ((s = in.readLine()) != null && s.length() != 0) {
      temp = Integer.parseInt(s);
      for (int j = 0; j < temp / 2; j++) {
        answer = (int) (answer * 2 + 1);
      }

      if (temp % 2 != 0) {
        answer *= 2;
      }
      System.out.println(answer);
      answer = 1;
    }
  }
예제 #14
0
파일: STRQ.java 프로젝트: jmankhan/ACM
  public void solve() throws Exception {
    String str = in.readLine();
    int n = str.length();

    int t = Integer.parseInt(in.readLine());

    int[][] dp = new int[26][n];

    dp[str.charAt(0) - 'a'][0] = 1;

    for (int i = 1; i < n; i++) {
      for (int j = 0; j < 26; j++) {
        if (str.charAt(i) == 'a' + j) {
          dp[j][i] = dp[j][i - 1] + 1;
        } else {
          dp[j][i] = dp[j][i - 1];
        }
      }
    }

    while (t-- > 0) {
      st = new StringTokenizer(in.readLine());
      char a = st.nextToken().toCharArray()[0];
      char b = st.nextToken().toCharArray()[0];

      int l = parseInt(st.nextToken()) - 1;
      int r = parseInt(st.nextToken()) - 1;

      int ans = 0;
      for (int i = l; i <= r; i++) {
        if (str.charAt(i) == a) {
          ans += dp[b - 'a'][r] - dp[b - 'a'][i];
        }
      }

      out.println(ans);
    }
  }
 public static void main(String[] args) throws Exception {
   BufferedReader st = new BufferedReader(new InputStreamReader(System.in));
   StringTokenizer s;
   s = new StringTokenizer(st.readLine());
   int n = Integer.parseInt(s.nextToken());
   int r = Integer.parseInt(s.nextToken()) - 1;
   visited = new int[n];
   int i, a, b;
   for (i = 0; i < n; i++) {
     adjList.add(new ArrayList<Integer>());
   }
   for (i = 0; i < n - 1; i++) {
     s = new StringTokenizer(st.readLine());
     a = Integer.parseInt(s.nextToken());
     b = Integer.parseInt(s.nextToken());
     adjList.get(a - 1).add(b - 1);
     adjList.get(b - 1).add(a - 1);
     visited[a - 1] = 0;
     visited[b - 1] = 0;
   }
   dfs(r, 0);
   System.out.println(maxh + " " + minh);
 }
  public static void main(String[] args) {
    try {
      BufferedReader br = new BufferedReader(new FileReader(args[0]));
      int tIndex = 0;
      int pIndex = 0;

      // This will probably change soon (name and implementation)
      NgramParser tnp = new NgramParser(args[1]);

      ArrayList<String> triplet = tnp.getTriplet();
      ArrayList<String> polarity = tnp.getPolarity();

      FileWriter sw = new FileWriter(args[2]);
      String line = null;

      while (((line = br.readLine()) != null)
          && (tIndex < triplet.size())
          && (pIndex < polarity.size())) {
        if (line.matches("^[\\d]*:")) {
          // System.out.println(line);
          sw.write(line + "\n");
        } else {
          Scanner sc = new Scanner(line);
          String trip = sc.findInLine(Pattern.compile("[a-zA-Z]+#[a-z]+[#]?[0-9]*"));
          // if (trip != null && trip.equals(triplet.get(tIndex))) {
          System.out.println(trip);
          if (trip != null && !trip.toLowerCase().contains("no#cl")) {
            // System.out.println(triplet.get(tIndex) + ":" +polarity.get(pIndex));
            String pol = polarity.get(pIndex);
            sw.write(line + " " + pol + "\n");
            sc.close();
            tIndex++;
            pIndex++;
          } else {
            String pol = "neg";
            sw.write("no#a#1" + " " + pol + "\n");
            sc.close();
          }
        }

        // sw.flush();
      }

      sw.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #17
0
 /** Execute the system command 'cmd' and fill an ArrayList with the results. */
 public static ArrayList<String> executeSystemCommand(String cmd) {
   if (debug) System.out.println("cmd: " + cmd);
   ArrayList<String> list = new ArrayList<>();
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec(/*comSpec +*/ cmd).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (debug) System.out.println(line);
       list.add(line);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return list;
 }
예제 #18
0
  protected void load() throws IOException {

    BufferedReader is = new BufferedReader(new FileReader("ReminderService.txt"));
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy MM dd hh mm");
    String aLine;
    while ((aLine = is.readLine()) != null) {
      ParsePosition pp = new ParsePosition(0);
      Date date = formatter.parse(aLine, pp);
      if (date == null) {
        message("Invalid date in " + aLine);
        continue;
      }
      String mesg = aLine.substring(pp.getIndex());
      l.add(new Item(date, mesg));
    }
  }
예제 #19
0
 public static String ping(String address) {
   String reply = "Request timed out";
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec("ping " + address).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (line.trim().startsWith("Reply ")) {
         reply = line;
         break;
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return reply;
 }
예제 #20
0
 /**
  * Input a line of text
  */
 public static String input()
 {
   String result = "";
   try
   {
     result = input.readLine();
   }
   catch (IOException e)
   {
     // Shouldn't happen since we are using System.in!
     System.out.println("Problem with System.in or bug in this code!");
     System.exit(1);
   }
  // _validated = false;
   return result;
 }
예제 #21
0
  private static void readLinkFile(boolean isHighway) {
    System.out.println("read link file...");
    int debug = 0;
    try {
      FileInputStream fstream =
          new FileInputStream(root + "/" + (isHighway ? highwayLinkFile : arterialLinkFile));
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

      while ((strLine = br.readLine()) != null) {
        debug++;
        String[] nodes = strLine.split(";");
        int linkId = Integer.parseInt(nodes[0]);
        String allDir = nodes[1];
        String streetName = nodes[2];
        int funcClass = Integer.parseInt(nodes[3]);
        ArrayList<PairInfo> nodeList = getPairListFromStr(nodes[4]);
        int speedCat = Integer.parseInt(nodes[5]);
        String dirTravel = nodes[6];
        int startNode = Integer.parseInt(nodes[7]);
        int endNode = Integer.parseInt(nodes[8]);

        LinkInfo linkInfo =
            new LinkInfo(
                linkId,
                funcClass,
                streetName,
                startNode,
                endNode,
                nodeList,
                dirTravel,
                speedCat,
                allDir);

        if (isHighway) highwayLinkList.add(linkInfo);
        else arterialLinkList.add(linkInfo);

        if (debug % 100000 == 0) System.out.println("record " + debug + " finish!");
      }
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
      System.err.println("Error Code: " + debug);
    }
    System.out.println("read link file finish!");
  }
  /**
   * Gets the value of the specified environment variable.
   *
   * @param ses SSH session.
   * @param cmd environment variable name.
   * @return environment variable value.
   * @throws JSchException In case of SSH error.
   * @throws IOException If failed.
   */
  private String exec(Session ses, String cmd) throws JSchException, IOException {
    ChannelExec ch = null;

    try {
      ch = (ChannelExec) ses.openChannel("exec");

      ch.setCommand(cmd);

      ch.connect();

      try (BufferedReader reader = new BufferedReader(new InputStreamReader(ch.getInputStream()))) {
        return reader.readLine();
      }
    } finally {
      if (ch != null && ch.isConnected()) ch.disconnect();
    }
  }
예제 #23
0
 public static Properties getEnvironmentVariables() {
   synchronized (cygstartPath) {
     if (envVars != null) return envVars;
     envVars = new Properties();
     try (BufferedReader br =
         new BufferedReader(
             new InputStreamReader(RUNTIME.exec(comSpec + "env").getInputStream()))) {
       for (String line = null; (line = br.readLine()) != null; ) {
         // if (debug) System.out.println("getEnvironmentVariables(): line=" + line);
         int idx = line.indexOf('=');
         if (idx > 0) envVars.put(line.substring(0, idx), line.substring(idx + 1));
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
     return envVars;
   }
 }
예제 #24
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    PrintWriter out = response.getWriter();
    String location = URLDecoder.decode(request.getParameter("location"));
    String type = URLDecoder.decode(request.getParameter("type"));
    String unit = URLDecoder.decode(request.getParameter("unit"));
    String awsURL =
        "http://default-environment-ii9naedwp8.elasticbeanstalk.com/?location="
            + URLEncoder.encode(location)
            + "&type="
            + type
            + "&unit="
            + unit;
    // out.write(awsURL);
    String myurl = URLEncoder.encode(awsURL);
    // out.write("\n"+myurl);
    URL url = new URL(awsURL);
    URLConnection urlConnection = url.openConnection();

    InputStream awsResponse = urlConnection.getInputStream();
    InputStreamReader iSReader = new InputStreamReader(awsResponse);
    StringBuffer sb = new StringBuffer();
    String xmlLine;
    BufferedReader buf = new BufferedReader(iSReader);
    try {
      while ((xmlLine = buf.readLine()) != null) {
        sb.append(xmlLine);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    xmlLine = sb.toString();

    response.setContentType("application/json; charset=UTF-8");
    int indent = 6;
    try {
      JSONObject jsonObj = XML.toJSONObject(xmlLine);
      String json1 = jsonObj.toString(indent);
      out.write(json1);
    } catch (JSONException ex) {
      ex.printStackTrace();
    }
  }
예제 #25
0
  public ClientGui(ORB o) throws Exception {
    ShutdownFrame sf;
    BufferedReader reader;
    boolean modulePresent;
    File file;
    CryoThread update;

    orb = o;

    obj = null;
    cryoBay = null;

    // System.out.println("running test client.");

    // instantiate ModuleAccessor
    file = new File("/vnmr/acqqueue/cryoBay.CORBAref");
    if (file.exists()) {
      reader = new BufferedReader(new FileReader(file));
      obj = orb.string_to_object(reader.readLine());
    }

    if (obj == null) {
      throw new Exception("string_to_object is null: cryoBay.CORBAref");
    }

    // System.out.println("Got object.");

    cryoBay = CryoBayHelper.narrow(obj);

    if (cryoBay == null) {
      throw new Exception("cryoBay is null");
    }

    if (cryoBay._non_existent()) {
      throw new Exception("cryoBay is not running");
    }

    sf = new ShutdownFrame(cryoBay);
    update = new CryoThread(cryoBay, sf, this);
    sf.show();
    update.start();
  } /*end of constructor*/
예제 #26
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    int i, j;
    String amount = req.getParameter("amount");
    String from = req.getParameter("from");
    String to = req.getParameter("to");
    String ch = req.getParameter("choice");
    String answer, answer1, answer2, answer3;

    if ("INFO".equals(ch)) {
      Redirect_info newurl = (Redirect_info) getServletContext().getAttribute("redirect");
      res.sendRedirect(newurl.getUrl());
    } else {
      out.println("<html>");
      out.println("<title>Currency Converter</title>");
      String addr = "http://www.google.com/ig/calculator?hl=en&q=" + amount + from + "=?" + to;
      URL convert = new URL(addr);
      BufferedReader in = new BufferedReader(new InputStreamReader(convert.openStream()));
      answer = in.readLine();
      answer = new String(answer.getBytes("ISO-8859-1"), "ISO-8859-7");
      from = new String(from.getBytes("ISO-8859-1"), "ISO-8859-7");
      to = new String(to.getBytes("ISO-8859-1"), "ISO-8859-7");
      amount = new String(amount.getBytes("ISO-8859-1"), "ISO-8859-7");

      in.close();
      i = answer.indexOf('"');
      answer = answer.substring(i + 1);
      i = answer.indexOf('"');
      answer = answer.substring(i + 1);
      i = answer.indexOf('"');
      answer = answer.substring(i + 1);
      i = answer.indexOf('"');
      answer = answer.substring(0, i);
      out.println("<p ALIGN=CENTER>" + amount + " " + from + " == " + answer + "(" + to + ")</p>");
      out.println("</body>");
      out.println("</html>");
    }
  }
예제 #27
0
  /** Set this news object using the news specified by newsFile */
  public void setNews(String newsFile) throws IOException {
    Pattern pDocId = Pattern.compile("<DOC-ID>(.*)</DOC-ID>");
    Pattern pTitle = Pattern.compile("<TITLE>(.*)</TITLE>");
    Pattern pTimestamp = Pattern.compile("<TIMESTAMP>(.*)</TIMESTAMP>");
    Pattern pContent = Pattern.compile("<CONTENT>(.*)</CONTENT>");
    Matcher m = null;

    BufferedReader br = new BufferedReader(new FileReader(newsFile));

    String line = "";
    String news = "";
    while ((line = br.readLine()) != null) {
      news += line;
    }

    // get news metadata and content
    m = pDocId.matcher(news);
    if (m.find()) {
      this.docId = m.group(1);
    }

    m = pTitle.matcher(news);
    if (m.find()) {
      this.title = m.group(1);
    }

    m = pTimestamp.matcher(news);
    if (m.find()) {
      this.timestamp = m.group(1);
    }

    m = pContent.matcher(news);
    if (m.find()) {
      this.content = m.group(1);
    }
  }
예제 #28
0
  /** main method - entry point for the entire program */
  public static void main(String[] args)
      throws IOException // just let IOExceptions terminate the program
      {
    // initialize loan variables from constants
    final double principal = PRINCIPAL;
    final double rate = RATE / 100; // convert rate into decimal form
    final double numPayments = TERM * MONTHS_PER_YEAR;

    // create output and input objects
    final PrintStream out = System.out;
    final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    // display the header for this assignment
    out.println("Name            : David C. Gibbons   ");
    out.println("Assignment      : Workshop 3         ");
    out.println("-------------------------------------");

    // determine interest rate per month
    final double monthlyRate = (rate / MONTHS_PER_YEAR);

    // calculate monthly payment
    final double monthlyPayment =
        principal * (monthlyRate / (1 - Math.pow(1 + monthlyRate, -numPayments)));

    // fetch needed decimal formatters needed for output
    final DecimalFormat numberFmt = new DecimalFormat("#0");
    final DecimalFormat currencyFmt = new DecimalFormat("$0.00");
    final DecimalFormat percentFmt = new DecimalFormat("0.00 %");

    // display overall loan information
    out.println("Principal       : " + currencyFmt.format(principal));
    out.println("Interest Rate   : " + percentFmt.format(rate));
    out.println("# of payments   : " + numberFmt.format(numPayments));
    out.println("Monthly payment : " + currencyFmt.format(monthlyPayment));

    // wait for the user to continue and then display the
    // details of all the payments
    out.println();
    out.println("Hit Enter to list Payment Detail");
    in.readLine();

    // calculate the payment detail in yearly blocks
    double currentPrincipal = principal;
    for (int month = 0; month < numPayments; month++) {
      // display header to match the benchmark at the start of the year
      if (month == 0 || (month % MONTHS_PER_YEAR) == 0) {
        // display a pause prompt if this isn't the first year
        if (month > 0) {
          out.println();
          out.println(" Hit Enter to continue");
          in.readLine();
        }
        out.println();
        out.println("\tInterest  Principal     Principal");
        out.println("Months\tPayment   Payment       Balance");
        out.println();
      }

      // calculate this month's interest payment and then the
      // principal payment and remaining principal balance
      double interestPayment = rate / MONTHS_PER_YEAR * currentPrincipal;
      double principalPayment = monthlyPayment - interestPayment;

      // always get the absolute value of the current principal as
      // sometimes the final value of 0 can be -0.0
      currentPrincipal = Math.abs(currentPrincipal - principalPayment);

      // format the fields and display to match benchmark
      out.print(numberFmt.format(month + 1) + " \t");
      out.print(currencyFmt.format(interestPayment) + "\t  ");
      out.print(currencyFmt.format(principalPayment) + "\t");
      out.println(currencyFmt.format(currentPrincipal));
    }
  }
예제 #29
0
  public void run(String arg) {
    GenericDialog gd = new GenericDialog("Options");
    double sfreq = 20000.0;
    gd.addNumericField("Sampling Frequency?", sfreq, 1, 10, null);
    String[] psfchoice = {"3D Gaussian", "Gaus-Lorentz^2", "2D Gaussian"};
    gd.addChoice("PSF Type?", psfchoice, psfchoice[0]);
    String[] filetypechoice = {
      "Confocor 3 raw", "Short binary trajectory", "PlotWindow trajectory", "Ascii Text File"
    };
    gd.addChoice("File Type?", filetypechoice, filetypechoice[0]);
    boolean ch2green = true;
    gd.addCheckbox("Ch2 is green?", ch2green);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    sfreq = gd.getNextNumber();
    int psfflag = gd.getNextChoiceIndex();
    int fileflag = gd.getNextChoiceIndex();
    ch2green = gd.getNextBoolean();
    int nfiles = 0;
    Object[] histograms = null;
    int xmax = 0;
    int ymax = 0;
    String[] names = null;
    if (fileflag < 2) {
      jdataio ioclass = new jdataio();
      File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance());
      if (filearray.length == 0) {
        return;
      }
      String dir = filearray[0].getAbsolutePath();
      int sepindex = dir.lastIndexOf(File.separator);
      String newdir = dir.substring(0, sepindex + 1);
      OpenDialog.setDefaultDirectory(newdir);
      nfiles = filearray.length / 2;
      if (nfiles > 25) {
        nfiles = 25;
      }
      histograms = new Object[nfiles];
      names = organize_c3_files(filearray);
      for (int i = 0; i < nfiles; i++) {
        try {
          int length1 = (int) (((double) filearray[2 * i].length() - 128.0) / 4.0);
          int length2 = (int) (((double) filearray[2 * i + 1].length() - 128.0) / 4.0);
          int length3 = (int) (((double) filearray[2 * i].length()) / 2.0);
          int length4 = (int) (((double) filearray[2 * i + 1].length()) / 2.0);
          InputStream instream = new BufferedInputStream(new FileInputStream(filearray[2 * i]));
          InputStream instream2 =
              new BufferedInputStream(new FileInputStream(filearray[2 * i + 1]));
          if (fileflag == 0) {
            int[] pmdata = new int[length1];
            int[] pmdata2 = new int[length2];
            if (!ioclass.skipstreambytes(instream, 128)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.skipstreambytes(instream2, 128)) {
              showioerror();
              instream2.close();
              return;
            }
            if (!ioclass.readintelintfile(instream, length1, pmdata)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.readintelintfile(instream2, length2, pmdata2)) {
              showioerror();
              instream2.close();
              return;
            }
            if (ch2green) {
              histograms[i] = (new pmodeconvert()).pm2pch(pmdata2, pmdata, sfreq, 20000000);
            } else {
              histograms[i] = (new pmodeconvert()).pm2pch(pmdata, pmdata2, sfreq, 20000000);
            }
          } else {
            float[] tmdata = new float[length3];
            float[] tmdata2 = new float[length4];
            if (!ioclass.readintelshortfile(instream, length3, tmdata)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.readintelshortfile(instream2, length4, tmdata2)) {
              showioerror();
              instream2.close();
              return;
            }
            if (ch2green) {
              histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata2, tmdata);
            } else {
              histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata, tmdata2);
            }
          }
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
          instream.close();
          instream2.close();
        } catch (IOException e) {
          showioerror();
          return;
        }
      }
    } else {
      if (fileflag == 2) {
        ImageWindow iw = WindowManager.getCurrentWindow();
        float[][] trajectories = (float[][]) jutils.runPW4VoidMethod(iw, "getYValues");
        float[][] tempxvals = (float[][]) jutils.runPW4VoidMethod(iw, "getXValues");
        sfreq = 1.0 / ((double) tempxvals[0][1]);
        nfiles = trajectories.length / 2;
        if (nfiles > 25) {
          nfiles = 25;
        }
        names = new String[nfiles + 1];
        names[nfiles] = "avg";
        histograms = new Object[nfiles];
        for (int i = 0; i < nfiles; i++) {
          names[i] = "trajectory " + (i + 1);
          if (ch2green) {
            histograms[i] =
                (new pmodeconvert())
                    .create_2Dhistogram(trajectories[2 * i + 1], trajectories[2 * i]);
          } else {
            histograms[i] =
                (new pmodeconvert())
                    .create_2Dhistogram(trajectories[2 * i], trajectories[2 * i + 1]);
          }
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
        }
      } else {
        // here we read tab delimited lines from files
        jdataio ioclass = new jdataio();
        File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance());
        if (filearray.length == 0) {
          return;
        }
        String dir = filearray[0].getAbsolutePath();
        int sepindex = dir.lastIndexOf(File.separator);
        String newdir = dir.substring(0, sepindex + 1);
        OpenDialog.setDefaultDirectory(newdir);
        nfiles = filearray.length;
        if (nfiles > 25) {
          nfiles = 25;
        }
        histograms = new Object[nfiles];
        names = new String[nfiles + 1];
        names[nfiles] = "avg";
        for (int i = 0; i < nfiles; i++) {
          try {
            names[i] = filearray[i].getName();
            BufferedReader d = new BufferedReader(new FileReader(filearray[i]));
            String[] lines = new String[256];
            int counter = 0;
            do {
              lines[counter] = d.readLine();
              counter++;
            } while ((lines[counter - 1] != null && lines[counter - 1] != "") && counter < 256);
            int numcolumns = 0;
            for (int j = 0; j < counter - 1; j++) {
              int temp = getncolumns(lines[j]);
              if (temp > numcolumns) {
                numcolumns = temp;
              }
            }
            float[][] temphist2 = null;
            if (ch2green) {
              temphist2 = new float[numcolumns][counter - 1];
            } else {
              temphist2 = new float[counter - 1][numcolumns];
            }
            for (int k = 0; k < counter - 1; k++) {
              float[] temp = tab_delim2float(lines[k]);
              for (int j = 0; j < numcolumns; j++) {
                if (ch2green) {
                  temphist2[j][k] = temp[j];
                } else {
                  temphist2[k][j] = temp[j];
                }
              }
            }
            histograms[i] = temphist2;
            d.close();
          } catch (IOException e) {
            showioerror();
            return;
          }
        }
        for (int i = 0; i < nfiles; i++) {
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
        }
      }
    }
    // note that here x is green and y is red
    float[][][] pch = new float[nfiles][xmax][ymax];
    for (int i = 0; i < nfiles; i++) {
      for (int j = 0; j < ((float[][]) histograms[i]).length; j++) {
        for (int k = 0; k < ((float[][]) histograms[i])[j].length; k++) {
          pch[i][j][k] = ((float[][]) histograms[i])[j][k];
        }
      }
    }

    final PCH2DFitWindow cw = new PCH2DFitWindow();
    cw.init(names, pch, psfflag);

    final Frame f = new Frame("PCH 2D Analysis");
    f.setLocation(10, 10);
    f.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            f.dispose();
          }
        });

    f.add(cw);
    f.pack();
    f.setResizable(false);
    Insets ins = f.getInsets();
    cw.totalSize.height = PCH2DFitWindow.H + ins.bottom + ins.top + 65;
    cw.totalSize.width = PCH2DFitWindow.WR + ins.left + ins.right;
    f.setSize(cw.totalSize);
    f.setVisible(true);
    cw.requestFocus();
  }
예제 #30
0
  public boolean readSrecCode(String fName) {

    FileInputStream fis = null;

    srec = new short[SREC_MAX_LINES][PKT_PAYLOAD_SIZE];
    numLines = 1;
    numPkts = 0;

    try {
      BufferedReader dis =
          new BufferedReader(new InputStreamReader(fis = new FileInputStream(fName)));
      System.out.println("--------------------------------------------------");
      System.out.println("Reading file: " + fName);
      // WARNING
      int curByte = 0; // 16; // account for S0 line which is not parsed

      while (true) {
        char bline[] = dis.readLine().toUpperCase().toCharArray();
        if (bline[1] == '1') {
          numLines++;
          if (bline.length > SREC_MAX_LINE_LEN) {
            System.out.println("ERROR: SREC Read: Too many byes on line: " + numLines);
            return false;
          }
          // srec length
          int length =
              Integer.parseInt(Character.toString(bline[2]) + Character.toString(bline[3]), 16) - 3;

          // data
          for (int i = 0, j = 8; i < length; i++, j += 2) {
            if (curByte >= PKT_PAYLOAD_SIZE) {
              numPkts++;
              curByte = 0;
            }
            srec[numPkts][curByte++] =
                (short)
                    Integer.parseInt(
                        Character.toString(bline[j]) + Character.toString(bline[j + 1]), 16);
            imgSize++;
          }
        } else if (bline[1] == '2') {
          numLines++;
          if (bline.length > SREC_MAX_LINE_LEN) {
            System.out.println("ERROR: SREC Read: Too many byes on line: " + numLines);
            return false;
          }
          // srec length
          int length =
              Integer.parseInt(Character.toString(bline[2]) + Character.toString(bline[3]), 16) - 4;

          // data
          for (int i = 0, j = 10; i < length; i++, j += 2) {
            if (curByte >= PKT_PAYLOAD_SIZE) {
              numPkts++;
              curByte = 0;
            }
            srec[numPkts][curByte++] =
                (short)
                    Integer.parseInt(
                        Character.toString(bline[j]) + Character.toString(bline[j + 1]), 16);
            imgSize++;
          }
        }
      }
    } catch (FileNotFoundException e) {
      System.out.println("ERROR: (SREC Read) " + e);
      return false;
    } catch (Exception e) {
      numPgs = (short) (((imgSize - 1) / BYTES_PER_PAGE) + 1);
      System.out.println(
          "Read END: (Lines="
              + numLines
              + ",Pages="
              + numPgs
              + ",Pkts="
              + numPkts
              + ",Size="
              + imgSize
              + ")");
      System.out.println("--------------------------------------------------");
    }

    try {
      if (fis != null) fis.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return true;
  }