text
stringlengths
14
410k
label
int32
0
9
@Override public void happens() { for (Character characterChecking : Game.getInstance().getCharacters()) { if (characterChecking.getCurrentRoom().getFloor() == Floor_Name.BASEMENT) { int rollResult = characterChecking.getTraitRoll(Trait.SANITY); if (rollResult >= 1 && rollResult <= 3){ Trait chosenTrait = Game.getInstance().chooseAMentalTrait(); int diceToRoll = 1; if (characterChecking.getCurrentRoom() instanceof EventRoom) { diceToRoll += 1; } int damage = Game.getInstance().rollDice(diceToRoll); characterChecking.decrementTrait(chosenTrait, damage); } else if (rollResult == 0){ Trait chosenTrait = Game.getInstance().chooseAMentalTrait(); int diceToRoll = 1; if (characterChecking.getCurrentRoom() instanceof EventRoom) { diceToRoll += 2; } int damage = Game.getInstance().rollDice(diceToRoll); characterChecking.decrementTrait(chosenTrait, damage); } } } }
7
private void updateStateEntry(List<Keyword> keywords, List<String> terms) { //Either jumped due to RecipeName passed, or no Recipe could be found if (keywords == null || keywords.isEmpty()) { if (terms != null && !terms.isEmpty()) { recipeName = terms.get(0); getCurrentDialogState().setCurrentState(RecipeAssistance.RA_RECIPE_NOT_FOUND); return; } //if no terms have been passed something went wrong or just recipe/other weird keyword passed else { if (keywords != null && !keywords.isEmpty()) { for (Keyword kw : keywords) { for (DialogState d : kw.getReference()) { if (d.getCurrentState().equals(RecipeAssistance.RA_ENTRY)) { getCurrentDialogState().setCurrentState(RecipeAssistance.RA_WAITING_FOR_RECIPE_NAME); return; } } } } DialogManager.giveDialogManager().setInErrorState(true); } } }
9
public void join() { if (!isOnline) { isOnline = true; System.out.println("Input IP-address of active node"); System.out.println("If it is the first online node input 127.0.0.1"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String ipAddress = null; try { ipAddress = br.readLine(); } catch (IOException e) { System.out.println("IO error!"); System.exit(1); } if (!ipAddress.equals("127.0.0.1")) { firstActiveNode = ipAddress; getListOfEvents(true); XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(stringToURL(firstActiveNode))); } catch (MalformedURLException e) { e.printStackTrace(); } XmlRpcClient client = new XmlRpcClient(); client.setConfig(config); Object[] params = new Object[] {}; try { Object[] listOfNodes = (Object[]) client.execute("Node.getListOfActiveNode", params); for (int i = 0; i < listOfNodes.length; i++) { activeNodes.add(listOfNodes[i].toString()); } } catch (XmlRpcException e) { e.printStackTrace(); } for (String s:activeNodes) { joinOverRPC(s); } } else { isOnline = true; } } else { System.out.println("Node is already online."); } }
7
@Test public void test() { // 00000000 00000001 11111111 String data = "Hello World!"; // SO: junit-how-to-simulate-system-in-testing InputStream stdin = System.in; try { System.setIn(new ByteArrayInputStream(data.getBytes())); RunLength.compress(); } finally { System.setIn(stdin); } }
0
public void testConstructor_ObjectStringEx5() throws Throwable { try { new LocalDateTime("10:20:30.040"); fail(); } catch (IllegalArgumentException ex) {} }
1
private int findRec(){ int i = TLTa_table.getSelectedRow(); int x; for (x = 0; i>0; x++){ i = i - patient.getTreatmentRec(x).getTreatmentSize(); if (i<0) x--; } return x; }
2
public void fusionWithHardLightFullAlpha(CPLayer fusion, CPRect rc) { CPRect rect = new CPRect(0, 0, width, height); rect.clip(rc); for (int j = rect.top; j < rect.bottom; j++) { int off = rect.left + j * width; for (int i = rect.left; i < rect.right; i++, off++) { int color1 = data[off]; int alpha1 = (color1 >>> 24) * alpha / 100; if (alpha1 == 0) { continue; } int color2 = fusion.data[off]; int alpha2 = (color2 >>> 24) * fusion.alpha / 100; int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255; if (newAlpha > 0) { int alpha12 = alpha1 * alpha2 / 255; int alpha1n2 = alpha1 * (alpha2 ^ 0xff) / 255; int alphan12 = (alpha1 ^ 0xff) * alpha2 / 255; int color = newAlpha << 24; int c1, c2; c1 = (color1 >>> 16 & 0xff); c2 = (color2 >>> 16 & 0xff); color |= (alpha1n2 * c1 + alphan12 * c2 + ((c1 <= 127) ? (alpha12 * 2 * c1 * c2 / 255) : (alpha12 * ((2 * (c1 ^ 0xff) * (c2 ^ 0xff) / 255) ^ 0xff)))) / newAlpha << 16; c1 = (color1 >>> 8 & 0xff); c2 = (color2 >>> 8 & 0xff); color |= (alpha1n2 * c1 + alphan12 * c2 + ((c1 <= 127) ? (alpha12 * 2 * c1 * c2 / 255) : (alpha12 * ((2 * (c1 ^ 0xff) * (c2 ^ 0xff) / 255) ^ 0xff)))) / newAlpha << 8; c1 = color1 & 0xff; c2 = color2 & 0xff; color |= (alpha1n2 * c1 + alphan12 * c2 + ((c1 <= 127) ? (alpha12 * 2 * c1 * c2 / 255) : (alpha12 * ((2 * (c1 ^ 0xff) * (c2 ^ 0xff) / 255) ^ 0xff)))) / newAlpha; fusion.data[off] = color; } } } fusion.alpha = 100; }
7
public GoTerm rootNode() { if( (parents == null) || parents.isEmpty() ) return this; return parents.iterator().next().rootNode(); }
2
public void setNum(String num) { this.num = num; }
0
public void run(){ while(loop()); new read("deletePlayer;"+gameTag+";",ID).start(); }
4
public double[] getBulkConcns(){ if(!this.psi0set && !this.sigmaSet)throw new IllegalArgumentException("Neither a surface potential nor a surface charge/density have been entered"); if(this.sigmaSet && !this.psi0set)this.getSurfacePotential(); if(this.psi0set && !this.sigmaSet)this.getSurfaceChargeDensity(); double[] conc = Conv.copy(this.bulkConcn); for(int i=0; i<this.numOfIons; i++)conc[i] *= 1e-3; return conc; }
7
@Test public void hahmoEiPaaseVasemmallaPuolellaOlevastaEsteestaLapi() { laitetaasPariEstetta(); for (int i = 0; i < 100; i++) { pe.liikuVasemmalle(); } assertTrue("Hahmo pääsi seinästä läpi vasemmalle paahtaessaan. x = " + pe.getX(), pe.getX() > 0); }
1
private int binarysearch(int[] arr,int target,int b, int e) { if (b >= e) return -1; if (b == e - 1) if (arr[b] == target) return b; else return -1; int mid = (b + e) /2; if (arr[mid] == target) return mid; if (arr[mid] > target) return binarysearch(arr, target, b, mid); return binarysearch(arr, target, mid+1, e); }
5
@Override public String textAendern(String text) { if (text == null) { return ""; } ArrayList<Integer> spaces = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); //Position der Spaces in eine ArrayList schreiben //und aus dem String entfernden for (int i = 0; i < text.length(); i++) { if (String.valueOf(text.charAt(i)).equals(" ")) { spaces.add(i); } else { buffer.append(String.valueOf(text.charAt(i))); } } text = buffer.toString(); buffer = new StringBuilder(); //Lower-Upper-Case anwenden for (int i = 0; i < text.length(); i++) { if (i % 2 == 0) { buffer.append(String.valueOf(text.charAt(i)).toUpperCase()); } else { buffer.append(String.valueOf(text.charAt(i)).toLowerCase()); } } //Spaces wieder einfuegen for (int i : spaces) { buffer.insert(i, " "); } return buffer.toString(); }
6
private void dropLink() throws Exception { Session s = HibernateUtil.getSessionFactory().getCurrentSession(); try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); Object obj = ois.readObject(); if(obj instanceof Link) { s.beginTransaction(); s.delete(obj); s.getTransaction().commit(); out.writeBytes(acceptCmd + "\n"); toLog("Link deleted."); } } catch(ConstraintViolationException e) { out.writeBytes(failCmd + "\n"); s.getTransaction().rollback(); } catch(Exception e) { throw new Exception("Data transfer error." ); } }
3
public void open(final InputStream is, final OutputStream os) throws BITalinoException { try { socket = new BITalinoSocket(new DataInputStream(is), os); Thread.sleep(SLEEP); } catch (Exception e) { e.printStackTrace(System.err); close(); } // set samplerate on the bluetooth device try { int command = 0; switch (samplerate) { case 1000: command = 0x3; break; case 100: command = 0x2; break; case 10: command = 0x1; break; case 1: command = 0x0; break; } command = (command << 6) | 0x03; socket.write(command); } catch (Exception e) { e.printStackTrace(System.err); throw new BITalinoException(BITalinoErrorTypes.LOST_COMMUNICATION); } }
6
static String stripAccess(String newClass) { // loop until all the known access flags are stripped boolean flag = true; while (flag) { flag = false; for (int i = 0; i < accessStrings.length; i++) { String s = accessStrings[i][0]; if (newClass.substring(0, s.length()).equals(s)) { // strip the attribute away from the string newClass = newClass.substring(s.length()); flag = true; // check if this is a synthetic field/method boolean synthetic = accessStrings[i][1].equals("1"); if (synthetic) return ""; } } } return newClass; }
4
public Beverage makeBeverage(String beverageType) { Beverage beverage = null; if (beverageType.equalsIgnoreCase("Coffee")) { beverage = new Coffee(); } else if (beverageType.equalsIgnoreCase("Tea")) { beverage = new Tea(); } else if (beverageType.equalsIgnoreCase("Lemonade")) { beverage = new Lemonade(); } return beverage; }
3
public Complex Newt(Complex z, double i, double j, int mode) { if (mode == 1) { return z.sub(UnityFunction(z, i, j).div(UnityDerivative(z, i, j))); } else if (mode == 2) { return z.sub(Poly2Function(z, i, j).div(Poly2Derivative(z, i, j))); } else if (mode == 3) { return z.sub(DivZ2Function(z, i, j).div(DivZ2Derivative(z, i, j))); } else if (mode == 4) { return z.sub(Poly3Function(z, i, j).div(Poly3Derivative(z, i, j))); } else if (mode == 5) { return z.sub(DivZFunction(z, i, j).div(DivZDerivative(z, i, j))); } else { return z.sub(PolyFunction(z, i, j).div(PolyDerivative(z, i, j))); } }
5
private void hideFile() { if (stegoImg == null) { ((StegoHide)getTopLevelAncestor()).showErrorMessage("Please select a cover image!"); return; } int seedValue; try { seedValue = Integer.parseInt(seed.getText()); } catch(NumberFormatException ex) { ((StegoHide)getTopLevelAncestor()).showErrorMessage("Please enter a valid number in the seed field!"); return; } if (embedFile == null) { ((StegoHide)getTopLevelAncestor()).showErrorMessage("Please select the desired file to be hidden!"); return; } try { byte[] fileBytes = Files.readAllBytes(embedFile.toPath()); String ext = embedFile.getName().substring(embedFile.getName().lastIndexOf('.') + 1); byte[] extBytes = String.format("%-5s", ext).substring(0, 5).getBytes(); byte[] bytes = new byte[fileBytes.length + extBytes.length]; System.arraycopy(extBytes, 0, bytes, 0, extBytes.length); System.arraycopy(fileBytes, 0, bytes, extBytes.length, fileBytes.length); BufferedImage newImg = stegoImg.hide(bytes, seedValue); String newName = imgName.getText().substring(0, imgName.getText().lastIndexOf('.')); newName += "Stego." + imgFormat; JFileChooser jfc = new JFileChooser(); jfc.setAcceptAllFileFilterUsed(false); jfc.addChoosableFileFilter(new FileNameExtensionFilter(imgFormat.toUpperCase() + " files", imgFormat)); jfc.setSelectedFile(new File(newName)); int result = jfc.showSaveDialog(this); if (result != JFileChooser.APPROVE_OPTION) return; ImageIO.write(newImg, imgFormat, jfc.getSelectedFile()); ((StegoHide)getTopLevelAncestor()).showInformationMessage("The embedding process is successful!"); } catch(IllegalArgumentException ex) { ((StegoHide)getTopLevelAncestor()).showErrorMessage("The selected file's size exceeds the image's hide capacity!"); } catch(IOException ex) { ((StegoHide)getTopLevelAncestor()).showErrorMessage("Could not save the image file!"); } catch(Exception ex) { ((StegoHide)getTopLevelAncestor()).showErrorMessage("Could not embed the text in the image!"); } }
7
public static long[] euclideEtendu(long x, long y) { if (x <= 1 || y <= 1) throw new IllegalArgumentException(); long r, q, xTemp, yTemp, x0 = 1, x1 = 0, y0 = 0, y1 = 1; while (y != 0) { r = x % y; q = x / y; x = y; y = r; xTemp = x0 - q * x1; yTemp = y0 - q * y1; x0 = x1; y0 = y1; x1 = xTemp; y1 = yTemp; } return new long[] {x, x0, y0}; //pgcd, x, y }
3
public void put(String cod_competicao, String cod_jogador) { try (Statement stm = conn.createStatement()) { int i = stm.executeUpdate("Update Marcadores set Cod_Competicao='" + cod_competicao + "',cod_jogador='" + cod_jogador + "',Golo=to_number('0') WHERE Cod_competicao='" + cod_competicao + "'and cod_jogador='"+cod_jogador+"'"); if (i == 0) { String sql = "INSERT INTO Marcadores(cod_competicao,cod_jogador,golo) VALUES('" + cod_competicao + "','" + cod_jogador + "',to_number('0'))"; i = stm.executeUpdate(sql); stm.close(); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, e.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); } }
2
@Override public void connected(ConnectedEvent e) { }
0
public boolean getStudentByUniqueId(IssueBookVO issueBookVO) throws LibraryManagementException { boolean returnValue = true; ConnectionFactory connectionFactory = new ConnectionFactory(); Connection connection; try { connection = connectionFactory.getConnection(); } catch (LibraryManagementException e) { throw e; } PreparedStatement preparedStatement = null; ResultSet resultSet; try { preparedStatement = connection .prepareStatement("select * from STUDENT where U_ID = ?"); preparedStatement.setString(1, issueBookVO.getStudentID()); resultSet = preparedStatement.executeQuery(); if (!resultSet.next()) { returnValue = false; throw new LibraryManagementException( ExceptionCategory.STUDENT_NOT_REGISTERED); } } catch (SQLException e) { throw new LibraryManagementException(ExceptionCategory.SYSTEM); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { throw new LibraryManagementException( ExceptionCategory.SYSTEM); } } connectionFactory.closeConnection(connection); } return returnValue; }
5
*/ public String getConfig() { StringBuilder buffer = new StringBuilder(); int count = mModel.getColumnCount(); buffer.append(OutlineModel.CONFIG_VERSION); buffer.append('\t'); buffer.append(count); for (int i = 0; i < count; i++) { Column column = mModel.getColumnAtIndex(i); buffer.append('\t'); buffer.append(column.getID()); buffer.append('\t'); buffer.append(column.isVisible()); buffer.append('\t'); buffer.append(column.getWidth()); buffer.append('\t'); buffer.append(column.getSortSequence()); buffer.append('\t'); buffer.append(column.isSortAscending()); } return buffer.toString(); }
1
public int calculerGain() { int gains = 0; Iterator<Territoire> it = this.territoiresOccupes.iterator(); // Calcul des gains pour chaque territoire while (it.hasNext()) { Territoire t = it.next(); gains += 1 + this.bonusGain(t) + t.bonusGain(); if (hasPower()) { gains += this.pouvoir.bonusGain(t); } } return gains; }
2
@Override public void onEntityTarget(EntityTargetEvent event) { if (event.isCancelled()) { return; } if (!(event.getTarget() instanceof Player)) { return; } Player player = (Player) event.getTarget(); if (player.getGameMode().equals(GameMode.CREATIVE) && !this.config.yml.getBoolean("Creative Players.Attack other entities", true) && !player.hasPermission("bcs.bypass.entityattack")) { event.setCancelled(true); } return; }
5
@Test public void readWorks() throws IOException { ConnectMessage msg = new ConnectMessage("test", true, 10000); msg.setCredentials("username", "password"); msg.setWill("/will/topic", "this is will message", QoS.EXACTLY_ONCE, true); byte[] data = msg.toBytes(); MessageInputStream is = new MessageInputStream( new ByteArrayInputStream(data)); ConnectMessage message = null; try { message = (ConnectMessage) is.readMessage(); } catch (Exception e) { e.printStackTrace(); assertEquals(true, false); } assertEquals("MQIsdp", message.getProtocolId()); assertEquals(3, message.getProtocolVersion()); assertEquals(true, message.hasUsername()); assertEquals(true, message.hasPassword()); assertEquals(true, message.isWillRetained()); assertEquals(QoS.EXACTLY_ONCE, message.getWillQoS()); assertEquals(true, message.hasWill()); assertEquals(true, message.isCleanSession()); assertEquals(10000, message.getKeepAlive()); assertEquals("test", message.getClientId()); assertEquals("/will/topic", message.getWillTopic()); assertEquals("this is will message", message.getWill()); assertEquals("username", message.getUsername()); assertEquals("password", message.getPassword()); }
1
public static void read() throws Exception { synchronized (SystemProperty.class) { if (instance == null) { instance = new SystemProperty(); } } // Map作成 if (prop != null) { prop.clear(); prop = null; } prop = new HashMap<String, List<String>>(); // ドキュメントビルダーファクトリを生成 DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbfactory.newDocumentBuilder(); // 読み込み時のファイル更新時間を取得 File file = new File( SYSTEM_PROP_PATH ); lastModified = file.lastModified(); // ドキュメント取得 Document doc = builder.parse(file); // ルート要素を取得(タグ名:properties) Element root = doc.getDocumentElement(); // properties要素のリストを取得 NodeList list = root.getElementsByTagName(TAG_PROPERTY); Element element = null; // properties要素 NodeList values = null; // value要素リスト Element valueElement = null; // value要素 List<String> valueList = null;// value値リスト // properties要素の数だけループ for (int i = 0; i < list.getLength(); i++) { // properties要素を取得 element = (Element) list.item(i); valueList = new ArrayList<String>(); values = element.getElementsByTagName(TAG_VALUE); for (int j = 0; j < values.getLength(); j++) { valueElement = (Element) values.item(j); if (valueElement.getFirstChild() != null) { valueList.add(valueElement.getFirstChild().getNodeValue()); } else { valueList.add(null); } } prop.put(element.getAttribute(ATTR_ID), valueList); } valueList = null; }
5
public static void run() { System.out.println("--|Basic Usage|--------------------------------------------------------------"); System.out.println("Some simple uses of the hat container"); // put some data into a hat and then get a random item String[] names = {"Alice", "Betty", "Celia", "Darcy"}; Hat<String> hatOfNames = new Hat<String>(names); for(int i = 0; i < 10; ++i){ System.out.print( hatOfNames.get() + " " ); // get a random item from hat } System.out.println(); // assign different chance weights to items in a hat Hat<String> weightedNames = new Hat<String>(); weightedNames.put("Alice", 5); // 5 chances out of the sum of all chances in the hat weightedNames.put("Betty", 3); // 3 chances weightedNames.put("Celia", 1); // 1 chance weightedNames.put("Darcy"); // default behavior of 1 chance for(int i = 0; i < 10; ++i){ System.out.print( weightedNames.get() + " " ); // draw a name } System.out.println(); // draw names randomly from a pre-existing data set Hat<Integer> index = new Hat<Integer>(); Integer[] chanceWeights = {50, 30, 10, 10}; // using 100 chances to simulate percentages for(int i = 0; i < 4; ++i){ index.put(i, chanceWeights[i]); // assigning chance weights when inserting items in hat } for(int i = 0; i < 10; ++i){ System.out.print( names[index.get()] + " " ); // draw a name using a random index } }
4
public static Node inorderSuccessor(Node root,int val) { if(root!=null) { if(root.data==val) { if(root.right!=null) { return minValue(root.right); } else { return maxAncestor; } } else if(root.data<val) { return inorderSuccessor(root.right, val); } else { maxAncestor=root; return inorderSuccessor(root.left, val); } } else return null; }
4
@Basic @Column(name = "SOL_FECHA_HASTA") public Date getSolFechaHasta() { return solFechaHasta; }
0
public FiilContactFormParameter(String nameF, String nameL, String address, String phoneH, String phoneM, String phoneW, String email1, String email2, String bday, String bmonth, String byear, String address2) { this.nameF = nameF; this.nameL = nameL; this.address = address; this.phoneH = phoneH; this.phoneM = phoneM; this.phoneW = phoneW; this.email1 = email1; this.email2 = email2; this.bday = bday; this.bmonth = bmonth; this.byear = byear; this.address2 = address2; }
0
private static void doHelpTest() { String[] args0 = { "-h" }; String[] args1 = { "-h","add"}; String[] args2 = { "-h","archive"}; String[] args3 = { "-h","compare"}; String[] args4 = { "-h","create"}; String[] args5 = { "-h","delete"}; String[] args6 = { "-h","description"}; String[] args7 = { "-h","export"}; String[] args8 = { "-h","find"}; String[] args9 = { "-h","help"}; String[] args10 = { "-h","import"}; String[] args11 = { "-h","list"}; String[] args12 = { "-h","read"}; String[] args13 = { "-h","update"}; String[] args14 = { "-h","usage"}; String[] args15 = { "-h","variants"}; emptyStream.clear(); try { System.out.print("Testing help command "); try { MvdTool.run( args0, out ); throw new MVDException("Failed to detect faulty arguments"); } catch ( Exception e ) { if ( !(e instanceof MVDToolException) ) throw new MVDTestException( e ); System.out.print("."); } testHelpCommand( args1 ); testHelpCommand( args2 ); testHelpCommand( args3 ); testHelpCommand( args4 ); testHelpCommand( args5 ); testHelpCommand( args6 ); testHelpCommand( args7 ); testHelpCommand( args8 ); testHelpCommand( args9 ); testHelpCommand( args10 ); testHelpCommand( args11 ); testHelpCommand( args12 ); testHelpCommand( args13 ); testHelpCommand( args14 ); testHelpCommand( args15 ); testsPassed++; System.out.println(" test passed."); } catch ( Exception e ) { doTestFailed( e ); } }
3
Object invoke(Object target, Object[] args) { Method method = method(); try { try { return method.invoke(target, args); } catch (IllegalAccessException ex) { Method accessible = searchAccessibleMethod(method, argTypes); if (accessible != null) { memberObject = accessible; method = accessible; } else { if (!VMBridge.instance.tryToMakeAccessible(method)) { throw Context.throwAsScriptRuntimeEx(ex); } } // Retry after recovery return method.invoke(target, args); } } catch (InvocationTargetException ite) { // Must allow ContinuationPending exceptions to propagate unhindered Throwable e = ite; do { e = ((InvocationTargetException) e).getTargetException(); } while ((e instanceof InvocationTargetException)); if (e instanceof ContinuationPending) throw (ContinuationPending) e; throw Context.throwAsScriptRuntimeEx(e); } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } }
7
public void setModelValue(Object obj) throws YException { if (obj == null) { this.setSelectedIndex(-1); } else { // searching corresponding item in list: if (items == null) { throw new YException("List model for YList is not set."); } else { for (int i=0; i < this.items.length; i++) { YListItem item = (YListItem)items[i]; if (this.modelField == null) { if (obj.equals(item.getItemModel())) { this.setSelectedValue(item, true); } } else { Object value = YCoreToolkit.getBeanValue(item.getItemModel(), modelField); if (obj.equals(value)) { this.setSelectedValue(item, true); } } } } } }
6
public BitTorrentMessage receiveMessage () throws IOException { try { // Message length inputBuffer.clear().limit(4); while (inputBuffer.remaining() > 0) { channel.read(inputBuffer); } inputBuffer.flip(); int length = inputBuffer.getInt(); // Message itself inputBuffer.clear().limit(length); while (inputBuffer.remaining() > 0) { channel.read(inputBuffer); } inputBuffer.flip(); return BitTorrentMessageDecoder.decodeMessageFromBuffer(inputBuffer, length); } catch (IOException e) { // Channel error close(); throw e; } }
3
static private final int jjMoveStringLiteralDfa14_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(12, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(13, active0); return 14; } switch(curChar) { case 79: return jjMoveStringLiteralDfa15_0(active0, 0x20L); case 100: return jjMoveStringLiteralDfa15_0(active0, 0x1000L); case 101: if ((active0 & 0x40L) != 0L) return jjStopAtPos(14, 6); break; case 116: return jjMoveStringLiteralDfa15_0(active0, 0x2000L); default : break; } return jjStartNfa_0(13, active0); }
7
public void sort(List <T> values) { // Check for empty or null array if (values ==null || values.size()==0){ return; } this.values = values; number = values.size(); quicksort(0, number - 1); }
2
private String findElement(String response, String elementTag, String elementTypeLink, String elementName) throws InvalidObjectException, ConnectorException { Document doc = RestClient.stringToXmlDocument(response); NodeList list = doc.getElementsByTagName(elementTag); for(int i=0; i < list.getLength();i++){ if(list.item(i).getAttributes().getNamedItem(Constants.TYPE)!=null){ if(list.item(i).getAttributes().getNamedItem(Constants.TYPE).getTextContent().trim().equalsIgnoreCase(elementTypeLink)) { if (elementName != null) { if(list.item(i).getAttributes().getNamedItem(Constants.NAME).getTextContent().trim().equalsIgnoreCase(elementName)) return list.item(i).getAttributes().getNamedItem(Constants.HREF).getTextContent().trim(); } else { return list.item(i).getAttributes().getNamedItem(Constants.HREF).getTextContent().trim(); } } } } // // if it reaches the end without finding the element, throw exception // if(elementName != null) { throw new InvalidObjectException("Element not found: " + elementName); } else { throw new InvalidObjectException("Element not found: " + elementTypeLink); } }
6
public static boolean implementsInterfaceIncludingSuper(Class<?> implementor, Class<?> interf) { List<Class<?>> interfaces = getAllInterfacesIncludingSuper(implementor); for (Class<?> intf : interfaces) { if (intf.equals(interf)) { return true; } } return false; }
6
public boolean removeByKey(String tableName, String key) throws DataBaseTableException { Table table = tableHashMap.get(tableName); if (table == null) { throw new DataBaseTableException("no such table"); } return table.remove(key); }
1
public void start() { server = new Server(); server.setPort(port); server.setNoSystemExit(true); server.setDatabasePath(0, path); server.setDatabaseName(0, name); server.setErrWriter(new PrintWriter(System.out)); server.setLogWriter(new PrintWriter(System.out)); server.setSilent(true); server.setTrace(false); server.start(); int maxWait = 5000 * 2; int currentWait = 0; while (server.getState() != ServerConstants.SERVER_STATE_ONLINE) { LOG.log(Level.INFO, "Starting hsqldb-server. State: " + server.getStateDescriptor()); LOG.log(Level.INFO, name); LOG.log(Level.INFO, path); LOG.log(Level.INFO, "Waiting 5 seconds ..."); try { Thread.sleep(5000); currentWait += 5000; } catch (InterruptedException interrupt) { LOG.log(Level.WARNING, "Start interrupted.", interrupt); break; } if(currentWait >= maxWait) { LOG.info("Giving up... ;-)"); break; } } if(server.getState() == ServerConstants.SERVER_STATE_ONLINE) { LOG.log(Level.INFO, "Started!"); } }
4
/** @param scrollTo The row index to scroll to. */ protected void keyScroll(int scrollTo) { Outline real = getRealOutline(); if (!keyScrollInternal(real, scrollTo)) { for (OutlineProxy proxy : real.mProxies) { if (keyScrollInternal(proxy, scrollTo)) { break; } } } }
3
public boolean setPituus(double pituus){ if (pituus > minPituus){ this.pituus = pituus; paivitaMinMax(); return true; } else { return false; } }
1
public String buscaLogin(String login, String pass) { String res = "error"; Statement statement; ResultSet resultSet; try { Connection con = DriverManager.getConnection(connectString, user, password); statement = con.createStatement(); resultSet = statement.executeQuery("SELECT * from buscaUsuario('" + login + "', '" + pass + "');"); while (resultSet.next()) { res = resultSet.getString(1); } } catch (SQLException ex) { System.err.println(ex.getMessage()); } return res; }
2
static void getCommand(int blocks, int bytesPerBlock, String filename) throws IOException { BufferedReader r = new BufferedReader(new FileReader(filename)); //StringTokenizer token = new StringTokenizer(r.readLine()); FileManager file = new FileManager(blocks, bytesPerBlock); String storageName; int bytes; String line; String Command = null; while((line = r.readLine()) != null) { StringTokenizer token; token = new StringTokenizer (line); if (token.hasMoreTokens()) { Command = token.nextToken(); } else { Command = "#"; } if ( Command.equals("#")) { // Do nothing skip line } else if (Command.equals(create)) { storageName = token.nextToken(); bytes = Integer.parseInt(token.nextToken()); file.addFile(storageName, bytes); } else if (Command.equals(delete)) { storageName = token.nextToken(); file.deleteFile(storageName); } else if (Command.equals(extend)) { storageName = token.nextToken(); bytes = Integer.parseInt(token.nextToken()); file.extendFile(storageName, bytes); } else if (Command.equals(truncate)) { storageName = token.nextToken(); bytes = Integer.parseInt(token.nextToken()); file.truncateFile(storageName, bytes); } else if (Command.equals(printState)) { file.print(); } } r.close(); }
8
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((nome == null) ? 0 : nome.hashCode()); result = prime * result + ((obs == null) ? 0 : obs.hashCode()); long temp; temp = Double.doubleToLongBits(preco); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; }
2
@Override protected DataSet doParse() { try { lineCount = 0; return doDelimitedFile(getDataSourceReader(), shouldCreateMDFromFile()); } catch (final IOException e) { LOGGER.error("error accessing/creating inputstream", e); } return null; }
1
public void playFirework(World world, Location loc, FireworkEffect fe) throws Exception { // Bukkity load (CraftFirework) Firework fw = (Firework) world.spawn(loc, Firework.class); // the net.minecraft.server.World Object nms_world = null; Object nms_firework = null; /* * The reflection part, this gives us access to funky ways of messing around with things */ if(world_getHandle == null) { // get the methods of the craftbukkit objects world_getHandle = getMethod(world.getClass(), "getHandle"); firework_getHandle = getMethod(fw.getClass(), "getHandle"); } // invoke with no arguments nms_world = world_getHandle.invoke(world, (Object[]) null); nms_firework = firework_getHandle.invoke(fw, (Object[]) null); // null checks are fast, so having this seperate is ok if(nms_world_broadcastEntityEffect == null) { // get the method of the nms_world nms_world_broadcastEntityEffect = getMethod(nms_world.getClass(), "broadcastEntityEffect"); } /* * Now we mess with the metadata, allowing nice clean spawning of a pretty firework (look, pretty lights!) */ // metadata load FireworkMeta data = (FireworkMeta) fw.getFireworkMeta(); // clear existing data.clearEffects(); // power of one data.setPower(1); // add the effect data.addEffect(fe); // set the meta fw.setFireworkMeta(data); /* * Finally, we broadcast the entity effect then kill our fireworks object */ // invoke with arguments nms_world_broadcastEntityEffect.invoke(nms_world, new Object[] {nms_firework, (byte) 17}); // remove from the game fw.remove(); }
2
@Override public boolean verifier() throws SemantiqueException { //Dans le cas où il y aurait d'autres methodes verifier pouvant retourner false /*if(value instanceof Identificateur){ if(!((Identificateur) value).verifier()) GestionnaireSemantique.getInstance().add(new SemantiqueException("La declaration de la variable "+((Identificateur) value).getNom()+" a la ligne "+line+" est manquante"); }els ((Expression) value).verifier();*/ //Pour le moment seule la methode verifier d'un identificateur peut retourner false if(value instanceof Expression && !((Expression) value).verifier()) GestionnaireSemantique.getInstance().add(new SemantiqueException("La declaration de la variable "+((Identificateur) value).getNom()+" a la ligne "+line+" est manquante")); return true; }
2
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tuple tuple = (Tuple) o; if (first != null ? !first.equals(tuple.first) : tuple.first != null) return false; if (second != null ? !second.equals(tuple.second) : tuple.second != null) return false; return true; }
7
public int numUpgrades() { if (upgrades == null) return 0 ; int num = 0 ; for (int i = 0 ; i < upgrades.length ; i++) { if (upgrades[i] == null || upgradeStates[i] != STATE_INTACT) continue ; num++ ; } return num ; }
4
@Override public void deleteIngredient(int index) { for(int i = 0; i<ingredientRepository.size(); i++){ if(ingredientRepository.get(i).getIngredientId() == index){ ingredientRepository.remove(i); return; } } }
2
private Field filterFields(Field[] fields, Class type) throws /*NoSuchFieldException,*/ TooManyMatchesException { ArrayList<Field> list = new ArrayList<Field>(); for(Field f : fields) { if(!f.getType().equals(type)) { continue; } list.add(f); } Field[] array = list.toArray(new Field[0]); if(array.length == 0) { // throw new NoSuchFieldException("No matching field found on class " + _className + "."); return null; } if(array.length > 1) { String msg = "Fields " + array[0].getName(); for(int i = 1; i < array.length - 1; i++) { msg += ", " + array[i].getName(); } msg += "and " + array[array.length - 1].getName() + " match on class " + _className + "."; throw new TooManyMatchesException(msg); } // array[0].setAccessible(true); return array[0]; }
5
public String toString() { String result = "Runs from: " + m_RunLower + " to: " + m_RunUpper + '\n'; result += "Datasets:"; for (int i = 0; i < m_Datasets.size(); i ++) { result += " " + m_Datasets.elementAt(i); } result += '\n'; result += "Custom property iterator: " + (m_UsePropertyIterator ? "on" : "off") + "\n"; if (m_UsePropertyIterator) { if (m_PropertyPath == null) { throw new Error("*** null propertyPath ***"); } if (m_PropertyArray == null) { throw new Error("*** null propertyArray ***"); } if (m_PropertyPath.length > 1) { result += "Custom property path:\n"; for (int i = 0; i < m_PropertyPath.length - 1; i++) { PropertyNode pn = m_PropertyPath[i]; result += "" + (i + 1) + " " + pn.parentClass.getName() + "::" + pn.toString() + ' ' + pn.value.toString() + '\n'; } } result += "Custom property name:" + m_PropertyPath[m_PropertyPath.length - 1].toString() + '\n'; result += "Custom property values:\n"; for (int i = 0; i < Array.getLength(m_PropertyArray); i++) { Object current = Array.get(m_PropertyArray, i); result += " " + (i + 1) + " " + current.getClass().getName() + " " + current.toString() + '\n'; } } result += "ResultProducer: " + m_ResultProducer + '\n'; result += "ResultListener: " + m_ResultListener + '\n'; if (!getNotes().equals("")) { result += "Notes: " + getNotes(); } return result; }
9
private void btn_aceptarActionPerformed(java.awt.event.ActionEvent evt) { if (lab_modo.getText().equals("Alta")){ if (camposCompletos()){ if (validarFechas()){ ocultar_Msj(); insertar(); combo_tipo.setEnabled(true); field_desdee.setEnabled(true); field_hasta.setEnabled(true); menuDisponible(true); modoConsulta(); updateTabla(); } } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } else{ if (lab_modo.getText().equals("Baja")){ if (!field_tasa.getText().equals("")){ if(!existe(Integer.parseInt(lab_ID.getText()))){ mostrar_Msj_Error("Ingrese una cuenta que se encuentre registrada en el sistema"); field_tasa.requestFocus(); } else{ ocultar_Msj(); eliminar(); menuDisponible(true); modoConsulta(); vaciarCampos(); updateTabla(); } } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } else{ if (lab_modo.getText().equals("Modificación")){ if (!field_tasa.getText().equals("")){ if (camposCompletos()){ ocultar_Msj(); modificar(); menuDisponible(true); modoConsulta(); updateTabla(); } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } } } }
9
protected void extendToString(StringBuffer buffer) { if (hasConstructor) buffer.append("hasConstructor "); super.extendToString(buffer); }
1
private void processOffScreen(String offScreenString){ String[] gameObjects = offScreenString.split("#"); //Object data contains two fields: type, number of the object for(int i = 1; i < gameObjects.length; i++){ ArrayList<String> objectData = processOffScreenObject(gameObjects[i]); String type = objectData.get(0); // if(type.equalsIgnoreCase("RedBall")){ // this.gameComponent.addToBallCount(Integer.valueOf(objectData.get(1))); // } if(type.equalsIgnoreCase("fan")){ this.gameComponent.addToFanCount(Integer.valueOf(objectData.get(1))); } if(type.equalsIgnoreCase("bounce")){ this.gameComponent.addToBounceCount(Integer.valueOf(objectData.get(1))); } if(type.equalsIgnoreCase("torch")){ this.gameComponent.addToTorchCount(Integer.valueOf(objectData.get(1))); } if(type.equalsIgnoreCase("wood")){ this.gameComponent.addToWoodCount(Integer.valueOf(objectData.get(1))); } if(type.equalsIgnoreCase("rock")){ this.gameComponent.addToRockCount(Integer.valueOf(objectData.get(1))); } if(type.equalsIgnoreCase("gear")){ this.gameComponent.addToGearCount(Integer.valueOf(objectData.get(1))); } if(type.equalsIgnoreCase("wall")){ this.gameComponent.addToWallCount(Integer.valueOf(objectData.get(1))); } // TO ADD ANOTHER TYPE OF OBJECT OFF-SCREEN, JUST COPY ONE OF THE ABOVE } this.gameComponent.generateButtons(); }
8
public Cuboid expand(CuboidDirection dir, int amount) { switch (dir) { case North: return new Cuboid(this.worldName, this.x1 - amount, this.y1, this.z1, this.x2, this.y2, this.z2); case South: return new Cuboid(this.worldName, this.x1, this.y1, this.z1, this.x2 + amount, this.y2, this.z2); case East: return new Cuboid(this.worldName, this.x1, this.y1, this.z1 - amount, this.x2, this.y2, this.z2); case West: return new Cuboid(this.worldName, this.x1, this.y1, this.z1, this.x2, this.y2, this.z2 + amount); case Down: return new Cuboid(this.worldName, this.x1, this.y1 - amount, this.z1, this.x2, this.y2, this.z2); case Up: return new Cuboid(this.worldName, this.x1, this.y1, this.z1, this.x2, this.y2 + amount, this.z2); default: throw new IllegalArgumentException("Invalid direction " + dir); } }
6
@Override public synchronized int read() throws IOException { if (bsize == 0) return -1; int returnValue = buffer[offset]; if (bsize == buffer.length) { int read = in.read(); if (read != -1) buffer[offset] = (byte) read; else --bsize; } else { --bsize; } offset = (++offset) % buffer.length; return returnValue; }
3
@Override public void run() { try { report("checking cache", 1); // same as in GetPageJob before trying to read cache; if (page.loadFromCache()) { report("read from cache", 1); // same as in GetPageJob on successful reading cache; //note: this iterator does not require locking because of CopyOnWriteArrayList implementation for (AbstractPage child: page.childPages) jobMaster.submit(new ReadCacheJob(child, jobMaster)); } else report("read cache failed", 1); } catch (InterruptedException e) { } }
3
public static boolean endsWithIgnoreCase(String s,String w) { if (w==null) return true; int sl=s.length(); int wl=w.length(); if (s==null || sl<wl) return false; for (int i=wl;i-->0;) { char c1=s.charAt(--sl); char c2=w.charAt(i); if (c1!=c2) { if (c1<=127) c1=lowercases[c1]; if (c2<=127) c2=lowercases[c2]; if (c1!=c2) return false; } } return true; }
8
private boolean r_prelude() { int among_var; int v_1; // repeat, line 36 replab0: while(true) { v_1 = cursor; lab1: do { // (, line 36 // [, line 37 bra = cursor; // substring, line 37 among_var = find_among(a_0, 3); if (among_var == 0) { break lab1; } // ], line 37 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 38 // <-, line 38 slice_from("a~"); break; case 2: // (, line 39 // <-, line 39 slice_from("o~"); break; case 3: // (, line 40 // next, line 40 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_1; break replab0; } return true; }
8
@Execute public void execute() { for (int a = 0; a < 100000; a++) { est_coeff = p1 * 1.2; estimate = p2 + p2 + p3; double d = Math.atan2(1.0666, 3.45); d = Math.sin(1.0666); } }
1
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Grupo)) { return false; } Grupo other = (Grupo) object; if ((this.codgrupo == null && other.codgrupo != null) || (this.codgrupo != null && !this.codgrupo.equals(other.codgrupo))) { return false; } return true; }
5
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainFrame().setVisible(true); } }); }
6
@Override protected boolean perform(final CommandSender sender, final Command command, final String label, final List<String> args, final Region region) { String owner = RegionExecutor.parse(args, 0, "<Owner>", sender); if (owner == null) return false; // Do not allow an owner to remove their own ownership accidentally if they can't add themselves back forcibly if (!sender.hasPermission("simpleregions.override.commands") && !sender.hasPermission(owner)) { Main.courier.send(sender, "demote-prevent"); return true; } owner = Bukkit.getOfflinePlayer(owner).getName(); region.owners.clear(); region.owners.add(owner); this.catalog.repository.saveRegion(region, false); Main.courier.send(sender, "reform", owner, RegionExecutor.formatName(region), RegionExecutor.formatWorld(region)); return true; }
3
private static void createGridResource(String name, int totalMachine, int totalPE, double bandwidth, int[] peRating, int policy, double cost) { // Here are the steps needed to create a Grid resource: // 1. We need to create an object of MachineList to store one or more // Machines MachineList mList = new MachineList(); int rating = 0; for (int i = 0; i < totalMachine; i++) { // even Machines have different PE rating compare to odd ones if (i % 2 == 0) { rating = peRating[0]; } else { rating = peRating[1]; } // 2. Create one Machine with its id, number of PEs and rating mList.add( new Machine(i, totalPE, rating) ); } // 3. Create a ResourceCharacteristics object that stores the // properties of a Grid resource: architecture, OS, list of // Machines, allocation policy: time- or space-shared, time zone // and its price (G$/PE time unit). String arch = "Sun Ultra"; // system architecture String os = "Solaris"; // operating system double time_zone = 0.0; // time zone this resource located ResourceCharacteristics resConfig = new ResourceCharacteristics( arch, os, mList, policy, time_zone, cost); // 4. Finally, we need to create a GridResource object. long seed = 11L*13*17*19*23+1; double peakLoad = 0.0; // the resource load during peak hour double offPeakLoad = 0.0; // the resource load during off-peak hr double holidayLoad = 0.0; // the resource load during holiday // incorporates weekends so the grid resource is on 7 days a week LinkedList Weekends = new LinkedList(); Weekends.add(new Integer(Calendar.SATURDAY)); Weekends.add(new Integer(Calendar.SUNDAY)); // incorporates holidays. However, no holidays are set in this example LinkedList Holidays = new LinkedList(); try { GridResource gridRes = new GridResource(name, bandwidth, seed, resConfig, peakLoad, offPeakLoad, holidayLoad, Weekends, Holidays); } catch (Exception e) { System.out.println("Error in creating GridResource."); System.out.println( e.getMessage() ); } System.out.println("Creates one Grid resource with name = " + name); return; }
3
private Set<VehiclePart> findConnectedFuelTanks(final VehiclePart engine) { final Set<VehiclePart> connectedParts = new HashSet<>(); final Set<VehiclePart> scanned = new HashSet<>(); final Deque<VehiclePart> parts = new ArrayDeque<>(); parts.add(engine); scanned.add(engine); while (!parts.isEmpty()) { final VehiclePart part = parts.pop(); final VehiclePart parent = part.getParent(); if (parent != null) { if (!scanned.contains(parent) && parent.getPart().getFuelCrossFeed()) { scanned.add(parent); connectedParts.add(parent); parts.add(parent); } } for (final VehiclePart child : part.getChildren()) { if (!scanned.contains(child) && child.getPart().getFuelCrossFeed()) { scanned.add(child); connectedParts.add(child); parts.add(child); } } } final Set<VehiclePart> connectedFuelTanks = new HashSet<>(); for (final VehiclePart vehiclePart : connectedParts) { if (vehiclePart.getLOXFuelMass() > 0) { connectedFuelTanks.add(vehiclePart); } } return connectedFuelTanks; }
9
public static Attributed readAttrs(Reader source) throws IOException{ StreamTokenizer in = new StreamTokenizer(source); AttributedImpl attrs = new AttributedImpl(); Attr attr = null; in.commentChar('#'); in.ordinaryChar('/'); while(in.nextToken() != StreamTokenizer.TT_EOF){ if(in.ttype == StreamTokenizer.TT_WORD){ if(attr != null){ attr.setValue(in.sval); attr = null; }else{ attr = new Attr(in.sval); attrs.add(attr); } }else if(in.ttype == '='){ if(attr == null) throw new IOException("misplaced '="); }else{ if(attr == null){ throw new IOException("bad Attr name"); } attr.setValue(new Double(in.nval)); attr = null; } } return attrs; }
6
public News[] LoadNews(){ News[] res = null; try{ File xmlFile = new File(xmlFileName); DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBulder = dFactory.newDocumentBuilder(); Document doc; doc = xmlBulder.parse(xmlFile); NodeList items = doc.getElementsByTagName("item"); String[] tagName = new String[]{"id","title","anounce","date","fulltext","rubric"}; res = new News[items.getLength()]; SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss"); for(int i=0; i<items.getLength(); i++){ Node item = items.item(i); News newsOne = new News(); NodeList newsVars = item.getChildNodes(); for(int j=0; j<newsVars.getLength(); j++){ Node node = newsVars.item(j); String cont = node.getTextContent(); String nodeName = node.getNodeName(); if(nodeName.equals("id")){ newsOne.setId(cont); }else if(nodeName.equals("title")){ newsOne.setTitle(cont); }else if(nodeName.equals("anounce")){ newsOne.setAnounce(cont); }else if(nodeName.equals("date")){ newsOne.setDate(sdf.parse(cont)); }else if(nodeName.equals("fulltext")){ newsOne.setFulltext(cont); }else if(nodeName.equals("rubric")){ newsOne.setRubric(cont); } } res[i] = newsOne; } }catch(Exception e){ e.printStackTrace(); } return res; }
9
public void run() { NPC cat = spiceLooter.getCat(); if (cat.interact("Interact-with", cat.getName())) { int time = 0; while (!chaseVermin.validate() && time <= 3000) { time += 50; Time.sleep(50); } } if (chaseVermin.validate() && chaseVermin.click(true)) { int time = 0; while (!cat.isMoving() && time <= 3000) { time += 50; Time.sleep(50); } } }
7
@SuppressWarnings("static-access") private void ROUND4() { enemises.clear(); System.out.println("Round4!!!!!!"); for (int i = 0; i < level.getWidth(); i++) { for (int j = 0; j < level.getHeight(); j++) { if ((level.getPixel(i, j) & 0x0000FF) == 2) { Transform monsterTransform = new Transform(); monsterTransform.setTranslation((i + 0.5f) * Game.getLevel().SPOT_WIDTH, 0.4375f, (j + 0.5f) * Game.getLevel().SPOT_LENGTH); enemises.add(new Enemies(monsterTransform)); } } } }
3
public String buscarProspectoPorTelefono(String telefono){ //##########################CARGA_BASE DE DATOS############# tablaDeProspectos(); //##########################INGRESO_VACIO################### if(telefono.equals("")){ telefono = "No busque nada"; return resultBusqueda = "Debe ingresar datos a buscar"; } int longitud = datos.size(); for(int i = 0; i<longitud;i++){ String TelefonoBuscado = datos.get(i).getTelefono(); if (TelefonoBuscado.equals(telefono)){ db_Temp.add(datos.get(i)); resultBusqueda = datos.get(i).getTelefono(); } } if (db_Temp.size()>0){ for (int j=0; j<db_Temp.size();j++){ System.out.println("SU BÚSQUEDA POR TELEFONO MUESTRA LOS SIGUIENTES RESULTADOS\t" + "\n"); mostrar(j); } }else{ resultBusqueda = "No se encontraron registros para los filtros ingresados"; } return resultBusqueda; }
5
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final JHeader other = (JHeader) obj; if (!Objects.equals(this.IdOrder, other.IdOrder)) { return false; } return true; }
3
public String getAmount() { return amount; }
0
private Set<String> complete(final String cmd) { final Set<String> set = new HashSet<>(); for (final String s : commandMap.keySet()) { if (s.startsWith(cmd)) { set.add(s); } } for (final String s : helpCommands.keySet()) { if (s == null) { if ("help".startsWith(cmd)) { set.add("help"); } } else if (s.startsWith(cmd)) { set.add(s); } } return set; }
6
public void save() throws IOException { try { this.mutex.acquire(); // On enregistre le fichier FileWriter fw = new FileWriter(XML_PATH, false); BufferedWriter bw = new BufferedWriter(fw); bw.write("<?xml version=\"1.0\"?>"); bw.newLine(); bw.append("<users>"); for (int i = 0; i < this.users.size(); i++) { writeUser(bw, this.users.get(i)); } bw.newLine(); bw.append("</users>"); bw.flush(); bw.close(); this.mutex.release(); } catch (InterruptedException ex) { Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex); } }
2
public Flip(int random, int s1, int s2) { this.random = random; this.state1 = s1; this.state2 = s2; }
0
@Test public void containsReturnsCorrectly() { for (int i = 0; i < 5; i++) { l.insert(v); } l.insert(a); for (int i = 0; i < 5; i++) { l.insert(v); } assertTrue(l.contains(a)); assertFalse(l.contains(b)); }
2
@Override public void assign(final Assignment<? extends Item> assignment) throws NullPointerException, IllegalArgumentException { if (assignment == null) throw new NullPointerException("assignment = null"); final Item value = assignment.value(); if (value == null) throw new IllegalArgumentException("value = null"); for (final Assigner<? super Item, ? super Item> assigner: this.assigners(assignment)) { assigner.assign(this, assignment); } }
6
public static void showBoards(BoardGen bg) { n = bg.getBoardNum(); System.out.println("Board " + n + ": "); for(int x = 1; x < b.length; x++) { for(int y = 1; y < b[x].length; y++) { System.out.print(b[x][y] + " "); } System.out.println(); } System.out.println("\nBoard " + n + ": "); for(int x = 1; x < b.length; x++) { for(int y = 1; y < b[x].length; y++) { System.out.print(ansCheck[x][y] + " "); } System.out.println(); } System.out.println("\nSyms used:"); for(int x = 1; x < used.length; x++) { System.out.print(used[x] + " "); } System.out.println(); }
5
public InetAddress[] getValueAsInetAddrs() throws IllegalArgumentException { if (!isOptionAsInetAddrs(code)) { throw new IllegalArgumentException("DHCP option type ("+ this.code +") is not InetAddr[]"); } if (this.value == null) { throw new IllegalStateException("value is null"); } if ((this.value.length % 4) != 0) // multiple of 4 { throw new DHCPBadPacketException("option " + this.code + " is wrong size:" + this.value.length + " should be 4*X"); } try { byte[] addr = new byte[4]; InetAddress[] addrs = new InetAddress[this.value.length / 4]; for (int i=0, a=0; a< this.value.length; i++, a+=4) { addr[0] = this.value[a]; addr[1] = this.value[a+1]; addr[2] = this.value[a+2]; addr[3] = this.value[a+3]; addrs[i] = InetAddress.getByAddress(addr); } return addrs; } catch (UnknownHostException e) { logger.log(Level.SEVERE, "Unexpected UnknownHostException", e); return null; // normally impossible } }
5
@SuppressWarnings("unchecked") public static Map<String, Object> parseMap(String json) { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = null; Map<String, Object> result = null; try { jp = factory.createParser(json); result = jp.readValueAs(HashMap.class); } catch (JsonParseException e) { _logger.error("JsonParseException: " + e.getMessage()); } catch (JsonProcessingException e) { _logger.error("JsonProcessingException: " + e.getMessage()); } catch (IOException e) { _logger.error("IOException: " + e.getMessage()); } return result; }
3
public List<String> getStringListFromString(String xArg) { if (xArg == null || xArg.equalsIgnoreCase("")) return null; List<String> d = new ArrayList<String>(); char[] c = xArg.toCharArray(); int lastPos = 0; for (int i = 0; i < c.length; i++) { if (c[i] == ',') { d.add(returnMergedCharacters(lastPos, i, c)); lastPos = i + 1; } } //Add final double. d.add(returnMergedCharacters(lastPos, c.length, c)); return d; }
4
public String getTypeSignature() { switch (((IntegerType) getHint()).possTypes) { case IT_Z: return "Z"; case IT_C: return "C"; case IT_B: return "B"; case IT_S: return "S"; case IT_I: default: return "I"; } }
5
@Override public void agisci(Parco parco) { if (this.isMorto()) { parco.eliminaAnimale(this); return; } this.riproduci(parco); Posizione nuovaPosizione; Animale roditore; roditore = trovaRoditore(parco); if (roditore != null) { this.incrementaCibo(1); parco.eliminaAnimale(roditore); nuovaPosizione = roditore.getPosizione(); } else { Animale rapace; rapace = rapacePiuDebole(parco); if (rapace != null) { this.incrementaCibo(1); parco.eliminaAnimale(rapace); nuovaPosizione = rapace.getPosizione(); } else { this.incrementaCibo(-1); nuovaPosizione = parco.posizioneLiberaVicino(this.getPosizione()); } } if (nuovaPosizione!=null){ parco.muovi(this, nuovaPosizione); } this.invecchia(); }
4
public static int get() { return value.get(); }
0
void radf2(int ido, int l1, final double cc[], double ch[], final double wtable[], int offset) { int i, k, ic; double ti2, tr2; int iw1; iw1 = offset; for(k=0; k<l1; k++) { ch[2*k*ido]=cc[k*ido]+cc[(k+l1)*ido]; ch[(2*k+1)*ido+ido-1]=cc[k*ido]-cc[(k+l1)*ido]; } if(ido<2) return; if(ido !=2) { for(k=0; k<l1; k++) { for(i=2; i<ido; i+=2) { ic=ido-i; tr2 = wtable[i-2+iw1]*cc[i-1+(k+l1)*ido] +wtable[i-1+iw1]*cc[i+(k+l1)*ido]; ti2 = wtable[i-2+iw1]*cc[i+(k+l1)*ido] -wtable[i-1+iw1]*cc[i-1+(k+l1)*ido]; ch[i+2*k*ido]=cc[i+k*ido]+ti2; ch[ic+(2*k+1)*ido]=ti2-cc[i+k*ido]; ch[i-1+2*k*ido]=cc[i-1+k*ido]+tr2; ch[ic-1+(2*k+1)*ido]=cc[i-1+k*ido]-tr2; } } if(ido%2==1)return; } for(k=0; k<l1; k++) { ch[(2*k+1)*ido]=-cc[ido-1+(k+l1)*ido]; ch[ido-1+2*k*ido]=cc[ido-1+k*ido]; } }
7
public void temporizador() throws SQLException { System.out.println("1"); long start = System.currentTimeMillis(); long aux = start; while (true) { long end = System.currentTimeMillis(); long res = end - start; if (aux != end) { aux = end; if (res % 1000 == 0) { TorniqueteDAO dao = new TorniqueteDAO(); int estado = dao.consultarEstado(GUI2.torniquete_id); int reset = dao.consultarReset(GUI2.torniquete_id); if (estado == -1) { System.out.println("Error en la consulta del estado"); } else if (GUI2.estado != estado) { if (estado == 0) { GUI2.estado = 0; window.jLabel1.setText("Torniquete bloqueado"); bloqueaDesbloquea(1); } else { GUI2.estado = 1; window.jLabel1.setText("Torniquete desbloqueado"); bloqueaDesbloquea(0); } } if (reset == -1) { System.out.println("Error en la consulta del reset"); } else if (reset == 1) { resetearContador(GUI2.torniquete_id, reset); } dao.desconectar(); } } } }
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @SuppressWarnings("unchecked") Range<T> other = (Range<T>) obj; if (max == null) { if (other.max != null) return false; } else if (!max.equals(other.max)) return false; if (min == null) { if (other.min != null) return false; } else if (!min.equals(other.min)) return false; return true; }
9
@AfterClass public static void afterClass() throws Exception { File file = new File(VALID_FILE); if (!file.delete()) { throw new Exception("Finished testing for routing table persistency" + "and trying to cleanup resources used, " + "but for some reason the file " + VALID_FILE + " could not be deleted."); } file = new File(INVALID_ADDRESS_FILE); if (!file.delete()) { throw new Exception("Finished testing for routing table persistency" + "and trying to cleanup resources used, " + "but for some reason the file " + INVALID_ADDRESS_FILE + " could not be deleted."); } file = new File(INVALID_PORT_FILE); if (!file.delete()) { throw new Exception("Finished testing for routing table persistency" + "and trying to cleanup resources used, " + "but for some reason the file " + INVALID_PORT_FILE + " could not be deleted."); } file = new File(INVALID_UUID_FILE); if (!file.delete()) { throw new Exception("Finished testing for routing table persistency" + "and trying to cleanup resources used, " + "but for some reason the file " + INVALID_UUID_FILE + " could not be deleted."); } }
4
public void addParticleSprite(String spriteName, BufferedImage spriteImage) { if (spriteName == null || spriteImage == null) { throw new IllegalArgumentException("Cannot add a null sprite!"); } particleSprites.put(spriteName, spriteImage); }
2
public static void checkCache(double[] cache, double[] read) { boolean error = false; if (cache.length != read.length) { System.out.println("\tERROR: Cache array length difference : cache length = " + cache.length + "\t obsval length = " + read.length); error = true; } for (int i = 0; i < cache.length; i++) { if (cache[i] != read[i]) { System.out.println("\tERROR: Data " + i + "mismatch: cache = " + cache[i] + "\t computed = " + read[i]); error = true; } } if (error == true) { throw new RuntimeException("\tERROR: !!!Check on validity of observed cache data check showed an Error!!!"); } error = false; if (showCacheStats) { System.out.print("\n\tRandom cache data validity check passed.\t"); } }
5
public Query handleInsertStatement(ZInsert s, TransactionId tId) throws TransactionAbortedException, DbException, IOException, simpledb.ParsingException, Zql.ParseException { int tableId; try { tableId = Database.getCatalog().getTableId(s.getTable()); // will // fall // through if // table // doesn't // exist } catch (NoSuchElementException e) { throw new simpledb.ParsingException("Unknown table : " + s.getTable()); } TupleDesc td = Database.getCatalog().getTupleDesc(tableId); Tuple t = new Tuple(td); int i = 0; DbIterator newTups; if (s.getValues() != null) { @SuppressWarnings("unchecked") Vector<ZExp> values = (Vector<ZExp>) s.getValues(); if (td.numFields() != values.size()) { throw new simpledb.ParsingException( "INSERT statement does not contain same number of fields as table " + s.getTable()); } for (ZExp e : values) { if (!(e instanceof ZConstant)) throw new simpledb.ParsingException( "Complex expressions not allowed in INSERT statements."); ZConstant zc = (ZConstant) e; if (zc.getType() == ZConstant.NUMBER) { if (td.getFieldType(i) != Type.INT_TYPE) { throw new simpledb.ParsingException("Value " + zc.getValue() + " is not an integer, expected a string."); } IntField f = new IntField(new Integer(zc.getValue())); t.setField(i, f); } else if (zc.getType() == ZConstant.STRING) { if (td.getFieldType(i) != Type.STRING_TYPE) { throw new simpledb.ParsingException("Value " + zc.getValue() + " is a string, expected an integer."); } StringField f = new StringField(zc.getValue(), Type.STRING_LEN); t.setField(i, f); } else { throw new simpledb.ParsingException( "Only string or int fields are supported."); } i++; } ArrayList<Tuple> tups = new ArrayList<Tuple>(); tups.add(t); newTups = new TupleArrayIterator(tups); } else { ZQuery zq = (ZQuery) s.getQuery(); LogicalPlan lp = parseQueryLogicalPlan(tId, zq); newTups = lp.physicalPlan(tId, TableStats.getStatsMap(), explain); } Query insertQ = new Query(tId); insertQ.setPhysicalPlan(new Insert(tId, newTups, tableId)); return insertQ; }
9
public boolean isConstant() { for (int i = 0; i < subExpressions.length; i++) if (!subExpressions[i].isConstant()) return false; return true; }
2
public CrossingStructure findPath(Crossing start, Crossing end, int limit) { closedList = new ArrayList<CrossingStructure>(); openList = new ArrayList<CrossingStructure>(); CrossingStructure current = new CrossingStructure(start, null); current.setgScore(0).sethScore( heuristic.calculateHScore(start, end) ); current.setParentStep(-1); addToOpen(current); while(!openList.isEmpty()) { current = openList.get(0); openList.remove(current); closedList.add(current); if( current.getCrossing().equals( end ) || (limit > 0 && current.getParentStep() == limit) ) { return current; } for(Vertex v : current.getCrossing().getNeighbours()) { CrossingStructure neighbour = new CrossingStructure( (Crossing) v ); if( findInList(closedList, neighbour.getCrossing()) != null ) { continue; } CrossingStructure found = findInList(openList, neighbour.getCrossing() ); double gScore = current.getgScore() + current.getCrossing().calcualteDistance( neighbour.getCrossing() ); if( found == null) { neighbour.setgScore( gScore ); neighbour.sethScore( neighbour.getCrossing().calcualteDistance(end) ); neighbour.setParent( current.getCrossing() ); neighbour.setParentStep( current.getParentStep() + 1 ); addToOpen(neighbour); } else if( gScore < found.getgScore() ) { found.setParent( current.getCrossing() ); found.setgScore( gScore ); found.setParentStep( current.getParentStep() + 1 ); Collections.sort(openList); } } } if(limit == -1) System.out.println("Path not found!"); return null; }
9
public static SwingDrawer createSwingDrawer( Drawable drawable ) { if ( drawable instanceof Cheese ) return new SwingDrawerCheese(); else if ( drawable instanceof Door ) return new SwingDrawerDoor( (Door)drawable ); else if ( drawable instanceof Floor ) return new SwingDrawerFloor(); else if ( drawable instanceof MouseSpawnPoint ) return new SwingDrawerMouseSpawnPoint(); else if ( drawable instanceof Wall ) return new SwingDrawerWall(); else if ( drawable instanceof Mouse ) return new SwingDrawerMouse( (Mouse)drawable, colorTable[mouseCounter++] ); else return null; }
6
private void onLoad(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onLoad toggler.setState(false); chooser.showOpenDialog(this); if (chooser.getSelectedFile() != null) { try (DataInputStream dis = new DataInputStream(new FileInputStream(chooser.getSelectedFile()))) { game.reset(); for (;;) { game.placeEntity(dis.readInt(), dis.readInt(), dis.readInt()); } } catch (FileNotFoundException ex) { game.log(Level.WARNING, "File not found"); } catch (EOFException ex) { repaint(); } catch (IOException ex) { game.log(Level.SEVERE, "Error loading", ex); } } }//GEN-LAST:event_onLoad
5