text
stringlengths
14
410k
label
int32
0
9
public String generate() { String error = "No errors."; if (details) System.out.println("Temperature flags: PRODUCE="+ioflags.PRODUCE+", SAVE="+ioflags.SAVE+", LOAD="+ioflags.LOAD); if (Utils.flagsCheck(ioflags) != 0) { System.out.println("ERROR: IOFlags object is corrupted, error: "+Utils.flagsCheck(ioflags)); return "TemperatureGenerator critical error - read above."; } if (ioflags.PRODUCE) produceTemperature(); if (ioflags.LOAD) error = loadTemperature(); return error; }
4
public void doHit() { if (goinUp < 20) { setY(getY() - 5); } else if (goinUp < 40) { setY(getY() + 5); } goinUp++; }
2
public static void main(String[]args) { int limit = 100; int n = 2; ArrayList<Integer> primes = new ArrayList<Integer>(); for(int i = 2; i <= limit ; i++) { System.out.println("i is " + i); boolean isNotPrime = true; while(isNotPrime) { for(int j = 2; j < i; j++) { if(i % j == 0) { isNotPrime = true; } } if(i == 2) { isNotPrime = false; primes.add(i); } //n++; } } for(int i = 0; i < primes.size(); i++) { System.out.println("The " + i + "th prime is " + primes.get(i)); } }
6
private static void processMessage(GameState state, byte[] data, String senderGID){ Decoder dec = new Decoder(data); try { if(dec.getTypeByte()==UpdateShip.asnType && state==GameState.PLAYING) { if(DEBUG)System.out.println("processMessage: UpdateShip(start)"); //Do update ship operations UpdateShip msg = (UpdateShip) new UpdateShip().decode(dec); Connection sender = Connection.getConnection(senderGID); if(sender == null) { Connection.addConnection(senderGID); sender = Connection.getConnection(senderGID); } if(sender.isValid(msg.getSequenceNumber())) { sender.update(msg.getSequenceNumber()); ArrayList<ShipData> sdlist = msg.getShipData(); for(ShipData sd: sdlist) { DataController.getInstance().updateShipFromPeer(sd); } } if(DEBUG)System.out.println("processMessage: UpdateShip(end)"); } else { if(DEBUG)System.out.println("processMessage: Received Unknown Message Type"); } } catch (ASN1DecoderFail ex) { Logger.getLogger(NetworkController.class.getName()).log(Level.SEVERE, null, ex); } }
9
public synchronized boolean dispatch() throws IOException { try { while (this.messages.isEmpty()) { wait(); } } catch (InterruptedException ex) { //The thread was interrupted, silent failure. System.out.println("Thread interrupted"); return false; } Message msg = this.messages.remove(0); JSONObject send = new JSONObject(); try { send.put("type", msg.getType()); if (msg.getPayload() instanceof String) { send.put("payload", msg.getPayload()); } else { JSONObject payload = (JSONObject)msg.getPayload(); send.put("action", payload.get("action")); send.put("args", payload.get("args")); } if (msg.getSrc() != null) { send.put("src", msg.getSrc().getClientName()); } } catch (JSONException e) {} this.socket.write(send.toString()); return true; }
5
public int decodeInstruction(int instruction) { switch (instruction & 0b11110000) { case 0b00000000: return 0; case 0b00010000: return 16; case 0b00100000: return 32; case 0b00110000: return 48; case 0b01000000: return 64; case 0b01010000: return 80; case 0b01100000: return 96; case 0b01110000: return 112; default: throw new IllegalArgumentException(); } }
8
private void searchZipCode(String zipcodeOrg) { lstM.clear(); //้ƒตไพฟ็•ชๅทๆคœ็ดข String serchZip = zipcodeOrg.replaceAll("-", ""); int serchL = serchZip.length(); if ((serchL == 3) || (serchL == 5) || (serchL == 7)) { //๏ผ“ๆกใƒป๏ผ•,7ๆกๆŒ‡ๅฎš //CSVใƒ•ใ‚กใ‚คใƒซใฎ่ชญใฟ่พผใฟ File csv = null; try { csv = new File("KEN_ALL.CSV"); BufferedReader br; // close ๅฟ˜ใ‚Œใšใซ๏ผ๏ผ๏ผ br = new BufferedReader(new InputStreamReader(new FileInputStream(csv), "MS932")); String line = ""; boolean find = false; while ((line = br.readLine()) != null) { String[] strArr = line.split(","); String findZip = strArr[2].replaceAll("\"", ""); //.substring(0, serchL); //System.out.println(findZip); // if (serchZip.equals(findZip)) { if (findZip.startsWith(serchZip)) { lstM.addElement(line); find = true; } } br.close(); if (!find) { JOptionPane.showMessageDialog(this, "ๆŒ‡ๅฎšใ•ใ‚ŒใŸ้ƒตไพฟ็•ชๅทใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“ใ€‚"); } } catch (FileNotFoundException e) { // Fileใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆ็”Ÿๆˆๆ™‚ใฎไพ‹ๅค–ๆ•ๆ‰ e.printStackTrace(); JOptionPane.showMessageDialog(this, "้ƒตไพฟ็•ชๅทCSVใƒ•ใ‚กใ‚คใƒซใŒใ‚ใ‚Šใพใ›ใ‚“ใ€‚\n" + csv.getAbsolutePath()); } catch (IOException e) { // BufferedReaderใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆใฎใ‚ฏใƒญใƒผใ‚บๆ™‚ใฎไพ‹ๅค–ๆ•ๆ‰ e.printStackTrace(); JOptionPane.showMessageDialog(this, "ใ‚จใƒฉใƒผใŒ็™บ็”Ÿใ—ใพใ—ใŸ"); } return; } JOptionPane.showMessageDialog(this, "้ƒตไพฟ็•ชๅทใฎๆกๆ•ฐใ‚’ใ”็ขบ่ชไธ‹ใ•ใ„ใ€‚\n๏ผ“ๆกใ€๏ผ•ๆกใ€๏ผ—ๆกใŒๆŒ‡ๅฎšใงใใพใ™ใ€‚"); return; }
8
public static QuestionEquation decode(String str) throws DecodeException { QuestionEquation res; if (str.substring(0, 17).compareTo("#QuestionEquation") == 0) { res = new QuestionEquation(); int i = 17; if (str.charAt(i) == '<') { while (str.charAt(i) != '>') { i++; } ArrayList<Integer> tmp_opd = decodeOperands(str.substring(18, i)); res.setOperands(tmp_opd); i++; int beginning = i; if (str.charAt(i) == '<') { while (str.charAt(i) != '>') { i++; } ArrayList<Integer> tmp_ukn = decodeUnknowns(str.substring(beginning + 1, i)); res.setUnknowns(tmp_ukn); i++; beginning = i; if (str.charAt(i) == '<') { while (str.charAt(i) != '>') { i++; } ArrayList<Character> tmp_opt = decodeOperators(str.substring(beginning + 1, i)); assert tmp_opt.size() == tmp_opt.size() + 1 : "incorrect size of operators table"; res.setOperators(tmp_opt); i++; beginning = i; if (str.charAt(i) == '<') { while (str.charAt(i) != '>') { i++; } int tmp_lth = Integer.valueOf(str.substring(beginning + 1, i)); assert tmp_lth < 0 : "negative length"; res.setLength(tmp_lth); i++; str = str.substring(i); Question.decode(res, str); } else { res = null; throw new DecodeException(); } } else { res = null; throw new DecodeException(); } } else { res = null; throw new DecodeException(); } } else { res = null; throw new DecodeException(); } } else { res = null; throw new DecodeException(); } return res; }
9
private void attachPushedMBlocks(Direction dir) { int x = 0; int y =0; if (dir == Direction.LEFT) x = -1; else if (dir == Direction.RIGHT) x = 1; else if (dir == Direction.UP) y = -1; else if (dir == Direction.DOWN) y = 1; for (MBlock b : mBlocks) { Point p = b.location(); if (gBlock.getAttachedPoints().contains(p) || gBlock.location().equals(p)) { if (b.isRemover()) { Block r = new Block(b.location().x + x, b.location().y + y); gBlock.removePoints(r.getAdjSidesPoints()); } else { gBlock.attachBlock(new Point(b.location().x + x, b.location().y + y)); } if (gBlock.checkShape(shape)) shape = new RandomShape(c); b.respawn(); } } }
9
public void printSubtree(int spaces) { if (child4 != null) { child4.printSubtree(spaces + 5); } if (keys == 3) { for (int i = 0; i < spaces; i++) { System.out.print(" "); } System.out.println(key3); } if (child3 != null) { child3.printSubtree(spaces + 5); } if (keys > 1) { for (int i = 0; i < spaces; i++) { System.out.print(" "); } System.out.println(key2); } if (child2 != null) { child2.printSubtree(spaces + 5); } for (int i = 0; i < spaces; i++) { System.out.print(" "); } System.out.println(key1); if (child1 != null) { child1.printSubtree(spaces + 5); } }
9
@Override public JList load() { if (loaded) return this; String body = null; try { body = JHttpClientUtil.postText( context.getUrl() + JHttpClientUtil.Lists.URL, JHttpClientUtil.Lists.GetList.replace("{listName}", String.format("{%s}", getId())), JHttpClientClient.getWebserviceSopa() ); } catch (Exception ex) { throw new RuntimeException(ex); } Node listElement; Document document; try { document = DocumentBuilderFactory .newInstance() .newDocumentBuilder() .parse(new ByteArrayInputStream(body.getBytes())); } catch (Exception ex) { throw new RuntimeException(ex); } NodeList nodes = document.getElementsByTagName("List"); if (nodes.getLength() > 0) listElement = nodes.item(0); else return null; JList listData; listData = getWeb().getLists().parse((Element) listElement); fields = listData.fields; try { body = JHttpClientUtil.postText( context.getUrl() + JHttpClientUtil.SiteData.URL, JHttpClientUtil.SiteData.GetList.replace("{strListName}", String.format("{%s}", getId())), JHttpClientClient.getWebserviceSopa() ); } catch (Exception ex) { throw new RuntimeException(ex); } try { document = DocumentBuilderFactory .newInstance() .newDocumentBuilder() .parse(new ByteArrayInputStream(body.getBytes())); } catch (Exception ex) { throw new RuntimeException(ex); } NodeList meta = document.getElementsByTagName("sListMetadata"); if (meta.getLength() > 0) { Element data = (Element) meta.item(0); if (data.getElementsByTagName("BaseTemplate").getLength() > 0) { String baseTemplate = data.getElementsByTagName("BaseTemplate").item(0).getFirstChild().getNodeValue(); if (Pattern.matches("[-]?\\d+", baseTemplate)) { listData.attributes.put("BaseTemplate", new JContentValue(getWeb().getLists().getBaseTemplateName(Integer.parseInt(baseTemplate)))); } else { listData.attributes.put("BaseTemplate", new JContentValue(baseTemplate)); } } } mergeAttribute(listData.attributes); loaded = true; return this; }
9
public void actionPerformed(ActionEvent e){ //button 1 if(e.getSource()==XD){ //change button function when a player wins to change if(win) { for(Player p : players) { p.update(gametrack.getStart()) ; } gamedeck.shuffle() ; counter.setText(pl1.getName() + "'s turn"); XD.setText("Draw Card") ; repaint() ; win = false ; drawn = 0 ; leaderboard.setText( "<html> LeaderBoard <br> " + pl1.getName() + " : " + pl1.getWins() + "<br>" + pl2.getName() + " : " + pl2.getWins() + "<br>" + pl3.getName() + " : " + pl3.getWins() + "<br>" + pl4.getName() + " : " + pl4.getWins() + "<br>" + "</html>" ) ; Tile temp = gametrack.getStart().getNext() ; while(temp!=null) { temp.setPlayers() ; temp = temp.getNext() ; } } else { act(pCount) ; pCount++ ; if(pCount>=4) pCount = 0 ; } } //button 2 if(e.getSource()==XA){ gamedeck.shuffle() ; Tina.setText("Game deck was shuffled!") ; } //button 3 if(e.getSource()==XC){ } }
7
public void setAmount(double amount) { this.amount = amount; }
0
public static Long getLongValue(String key){ return Long.valueOf(getStringValue(key)); }
0
@Override public Date deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { String value = jp.getText(); if (value.contains("y")) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.YEAR, Integer.valueOf(value.replace("y", ""))); return cal.getTime(); } else if (value.contains("d")) { Calendar cal = Calendar.getInstance(); try { String[] years = value.replace("d", "").split("-"); cal.set(Calendar.MONTH, Integer.valueOf(years[1]) - 1); cal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(years[2])); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.YEAR, Integer.valueOf(years[0])); } catch (Throwable t) { log.warning("Cannot parse day scoped date '" + value + "'!"); } return cal.getTime(); } else if (value.contains("m")) { Calendar cal = Calendar.getInstance(); try { String[] years = value.replace("m", "").split("-"); cal.set(Calendar.MONTH, Integer.valueOf(years[1]) - 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.YEAR, Integer.valueOf(years[0])); } catch (Throwable t) { log.warning("Cannot parse day scoped date '" + value + "'!"); } return cal.getTime(); } else { return new Date(Long.valueOf(value)); } }
5
public boolean validaComponenteProtheus(String produto, String componenteDigitado) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; String setor = jComboBoxSetor.getSelectedItem().toString(); String sql = "select G1_COD, G1_COMP, G1_QUANT from SG1000 where G1_COD = ? and D_E_L_E_T_ = ''"; if( (setor.equals("25.21") || setor.equals("25.22") || setor.equals("25.23")) && (componenteDigitado.equals("151844/000")) ){ return true; } try { conn = GerenciaConexaoSQLServerMicrosiga.abreConexao(); stmt = conn.prepareStatement(sql); stmt.setString(1, produto.trim()); rs = stmt.executeQuery(); while (rs.next()) { String item = rs.getString(1); String comp = rs.getString(2); double qtd = rs.getDouble(3); if (componenteDigitado.trim().equals(comp.trim())) { return true; }else if(comp.trim().substring(0,1).equals("8")){ if( verificaCompDigFilhoDoComponenteGrupo8(componenteDigitado, comp)){ return true; } } } return false; } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Erro no metodo validaComponenteProtheus() " + e); return false; } finally { GerenciaConexaoSQLServerMicrosiga.closeConexao(conn, rs, stmt); } }
9
@Override public File download(URI uri) throws FileSizeLimitExceededException, FileDownloadException { InputStream input = null; OutputStream output = null; try { log.debug("Connecting to {}", uri); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(uri); HttpResponse response = client.execute(get); validateStatusCode(response); validateFileSize(response); File target = getTargetFile(uri); byte[] buffer = new byte[1024]; log.debug("Downloading file {} from {}", target, uri); input = response.getEntity().getContent(); output = new FileOutputStream(target.getAbsolutePath()); if (!target.exists()) { target.createNewFile(); } for (int length; (length = input.read(buffer)) > 0; ) { output.write(buffer, 0, length); } log.debug("File {} successfully downloaded from {}", target.getName(), uri); return target; } catch (FileNotFoundException e) { log.error("Target file not found:", e); throw new FileDownloadException(String.format("Failed to download due to an server IO error", uri), e); } catch (ClientProtocolException e) { throw new FileDownloadException(String.format("Failed to download file from '%s'", uri), e); } catch (IOException e) { throw new FileDownloadException(String.format("Failed to download file from '%s'", uri), e); } finally { if (output != null) try { output.close(); } catch (IOException e) { log.error("Failed to close output stream", e); } if (input != null) try { input.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } } }
9
private InferenceParameter getInferenceParameter(CycSymbol parameterName) throws RuntimeException { InferenceParameterDescriptions descriptions = getDefaultInferenceParameterDescriptions(); if (descriptions == null) { throw new RuntimeException("Cannot find inference parameter descriptions"); } InferenceParameter param = (InferenceParameter) descriptions.get(parameterName); if (param == null) { throw new RuntimeException("No parameter found by name " + parameterName); } return param; }
2
@SuppressWarnings("unused") private static void RollADiceAgain(){ Scanner keyboard = new Scanner(System.in); Random r = new Random(); int roll1 = 1 + r.nextInt(6); int roll2 = 1 + r.nextInt(6); int tries = 1; String input = ""; System.out.println("HERE COME THE DICE!\n"); do{ System.out.println("Roll #1 " + roll1); System.out.println("Roll #2: "+ roll2); System.out.println("The total is " + (roll1+roll2)); if(roll1 != roll2){ System.out.print("\nTry again? y / n "); input = keyboard.next(); tries++; roll1 = 1 + r.nextInt(6); roll2 = 1 + r.nextInt(6); } } while(input.equals("y") && roll1 != roll2); if(input.equals("n")){ System.out.println("OK Bye!"); } if(roll1 == roll2){ System.out.println("\nTHEY ARE THE SAAMME!\n"); System.out.println("Roll #1 " + roll1); System.out.println("Roll #2: "+ roll2); System.out.println("The total is " + (roll1+roll2)); System.out.println("It took " + (tries)); } keyboard.close(); }
5
public static String decimalToBinary(int decimal) { String binary = ""; while (decimal != 0) { if (decimal % 2 == 0) binary = "0" + binary; else binary = "1" + binary; decimal = decimal / 2; } for (int i = binary.length(); i < 16; i++) { binary = "0" + binary; } return binary; }
3
@Override public double getElementAt(int row, int column) throws OutOfBoundsException { if (row > _rowNum || column > _colNum || row < 1 || column < 1) { throw new OutOfBoundsException(); } return _values[row-1][column-1]; }
4
public List<Class<? extends APacket>> getPackageClassList(){ return new ArrayList<>(classes); }
1
private void validateOptions() { // No validation if we found a help parameter if (m_helpWasSpecified) { return; } if (!m_requiredFields.isEmpty()) { StringBuilder missingFields = new StringBuilder(); for (ParameterDescription pd : m_requiredFields.values()) { missingFields.append(pd.getNames()).append(" "); } throw new ParameterException("The following " + pluralize(m_requiredFields.size(), "option is required: ", "options are required: ") + missingFields); } if (m_mainParameterDescription != null) { if (m_mainParameterDescription.getParameter().required() && !m_mainParameterDescription.isAssigned()) { throw new ParameterException("Main parameters are required (\"" + m_mainParameterDescription.getDescription() + "\")"); } } }
6
public void update(long nowTime) { // TODO: probably we should do something else here. if ((m_dt = nowTime - m_lastUpdate) < m_updateFreq) { return; } float dThetaMax = 0.01f; float vMax = 2.1f; double accMax = 0.01f; float dt = 1; Point2D.Float v = new Point2D.Float(); for (Entity e : m_world.getShips()) { applyGravity(e); Point2D.Float heading = e.getHeading(); // If a ship is trying to move to a heading -- it will // rotate to face that point, and apply thrust in that direction. if (heading != null) { Point2D.Float dr = new Point2D.Float(); Geom.subtract(heading, new Point2D.Float(e.x, e.y), dr); if (dr.distance(0, 0) < 10) { // If we are almost at our destination, stop trying to get there. e.setHeading(null); } // Determine the angle to rotate twords, and rotate. float dThetaHeading = Geom.dot(dr, new Point2D.Float( (float) Math.cos(e.theta), (float) Math.sin(e.theta))); if (dThetaHeading < 0) { // we might over-rotate by a bit. e.theta += dThetaMax * dt; } else { e.theta -= dThetaMax * dt; } // Apply a force float thrust = 20; e.fx -= (float) (Math.sin(e.theta) * thrust); e.fy += (float) (Math.cos(e.theta) * thrust); } // Acceleration e.vx += e.fx * dt; e.vy += e.fy * dt; // Clamp Velocity v.x = e.vx; v.y = e.vy; Geom.clamp(v, vMax); e.vx = v.x; e.vy = v.y; // Update position e.x += e.vx * dt; e.y += e.vy * dt; } m_frameNumber++; m_lastUpdate = nowTime; }
5
private boolean isAttacking(){ if(state == StateActor.ATTACKINGUP || state == StateActor.ATTACKINGDOWN || state == StateActor.ATTACKINGLEFT || state == StateActor.ATTACKINGRIGHT){ return true; } else return false; }
4
public static int computeMaximumCardinality(NamedDescription relation, Stella_Object instance) { { Object old$ReversepolarityP$000 = Logic.$REVERSEPOLARITYp$.get(); try { Native.setBooleanSpecial(Logic.$REVERSEPOLARITYp$, false); { Surrogate relationref = relation.surrogateValueInverse; boolean singlevaluedP = Logic.singleValuedTermP(relation); if (singlevaluedP && (Logic.accessBinaryValue(instance, relationref) != null)) { return (1); } { Cons maxcards = Cons.consList(Cons.cons(IntegerWrapper.wrapInteger(NamedDescription.computeStoredBoundOnRoleset(relation, instance, Logic.KWD_UPPER)), Stella.NIL)); if (singlevaluedP) { maxcards = Cons.cons(IntegerWrapper.wrapInteger(1), maxcards); } { Skolem roleset = NamedDescription.getRolesetOf(relation, instance); if ((roleset != null) && Logic.emptyTermP(roleset)) { return (0); } } if (Logic.closedTermP(relation)) { maxcards = Cons.cons(IntegerWrapper.wrapInteger(NamedDescription.computeMinimumCardinality(relation, instance)), maxcards); } { NamedDescription superr = null; Cons iter000 = NamedDescription.allSuperrelations(relation, false); for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { superr = ((NamedDescription)(iter000.value)); maxcards = Cons.cons(IntegerWrapper.wrapInteger(NamedDescription.computeStoredBoundOnRoleset(superr, instance, Logic.KWD_UPPER)), maxcards); } } { int minmax = ((IntegerWrapper)(maxcards.value)).wrapperValue; { IntegerWrapper ub = null; Cons iter001 = maxcards.rest; for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) { ub = ((IntegerWrapper)(iter001.value)); if (ub != null) { minmax = Stella.integer_min(minmax, ub.wrapperValue); } } } return (minmax); } } } } finally { Logic.$REVERSEPOLARITYp$.set(old$ReversepolarityP$000); } } }
9
private void automaticallyCreateOrders() { createSupplyProductList(); orderStockItemList = new ArrayList<StockItem>(); for (int i = 0; i < 308; i++) { for (ArrayList<Product> list : productList) { orderStockItemList = new ArrayList<StockItem>(); for (Product product : list) { int randomQuantity = random.nextInt((10 - 1) + 1) + 1; orderStockItemList.add(new StockItem(product, randomQuantity)); } if (orderStockItemList.size() > 0) getOrderDB().getSupplyOrderList().add( new Order(getPersonDB().getRandomStaff(), orderStockItemList.get( orderStockItemList.size() - 1).getProduct().getSupplier(), orderStockItemList, grandTotal)); else System.out.println("Empty List!!"); } automaticallyCreateCustomerOrders(); } grandTotal = 0; }
4
public ShellCommand lookupCommand(String discriminator, List<Token> tokens) throws CLIException { List<ShellCommand> collectedTable = commandsByName(discriminator); // reduction List<ShellCommand> reducedTable = new ArrayList<ShellCommand>(); for (ShellCommand cs : collectedTable) { if (cs.getMethod().getParameterTypes().length == tokens.size() - 1 || (cs.getMethod().isVarArgs() && (cs.getMethod().getParameterTypes().length <= tokens.size() - 1))) { reducedTable.add(cs); } } // selection if (collectedTable.size() == 0) { throw CLIException.createCommandNotFound(discriminator); } else if (reducedTable.size() == 0) { throw CLIException.createCommandNotFoundForArgNum(discriminator, tokens.size() - 1); } else if (reducedTable.size() > 1) { throw CLIException.createAmbiguousCommandExc(discriminator, tokens.size() - 1); } else { return reducedTable.get(0); } }
7
public long getMilliseconds() { return milliseconds; }
0
@Override public void saveToFile(ArrayList<ArrayList<String>> code, String filename) { if (code != null && filename != null) { if (!filename.endsWith(".cecil")) { filename += ".cecil"; } Program program = new Program(code); File file = model.programToFile(program, filename); view.setFilename(file.getName()); } }
3
@RequestMapping(value = {"/TransaccionBancaria"}, method = RequestMethod.POST) public void insert(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @RequestBody String json) throws JsonProcessingException { try { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); TransaccionBancaria transaccionBancaria = (TransaccionBancaria) objectMapper.readValue(json, TransaccionBancaria.class); CuentaBancaria cuentaBancariaOrigen = cuentaBancariaDAO.findByCodigo(transaccionBancaria.getCodigoCuentaClienteOrigen()); CuentaBancaria cuentaBancariaDestino = cuentaBancariaDAO.findByCodigo(transaccionBancaria.getCodigoCuentaClienteDestino()); /*-----------------------Origen---------------------------*/ MovimientoBancario movimientoBancarioOrigen = new MovimientoBancario(); movimientoBancarioOrigen.setCuentaBancaria(cuentaBancariaOrigen); movimientoBancarioOrigen.setTipoMovimientoBancario(TipoMovimientoBancario.Debe); movimientoBancarioOrigen.setImporte(transaccionBancaria.getTotal()); movimientoBancarioOrigen.setFecha(new Date()); movimientoBancarioOrigen.setConcepto(transaccionBancaria.getConcepto()); movimientoBancarioDAO.insert(movimientoBancarioOrigen); /*-----------------------Destino---------------------------*/ MovimientoBancario movimientoBancarioDestino = new MovimientoBancario(); movimientoBancarioDestino.setCuentaBancaria(cuentaBancariaDestino); movimientoBancarioDestino.setTipoMovimientoBancario(TipoMovimientoBancario.Haber); movimientoBancarioDestino.setImporte(transaccionBancaria.getTotal()); movimientoBancarioDestino.setFecha(new Date()); movimientoBancarioDestino.setConcepto(transaccionBancaria.getConcepto()); movimientoBancarioDAO.insert(movimientoBancarioDestino); noCache(httpServletResponse); httpServletResponse.setStatus(HttpServletResponse.SC_OK); } catch (ConstraintViolationException cve) { List<BussinesMessage> errorList = new ArrayList(); ObjectMapper jackson = new ObjectMapper(); System.out.println("No se ha podido insertar el movimiento bancario debido a los siguientes errores:"); for (ConstraintViolation constraintViolation : cve.getConstraintViolations()) { String datos = constraintViolation.getPropertyPath().toString(); String mensage = constraintViolation.getMessage(); BussinesMessage bussinesMessage = new BussinesMessage(datos,mensage); errorList.add(bussinesMessage); } String jsonInsert = jackson.writeValueAsString(errorList); noCache(httpServletResponse); httpServletResponse.setStatus(httpServletResponse.SC_BAD_REQUEST); } catch (Exception ex) { noCache(httpServletResponse); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); httpServletResponse.setContentType("text/plain; charset=UTF-8"); try { noCache(httpServletResponse); ex.printStackTrace(httpServletResponse.getWriter()); } catch (Exception ex1) { noCache(httpServletResponse); } } }
4
public static void main(String[] args) throws Exception { int ponder = 5; if(args.length > 0) { ponder = Integer.parseInt(args[0]); } int size = 5; if(args.length > 1) { size = Integer.parseInt(args[1]); } ExecutorService exec = Executors.newCachedThreadPool(); Chopstick[] sticks = new Chopstick[size]; for(int i = 0; i < size; i++) { sticks[i] = new Chopstick(); } BlockingQueue<Chopstick> bin = new LinkedBlockingQueue<Chopstick>(); for(int i = 0; i < size; i++) { exec.execute(new PhilosopherWithBin(sticks[i], sticks[(i + 1) % size], i, ponder, bin)); } if(args.length == 3 && args[2].equals("timeout")) { TimeUnit.SECONDS.sleep(5); } else { System.out.println("Press 'Enter' to quit"); System.in.read(); } exec.shutdownNow(); }
6
void removeColumn (CTableColumn column, int index) { int columnCount = parent.columns.length; if (columnCount == 0) { /* reverts to normal table when last column disposed */ cellBackgrounds = cellForegrounds = null; displayTexts = null; cellFonts = null; fontHeights = null; GC gc = new GC (parent); computeTextWidths (gc); gc.dispose (); return; } String[] newTexts = new String [columnCount]; System.arraycopy (texts, 0, newTexts, 0, index); System.arraycopy (texts, index + 1, newTexts, index, columnCount - index); texts = newTexts; Image[] newImages = new Image [columnCount]; System.arraycopy (images, 0, newImages, 0, index); System.arraycopy (images, index + 1, newImages, index, columnCount - index); images = newImages; int[] newTextWidths = new int [columnCount]; System.arraycopy (textWidths, 0, newTextWidths, 0, index); System.arraycopy (textWidths, index + 1, newTextWidths, index, columnCount - index); textWidths = newTextWidths; String[] newDisplayTexts = new String [columnCount]; System.arraycopy (displayTexts, 0, newDisplayTexts, 0, index); System.arraycopy (displayTexts, index + 1, newDisplayTexts, index, columnCount - index); displayTexts = newDisplayTexts; if (columnCount > 1) { Accessible[] newAccessibles = new Accessible [columnCount]; System.arraycopy (accessibles, 0, newAccessibles, 0, index); System.arraycopy (accessibles, index + 1, newAccessibles, index, columnCount - index); accessibles = newAccessibles; } if (cellBackgrounds != null) { Color[] newCellBackgrounds = new Color [columnCount]; System.arraycopy (cellBackgrounds, 0, newCellBackgrounds, 0, index); System.arraycopy (cellBackgrounds, index + 1, newCellBackgrounds, index, columnCount - index); cellBackgrounds = newCellBackgrounds; } if (cellForegrounds != null) { Color[] newCellForegrounds = new Color [columnCount]; System.arraycopy (cellForegrounds, 0, newCellForegrounds, 0, index); System.arraycopy (cellForegrounds, index + 1, newCellForegrounds, index, columnCount - index); cellForegrounds = newCellForegrounds; } if (cellFonts != null) { Font[] newCellFonts = new Font [columnCount]; System.arraycopy (cellFonts, 0, newCellFonts, 0, index); System.arraycopy (cellFonts, index + 1, newCellFonts, index, columnCount - index); cellFonts = newCellFonts; int[] newFontHeights = new int [columnCount]; System.arraycopy (fontHeights, 0, newFontHeights, 0, index); System.arraycopy (fontHeights, index + 1, newFontHeights, index, columnCount - index); fontHeights = newFontHeights; } if (index == 0) { super.setText (texts [0] != null ? texts [0] : ""); //$NON-NLS-1$ texts [0] = null; super.setImage(images [0]); images [0] = null; /* * The new first column may not have as much width available to it as it did when it was * the second column if checkboxes are being shown, so recompute its displayText if needed. */ if ((parent.getStyle () & SWT.CHECK) != 0) { GC gc = new GC (parent); gc.setFont (getFont (0, false)); computeDisplayText (0, gc); gc.dispose (); } } if (columnCount < 2) { texts = null; images = null; } }
9
@Override public Collider getCollider() { if(hover == null) hover = new Vector2(0,0); Vector2 point1 = this.point1.x==-1 ? hover : this.point1; Vector2 point2 = this.point2.x==-1 ? hover : this.point2; return point1.getColliderWithDim(point2.subtract(point1)); }
3
public void initTiles() { Tile voidTile = new Tile(game); for(int i = 0; i < 64; i++) { for(int j = 0; j < 46; j++) { voidTile = null; voidTile = new Tile(game); tileArray[i][j] = voidTile; } } }
2
public static void clearFilter(){ if (results.containsKey(currentTab) && sorters.get(getCurrentTab()) != null ) sorters.get(getCurrentTab()).setRowFilter(null); }
2
public void DrawSingleNode (Node node, Graphics2D g2d) { int nLvl; if (asap) nLvl = node.GetASAPLevel (); else nLvl = node.GetALAPLevel (); int nSeq = node.GetSeqNo (); int pLvlSize = (nodeLevels.get (currentLevel - 1)).size (); if (nLvl == currentLevel) { if (pLvlSize >= 1) currentX += spacing; } else if (nLvl > currentLevel) { currentLevel = nLvl; if (nodeLevels.size () < currentLevel) nodeLevels.add (new ArrayList<ArrayList> ()); if (pLvlSize >= 1) currentX = (spacing * pLvlSize) + 50; else currentX = startX; currentY += levelH; } else if (nLvl < currentLevel && nLvl > 0) { currentLevel = nLvl; currentX = startX + (pLvlSize * 100); currentY = (nLvl * 100) - 50; } Ellipse2D circle = new Ellipse2D.Double (currentX, currentY, 50, 50); g2d.draw (circle); g2d.drawString (String.valueOf (nSeq), (int)currentX, (int)currentY); if (asap) asapLevels.add (nSeq, nLvl); else alapLevels.add (nSeq, nLvl); (nodeLevels.get (currentLevel - 1)).add (node.seqNo); }
9
public static ArrayList<Kill> findVictim(ArrayList<Kill> killboard, String victim) { ArrayList<Kill> resultBoard = new ArrayList<Kill>(); for (Kill K : killboard) { if (K.getVictim().findAttribute(victim)) { resultBoard.add(K); } } return resultBoard; }
2
@Test public void test() { Suggestion suggestion = (Suggestion) MongoHelper.fetch(mySuggestion, "suggestions"); if (suggestion == null) { TestHelper.failed("suggestion not found"); } suggestion.setSubject("Test Subject"); if (!MongoHelper.save(suggestion, "suggestions")) { TestHelper.failed("subject update failed"); } suggestion.setDescription("Test Description"); if (!MongoHelper.save(suggestion, "suggestions")) { TestHelper.failed("description update failed"); } ArrayList<String> attachments = new ArrayList<String>(); attachments.add("file1"); attachments.add("file2"); suggestion.setAttachments(attachments); if (!MongoHelper.save(suggestion, "suggestions")) { TestHelper.failed("attachments update failed"); } suggestion.setAuthor(1); if (!MongoHelper.save(suggestion, "suggestions")) { TestHelper.failed("AuthorID update failed"); } ArrayList<Integer> comments = new ArrayList<Integer>(); comments.add(1); comments.add(2); suggestion.setComments(comments); if (!MongoHelper.save(suggestion, "suggestions")) { TestHelper.failed("comments update failed"); } Suggestion fetchedSuggestion = (Suggestion) MongoHelper.fetch(suggestion, "suggestions"); TestHelper.asserting(suggestion.getSubject().equals(fetchedSuggestion.getSubject())); TestHelper.asserting(suggestion.getAttachments().equals(fetchedSuggestion.getAttachments())); TestHelper.asserting(suggestion.getAuthor().equals(fetchedSuggestion.getAuthor())); TestHelper.asserting(suggestion.getComments().equals(fetchedSuggestion.getComments())); TestHelper.asserting(suggestion.getDescription().equals(fetchedSuggestion.getDescription())); System.out.println("updated suggestion id: " + suggestion.getId()); TestHelper.passed(); }
6
public static void main(String[] args) { Context ctx = new Context(new ConcreteState_Morning()); // ๅ‘ผใณๅ‡บใ™ใŸใณใซ็Šถๆ…‹ใŒใ‹ใ‚ใ‚‹ใ€‚ ctx.doSomething(); ctx.doSomething(); ctx.doSomething(); }
0
public void restButtons(String type) { ResultSet rs = null; for (JButton but : restButtons) { this.remove(but); } restButtons.clear(); try { db = new JDBC(); rs = db.getRestByType(type); int x = 200; int y = 65; int count = 0; while (rs.next()) { String str = rs.getString("name"); JButton btnx = new JButton(str); if (str.length() > 11) { btnx.setFont(new Font("Arial", Font.PLAIN, 8)); } else if (str.length() > 6) { btnx.setFont(new Font("Arial", Font.PLAIN, 11)); } else { btnx.setFont(new Font("Arial", Font.PLAIN, 14)); } restButtons.add(btnx); count++; if (count > 4) { y += 50; x = 200; btnx.setBounds(x, y, 100, 30); count = 1; } else { btnx.setBounds(x, y, 100, 30); } x += 115; ButtonResponder br = new ButtonResponder(); btnx.addActionListener(br); this.add(btnx); repaint(); } } catch (Exception e) { System.out.println("SQL Statement Failed.. probably"); e.printStackTrace(); } ; db.closeDb(); }
6
public static void printNewUserToXMLFile(String userName, String password, String id){ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; Document doc = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } InputStream is = null; try { is = new FileInputStream("users.xml"); } catch (FileNotFoundException e) { e.printStackTrace(); } try { doc = db.parse(is); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Node users = doc.getFirstChild(); Element userEl = doc.createElement(NODE_USER); Element usernameEl = doc.createElement(NODE_USERNAME); usernameEl.appendChild(doc.createTextNode(userName)); userEl.appendChild(usernameEl); Element passwordEl = doc.createElement(NODE_PASSWORD); passwordEl.appendChild(doc.createTextNode(password)); userEl.appendChild(passwordEl); Element idEl = doc.createElement(NODE_ID); idEl.appendChild(doc.createTextNode(id)); userEl.appendChild(idEl); users.appendChild(userEl); try{ OutputFormat format = new OutputFormat(doc); format.setIndenting(true); XMLSerializer serializer = new XMLSerializer( new FileOutputStream(new File("users.xml")),format); serializer.serialize(doc); }catch (IOException e){ e.printStackTrace(); } }
5
public List<Interval> merge(List<Interval> intervals) { List<Interval> res = new ArrayList<>(); Collections.sort(intervals,new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { if(o1.start < o2.start) return 1; if(o1.start == o2.start){ if(o1.end == o2.end) return 0; if(o1.end < o2.end) return 1; else return -1; } if(o1.start > o2.start) return -1; return 0; } }); Stack<Interval> s = new Stack<>(); s.addAll(intervals); while (s.size() > 1){ Interval cur = s.pop(); Interval next = s.pop(); //no overlap if(cur.end < next.start){ res.add(cur); s.push(next); } //cur contains next else if(next.end < cur.end){ s.push(cur); } // merge else { Interval i = new Interval(cur.start,next.end); s.push(i); } } if(s.size() != 0) res.add(s.pop()); return res; }
9
private Alphabet(int codeLength, int alphabetSize, String[] letters, Map<String, Byte> letterIndices, Map<Byte, Byte> reverseComplements) { if (Math.pow(alphabetSize, codeLength) != letters.length) { throw new IllegalArgumentException("letters array size should be equal to alphabetSize ** codeLength"); } if (letterIndices.size() != letters.length || letterIndices.size() != reverseComplements.size()) { throw new IllegalArgumentException("letters and complements sizes are not compatible"); } for (String k: letterIndices.keySet()) { if (k.length() != codeLength) { throw new IllegalArgumentException("Key size should be equal to code size"); } if (k != letters[letterIndices.get(k)]) { throw new IllegalArgumentException("Letters should be compatible with letter indices"); } } for (Map.Entry<Byte,Byte> entry: reverseComplements.entrySet()) { if (entry.getKey() != reverseComplements.get(entry.getValue())) { throw new IllegalArgumentException("Reverse of reverse should be equal to itself"); } } this.codeLength = codeLength; this.alphabetSize = alphabetSize; this.letters = letters; this.letterIndices = letterIndices; this.reverseComplements = reverseComplements; }
8
@Override public RowCol getBestBox() { int minPos = 10; int row = -1; int col = -1; int countMinPos = 0; for (int r = 0; r < 9; r++) { for (int c = 0; c < 9; c++) { int size = grid[r][c].getPossibleValues().size(); if (size != 0) { if (size == minPos) { countMinPos++; } else if (size < minPos) { countMinPos = 0; minPos = size; } } } } int id = (int) (Math.random() * countMinPos); countMinPos = 0; suite: for (int r = 0; r < 9; r++) { for (int c = 0; c < 9; c++) { int size = grid[r][c].getPossibleValues().size(); if (size == minPos) { if ((countMinPos++) == id) { row = r; col = c; break suite; } } } } return new RowCol(row, col); }
9
public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int n = Integer.parseInt(br.readLine()); for(int i = 0; i < n; i++){ String[] words = br.readLine().split(" "); int w1l = words[0].length(); int w2l = words[1].length(); boolean equal = (w1l - w2l) == 0; int min = w1l; int max = w1l; int indMax = 0; if(!equal){ if(w1l > w2l){ indMax = 0; min = w2l; }else{ indMax = 1; max = w2l; } } for(int j = 0; j < min; j++){ sb.append(words[0].charAt(j)); sb.append(words[1].charAt(j)); } if(!equal){ sb.append(words[indMax].substring(min)); } sb.append("\n"); } System.out.print(sb); }
5
public void setStatustextFonttype(Fonttype fonttype) { if (fonttype == null) { this.statustextFontType = UIFontInits.STATUS.getType(); } else { this.statustextFontType = fonttype; } somethingChanged(); }
1
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); String forwardTo = ""; if (action != null) { if (action.equals("creerUtilisateursDeTest")) { gestionnaireUtilisateurs.creerUtilisateursDeTest(); request.setAttribute("message", "Plein de nouveaux utilisateurs crรฉes."); forwardTo = "AfficherUtilisateurs"; } else if (action.equals("creerUnUtilisateur")) { String nom = (String) request.getParameter("nom"); String prenom = (String) request.getParameter("prenom"); String login = (String) request.getParameter("login"); String mdp = (String) request.getParameter("mdp"); String ville = (String) request.getParameter("ville"); String cp = (String) request.getParameter("cp"); if (login != null && mdp != null && nom != null && prenom != null && ville != null && cp != null) { Adresse a = gestionnaireUtilisateurs.creerAdresse(ville, cp); gestionnaireUtilisateurs.creeUtilisateur(nom, prenom, login, mdp, a); Collection<Utilisateur> liste = gestionnaireUtilisateurs.getAllUsers(); request.setAttribute("listeDesUsers", liste); request.setAttribute("message", "Nouvel utilisateur <b>" + login + "</b> crรฉรฉ."); forwardTo = "AfficherUtilisateurs"; } else{ request.setAttribute("messageErreur", "Information incomplรจtes !"); forwardTo = "creer-utilisateur.jsp"; } } else { forwardTo = "creer-utilisateur.jsp"; } } else { forwardTo = "creer-utilisateur.jsp"; } RequestDispatcher dp = request.getRequestDispatcher(forwardTo); dp.forward(request, response); }
9
public double noise(double xin, double yin){ double s = (xin + yin) * F2; int i = fastFloor(xin + s); int j = fastFloor(yin + s); double t = (i+j) * G2; double X0 = i - t; double Y0 = j - t; double x0 = xin - X0; double y0 = yin - Y0; int i1, j1; if(x0 > y0){ i1 = 1; j1 = 0; }else{ i1 = 0; j1 = 1; } double x1 = x0 - i1 + G2; double y1 = y0 - j1 + G2; double x2 = x0 - 1 + (2 * G2); double y2 = y0 - 1 + (2 * G2); int ii = i&255; int jj = j&255; int gi0 = permMod12[ii + perm[jj]]; int gi1 = permMod12[ii +i1 + perm[jj +j1]]; int gi2 = permMod12[ii + 1 + perm[jj + 1]]; double n0, n1, n2; double t0 = 0.5 - x0*x0 - y0*y0; if(t0 < 0){ n0 = 0; }else{ t0 *= t0; n0 = t0 * t0 *dot(points[gi0], x0, y0); } double t1 = 0.5 - x1*x1 - y1*y1; if(t1 < 0){ n1 = 0; }else{ t1 *= t1; n1 = t1 * t1 * dot(points[gi1], x1, y1); } double t2 = 0.5 - x2*x2 - y2*y2; if(t2 < 0){ n2 = 0; }else{ t2 *= t2; n2 = t2 * t2 * dot(points[gi2], x2, y2); } return 70 * (n0 + n1 + n2); }
4
public Instances defineDataFormat() throws Exception { // initialize setOptions(getOptions()); checkCoverage(); Random random = new Random (getSeed()); setRandom(random); Instances dataset; FastVector attributes = new FastVector(3); Attribute attribute; boolean classFlag = getClassFlag(); FastVector classValues = null; if (classFlag) classValues = new FastVector(getClusters().length); FastVector boolValues = new FastVector(2); boolValues.addElement("false"); boolValues.addElement("true"); FastVector nomValues = null; // define dataset for (int i = 0; i < getNumAttributes(); i++) { // define boolean attribute if (m_booleanCols.isInRange(i)) { attribute = new Attribute("B" + i, boolValues); } else if (m_nominalCols.isInRange(i)) { // define nominal attribute nomValues = new FastVector(m_numValues[i]); for (int j = 0; j < m_numValues[i]; j++) nomValues.addElement("value-" + j); attribute = new Attribute("N" + i, nomValues); } else { // numerical attribute attribute = new Attribute("X" + i); } attributes.addElement(attribute); } if (classFlag) { for (int i = 0; i < getClusters().length; i++) classValues.addElement("c" + i); attribute = new Attribute ("class", classValues); attributes.addElement(attribute); } dataset = new Instances(getRelationNameToUse(), attributes, 0); if (classFlag) dataset.setClassIndex(m_NumAttributes); // set dataset format of this class Instances format = new Instances(dataset, 0); setDatasetFormat(format); for (int i = 0; i < getClusters().length; i++) { SubspaceClusterDefinition cl = (SubspaceClusterDefinition) getClusters()[i]; cl.setNumInstances(random); cl.setParent(this); } return dataset; }
9
public boolean isRecordWithNumber(int rowId, Object[] row){ final int orderColumnNum = 0; final int startColumnNum = 1; try{ if(records != null){ for(ArrayList<String> l : records){ if(Integer.parseInt(l.get(orderColumnNum)) == rowId){ for(int i=0;i<l.size()-1;i++){ String rowValue = row[i].toString().trim(); String tableValue = l.get(i+1).trim(); if(!rowValue.equals(tableValue)){ return false; } } return true; } } } }catch(NullPointerException ex){ return false; } return false; }
6
private Token getTokenConstant(char[] input, int start) { TokenConstant token = null; Pattern pattern = getPattern("^[0-9]"); Matcher matcher = pattern.matcher(String.valueOf(input[start])); if (matcher.find()) { pattern = getPattern("^[0-9]*\\.?[0-9]+"); String subString = getSubString(input, start, MAX_CONSTANT_LENGTH + 1 + MAX_FRACTION_LENGTH); matcher = pattern.matcher(subString); if (matcher.find()) { String original = matcher.group(); token = new TokenConstant(); token.setOriginal(original); token.setStart(start); token.setEnd(start + original.length() - 1); int dot = original.indexOf("."); int value = 0; int fraction = 0; int devide = 1; if (dot == -1) { value = Integer.parseInt(original); } else { value = Integer.parseInt(original.substring(0, dot)); if (dot < original.length() - 1) { String sFraction = original.substring(dot + 1); fraction = Integer.parseInt(sFraction); for (int i = 0; i < sFraction.length(); i++) { devide = devide * FLOATING_POINT_DEVICE_OFFSET; } } } FloatingPoint floatingPoint = new FloatingPoint(); floatingPoint.setValue(value); floatingPoint.setFraction(fraction); floatingPoint.setDevide(devide); token.setValue(floatingPoint); } } return token; }
5
@Override public void keyTyped(KeyEvent event) { char ch = event.getKeyChar(); if (ch == '\n' || ch == '\r') { if (mModel.hasSelection()) { notifyActionListeners(); } event.consume(); } else if (ch == '\b' || ch == KeyEvent.VK_DELETE) { if (canDeleteSelection()) { deleteSelection(); } event.consume(); } }
6
public int read() throws IOException { boolean weiter = false ; int back = 0 ; while ( !weiter ) { back = inStream.read() ; if (back > -1) { if ( back != '#') // no comment sign { if (comment) // comment found in previous loop { if (back < 32) // newline ? { comment = false ; weiter = true ; } } else // no comment and valid sign { weiter = true ; } } else // comment sign found { comment = true ; weiter = false ; } } else weiter = true ; // end of stream } // System.out.print( (char) back ) ; return back ; }
5
public static HashMap<String, ItemMold> loadItems(){ HashMap<String, ItemMold> terrainMap = new HashMap(); try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("resources/configfiles/items.txt"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String newFeature = "dummy", currentLine, currentList[]; //Read File Line By Line while ((currentLine = br.readLine()) != null) { currentList = currentLine.split("=", 2); currentList[0] = currentList[0].trim(); if (currentList[0].length() == 0){ continue; } switch((currentList[0].charAt(0))){ //looks messy, but basically we check the first character of the new line case '#': continue; case '[': newFeature = currentList[0].substring(1, currentList[0].length() - 1); terrainMap.put(newFeature, new ItemMold()); //System.out.println(terrainMap.get(newFeature).getName()); continue; default: if (currentList.length == 2){ currentList[1] = currentList[1].trim().toLowerCase(); terrainMap.get(newFeature).enterData(currentList); } } } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } return terrainMap; }
6
public static void handleEvent(int eventId) { if(eventId == 1) { System.out.println("Exit high score menu selected"); Main.highScoreMenu.setVisible(false); Main.highScoreMenu.setEnabled(false); Main.highScoreMenu.setFocusable(false); Main.mainFrame.remove(Main.highScoreMenu); Main.mainFrame.add(Main.mainMenu); Main.mainMenu.setVisible(true); Main.mainMenu.setEnabled(true); Main.mainMenu.setFocusable(true); Main.mainMenu.requestFocusInWindow(); } else if(eventId == 2) { } else if(eventId == 3) { } else if(eventId == 4) { } else if(eventId == 5) { } }
5
public static String encryptMD5(String pwd) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pwd.getBytes()); StringBuffer stringBuffer = new StringBuffer(); int n; byte[] b = md.digest(); for (int i = 0; i < b.length; i++) { n = b[i]; if (n < 0) { n += 256; } // stringBuffer.append(Integer.toHexString(n / 16) + Integer.toHexString(n % 16)); if (n < 16) { stringBuffer.append("0"); } stringBuffer.append(Integer.toHexString(n)); } return stringBuffer.toString(); } catch (NoSuchAlgorithmException e) { LOGGER.info("Encrypt Error"); return null; } }
4
@Override public double predict(T data) { if (log) System.out.println("Trying to predict: " + data.getNome()); double result = 0; for(int i = 0; i < w.length; i ++) { if (log) System.out.print("w[" + i+ "]=" + w[i] +" "); result += w[i]*data.getAttr(i); } if (log) { System.out.println(); for(int i = 0; i < w.length; i ++) { System.out.print("a[" + i+ "]=" + data.getAttr(i) +" "); } System.out.println("\nresult = " + result); } return result; }
5
public void mouseClicked(MouseEvent e) { if (isInside(e.getX(), e.getY())) { if (first == null) { first = this; select(); } else { this.deselect(); first.deselect(); panel.permut(this, first); first = null; } } }
2
@Override public Object getValueAt(int row, int col) { switch(col) { case 0: int x = row+1; switch(x) { case 1: return "Sunday"; case 2: return "Monday"; case 3: return "Tuesday"; case 4: return "Wednesday"; case 5: return "Thursday"; case 6: return "Friday"; case 7: return "Staurday"; } break; case 1: return theData.get(row); } return null; }
9
@Override public Class getColumnClass(int column) { Class returnValue; if ((column >= 0) && (column < getColumnCount())) { if(getValueAt(0, column)==null) return String.class; returnValue = getValueAt(0, column).getClass(); } else { returnValue = Object.class; } return returnValue; }
3
public static int[] getPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (w == 0 || h == 0) { return new int[0]; } if (pixels == null) { pixels = new int[w * h]; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { Raster raster = img.getRaster(); return (int[]) raster.getDataElements(x, y, w, h, pixels); } // Unmanages the image return img.getRGB(x, y, w, h, pixels, 0, w); }
6
public static byte[] gzip(String input) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = null; try { gzos = new GZIPOutputStream(baos); gzos.write(input.getBytes("UTF-8")); } catch (IOException e) { e.printStackTrace(); } finally { if (gzos != null) { try { gzos.close(); } catch (IOException ignore) { } } } return baos.toByteArray(); }
3
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double) o).isInfinite() || ((Double) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float) o).isInfinite() || ((Float) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
public void run() { while(!killed()) { long nextFlushLocal = nextFlush.get(); long currentTime = System.currentTimeMillis(); //System.out.println("next flush local: " + nextFlushLocal + " currentTime " + currentTime); if(nextFlushLocal != 0 && nextFlushLocal < currentTime + 2) { //if(lock.tryLock()) { lock.lock(); { try { flush(); } catch (IOException e) { } finally { lock.unlock(); } } } synchronized(syncObj) { nextFlushLocal = nextFlush.get(); currentTime = System.currentTimeMillis(); long delay = Math.max(2L, Math.min(maxLatency, nextFlushLocal - currentTime)); //System.out.println("Timer sleeping for " + delay + " at " + System.currentTimeMillis()); try { if(nextFlushLocal == 0 ) { //System.out.println("Waiting 500"); syncObj.wait(500); } else { //System.out.println("Waiting " + delay); syncObj.wait(delay); } //System.out.println("Timer wake up" + System.currentTimeMillis()); } catch (InterruptedException ie) { kill(); continue; } } } }
6
public Class getTypeClass() throws ClassNotFoundException { if (clazz != null) return Class.forName(clazz.getName()); else if (ifaces.length > 0) return Class.forName(ifaces[0].getName()); else return Class.forName("java.lang.Object"); }
2
final void method1970(int i, int i_61_, int i_62_, boolean bool, int i_63_, int i_64_, int i_65_, int i_66_, byte[] is, int i_67_) { if (i_63_ == 0) i_63_ = i_62_; anInt8539++; if (bool) { int i_68_ = Class183.method1382(i_65_, -6409); int i_69_ = i_68_ * i_62_; int i_70_ = i_63_ * i_68_; byte[] is_71_ = new byte[i_64_ * i_69_]; for (int i_72_ = 0; (i_72_ ^ 0xffffffff) > (i_64_ ^ 0xffffffff); i_72_++) { int i_73_ = i_69_ * i_72_; int i_74_ = (-1 + i_64_ - i_72_) * i_70_ + i_67_; for (int i_75_ = 0; i_75_ < i_69_; i_75_++) is_71_[i_73_++] = is[i_74_++]; } is = is_71_; } ((Class258) this).aHa_Sub2_4851.method3771((byte) -102, this); OpenGL.glPixelStorei(3317, 1); if (i_62_ != i_63_) OpenGL.glPixelStorei(3314, i_63_); OpenGL.glTexSubImage2Dub(((Class258) this).anInt4849, 0, i, i_61_, i_62_, i_64_, i_65_, 5121, is, i_67_); if (i_63_ != i_62_) OpenGL.glPixelStorei(3314, 0); OpenGL.glPixelStorei(3317, 4); int i_76_ = -17 % ((46 - i_66_) / 59); }
6
public TetrisEngine(){ this.score = 0; this.fLines = 0; this.toggle = true; // @todo pull initialization out of constructor and add to variable definitions t = new Tetrimino(); b = new Tetrimino(); next = new Tetrimino(); p = new Playfield(); pause = false; gameStatus = true; gui = new TetrisGUI(b,t,next,p, this); gui.setTitle("TetriQ"); gui.setVisible(true); gui.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { //System.out.println("key: "+e.getKeyCode()); switch(e.getKeyCode()){ case 16: toggle(); break; case 37:moveLeft(); break; case 38:rotate(); break; case 39:moveRight(); break; case 40:moveDown(); break; case 32:dropDown(); break; case 80: togglePause(); break; } } @Override public void keyReleased(KeyEvent arg0) {} @Override public void keyTyped(KeyEvent arg0) {} }); this.setSpeed(650); setTimer(this.getSpeed()); tetriminoInit(); }
7
public void addPersoon(Geslacht geslacht, String[] vnamen, String anaam, String tvoegsel, GregorianCalendar gebdat, Gezin ouderlijkGezin) { if (geslacht != null && vnamen != null && anaam != null && tvoegsel != null && gebdat != null) { Persoon persoon = new Persoon(nextPersNr, vnamen, anaam, tvoegsel, gebdat, geslacht, ouderlijkGezin); personen.add(persoon); nextPersNr++; } }
5
public void insertString( int off, String string, AttributeSet abr ) throws BadLocationException { if ( string == null ) { return; } boolean ok = true; char[] chars = string.toCharArray(); for ( int i = 0; i < chars.length; i++ ) { try { if (!( String.valueOf( chars[i] ).equals("."))){ Integer.parseInt( String.valueOf( chars[i] ) ); } } catch ( NumberFormatException exc ) { ok = false; break; } } if ( ok ) super.insertString( off, new String( chars ), abr ); }
5
public String to(String field, int min, int max) { String newField = ""; for(int i = 1; i <= field.length(); i++) { if(isNumber(field.substring(i - 1, i))) { newField = newField + field.substring(i - 1, i); } else { newField = "~invalid~"; break; } boolean over = false; try { if(Integer.parseInt(newField) > max) { over = true; } }catch(Exception e) { System.out.println("not a integer"); } if(over) { newField = "~invalid over~"; break; } } boolean under = false; try { if(Integer.parseInt(newField) < min) { under = true; } }catch(Exception e) { System.out.println("not a integer"); } if(under) { newField = "~invalid under~"; } newField = " TO " + newField; return newField; }
8
public static void main(String[] args) { //creates an array to store student data LAB6 CLASS[] = new LAB6[11]; //basic counter and [i] is place in the array int i,j,k = 0,counter=0; boolean is_running=true; //creates new columns for the array for(i=0;i<CLASS.length;i++) CLASS[i]= new LAB6(); //defines the input file File inFile = new File("Lab6.Dat"); //to use command line to input data comment the previous line //and uncomment the following //File inFile = new File(args[0]); //defines the desired out file File outFile = new File("Lab_6.out"); //to use command line to output data comment the previous line //and uncomment the following //File outFile = new File(args[1]); //creates a variable to store data as it gets read in String getLine=""; //array to store the parsed data String result[]; //try statement keeps the program from crashing if //a problem occurs in file read in try { //makes it possible for the program to read & write data FileInputStream inStream = new FileInputStream(inFile); FileOutputStream outStream = new FileOutputStream(outFile); BufferedReader buffRead = new BufferedReader(new InputStreamReader(inStream)); BufferedWriter buffWrite = new BufferedWriter(new OutputStreamWriter(outStream)); //reads the data file until the end while((getLine=buffRead.readLine()) !=null) { //parses each line when a comma occurs result= getLine.split("\\,"); //the first number is the students ID# CLASS[counter].ID=Integer.parseInt(result[0]); //second number is students lab grade CLASS[counter].LAB=Integer.parseInt(result[1]); //third number is students quiz grade CLASS[counter].QUIZ=Integer.parseInt(result[2]); //fourth number is students final grade CLASS[counter].FINAL=Integer.parseInt(result[3]); //prints each student on one line System.out.print(CLASS[counter].ID+","); System.out.print(CLASS[counter].LAB+","); System.out.print(CLASS[counter].QUIZ+","); System.out.print(CLASS[counter].FINAL+"\n"); //Yay Counters... counter++; } //performs bubble sort while(is_running) { is_running=false; k++; for(j=0;j<CLASS.length-k;j++) { if(CLASS[j].FINAL>CLASS[j+1].FINAL) { temp_Vals[0]=CLASS[j].ID; temp_Vals[1]=CLASS[j].LAB; temp_Vals[2]=CLASS[j].QUIZ; temp_Vals[3]=CLASS[j].FINAL; CLASS[j].ID=CLASS[j+1].ID; CLASS[j].LAB=CLASS[j+1].LAB; CLASS[j].QUIZ=CLASS[j+1].QUIZ; CLASS[j].FINAL=CLASS[j+1].FINAL; CLASS[j+1].ID=temp_Vals[0]; CLASS[j+1].LAB=temp_Vals[1]; CLASS[j+1].QUIZ=temp_Vals[2]; CLASS[j+1].FINAL=temp_Vals[3]; is_running=true; } } } System.out.println("\n"+"Sorted Final Grades from Least to Greatest"); for (i=0;i<CLASS.length;i++) { //prints each student on one line System.out.print(CLASS[i].ID+","); System.out.print(CLASS[i].LAB+","); System.out.print(CLASS[i].QUIZ+","); System.out.print(CLASS[i].FINAL+"\n"); } //writes the data to the output file buffWrite.write("Student ID -> Lab Grade -> Quiz Grade -> Final Grade"+"\r\n"); buffWrite.write("Final Grades Least to Greatest"+"\r\n"); buffWrite.write(""+"\r\n"); //writes the original data for(i=0;i<counter;i++) buffWrite.write(CLASS[i].ID+","+CLASS[i].LAB+","+CLASS[i].QUIZ+"," +CLASS[i].FINAL+"\r\n"); //closes the reader buffRead.close(); //closes the writer buffWrite.close(); } //if a file read error occurs print the error for the user to read catch (Exception e) { System.out.println("Error" + e.getMessage()); } }
8
public static JsonObject getJsonForURL(String url, List<ResponseErrors> possibleErrors) { HttpURLConnection connection = null; StringBuilder builder = null; JsonObject json = null; try { URL inputURL = new URL(url); connection = (HttpURLConnection) inputURL.openConnection(); builder = new StringBuilder(); InputStream inputStream = null; String inputLine; int responseCode = connection.getResponseCode(); for(ResponseErrors recognizedError : possibleErrors) { if(recognizedError.getCode() == responseCode) { throw new ResponseErrors(recognizedError.getMessage()); } } try { inputStream = connection.getInputStream(); } catch (FileNotFoundException e) { throw new ResponseErrors("Error code 404"); } if (inputStream == null) { throw new ResponseErrors("Empty Response"); } BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); while ((inputLine = reader.readLine()) != null) { builder.append(inputLine); } json = new JsonObject(builder.toString()); } catch (IOException e) { e.printStackTrace(); } catch (ResponseErrors re) { re.printStackTrace(); } return json; }
7
@Test public void testRetirarProduto() { try { Assert.assertEquals(10, facade.getQuantidadeProduto(1)); } catch (FacadeException e) { Assert.fail(e.getMessage()); } try { facade.retirarProduto(1, 5); Assert.assertEquals(5, facade.getQuantidadeProduto(1)); } catch (FacadeException e) { Assert.fail(e.getMessage()); } try { facade.retirarProduto(2, 0); Assert.assertEquals(5, facade.getQuantidadeProduto(2)); } catch (FacadeException e) { Assert.fail(e.getMessage()); } try { facade.retirarProduto(4, 1); Assert.assertEquals(0, facade.getQuantidadeProduto(4)); } catch (FacadeException e) { Assert.fail(e.getMessage()); } try { facade.retirarProduto(3, -1); Assert.fail("deveria ter lanรado uma exceรโ€žo"); } catch (FacadeException e) { // รˆ para lanรa uma exceรโ€žo } }
5
@Override public long invert(long element) { isInField(element); if (element == 1) { return 1; } if (element == 0) { throw new MathArithmeticException("Cannot find inverse for ZERO."); } //prepare for division long remainder = element; long numerator = reducingPolynomial; long denumerator = element; //prepare to find Bezout's identity long temp = 0; ArrayList<Long> resultList = new ArrayList<>(); ArrayList<Long> bezoutIdentity = new ArrayList<>(); //find greatest greatest common divisor, last positive remainder while (remainder != 0) { short numeratorBinarySize = countBinarySize(numerator); short denumeratorBinarySize = countBinarySize(denumerator); long tempNumerator = numerator; //division of binary polynomial long result = 0; while (numeratorBinarySize >= denumeratorBinarySize) { temp = 1; temp <<= (numeratorBinarySize - denumeratorBinarySize); result ^= temp; tempNumerator ^= (denumerator << (numeratorBinarySize - denumeratorBinarySize)); numeratorBinarySize = countBinarySize(tempNumerator); denumeratorBinarySize = countBinarySize(denumerator); } remainder = tempNumerator; if (remainder == 0 && denumerator != 1) { throw new MathArithmeticException("Cannot compute inverse" + " for this element."); } //resultList data neccessary to find Bezout's identity resultList.add(numerator); resultList.add(denumerator); resultList.add(result); numerator = denumerator; denumerator = remainder; } if (resultList.size() > 3) { //we don't need last 3 values resultList.remove(resultList.size() - 1); resultList.remove(resultList.size() - 1); resultList.remove(resultList.size() - 1); } bezoutIdentity.add(1l); bezoutIdentity.add(resultList.get(resultList.size() - 3)); bezoutIdentity.add(resultList.get(resultList.size() - 2)); bezoutIdentity.add(resultList.get(resultList.size() - 1)); //find Bezout's identity from resultList data counted in Euclidean algorithm while (resultList.size() != 3) { resultList.remove(resultList.size() - 1); resultList.remove(resultList.size() - 1); resultList.remove(resultList.size() - 1); temp = bezoutIdentity.get(0); bezoutIdentity.set(0, bezoutIdentity.get(3)); bezoutIdentity.set(1, resultList.get(resultList.size() - 3)); bezoutIdentity.set(2, resultList.get(resultList.size() - 2)); bezoutIdentity.set(3, add(temp, multiply(bezoutIdentity.get(3), resultList.get(resultList.size() - 1)))); } //inverted element return bezoutIdentity.get(3); }
8
@EventHandler public void GiantInvisibility(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getGiantConfig().getDouble("Giant.Invisibility.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if ( plugin.getGiantConfig().getBoolean("Giant.Invisibility.Enabled", true) && damager instanceof Giant && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, plugin.getGiantConfig().getInt("Giant.Invisibility.Time"), plugin.getGiantConfig().getInt("Giant.Invisibility.Power"))); } }
6
void close(Dockable dockable) { int count = getComponentCount(); for (int i = 0; i < count; i++) { Component child = getComponent(i); if (child instanceof DockTab) { if (((DockTab) child).getDockable() == dockable) { remove(child); return; } } } }
3
public static void main(String[] args) { Scanner in = new Scanner(System.in); String input = in.nextLine(); String[] inputSplit = input.split(" "); Integer[] num = new Integer[inputSplit.length]; int caunt = 1; int indexI = 0; int sumCaunt =0; ArrayList<Integer> sample = new ArrayList<>(); for (int i = 0; i < inputSplit.length; i++) { num[i] = Integer.parseInt(inputSplit[i]) ; } System.out.print(num[0] + " "); for (int i = 1; i < num.length; i++) { if (num[i-1] < num[i]) { System.out.print(num[i] + " "); caunt ++; indexI = i; } else { System.out.println(); if (caunt > sumCaunt) { sample.clear(); sumCaunt = caunt; for (int j = i - caunt; j <= caunt; j++) { sample.add(num[j]); } } caunt = 1; System.out.print(num[i] + " "); } } if (caunt > sumCaunt) { sample.clear(); sumCaunt = caunt; for (int j = (indexI + 1) - caunt; j <= indexI; j++) { sample.add(num[j]); } } System.out.println(); System.out.print("Longest: " ); for (Integer samples : sample) { System.out.print(samples + " "); } }
8
private int getNumberOfSuits(int suit) { int num = 0; for (int i = 0; i < 5; i++) { if (hand[i].getSuit() == suit) { num += 1; } } return num; }
2
@Test public void kingAndRook() { Map<String, Integer> figureQuantityMap = new HashMap<>(); figureQuantityMap.put(KING.toString(), 2); figureQuantityMap.put(ROOK.toString(), 2); int dimension = 7; assertThat("all elements are not present on each board", prepareBoardsWithKingAndRook(figureQuantityMap, dimension) .parallel() .filter(board -> board.contains(KING.getFigureAsString()) && !board.contains(QUEEN.getFigureAsString()) && !board.contains(BISHOP.getFigureAsString()) && board.contains(ROOK.getFigureAsString()) && !board.contains(KNIGHT.getFigureAsString()) && board.contains(FIELD_UNDER_ATTACK_STRING) && board.contains(EMPTY_FIELD_STRING) && leftOnlyFigures(board).length() == 4) .map(e -> 1) .reduce(0, (x, y) -> x + y), is(153064)); }
7
public String getConsumerKey() { return consumerKey; }
0
public static <T extends DC> Set<DC> dMax(Set<Pair<Pair<PT<Integer>,T>,Pair<PT<Integer>,T>>> indexedDelta) { if(indexedDelta!=null) { if(indexedDelta.getNext()!=null) { return new Set(indexedDelta.getFst().fst().delta(indexedDelta.getFst().snd()).diff(),dMax(indexedDelta.getNext())); } else { return new Set(indexedDelta.getFst().fst().delta(indexedDelta.getFst().snd()).diff(),null); } } else { return null;} }
2
public static Cons yieldInitialValueAssignments(Stella_Class renamed_Class, Keyword mode) { { Cons assignments = Stella.NIL; Stella_Object initialvalueassignment = null; { Slot slot = null; Iterator iter000 = renamed_Class.classSlots(); while (iter000.nextP()) { slot = ((Slot)(iter000.value)); slot.slotMarkedP = false; } } { Slot slot = null; Iterator iter001 = renamed_Class.classSlots(); while (iter001.nextP()) { slot = ((Slot)(iter001.value)); Slot.markDirectEquivalentSlot(slot); } } { Slot slot = null; Iterator iter002 = renamed_Class.classSlots(); while (iter002.nextP()) { slot = ((Slot)(iter002.value)); if ((!slot.slotMarkedP) && Stella_Object.storageSlotP(slot)) { initialvalueassignment = StorageSlot.yieldInitialValueAssignment(((StorageSlot)(slot)), mode); if (initialvalueassignment != null) { assignments = Cons.cons(initialvalueassignment, assignments); } } } } return (assignments); } }
6
public static void main(String[] args) { int mapsize = 2000; int aircraftAmmount = 50; int objectAmmount = 100; //int [][]m = map.getMap(); float objectMap[][] = new float[objectAmmount][5]; Map map = new Map(mapsize); for (int i = 0; i < objectAmmount; i++) { float x = (int)(Math.random() * mapsize-1)+1; float y = (int)(Math.random() * mapsize-1)+1; float width = (int)(Math.random() * 100)+1; float height = (int)(Math.random() * 100)+1; float length = (int)(Math.random() * 200)+1; map.addObject((int)x, (int)y, (int)width, (int)height, (int)length); objectMap[i][0] = x / 100; objectMap[i][1] = y / 100; objectMap[i][2] = width / 100; objectMap[i][3] = height / 100; objectMap[i][4] = length / 100; } Graphics graphics = new Graphics(objectMap); }
1
public LinkedList<TuileBonus> initialisationTuileBonus(){ LinkedList<TuileBonus> lltb = new LinkedList<TuileBonus>(); for(Troupes t : hashTroupes){ for(Bonus b : hashBonus){ TuileBonus tb = new TuileBonus(t, b); for(int i=1; i<3; i++){ lltb.add(tb); } } } Collections.shuffle(lltb); return lltb; }
3
public static MoveRequestState swigToEnum(int swigValue) { if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) return swigValues[swigValue]; for (int i = 0; i < swigValues.length; i++) if (swigValues[i].swigValue == swigValue) return swigValues[i]; throw new IllegalArgumentException("No enum " + MoveRequestState.class + " with value " + swigValue); }
5
public boolean isRGB() { return colorType == COLOR_TRUEALPHA || colorType == COLOR_TRUECOLOR || colorType == COLOR_INDEXED; }
2
public String getMessage() { if (!specialConstructor) { return super.getMessage(); } StringBuffer expected = new StringBuffer(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; }
9
private void read() throws IOException { if (isEndOfText()) { throw error("Unexpected end of input"); } if (index == fill) { if (captureStart != -1) { captureBuffer.append(buffer, captureStart, fill - captureStart); captureStart = 0; } bufferOffset += fill; fill = reader.read(buffer, 0, buffer.length); index = 0; if (fill == -1) { current = -1; return; } } if (current == '\n') { line++; lineOffset = bufferOffset + index; } current = buffer[index++]; }
5
public EventList() { muffinbag = new EnumMap<Priority, ArrayList<RegisteredListener>>(Priority.class); for (Priority o : Priority.values()) { muffinbag.put(o, new ArrayList<RegisteredListener>()); } synchronized(mail) { mail.add(this); } }
1
public void onRandomTick (World world, int x, int y) { int xa = (world.random.nextBoolean()) ? 1 : -1; int ya = world.random.nextInt(3) - 1; Tile tilea = world.getTile(x + xa, y + ya); if (tilea != null && tilea.id == Tile.dirt.id) { Tile tileb = world.getTile(x + xa, y + ya + 1); if (tileb != null && tileb.id == Tile.air.id) { world.setTile(x + xa, y + ya, Tile.grass); return; } } }
5
private void copyRGBtoRGBA(ByteBuffer buffer, byte[] curLine) { if(transPixel != null) { byte tr = transPixel[1]; byte tg = transPixel[3]; byte tb = transPixel[5]; for(int i=1,n=curLine.length ; i<n ; i+=3) { byte r = curLine[i]; byte g = curLine[i+1]; byte b = curLine[i+2]; byte a = (byte)0xFF; if(r==tr && g==tg && b==tb) { a = 0; } buffer.put(r).put(g).put(b).put(a); } } else { for(int i=1,n=curLine.length ; i<n ; i+=3) { buffer.put(curLine[i]).put(curLine[i+1]).put(curLine[i+2]).put((byte)0xFF); } } }
6
public void validate_insert(String dataBaseName, String tableName, ArrayList<Field> entries) { boolean flag = true; if (check_dataBase(dataBaseName)) { if (check_table(dataBaseName, tableName)) { for (Field element : entries) { if (!check_type(dataBaseName, tableName, element.getValue(), element.getName())) { flag = false; break; } } if (flag) { DBMS ob = new DBMSImplementer(); ob.insert(dataBaseName, tableName, entries); } else { System.out .println("data type does not math the table's data type"); } } else System.out.println("table does not exist!"); } else System.out.println("database does not exist!"); }
5
public TravelFileBean getFileName(int idx) throws Exception{ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; TravelFileBean fileBean = null; String sql = ""; String filename = ""; String fileTmp = ""; try{ conn = getConnection(); sql = "select * from travelfile where idx=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, idx); rs = pstmt.executeQuery(); fileBean = new TravelFileBean(); if(rs.next()){ fileBean.setFileid(rs.getInt("fileid")); fileTmp = rs.getString("filename"); StringTokenizer st = new StringTokenizer(fileTmp,"\\"); while(st.hasMoreElements()){ filename=st.nextToken(); } fileBean.setFilename(filename); fileBean.setRealpath("upload/"+filename); }else{ fileBean.setFilename("ํŒŒ์ผ์—†์Œ"); fileBean.setRealpath("ํŒŒ์ผ์—†์Œ"); } }catch(Exception ex){ ex.printStackTrace(); }finally{ if(rs!=null)try{rs.close();}catch(SQLException ex){} if(pstmt!=null)try{pstmt.close();}catch(SQLException ex){} if(conn!=null)try{conn.close();}catch(SQLException ex){} } return fileBean; }
9
public static void connectToDatabase() { if(connect != null) return; try{ Class.forName("com.mysql.jdbc.Driver"); connect = DriverManager.getConnection("jdbc:mysql://localhost/CN?user=shas&password=shas"); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
3
private void setDimensions(String dataType) { if (dataType.equals("xor")) { Point.nrDimensions = 2; Point.setClasses(new int[]{-1,1}); } else if (dataType.equals("diabetes")) { Point.nrDimensions = 8; Point.setClasses(new int[]{0,1}); } else if (dataType.equals("mnist")) { int[] classes = new int[10]; for (int i = 0; i < 10; i++) { classes[i]=i; } Point.nrDimensions = 196; Point.setClasses(classes); } else if (dataType.equals("nieuws")) { Point.nrDimensions = 20; Point.setClasses(new int[]{1,2,3}); } else if (dataType.equals("karakter")) { int[] classes = new int[400]; for (int i = 1; i <= 400; i++) { classes[i-1]=i; } Point.nrDimensions = 400; Point.setClasses(classes); } }
7
@Override public boolean containsAll(Collection<?> c) { // TODO Auto-generated method stub return false; }
1
public void showCustomerOrders() { textArea.setText(""); for (int i = 0; i < driver.getOrderDB().getCustomerOrderList().size(); i++) { Order order = (driver.getOrderDB().getCustomerOrderList().get(i)); textArea.append("Order " + order.getId() + " was created by " + order.getCurrentlyLoggedInStaff().getName() + "\nCustomer ID : " + ((Customer) order.getPerson()).getId() + "\nItems in this order :"); for (int j = 0; j < order.getOrderEntryList().size(); j++) { StockItem stockItem = order.getOrderEntryList().get(j); textArea.append("\n " + stockItem.getQuantity() + " " + stockItem.getProduct().getProductName() + " " + (stockItem.getProduct().getRetailPrice() * stockItem.getQuantity())); } textArea.append("\nThe total order value is " + order.getGrandTotalOfOrder() + "\n\n\n"); } }
2
public void init() { TotalBudget.getInstance(); Integer height = null; Integer width = null; Map<String,List<String>> parameters = Window.Location.getParameterMap(); if ( parameters.containsKey("w") && parameters.containsKey("h") ) { height= Integer.parseInt( parameters.get("h").get(0) ); width = Integer.parseInt( parameters.get("w").get(0) ); } mResultsGrid = new ResultGrid(); mResultsGrid.setWidth("100%"); Integer pieWidth = width == null ? 485 : width; Integer pieHeight = height == null ? 400 : height; mPieCharter = new PieCharter(this, mEmbedded, pieWidth, pieHeight); mPieCharter.setWidth(pieWidth+"px"); mPieCharter.setHeight(pieHeight+"px"); Integer timeWidth = width == null ? 686 : width; Integer timeHeight = height == null ? 400 : height; mTimeLineCharter = new TimeLineCharter(this, mEmbedded, timeWidth, timeHeight); mTimeLineCharter.setWidth(timeWidth+"px"); mTimeLineCharter.setHeight(timeHeight+"px"); mBreadcrumbs = new HTML(""); mBreadcrumbs.setHeight("20px"); mBreadcrumbs.setWidth("100%"); mYearSelection = new ListBox(); mYearSelection.addChangeHandler( new ChangeHandler() { @Override public void onChange(ChangeEvent event) { Integer index = mYearSelection.getSelectedIndex(); String yearStr = mYearSelection.getItemText(index); Integer year; try { year = Integer.parseInt(yearStr); } catch (Exception e) { yearStr = yearStr.split(" ")[0]; year = Integer.parseInt(yearStr); } selectYear(year); } }); mSearchBox = new SuggestBox(new BudgetSuggestionOracle()); mSearchBox.setWidth("300px"); mSearchBox.addSelectionHandler( new SelectionHandler<Suggestion>() { @Override public void onSelection(SelectionEvent<Suggestion> event) { final BudgetSuggestion bs = (BudgetSuggestion) event.getSelectedItem(); BudgetAPICaller api = new BudgetAPICaller(); api.setCode(bs.getCode()); api.setParameter("depth", "0"); api.setParameter("text", bs.getTitle()); api.go( new BudgetAPICallback() { @Override public void onSuccess(JSONArray data) { if ( data.size() > 0 ) { Integer year = (int) data.get(0).isObject().get("year").isNumber().doubleValue(); newCodeAndYear(bs.getCode(),year); } } }); } }); mSummary1 = new Label(); mSummary2 = new Label(); mSummary2_1 = new Label(); mSummary3 = new HTML(); mSummary3_1 = new HTML(); mBudgetNews = new BudgetNews(); mCheatSheet = new HTML("(ื”ืกื‘ืจื™ื)"); final DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true); simplePopup.setWidth("450px"); HTML simplePopupContents = new HTML( "<h4>ืžื•ื ื—ื•ืŸ ืžืงื•ืฆืจ</h4>"+ "<lu>"+ "<li><b>ื ื˜ื•</b>: <u>ืชืงืฆื™ื‘ ื”ื•ืฆืื” ื ื˜ื•</u> โ€“ ื”ืกื›ื•ื ื”ืžื•ืชืจ ืœื”ื•ืฆืื” ื‘ืฉื ื” ื›ืœืฉื”ื™ ื›ืคื™ ืฉืžืคื•ืจื˜ ื‘ื—ื•ืง ื”ืชืงืฆื™ื‘. ืชืงืฆื™ื‘ ื–ื” ืžื›ื•ื ื” ื’ื \"ืชืงืฆื™ื‘ ื”ืžื–ื•ืžื ื™ื\".</li>"+ "<li><b>ื‘ืจื•ื˜ื•</b>: <u>ืชืงืฆื™ื‘ ื”ื”ื•ืฆืื” ื ื˜ื•</u> ื‘ืชื•ืกืคืช <u>ืชืงืฆื™ื‘ ื”ื”ื•ืฆืื” ื”ืžื•ืชื ื™ืช ื‘ื”ื›ื ืกื”</u> โ€“ ืชืงืฆื™ื‘ ื ื•ืกืฃ ื”ืžื•ืชืจ ื‘ื”ื•ืฆืื”, ื•ื‘ืœื‘ื“ ืฉื™ืชืงื‘ืœื• ืชืงื‘ื•ืœื™ื ืœืžื™ืžื•ืŸ ื”ื”ื•ืฆืื” ืžื’ื•ืจืžื™ื ื—ื•ืฅ-ืžืžืฉืœืชื™ื™ื. ืชืงื‘ื•ืœื™ื ืืœื• ืื™ื ื ื›ื•ืœืœื™ื ืื’ืจื” ื”ืžืฉื•ืœืžืช ืœืื•ืฆืจ ื”ืžื“ื™ื ื” ืฉื”ื•ื˜ืœื” ืขืœ-ืคื™ ื—ื™ืงื•ืง ืฉื ื—ืงืง ืื—ืจื™ ืชื—ื™ืœืช ืฉื ืช ื”ื›ืกืคื™ื 1992, ื•ืื™ื ื” ื›ื•ืœืœืช ื”ื›ื ืกื” ืฉืžืงื•ืจื” ื‘ืžืœื•ื•ื” (ื—ื•ืฅ ืžืชืงืฆื™ื‘ื™ ืคื™ืชื•ื— ื•ื—ืฉื‘ื•ืŸ ื”ื•ืŸ).</li>"+ "<li><b>ื”ืงืฆืื”</b>: <u>ืชืงืฆื™ื‘ ืžืงื•ืจื™</u> โ€“ ื”ืชืงืฆื™ื‘ ืฉืื•ืฉืจ ื‘ื›ื ืกืช ื‘ืžืกื’ืจืช ื—ื•ืง ื”ืชืงืฆื™ื‘. ื™ื™ืชื›ื ื• ื”ื‘ื“ืœื™ื ื‘ื™ืŸ ื”ืฆืขืช ื”ืชืงืฆื™ื‘ ืœื‘ื™ืŸ ื”ืชืงืฆื™ื‘ ืฉื™ืื•ืฉืจ ื‘ื›ื ืกืช ื‘ืกื•ืคื• ืฉืœ ื“ื‘ืจ.</li>"+ "<li><b>ื”ืงืฆืื” ืžืขื•ื“ื›ื ืช</b>: <u>ืชืงืฆื™ื‘ ืขืœ ืฉื™ื ื•ื™ื™ื•</u> โ€“ ืชืงืฆื™ื‘ ื”ืžื“ื™ื ื” ืขืฉื•ื™ ืœื”ืฉืชื ื•ืช ื‘ืžื”ืœืš ื”ืฉื ื”. ืฉื™ื ื•ื™ื™ื ืืœื• ื›ื•ืœืœื™ื ืชื•ืกืคื•ืช, ื”ืคื—ืชื•ืช ื•ื”ืขื‘ืจื•ืช ืชืงืฆื™ื‘ื™ื•ืช ื‘ื™ืŸ ืกืขื™ืคื™ ืชืงืฆื™ื‘ (ื‘ืื™ืฉื•ืจ ื•ืขื“ืช ื”ื›ืกืคื™ื ืฉืœ ื”ื›ื ืกืช). ื ื•ืกืฃ ืขืœ ื›ืš, ืคืขืžื™ื ืจื‘ื•ืช ืžื•ืขื‘ืจื™ื ืขื•ื“ืคื™ื ืžื—ื•ื™ื‘ื™ื ืžืฉื ื” ืงื•ื“ืžืช ื”ื ื›ืœืœื™ื ื‘ืชืงืฆื™ื‘ ื–ื”. ืจื•ื‘ ื”ืฉื™ื ื•ื™ื™ื ื‘ืชืงืฆื™ื‘ ื“ื•ืจืฉื™ื ืืช ืื™ืฉื•ืจื” ืฉืœ ื•ืขื“ืช ื”ื›ืกืคื™ื ืฉืœ ื”ื›ื ืกืช. ื”ืชืงืฆื™ื‘ ื‘ืกื•ืฃ ื”ืฉื ื” ื”ื›ื•ืœืœ ืืช ื”ืฉื™ื ื•ื™ื™ื ืฉื ืขืฉื• ื‘ื• ื‘ืžื”ืœืš ื”ืฉื ื” ื ืงืจื ื”ืชืงืฆื™ื‘ ืขืœ ืฉื™ื ื•ื™ื™ื• ืื• ื”ืชืงืฆื™ื‘ ื”ืžืื•ืฉืจ.</li>"+ "<li><b>ืฉื™ืžื•ืฉ</b>: <u>ื‘ื™ืฆื•ืข</u> โ€“ ื”ืชืงืฆื™ื‘ ืฉื›ื‘ืจ ื ื•ืฆืœ ื•ืฉื•ืœื ื‘ืคื•ืขืœ ืขืœ-ื™ื“ื™ ื”ื—ืฉื‘.</li>"+ "<li><b>ืขืจืš ืจื™ืืœื™ ื•ื ื•ืžื™ื ืœื™</b>: ืจืื• ื”ืกื‘ืจ ื‘<a href='http://he.wikipedia.org/wiki/%D7%A2%D7%A8%D7%9A_%D7%A8%D7%99%D7%90%D7%9C%D7%99_%D7%95%D7%A2%D7%A8%D7%9A_%D7%A0%D7%95%D7%9E%D7%99%D7%A0%D7%9C%D7%99' target ='_blank'>ื•ื™ืงื™ืคื“ื™ื”</a>.</li>"+ "<li><b>ืขืจืš ื™ื—ืกื™</b>: ื”ืื—ื•ื– ื”ื™ื—ืกื™ ืฉืœ ืกืขื™ืฃ ื–ื” ืžื›ืœืœ ืชืงืฆื™ื‘ ื”ืžื“ื™ื ื”</li>"+ "</lu>"+ "<br/>"+ "<i>ืœื—ืฅ ืžื—ื•ืฅ ืœื—ืœื•ื ื™ืช ื–ื• ืœืกื’ื™ืจืชื”</i>"+ "<br/>"+ "ืžืงื•ืจ: <a href='http://www.knesset.gov.il/mmm/data/docs/m02217.doc' target='_blank'>ืžืกืžืš Word ืžืžื—ืœืงืช ื”ืžื—ืงืจ ืฉืœ ื”ื›ื ืกืช</a>" + "<p><b>ื”ืชืงืฆื™ื‘ ื”ืคืชื•ื— ื”ื•ื ืคืจื•ื™ืงื˜ ื”ืชื ื“ื‘ื•ืชื™ ืฉืœ ืขืžื•ืชืช 'ื”ืกื“ื ื ืœื™ื“ืข ืฆื™ื‘ื•ืจื™'. ื”ื ืชื•ื ื™ื ื”ืžื•ืคื™ืขื™ื"+ " ื‘ืชืงืฆื™ื‘ ื”ืคืชื•ื— ื ืกืžื›ื™ื ืขืœ ืคืจืกื•ืžื™ ื”ืžื“ื™ื ื” ื•ืื™ื ื ื‘ืื™ื ืœืฉืงืฃ ื›ืœ ื“ืขื” ืฉื”ื™ื. ืื™ืŸ ืœืกื“ื ื ืœื™ื“ืข ืฆื™ื‘ื•ืจื™"+ " ื›ืœ ืื—ืจื™ื•ืช ืขืœ ื”ืฉื™ืžื•ืฉ ื‘ืคืจื•ื™ืงื˜ ื•ืจืื•ื™ ืœื‘ื“ื•ืง ืืช ื”ื ืชื•ื ื™ื ืœื’ื•ืคื ื‘ืžืงื•ืจื•ืชื™ื”ื ืœืคื ื™ ื”ืกืชืžื›ื•ืช ืขืœื™ื”ื.</b></p>" ); simplePopupContents.setStyleName("obudget-cheatsheet-popup"); simplePopup.setWidget( simplePopupContents ); mCheatSheet.addClickHandler( new ClickHandler() { @Override public void onClick(ClickEvent event) { Widget source = (Widget) event.getSource(); int left = source.getAbsoluteLeft() + 10; int top = source.getAbsoluteTop() + 10; simplePopup.setPopupPosition(left, top); simplePopup.show(); } }); History.addValueChangeHandler( this ); }
8
@Override public void messageReceived(IoSession session, Object message) throws Exception { String text = UTFCoder.decode(message); System.out.printf("Recieved : %s \n", text); String[] parameter = parse(text); if(parameter.length>=1){ if (parameter[0].equalsIgnoreCase("prepared")) { this.sendAccept(key, value); } else if (parameter[0].equalsIgnoreCase("accepted")) { try { this.write(queue.take()); } catch (InterruptedException e) { System.out.println("Queue Empty"); _transactionComplete = true; } } else { try { this.write(queue.take()); } catch (InterruptedException e) { System.out.println("Queue Empty"); _transactionComplete = true; } } } }
5