/**
   * Connects to the remote machine by establishing a tunnel through a HTTP proxy with Basic
   * authentication. It issues a CONNECT request and authenticates with the HTTP proxy with Basic
   * protocol.
   *
   * @param address remote machine to connect to
   * @return a TCP/IP socket connected to the remote machine
   * @throws IOException if an I/O error occurs during handshake (a network problem)
   */
  private Socket authenticateBasic(InetSocketAddress address, ConnectivitySettings cs)
      throws IOException {
    Socket proxy = new Socket(cs.getProxyHost(), cs.getProxyPort());
    BufferedReader r =
        new BufferedReader(
            new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream())));
    DataOutputStream dos = new DataOutputStream(proxy.getOutputStream());

    String username = cs.getProxyUsername() == null ? "" : cs.getProxyUsername();
    String password = cs.getProxyPassword() == null ? "" : String.valueOf(cs.getProxyPassword());
    String credentials = username + ":" + password;
    String basicCookie = Base64Encoder.encode(credentials.getBytes("US-ASCII"));

    dos.writeBytes("CONNECT ");
    dos.writeBytes(address.getHostName() + ":" + address.getPort());
    dos.writeBytes(" HTTP/1.0\r\n");
    dos.writeBytes("Connection: Keep-Alive\r\n");
    dos.writeBytes("Proxy-Authorization: Basic " + basicCookie + "\r\n");
    dos.writeBytes("\r\n");
    dos.flush();

    String line = r.readLine();
    if (sConnectionEstablishedPattern.matcher(line).find()) {
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
      }
      return proxy;
    }
    throw new IOException("Basic authentication failed: " + line);
  }
Пример #2
1
  public static void main(String arr[]) {
    ParseQuery pq = new ParseQuery();
    // DBSystem.readConfig("/tmp/config.txt");
    String configFilePath = arr[0];
    DBSystem.readConfig(configFilePath);
    // String query = "Select distinct * from countries where id=123 and code like 'jkl' group by
    // continent having code like 'antartic' order by name";
    String inputFile = arr[1];
    try {
      BufferedReader br = new BufferedReader(new FileReader(inputFile));
      String line;
      while ((line = br.readLine()) != null) {
        pq.queryType(line);
      }
    } catch (FileNotFoundException e) {
      System.out.println("Input file not found");
      // e.printStackTrace();
    } catch (IOException e) {
      System.out.println("I/O Exception");
      // e.printStackTrace();
    }

    //        /String query = "create table rtyui(name varchar, age int, rollno int)";

  }
Пример #3
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st;
    int cases = 1;
    while (true) {
      st = new StringTokenizer(in.readLine());
      n = Integer.parseInt(st.nextToken());
      m = Integer.parseInt(st.nextToken());
      if (n == 0 && m == 0) break;
      a = new int[n];
      b = new int[m];
      dp = new int[n + 1][m + 1];
      st = new StringTokenizer(in.readLine());
      for (int i = 0; i < n; i++) {
        a[i] = Integer.parseInt(st.nextToken());
        Arrays.fill(dp[i], -1);
      }
      Arrays.fill(dp[n], -1);
      st = new StringTokenizer(in.readLine());
      for (int i = 0; i < m; i++) b[i] = Integer.parseInt(st.nextToken());

      System.out.println("Twin Towers #" + cases);
      System.out.println("Number of Tiles : " + LCS(0, 0));
      System.out.println();
      cases++;
    }
    in.close();
    System.exit(0);
  }
Пример #4
0
  public String readFromFile(String fileName) {
    StringBuilder sb = new StringBuilder();
    try {
      if (exists(fileName) == false) { // todo - исправь это плиз, а то выебу DONE
        throw new FileNotFoundException();
      } else {

        File file = new File(String.valueOf(fileName));
        String s;

        try {
          BufferedReader bufferedReaderIn =
              new BufferedReader(new FileReader(file.getAbsoluteFile()));
          try {
            while ((s = bufferedReaderIn.readLine()) != null) {
              sb.append(s).append(" ");
            }
          } finally {
            bufferedReaderIn.close();
          }
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    } catch (FileNotFoundException e) {
      log.error("File not found");
    }

    return sb.toString();
  }
Пример #5
0
 /**
  * This assumes each line is of the form (number=value) and it adds each value in order of the
  * lines in the file
  *
  * @param file Which file to load
  * @return An index built out of the lines in the file
  */
 public static Index<String> loadFromFilename(String file) {
   Index<String> index = new HashIndex<String>();
   BufferedReader br = null;
   try {
     br = new BufferedReader(new FileReader(file));
     for (String line; (line = br.readLine()) != null; ) {
       int start = line.indexOf('=');
       if (start == -1 || start == line.length() - 1) {
         continue;
       }
       index.add(line.substring(start + 1));
     }
     br.close();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (br != null) {
       try {
         br.close();
       } catch (IOException ioe) {
         // forget it
       }
     }
   }
   return index;
 }
Пример #6
0
  public void processFile(String inputFileName) {

    try {
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(new FileInputStream(new File(inputFileName))));
      String[] headers = reader.readLine().split(SEPARATOR);

      for (String s : headers) {
        attrByValue.put(s, new HashSet<String>());
      }

      String line = null;
      while ((line = reader.readLine()) != null) {
        String[] columnValues = line.split(SEPARATOR);
        if (columnValues.length != headers.length) {
          System.err.println("There is a huge problem with data file");
        }

        for (int i = 0; i < columnValues.length; i++) {
          attrByValue.get(headers[i]).add(columnValues[i]);
        }
      }

      reader.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #7
0
  // прочитать весь json в строку
  private static String readAll() throws IOException {
    StringBuilder data = new StringBuilder();
    try {
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("GET");

      con.setDoInput(true);
      String s;
      try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
        while ((s = in.readLine()) != null) {
          data.append(s);
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc.");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot read from  server");
    }
    return data.toString();
  }
Пример #8
0
  public static void main(String args[]) throws IOException {

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    while (true) {

      String str = in.readLine();

      //     Scanner in = new Scanner(System.in);

      if (str == null) {
        break;
      } else {
        BigInteger num = new BigInteger(str);

        if (str.equals("0") || str.equals("1")) {
          System.out.println(str);
        } else {
          //        BigInteger num = new BigInteger(str);
          //
          // System.out.println(num.subtract(BigInteger.ONE).multiply(BigInteger.valueOf(2)));
          System.out.println(num.multiply(BigInteger.valueOf(2)).subtract(BigInteger.valueOf(2)));
        }
      }
    }
  }
Пример #9
0
  /** {@inheritDoc} */
  public String RPC(String Name, String Method, String[] Args) {
    // write to serial port and receive result
    String Response;
    String Arguments = "";
    if (Args != null) {
      int s = Args.length;
      for (int i = 0; i < s; i++) {
        Arguments = Arguments + " " + Args[i];
      }
    }
    try {
      to_mbed.println("/" + Name + "/" + Method + Arguments);
      mbedSerialPort.notifyOnDataAvailable(false);
    } catch (NullPointerException e) {

    }
    boolean valid = true;
    try {
      while (reader.ready() == false) {}
      ;
      do {
        Response = reader.readLine();

        if (Response.length() >= 1) {
          valid = Response.charAt(0) != '!';
        }
      } while (valid == false);
    } catch (IOException e) {
      System.err.println("IOException, error reading from port");
      Response = "error";
    }

    mbedSerialPort.notifyOnDataAvailable(true);
    return (Response);
  }
  private void parse(String filename) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
    StringBuffer sb = new StringBuffer();

    int j;
    while ((j = br.read()) != -1) {
      char next = (char) j;

      if (next >= 'A' && next <= 'z') {
        sb.append(next);
      }

      if (sb.length() == 4) {
        String qGram = sb.toString().toUpperCase();
        sb = new StringBuffer();

        int frequency = 0;

        if (map.containsKey(qGram)) {
          frequency = map.get(qGram);
        }

        frequency++;
        map.put(qGram, frequency);
      }
    }
    br.close();
  }
Пример #11
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    String line;
    StringTokenizer stk;
    while ((line = in.readLine()) != null) {
      stk = new StringTokenizer(line);
      int n = Integer.parseInt(stk.nextToken());
      int k = Integer.parseInt(stk.nextToken());
      int m = Integer.parseInt(stk.nextToken());

      long[][] dp = new long[n + 1][k + 1];

      dp[0][0] = 1;
      for (int i = 1; i <= n; ++i) // units
      for (int j = 1; j <= k; ++j) // bars
        for (int l = 1; l <= m && l <= i; ++l) // size of the next bar
          dp[i][j] += dp[i - l][j - 1];

      System.out.println(dp[n][k]);
    }

    in.close();
    System.exit(0);
  }
  /**
   * @param args
   * @throws IOException
   */
  public static void main(String args[]) throws IOException {

    // Enable Debugging
    System.setProperty("DEBUG", "1");

    // Instantiate the Test Controller
    new TestDeviceManagerProtocol();

    // ********************************************
    // Prompt to enter a command
    // ********************************************

    System.out.println("Type exit to quit");
    System.out.print("SYSTEM>");

    BufferedReader keyboardInput;
    keyboardInput = new BufferedReader(new InputStreamReader(System.in));
    String command = "";

    try {
      while (!command.equalsIgnoreCase("exit")) {
        command = keyboardInput.readLine();
        if (!command.equalsIgnoreCase("exit")) {
          System.out.print("\nSYSTEM>");
        }
      }
    } finally {
      System.out.println("\nDisconnecting from ProtocolFactory");
      try {
        ProtocolFactory.shutdown();
      } catch (Exception e) {
      }
      ;
    }
  }
Пример #13
0
  static void eliminarLugarFicheroLOC(Lugar lugar) {
    String fichero = lugar.getFicheroLOC();

    try {
      FileReader fr = new FileReader(fichero);
      BufferedReader br = new BufferedReader(fr);

      String linea;
      ArrayList lineas = new ArrayList();

      do {
        linea = br.readLine();
        if (linea != null) {
          if (!linea.substring(0, lugar.nombre.length()).equals(lugar.nombre)) lineas.add(linea);
        } else break;
      } while (true);
      br.close();
      fr.close();

      FileOutputStream fos = new FileOutputStream(fichero);
      PrintWriter pw = new PrintWriter(fos);

      for (int i = 0; i < lineas.size(); i++) pw.println((String) lineas.get(i));
      pw.flush();
      pw.close();
      fos.close();

    } catch (FileNotFoundException e) {
      System.err.println("error: eliminando " + e);

    } catch (IOException e) {
      System.err.println("error: eliminando 2 : " + e);
    }
  }
Пример #14
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);
    }
  }
Пример #15
0
 public static void main(String[] args) throws IOException {
   BufferedReader f = new BufferedReader(new FileReader("barn1.in"));
   out = new PrintWriter(new BufferedWriter(new FileWriter("barn1.out")));
   StringTokenizer nstr = new StringTokenizer(f.readLine());
   int m = Integer.parseInt(nstr.nextToken());
   int s = Integer.parseInt(nstr.nextToken());
   occupied = new ArrayList<ArrayList<Integer>>();
   occupied.add(new ArrayList<Integer>());
   for (int i = 0; i < s; i++) {
     try {
       nstr = new StringTokenizer(f.readLine());
       occupied.get(0).add(Integer.parseInt(nstr.nextToken()));
     } catch (NullPointerException e) {
       break;
     }
   }
   Collections.sort(occupied.get(0));
   int bound = m - 1;
   if (occupied.get(0).size() - 1 < bound) {
     bound = occupied.get(0).size() - 1;
   }
   for (int i = 0; i < bound; i++) {
     findMaxCut();
   }
   int total = 0;
   int len = occupied.size();
   for (int i = 0; i < len; i++) {
     ArrayList<Integer> arr = occupied.get(i);
     int len2 = arr.size();
     total += arr.get(len2 - 1) - arr.get(0) + 1;
   }
   out.println(total);
   out.close();
   System.exit(0);
 }
Пример #16
0
  /**
   * ************************************************************************* loadHashFromFile -
   * loads a hastable from a file the format of the file is inflected_word base_form with a space
   * between both words ************************************************************************
   */
  private HashMap<String, ArrayList<String>> loadHashFromFile(String filename) {
    HashMap<String, ArrayList<String>> hashtable = new HashMap<String, ArrayList<String>>();

    try {
      BufferedReader br = new BufferedReader(new FileReader(filename));
      StringTokenizer st;

      for (; ; ) {

        String line = br.readLine();

        if (line == null) {
          br.close();
          break;
        } else {
          st = new StringTokenizer(line, " ");
          ArrayList<String> baseList = new ArrayList<String>();
          String inflected = st.nextToken();
          while (st.hasMoreTokens()) {
            baseList.add(st.nextToken());
          }
          hashtable.put(inflected, baseList);
        }
      }
    } catch (Exception e) {
      // System.out.println(line);
      System.out.println("Error:" + e);
    }

    return hashtable;
  }
Пример #17
0
  static void writeNewData(String datafile) {

    try {
      BufferedReader bufr = new BufferedReader(new FileReader(datafile));
      BufferedWriter bufw = new BufferedWriter(new FileWriter(datafile + ".nzf"));

      String line;
      String[] tokens;

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

        tokens = line.split(" ");
        bufw.write(tokens[0]);
        for (int i = 1; i < tokens.length; i++) {

          Integer index = Integer.valueOf(tokens[i].split(":")[0]);
          if (nnzFeas.contains(index)) {
            bufw.write(" " + tokens[i]);
          }
        }
        bufw.newLine();
      }
      bufw.close();
      bufr.close();

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }
  }
Пример #18
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner ler = new Scanner(System.in);
    System.out.printf("informe o nome do arquivo de texto: \n");
    String nome = ler.nextLine();
    System.out.printf("\nconteudo do arquivo texto");

    try {
      FileReader arq = new FileReader(nome);
      BufferedReader lerArq = new BufferedReader(arq);
      String linha = lerArq.readLine();

      while (linha != null) {
        System.out.printf("%s\n", linha);
        linha = lerArq.readLine();

        String val1 = linha.substring(0, linha.indexOf(','));
        int a = Integer.parseInt(val1);
        String val2 = linha.substring(linha.indexOf(',') + 1, linha.lastIndexOf(','));
        int b = Integer.parseInt(val2);
        String val3 = linha.substring(linha.lastIndexOf(',') + 1, linha.length());
        int c = Integer.parseInt(val3);
        setValida(new ValidaTriangulo(a, b, c));
      }
      arq.close();
    } catch (IOException e) {
      System.out.printf("erra na abertura do arquivo: %s.n", e.getMessage());
    }
    System.out.println();
  }
Пример #19
0
    protected void buildPanel(String strPath) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      String strLine;

      if (reader == null) return;

      try {
        while ((strLine = reader.readLine()) != null) {
          if (strLine.startsWith("#") || strLine.startsWith("%") || strLine.startsWith("@"))
            continue;

          StringTokenizer sTokLine = new StringTokenizer(strLine, ":");

          // first token is the label e.g. Password Length
          if (sTokLine.hasMoreTokens()) {
            createLabel(sTokLine.nextToken(), this);
          }

          // second token is the value
          String strValue = sTokLine.hasMoreTokens() ? sTokLine.nextToken() : "";
          if (strValue.equalsIgnoreCase("yes") || strValue.equalsIgnoreCase("no"))
            createChkBox(strValue, this);
          else createTxf(strValue, this);
        }
      } catch (Exception e) {
        Messages.writeStackTrace(e);
        // e.printStackTrace();
        Messages.postDebug(e.toString());
      }
    }
Пример #20
0
  /**
   * Generate license plates from a file.
   *
   * @param filename
   */
  private void generateLicensePlates(String filename) {
    File licenseplatefile = getResourceFile(filename);
    BufferedReader in = null;
    try {
      in = new BufferedReader(new InputStreamReader(new FileInputStream(licenseplatefile)));
    } catch (FileNotFoundException ex) {
      Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<String> licensePlates = new ArrayList();
    String line;

    try {
      while ((line = in.readLine()) != null) {
        licensePlates.add(line);
      }
    } catch (IOException ex) {
      Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        in.close();
      } catch (IOException ex) {
        Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    itLicensePlates = licensePlates.iterator();
  }
Пример #21
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);
  }
Пример #22
0
  public static void main(String[] args) throws IOException {
    BufferedReader f = new BufferedReader(new FileReader("beads.in"));
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("beads.out")));
    int n = Integer.parseInt(f.readLine());
    String s = f.readLine();
    int max = Integer.MIN_VALUE;

    for (int i = 0; i < n; i++) {
      String straight = s.substring(i + 1) + s.substring(0, i + 1);
      char[] beads = straight.toCharArray();
      int temp = 0;
      char color = ' ';
      for (int j = 0; j < n; j++) {
        char currColor = beads[j];
        if (color == ' ' && currColor != 'w') color = currColor;
        if (currColor == color || currColor == 'w') temp++;
        else break;
      }

      color = ' ';
      for (int j = n - 1; j > -1; j--) {
        char currColor = beads[j];
        if (color == ' ' && currColor != 'w') color = currColor;
        if (currColor == color || currColor == 'w') temp++;
        else break;
      }
      max = Math.max(temp, max);
    }
    if (max > n) max = n;
    out.println(max);
    out.close();
    System.exit(0);
  }
Пример #23
0
  public static void main(String[] args) throws IOException, FileNotFoundException {
    FileReader file = new FileReader("chalice.in");
    BufferedReader reader = new BufferedReader(file);

    int cases =
        Integer.parseInt(reader.readLine()); // Input the number of cases and store it in cases
    for (int i = 0; i < cases; i++) { // Loop through all the cases
      int weight =
          Integer.parseInt(
              reader.readLine()); // Input the weight of the accused and store it in weight

      int geese =
          Integer.parseInt(reader.readLine()); // Input the number of geese and store it in geese
      int sum = 0; // Stores the total weight of the flock of geese
      StringTokenizer tokens =
          new StringTokenizer(
              reader.readLine()); // Read in the line with the weight of the geese and tokenize it
      for (int j = 0; j < geese; j++) { // Loop through all the geese
        sum +=
            Integer.parseInt(
                tokens.nextToken()); // Add the weight of one goose to the weight of the flock
      }

      System.out.print("Trial #" + (i + 1) + ": "); // Output trial number

      // Based on weight comparison output whether she is or isn't a witch
      if (weight <= sum) System.out.println("SHE'S A WITCH! BURN HER!");
      else System.out.println("She's not a witch. BURN HER ANYWAY!");
    }
  }
Пример #24
0
  public void run() {
    System.out.println("New Communication Thread Started");

    try {
      PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      String inputLine;
      String[] inputTemp = new String[3];

      while ((inputLine = in.readLine()) != null) {
        System.out.println("Server: " + inputLine);

        out.println(inputLine);

        if (inputLine.equals("Bye.")) break;
      }

      out.close();
      in.close();
      clientSocket.close();
    } catch (IOException e) {
      System.err.println("Problem with Communication Server");
      System.exit(1);
    }
  }
Пример #25
0
  private void readProblemInfo(String pathName) {
    ProblemManager problemManager = new ProblemManager();
    File file = new File(pathName);
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
      String line;
      while ((line = br.readLine()) != null) {
        String[] sp = line.split(",");
        String input = MyUtil.readFromFile(new File(sp[1]));
        String output = MyUtil.readFromFile(new File(sp[2]));
        int timeLimit = Integer.valueOf(sp[3]);
        int memoryLimit = Integer.valueOf(sp[4]);
        String judgeMethod = "";
        if (sp.length == 6) judgeMethod = MyUtil.readFromFile(new File(sp[5]));

        Map<String, String> pinfo = new HashMap<String, String>();
        this.problems.put(sp[0], new ProblemInfo(sp[0], timeLimit, memoryLimit, 0));
        pinfo.put("problem_id", sp[0]);
        pinfo.put("time_limit", String.valueOf(timeLimit));
        pinfo.put("memory_limit", String.valueOf(memoryLimit));
        pinfo.put("special_judge", judgeMethod);
        pinfo.put("input", input);
        pinfo.put("output", output);
        pinfo.put("time_stamp", "0");
        problemManager.addEntry(pinfo);
      }
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Пример #26
0
 public Program compileFile(String fileName) {
   String code = "";
   String dummy;
   try {
     long ms = System.currentTimeMillis();
     long atAll = ms;
     BufferedReader r;
     if (fileName.compareToIgnoreCase("stdin") == 0) {
       owner.writeLn("Please type in your Prolog program. EOF is indicated by \"#\".");
       r = new BufferedReader(new InputStreamReader(System.in));
     } else r = new BufferedReader(new FileReader(fileName));
     do {
       dummy = r.readLine();
       if (dummy != null) {
         if (dummy.compareTo("#") == 0) break;
         code += " " + dummy;
       }
     } while (dummy != null);
     owner.debug("File Operations: " + (System.currentTimeMillis() - ms) + " ms.", -1);
     Program p = compile(code);
     return p;
   } catch (Exception io) {
     owner.writeLn("File \"" + fileName + "\" could not be opened.");
     return null;
   }
 } // end of PrologCompiler.compileFile(String)
  public static void main(String[] args) throws Exception {

    /*  BufferedReader br=new BufferedReader(new FileReader("input.txt"));
        BufferedWriter out=new BufferedWriter(new FileWriter("output.txt"));
    */
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 2000);
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out), 2000);
    String[] s = br.readLine().split(" ");
    int n = Integer.parseInt(s[0]);
    int q = Integer.parseInt(s[1]);
    int num[] = new int[n + 1];
    int[] m = new int[3 * n + 1]; // size = 2*n+1
    Arrays.fill(num, -1);
    s = br.readLine().split(" ");
    for (int i = 1; i <= n; i++) num[i] = Integer.parseInt(s[i - 1]);
    /// build tree
    maketree(1, 1, n, m, num);

    for (int qq = 1; qq <= q; qq++) {
      s = br.readLine().split(" ");
      int i = Integer.parseInt(s[0]);
      int j = Integer.parseInt(s[1]);
      int ans = query(1, 1, n, m, num, i, j);
      out.write("" + num[ans] + "\n");
      out.flush();
    }
  }
Пример #28
0
  public boolean shutdown(int port, boolean ssl) {
    try {
      String protocol = "http" + (ssl ? "s" : "");
      URL url = new URL(protocol, "127.0.0.1", port, "shutdown");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("servicemanager", "shutdown");
      conn.connect();

      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      int n;
      char[] cbuf = new char[1024];
      while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n);
      br.close();
      String message = sb.toString().replace("<br>", "\n");
      if (message.contains("Goodbye")) {
        cp.appendln("Shutting down the server:");
        String[] lines = message.split("\n");
        for (String line : lines) {
          cp.append("...");
          cp.appendln(line);
        }
        return true;
      }
    } catch (Exception ex) {
    }
    cp.appendln("Unable to shutdown CTP");
    return false;
  }
  private boolean handshake() throws Exception {
    URL homePage = new URL("http://mangaonweb.com/viewer.do?ctsn=" + ctsn);

    HttpURLConnection urlConn = (HttpURLConnection) homePage.openConnection();
    urlConn.connect();
    if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) return (false);

    // save the cookie
    String headerName = null;
    for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) {
      if (headerName.equals("Set-Cookie")) {
        cookies = urlConn.getHeaderField(i);
      }
    }

    // save cdn and crcod
    String page = "", line;
    BufferedReader stream =
        new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
    while ((line = stream.readLine()) != null) page += line;

    cdn = param(page, "cdn");
    crcod = param(page, "crcod");

    return (true);
  }
Пример #30
0
 /**
  * read AIMLIF categories from a file into bot brain
  *
  * @param filename name of AIMLIF file
  * @return array list of categories read
  */
 public ArrayList<Category> readIFCategories(String filename) {
   ArrayList<Category> categories = new ArrayList<Category>();
   try {
     // Open the file that is the first
     // command line parameter
     FileInputStream fstream = new FileInputStream(filename);
     // Get the object
     BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
     String strLine;
     // Read File Line By Line
     while ((strLine = br.readLine()) != null) {
       try {
         Category c = Category.IFToCategory(strLine);
         categories.add(c);
       } catch (Exception ex) {
         System.out.println("Invalid AIMLIF in " + filename + " line " + strLine);
       }
     }
     // Close the input stream
     br.close();
   } catch (Exception e) { // Catch exception if any
     System.err.println("Error: " + e.getMessage());
   }
   return categories;
 }