method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
243c57b6-6665-4d50-9a66-a4be72a190cb
2
public int getIndex(String ID) { for (int i = 0; i < rows.size(); i++) if (ID.equals((String) (rows.get(i)[1]))) return i; return -1; }
4d9d0d7e-15bb-4a90-b339-405d49006c74
0
public void setFunCedula(Long funCedula) { this.funCedula = funCedula; }
e05598ad-862a-4d43-b70e-bee1f9d40ec4
9
public boolean similar(Object other) { try { if (!(other instanceof JSONObject)) { return false; } Set set = this.keySet(); if (!set.equals(((JSONObject)other).keySet())) { return false; } Iterator iterator = set.iterator(); while (iterator.hasNext()) { String name = (String)iterator.next(); Object valueThis = this.get(name); Object valueOther = ((JSONObject)other).get(name); if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { if (!((JSONArray)valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { return false; } } return true; } catch (Throwable exception) { return false; } }
456e9358-a46d-4883-82f6-210d02813911
7
public static int runToAddressOrNextInputFrameLimit(State initial, int move, int limit, int... addresses) { int expectedRet = -2; if ((move & 0b00001111) == 0) { expectedRet = runToAddressOrNextInputFrameHiOrLoLimit(initial, curGb.rom.readJoypadInputHi, limit, addresses); return expectedRet; } else if ((move & 0b11110000) == 0) { expectedRet = runToAddressOrNextInputFrameHiOrLoLimit(initial, curGb.rom.readJoypadInputLo, limit, addresses); return expectedRet; } int initialSteps = curGb.stepCount; if (initial == null) initial = curGb.newState(); if (runToNextInputFrameLimit(move, limit) == 0) { // if (expectedRet != -2 && expectedRet != -1) // throw new RuntimeException("-1 != " + Util.toHex(expectedRet)); // return -1; return expectedRet != -2 ? expectedRet : -1; } int inputSteps = curGb.stepCount; curGb.restore(initial); int actualRet = runToAddressLimit(0, 0, inputSteps - initialSteps, addresses); // run at most to the input frame if (expectedRet != -2 && actualRet != expectedRet) throw new RuntimeException(Util.toHex(actualRet) + " != " + Util.toHex(expectedRet)); return actualRet; }
52c45eb2-b074-4d9f-9637-422ccd4e8859
8
protected static String trimSpacesOnly(String s) { while(s.startsWith(" ")||s.startsWith("\t")||s.startsWith("\n")||s.startsWith("\r")) s=s.substring(1); while(s.endsWith(" ")||s.endsWith("\t")||s.endsWith("\n")||s.endsWith("\r")) s=s.substring(0,s.length()-1); return s; }
b36e0cfd-f9b4-4b26-8ce5-4c4459507157
2
public void addDstore(int n) { if (n < 4) addOpcode(71 + n); // dstore_<n> else if (n < 0x100) { addOpcode(DSTORE); // dstore add(n); } else { addOpcode(WIDE); addOpcode(DSTORE); addIndex(n); } }
5620fe47-230d-4a4b-bbe7-670cc9a9ae87
5
public void checkAnonymousClasses() { if (methodFlag != CONSTRUCTOR || (Options.options & Options.OPTION_ANON) == 0) return; InnerClassInfo outer = getOuterClassInfo(getClassInfo()); if (outer != null && (outer.outer == null || outer.name == null)) { methodAnalyzer.addAnonymousConstructor(this); } }
3627ae6e-e7e8-435e-97fa-646902e5a6cc
3
private double findItem(String string, float value) { for(int x=0; x<craftWidth; x++){ for(int y=0; y<craftHeight; y++){ //System.out.println(x + ", " + y); if((itemGrid[x][y].getPreName() + itemGrid[x][y].getName()).equals(string)){ return value; } } } return 0; }
f971627a-4a03-4f5e-8ee6-852db8b970aa
8
public static void eachBoatTakeActions(int time, boolean night) { Iterator<Boat> iter = River.boats.iterator(); ArrayList<Boat> boatsToBeRemoved = new ArrayList<Boat>(); while (iter.hasNext()) { Boat currentBoat = iter.next(); currentBoat.minutesTraveled += God.UNIT; if (!currentBoat.inCamp) { currentBoat.minutesOnWater += God.UNIT; currentBoat.move(); if (currentBoat.withinRange()) { if (!currentBoat.halfway()) { currentBoat.decideCampingProblem(night); } } else { // System.out.println("out"); Double[] data = { currentBoat.startTime, time * God.UNIT, currentBoat.restTime, currentBoat.minutesTraveled, (double) currentBoat.encountersCount, currentBoat.speed, (double) currentBoat.campStayed, currentBoat.minutesOnWater / currentBoat.campStayed }; God.report.put((Integer) currentBoat.id, data); boatsToBeRemoved.add(currentBoat); } } else { currentBoat.restTime += God.UNIT; } // System.out.println(currentBoat.minutesTraveled // +"\t"+currentBoat.minutesOnWater+"\t"+currentBoat.restTime); // if(time==100000){ // System.out.println(currentBoat.cellId); // } } iter = River.boats.iterator(); while (iter.hasNext()) { Boat currentBoat = iter.next(); if (!currentBoat.inCamp) { if (currentBoat.withinRange()) { currentBoat.decideEncounterProblem(); } } } // remove boats iter = boatsToBeRemoved.iterator(); while (iter.hasNext()) { Boat currentBoat = iter.next(); River.boats.remove(currentBoat); } // System.out.println(River.boats.size()); }
d35fb8b8-0701-41a2-921b-32489266c9d1
4
public static void main(String[] args) { Socket clientSocket; BufferedReader inFromUser; DataOutputStream outToServer; BufferedReader inFromServer; String writeUser; String messageToServer; try { clientSocket = initSocket(HOST, PORT); outToServer = new DataOutputStream(clientSocket.getOutputStream()); inFromServer = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); inFromUser = new BufferedReader(new InputStreamReader(System.in)); while (makeChat) { writeUser = inFromUser.readLine()+ "\r\n"; outToServer.write(writeUser.getBytes("UTF-8")); messageToServer = inFromServer.readLine(); System.out.println("FROM SERVER: " + messageToServer); if (messageToServer.startsWith("BYE") || messageToServer.startsWith("OK_BYE")) makeChat = false; } clientSocket.close(); } catch (IOException e) { System.exit(1); } System.out.println("client is stopped!"); }
c76c8028-91ef-4862-b57a-1d363f9132eb
7
public static int discrete(double[] a) { double EPSILON = 1E-14; double sum = 0.0; for (int i = 0; i < a.length; i++) { if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]); sum = sum + a[i]; } if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) throw new IllegalArgumentException("sum of array entries not equal to one: " + sum); // the for loop may not return a value when both r is (nearly) 1.0 and when the // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) while (true) { double r = uniform(); sum = 0.0; for (int i = 0; i < a.length; i++) { sum = sum + a[i]; if (sum > r) return i; } } }
08ad83ef-bcc8-40f9-b50f-a7d88dd511f2
1
int countTailingZero(int n) { int res = 0; while (n > 0) { res += n / 5; n /= 5; } return res; }
f4787ec8-077b-409f-b296-9318fdd85889
8
private boolean r_instrum() { int among_var; // (, line 76 // [, line 77 ket = cursor; // substring, line 77 among_var = find_among_b(a_3, 2); if (among_var == 0) { return false; } // ], line 77 bra = cursor; // call R1, line 77 if (!r_R1()) { return false; } switch(among_var) { case 0: return false; case 1: // (, line 78 // call double, line 78 if (!r_double()) { return false; } break; case 2: // (, line 79 // call double, line 79 if (!r_double()) { return false; } break; } // delete, line 81 slice_del(); // call undouble, line 82 if (!r_undouble()) { return false; } return true; }
afd9fdd9-cc45-483f-bb6e-b0cbca665116
6
public boolean loadDataFiles(String filePath, String dataType) { File folder = new File(filePath); LoadDataWithHibernate obj2 = new LoadDataWithHibernate(); String filename = ""; File[] listOfFiles = folder.listFiles(); int count = 0; try { for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile() && listOfFiles[i].getName().toString() != ".DS_Store") { filename = listOfFiles[i].getName(); count++; //Start Time WriteToFile.appendToFileMethod(count+" :: "+ new Timestamp(System.currentTimeMillis())+" :: FileName : "+filename+" \n", "/home/krish/Documents/CMPE226/Project1/logLoadTime.txt"); if(dataType.equals("weatherData")) obj2.readFromOutDataFileMethod(filePath+filename); else obj2.readFromFileMethod(filePath+filename); //End Time WriteToFile.appendToFileMethod(count+" :: "+ new Timestamp(System.currentTimeMillis())+" :: FileName : "+filename+" \n", "/home/krish/Documents/CMPE226/Project1/logLoadTime.txt"); File movefile = new File(filePath+filename); if (movefile.renameTo(new File(filePath + "archive/" + movefile.getName()))) { System.out.println("File is moved successful!"); } else { System.out.println("File is failed to move!"); } } } } catch (Exception e) { System.out.println("File was not processed" + filename); e.printStackTrace(); } return true; }
deee2da5-300a-448b-a4e2-ca68b0f91c2d
4
@Override public boolean create(Hotelier x) { String req = "INSERT INTO hotelier ( email, motdepasse, siteweb, nomentreprise)\n" +"select \""+x.getEmail()+"\", \""+x.getMotDePasse()+"\", \""+x.getSiteweb()+"\", \""+x.getNomEntreprise()+"\" from dual\n" +"where not exists (select * from particulier where email = \""+x.getEmail()+"\")\n" +"and not exists (select * from hotelier where email = \""+x.getEmail()+"\")"; Statement stm = null; try { stm = cnx.createStatement(); int n= stm.executeUpdate(req,Statement.RETURN_GENERATED_KEYS); if (n>0) { x.setHotelierId(n); stm.close(); return true; } } catch (SQLException exp) { } finally { if (stm!=null) try { stm.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; }
a19afeb6-5670-4b4c-940d-75227336156f
0
public void setVue(VueMenu vue) { this.vue = vue; }
7a36fee0-407a-434d-bc8a-246e2d26befb
6
public void loadHexFile(String hexFile) throws Exception { String strLine; int lineNumber = 0; FileInputStream fstream = new FileInputStream(hexFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((strLine = br.readLine()) != null) { // Intel Hex Format // < : 1b> <data length 1b> <offset 2b> < type 1b > <data nb> <checksum 1b> // switch(Integer.parseInt(strLine.substring(7,9))) { // RECTYPE case 0: int datalen = Integer.parseInt(strLine.substring(1,3), 16); //RECLEN byte data[] = BinaryFunctions.hexStringToByteArray(strLine.substring(9, 9+datalen*2)); // Switch every two bytes - fix Endianness for (int i = 0; i < data.length-1; i+=2 ) { byte b = data[i]; data[i] = data[i+1]; data[i+1] = b; } for (int i = 0; i< data.length; i++) { this.i_mem[lineNumber + i] = (byte) (data[i] & 0xff); if (i %2 == 0) this.i_count++; } /* for (int i = 0; i < data.length/2; i+=2) { this.i_mem[i] = data[i]; //this.i_mem[this.i_count] = (byte) (data[i] << 8 | data[i+1]); //this.i_count++; } */ break; case 1: // EOF break; } lineNumber += 0x10; } }
0d58128f-9a99-4d89-a48c-f015ebafed0a
2
public int charAt(int x) { for(int i=start+1; i<end; i++) { if(x < tm().getAdvanceBetween(start, i)) return i - start - 1; } return -1; }
62161623-038e-4970-a6c8-07405a2331e7
0
public JNotifyListener getListener() { return listener; }
feded9e4-fa5a-47c0-be99-bc7c6a17d951
8
public Construct createConstruct(String uri, GenericTreeNode<SyntaxTreeElement> node) { String className = config.getConstructClassName(uri); if(className == null) { return null; } @SuppressWarnings("rawtypes") Class constructClass; Constructor constructor; try { constructClass = Class.forName(className); constructor = constructClass.getDeclaredConstructor(GenericTreeNode.class); } catch (ClassNotFoundException e) { return null; } catch (NoSuchMethodException e) { return null; } catch (SecurityException e) { return null; } try { return (Construct) constructor.newInstance(node); } catch (InstantiationException e) { e.printStackTrace(); return null; } catch (IllegalAccessException e) { e.printStackTrace(); return null; } catch (IllegalArgumentException e) { e.printStackTrace(); return null; } catch (InvocationTargetException e) { e.printStackTrace(); return null; } }
edbda91d-3353-414d-aef8-246d52c3c084
8
static float lpc_from_data(float[] data, float[] lpc, int n, int m){ float[] aut=new float[m+1]; float error; int i, j; // autocorrelation, p+1 lag coefficients j=m+1; while(j--!=0){ float d=0; for(i=j; i<n; i++) d+=data[i]*data[i-j]; aut[j]=d; } // Generate lpc coefficients from autocorr values error=aut[0]; /* if(error==0){ for(int k=0; k<m; k++) lpc[k]=0.0f; return 0; } */ for(i=0; i<m; i++){ float r=-aut[i+1]; if(error==0){ for(int k=0; k<m; k++) lpc[k]=0.0f; return 0; } // Sum up this iteration's reflection coefficient; note that in // Vorbis we don't save it. If anyone wants to recycle this code // and needs reflection coefficients, save the results of 'r' from // each iteration. for(j=0; j<i; j++) r-=lpc[j]*aut[i-j]; r/=error; // Update LPC coefficients and total error lpc[i]=r; for(j=0; j<i/2; j++){ float tmp=lpc[j]; lpc[j]+=r*lpc[i-1-j]; lpc[i-1-j]+=r*tmp; } if(i%2!=0) lpc[j]+=lpc[j]*r; error*=1.0-r*r; } // we need the error value to know how big an impulse to hit the // filter with later return error; }
9aae266f-5932-43ef-83a6-b1d0e77b3cb2
4
public void enableEdit() { disableEdit(); nameField.setEnabled(true); nameField.setText(list.getSelectedValue().substring(0, list.getSelectedValue().indexOf(';'))); switch(list.getSelectedValue().charAt(list.getSelectedValue().indexOf(';') + 1)) { case 'S': stringField.setEnabled(true); stringField.setText(list.getSelectedValue().substring(list.getSelectedValue().lastIndexOf(';') + 1, list.getSelectedValue().length())); break; case 'I': intSpinner.setEnabled(true); intSpinner.setValue(Integer.parseInt(list.getSelectedValue().substring(list.getSelectedValue().lastIndexOf(';') + 1, list.getSelectedValue().length()))); break; case 'B': booleanBox.setEnabled(true); booleanBox.setSelected(Boolean.parseBoolean(list.getSelectedValue().substring(list.getSelectedValue().lastIndexOf(';') + 1, list.getSelectedValue().length()))); break; case 'F': floatSpinner.setEnabled(true); floatSpinner.setValue(Float.parseFloat(list.getSelectedValue().substring(list.getSelectedValue().lastIndexOf(';') + 1, list.getSelectedValue().length()))); break; } save.setEnabled(true); remove.setEnabled(true); }
941fe2e7-5e80-4944-96a9-276ecd208453
3
@Override public Funcionario listById(int codigo) { Connection con = null; PreparedStatement pstm = null; ResultSet rs = null; Funcionario f = new Funcionario(); try { con = ConnectionFactory.getConnection(); pstm = con.prepareStatement(LISTBYID); pstm.setInt(1, codigo); rs = pstm.executeQuery(); while (rs.next()) { f.setCodigo(rs.getInt("codigo")); f.setNome(rs.getString("nome")); f.setLogin(rs.getString("login")); f.setSenha(rs.getString("senha")); f.setTelefone(rs.getString("telefone")); f.setCelular(rs.getString("celular")); f.setCargo(rs.getString("cargo")); f.setDataNascimento(rs.getDate("data_nascimento")); f.setRg(rs.getString("rg")); f.setEndereco(rs.getString("endereco")); f.setCidade(rs.getString("cidade")); f.setEstado(rs.getString("estado")); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao listar funcionário: " + e.getMessage()); } finally { try { ConnectionFactory.closeConnection(con, pstm, rs); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao fechar conexão do listar: " + ex.getMessage()); } } return f; }
92d3956a-4858-4613-a9f9-c17c275eaccc
8
void mover() { int cabezaAnterior = inicioSnake + longSnake - 1; cabezaAnterior =cabezaAnterior %(ancho*alto); int cabeza = inicioSnake + longSnake; cabeza = cabeza %(ancho*alto); switch(direccion) { case DERECHA: snakeX[cabeza] = snakeX[cabezaAnterior] + 1; snakeY[cabeza] = snakeY[cabezaAnterior]; break; case IZQUIERDA: snakeX[cabeza] = snakeX[cabezaAnterior] - 1; snakeY[cabeza] = snakeY[cabezaAnterior]; break; case ARRIBA: snakeX[cabeza] = snakeX[cabezaAnterior]; snakeY[cabeza] = snakeY[cabezaAnterior] - 1; break; case ABAJO: snakeX[cabeza] = snakeX[cabezaAnterior]; snakeY[cabeza] = snakeY[cabezaAnterior] + 1; break; } if (snakeX[cabeza] >= ancho){ snakeX[cabeza] =0; }else if (snakeX[cabeza]<0){ snakeX[cabeza]=ancho -1; } { } if(snakeX[cabeza]==manzanaX && snakeY[cabeza]== manzanaY){ longSnake++; generarManzana(); }else{ inicioSnake++; inicioSnake= inicioSnake %(alto*ancho); } }
93a5e8af-3c3f-4bac-95fb-5e8482082219
4
public static int berechneEinkommensteuer(int wert) { if (wert <= 0) { return 0; } else { int steuer = 0; if (wert > ONEHUNDREDTWENTYTHOUSAND) { steuer += ((wert - ONEHUNDREDTWENTYTHOUSAND) / HUNDRED) * FIFTY; wert -= (wert - ONEHUNDREDTWENTYTHOUSAND); } if (wert > SIXTYTHOUSAND) { steuer += ((wert - SIXTYTHOUSAND) / HUNDRED) * THIRTYFIVE; wert -= (wert - SIXTYTHOUSAND); } if (wert > TWENTYTHOUSAND) { steuer += (((wert - TWENTYTHOUSAND) / HUNDRED) * TWENTYFIVE); wert -= (wert - TWENTYTHOUSAND); } steuer = steuer + (wert / HUNDRED) * TEN; return steuer; } }
86d7b376-02d4-4e7d-b023-9c5fbec7110f
9
public void scrollCellToView(JTable table, int rowIndex, int vColIndex) { if (!(table.getParent() instanceof JViewport)) { return; } JViewport viewport = (JViewport) table.getParent(); Rectangle rect = table.getCellRect(rowIndex, vColIndex, true); Rectangle viewRect = viewport.getViewRect(); int x = viewRect.x; int y = viewRect.y; if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){ } else if (rect.x < viewRect.x){ x = rect.x; } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) { x = rect.x - viewRect.width + rect.width; } if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){ } else if (rect.y < viewRect.y){ y = rect.y; } else if (rect.y > (viewRect.y + viewRect.height - rect.height)){ y = rect.y - viewRect.height + rect.height; } viewport.setViewPosition(new Point(x,y)); }
5eb45b78-4a0d-422a-bd49-518ac18d50c6
4
public void startGame() { started = true; orderMark = Mark.RED; size = order.size(); if (size == 2) { order.put(Mark.GREEN, order.get(Mark.YELLOW)); order.remove(Mark.YELLOW); order.get(Mark.GREEN).setMark(Mark.GREEN); } if (!server) { gameGameGUI = new GameGUI(board, this); } if (order.get(orderMark) instanceof ComputerPlayer) { turnAI(); } else if (!server) { gameGameGUI.paintComponents(board, turn); } }
77238189-379f-4b83-9c8b-de027f798092
4
public boolean ifTextMsgContentIllegal(String content) { return content.contains("<") || content.contains(">") || content.contains("[") || content.contains("]") || content.contains("/"); }
d79a63ea-d977-4df5-a9aa-10035ac7505a
7
public static void Eleven(String str){ int result=0; if(str.length() == 2) System.out.println(0); else{ for(int i=2;i<str.length();i++){ int num=str.length()-i-1; int multi=1; for(int j=0;j<num;j++) { multi=multi*11; } int temp=0; if(str.charAt(i) == 'A' || str.charAt(i) == 'a') temp=10; else { temp=(int)str.charAt(i)-(int)('0'); } if(temp < 11 && temp >=0) result +=temp*multi; else { System.out.println("-1"); return; } } System.out.println(result); } }
3f76e26f-57c2-49fc-8f9f-0fc99a7fe687
1
@Test public void testReserveInvalidIsbn() { int x; try { assertEquals(new Book().Reserve(123,1111111),0); } catch (IOException e) { System.out.println("Invalid data"); } }
e2564884-97cf-466f-93a6-19c544867b76
9
public static void main(String[] args) { int port = -1; String host = null; if (args.length>=3) { name = args[0]; host = args[1]; try { port = Integer.parseInt(args[2]); } catch (Exception e) { port = -1; } } if (port==(-1)) { io.p("What server would you like to connect to? "); host = io.readLine(); io.p("What port would you like to connect on? "); port = io.readInt(); if ((port<1)||(port>65535)) { io.pl("Invalid port number."); System.exit(1); } } io.pl("Connecting to " + host + ":" + port + "..."); Socket s = null; try { s = new Socket(host, port); } catch (Exception e) { io.pl("Couldn't connect to that server."); UIWindow.alert(null, "Couldn't connect to that server."); System.exit(1); } server = new NetThread(s, al, -1); io.pl("Connected to server."); Message nameMessage = new Message(Message.SET_NAME, name, null); server.sendMessage(nameMessage); while (true) { synchronized (al) { if (haveMessages()) { Message m = null; m = al.get(0); al.remove(0); handleMessage(m); } else { try { al.wait(); } catch (Exception e) { io.pl("An exception occurred while trying to wait for messages from the server."); UIWindow.alert(null, "AI Client error occurred."); System.exit(1); } } } } }
bf8acb37-2eca-4b61-92ab-eebfc43157bf
4
private void jButton2ActionPerformed() { String identityOfStreamer = JOptionPane.showInputDialog(null, "Enter the streamer's ID.\n" + "http://twitch.tv/riotgames id is riotgames"); if (identityOfStreamer == null || identityOfStreamer.isEmpty() ) { return; } String nameOfStreamer = JOptionPane.showInputDialog(null, "Enter the name of the streamer: "); if (nameOfStreamer == null || nameOfStreamer.isEmpty()) { return; } new TwitchStream(identityOfStreamer, nameOfStreamer); TwitchStream.restartStreams(); }
353fb8ef-7122-4d46-89f4-37b11823f899
4
public void flipCard(int row, int col){ if (prevSelectedCardRow == -1 && prevSelectedCardCol == -1){ prevSelectedCardRow = row; prevSelectedCardCol = col; cards[row][col].setShowing(true); updateButtons(); } else if ( prevSelectedCardRow != -1 && prevSelectedCardCol != -1){ cards[row][col].setShowing(true); updateButtons(); this.game.matchedCards( cards[prevSelectedCardRow][prevSelectedCardCol], cards[row][col]); scoreLabel.setText(Integer.toString(this.game.getScore())); //update the score in the UI prevSelectedCardRow = -1; prevSelectedCardCol = -1; } }
036755c5-38ae-4703-850d-b86ebe349ab3
3
public void save(){ try { File file = new File(getDataFolder() + "/names.txt"); boolean createFile = file.createNewFile(); if(createFile){ getLogger().info("Creating a file called names.txt"); } PrintWriter write = new PrintWriter(file, "UTF-8"); for (String name : names) { write.println(name); } write.close(); } catch (IOException e) { e.printStackTrace(); } }
03464e7f-b50c-4b74-9e57-a881f10e581f
4
@Override public void mouseReleased(MouseEvent e) { if (graphComponent.isEnabled() && isEnabled() && !e.isConsumed() && current != null) { mxGraph graph = graphComponent.getGraph(); double scale = graph.getView().getScale(); mxPoint tr = graph.getView().getTranslate(); current.setX(current.getX() / scale - tr.getX()); current.setY(current.getY() / scale - tr.getY()); current.setWidth(current.getWidth() / scale); current.setHeight(current.getHeight() / scale); Object cell = insertCell(current); eventSource.fireEvent(new mxEventObject(mxEvent.INSERT, "cell", cell)); e.consume(); } reset(); }
18a15eb5-b7fc-473b-95e8-acb02ded7353
6
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = this.getServletConfig().getServletContext(); String localPath = sc.getInitParameter("ottzRimagePath"); HttpSession session =request.getSession(); BeanFilter_test bf_test = null; try { bf_test = new BeanFilter_test(); bf_test.setBestK(request.getParameter("bestK")); bf_test.setBestN(request.getParameter("bestN")); bf_test.setRplotUrl(localPath + "/web/Rimage/Filter/"); if("yahoo".equals(request.getParameter("datasource"))){ bf_test.setRDataSource(request.getParameter("testStockSymbol"), request.getParameter("testStartDate"), request.getParameter("testEndDate")); request.setAttribute("testStartDatetime", request.getParameter("testStartDate")); request.setAttribute("testEndDatetime", request.getParameter("testEndDate")); }else if("db".equals(request.getParameter("datasource"))){ bf_test.setRDataSource(sc,request.getParameter("testStockSymbol"),request.getParameter("testStartDate"),request.getParameter("testStartTime"),request.getParameter("testEndDate"),request.getParameter("testEndTime")); request.setAttribute("testStartDatetime", request.getParameter("testStartDate") + " " + request.getParameter("testStartTime")); request.setAttribute("testEndDatetime", request.getParameter("testEndDate") + " " + request.getParameter("testEndTime")); } bf_test.excute(); } catch (Exception ex) { throw new ServletException(ex); }finally{ //關閉Rconnection連結 if(bf_test!=null) try { bf_test.closeRconn(); } catch (RserveException ex) { throw new ServletException(ex); } } //test show if(bf_test != null){ request.setAttribute("BestN", bf_test.getBestN()); request.setAttribute("BestK", bf_test.getBestK()); request.setAttribute("testStockSymbol", request.getParameter("testStockSymbol")); request.setAttribute("hasTrade", bf_test.getHasTrade()); request.setAttribute("testingCode", bf_test.getTestingCode()); request.setAttribute("revenue", bf_test.getRevenuTrade()); //trade list物件直接放入session 供之後operatorDB使用 session.setAttribute("trade", bf_test.getRecordTrade()); request.setAttribute("RplotUrl", bf_test.getFilterPictureURL()); request.getRequestDispatcher("/WEB-INF/FilterPages/testing/displayFilter_test.jsp").forward(request, response); } }
1d315e67-8134-44ed-9755-47fc1fc708a0
8
private Component cycle(Component currentComponent, int delta) { int index = -1; loop : for (int i = 0; i < m_Components.length; i++) { Component component = m_Components[i]; for (Component c = currentComponent; c != null; c = c.getParent()) { if (component == c) { index = i; break loop; } } } // try to find enabled component in "delta" direction int initialIndex = index; while (true) { int newIndex = indexCycle(index, delta); if (newIndex == initialIndex) { break; } index = newIndex; // Component component = m_Components[newIndex]; if (component.isEnabled() && component.isVisible() && component.isFocusable()) { return component; } } // not found return currentComponent; }
4bd7622f-e398-4a4c-86a8-be9267876417
4
private int typeID(Object item) { int id=OP.typeIDObject(item); if (id<8) return id; if (item instanceof String) return 8; if (item instanceof Class) return 9; if (item instanceof Member) return 10; return -1; };
2d6d00f3-fe46-4156-b410-93c29985e64a
6
public Cycle(int a, int b, int c) { int[] p = new int[] { a + 1, b + 1, c + 1 }; boolean asc, desc; for (int i = 0; i <= 2; i++) { asc = desc = true; for (int j = 0; j <= 1; j++) if (p[(i + j + 1) % 3] > p[(i + j) % 3]) desc = false; else if (p[(i + j + 1) % 3] < p[(i + j) % 3]) asc = false; if (asc || desc) { this.a = p[i]; this.b = p[(i + 1) % 3]; this.c = p[(i + 2) % 3]; break; } } }
8b1b5843-31e0-4316-a4e8-b7ea1c8c0bea
0
public int size() { return size; }
9f32fc7d-151f-46db-81f5-dbc2b1580e00
6
@Override public void run() { // System.out.println("download meta data");// TODO try (Socket peerSocket = new Socket(peerIp, peerPort); OutputStream output = peerSocket.getOutputStream(); InputStream input = peerSocket.getInputStream()) { byte[] handshakeMsg = new byte[68]; handshakeMsg[0] = 19; System.arraycopy("BitTorrent protocol".getBytes(), 0, handshakeMsg, 1, 19); handshakeMsg[25] = 16; System.arraycopy(infoHash, 0, handshakeMsg, 28, 20); System.arraycopy(peerNodeId, 0, handshakeMsg, 48, 20); output.write(handshakeMsg); byte[] replyMsg = new byte[65535]; int totalBytes = 0; int n; System.out.print("handshake reply:"); byte[] lengthBytes = new byte[8]; while ((n = input.read(lengthBytes, totalBytes + 4, 4 - totalBytes)) != -1) { totalBytes += n; if (totalBytes == 4) { break; } } long length = ByteBuffer.wrap(lengthBytes).getLong(); System.out.print("length prefix:" + length + ","); while ((n = input.read(replyMsg)) != -1) { totalBytes += n; if (n == 0) { break; } // System.out.print(new String(replyMsg, 0, n)); } System.out.println("total bytes:" + totalBytes); } catch (ConnectException ex) { Logger.getLogger(BtCrawler.class.getName()).log(Level.FINE, null, ex); } catch (Exception ex) { Logger.getLogger(BtCrawler.class.getName()).log(Level.SEVERE, null, ex); } }
b79e7478-ca0e-4c08-8f7a-86d909cbeff4
1
private int calculateExponent(int[] binaryNumber) { int exponent = 0; for(int i = 1; i < 9; i++){ exponent = exponent + binaryNumber[i] * (int) Math.pow(2, 8 - i); } return exponent; }
ca6c9259-2e8b-4951-b5eb-652c959a6319
2
public Mirror (String gridDates, String gridStr) { height = Integer.parseInt(gridDates.split(" ")[0]); width = Integer.parseInt(gridDates.split(" ")[1]); distance = Integer.parseInt(gridDates.split(" ")[2]); grid = new byte[height][width]; for (int row = 0; row < height; row++) { for (int column = 0; column < width; column++) { grid[row][column] = (byte)gridStr.charAt(column+(row*width)); } } }
78e32743-f022-4b07-9779-c7bfa4407446
9
private static Expression parseFunction() { System.out.println("解析函数表达式"); int opType = CurrentToken.type; eat( opType ); eat( TokenType.OpenParen ); Expression exp = parseAddExpression(); eat( TokenType.CloseParen ); switch ( opType ) { case TokenType.Sine: return new SineExpression( exp ); case TokenType.Cosine: return new CosineExpression( exp ); case TokenType.Tangent: return new TangentExpression( exp ); case TokenType.ASine: return new ASineExpression( exp ); case TokenType.ACosine: return new ACosineExpression( exp ); case TokenType.ATangent: return new ATanExpression( exp ); case TokenType.Ln: return new LnExpression( exp ); case TokenType.Log: return new LogExpression( exp ); default: try { throw new Exception( "Unexpected Function type: " + opType ); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; }
5a64973d-8b72-4d70-bb3f-707f437294e3
5
protected int readBlock() { blockSize = read(); int n = 0; if (blockSize > 0) { try { int count = 0; while (n < blockSize) { count = in.read(block, n, blockSize - n); if (count == -1) break; n += count; } } catch (IOException e) { } if (n < blockSize) { status = STATUS_FORMAT_ERROR; } } return n; }
56cd7a97-babc-46aa-b87f-ac59ebdef97c
4
@Override public int getPreferredHeight(Row row, Column column) { Font font = getFont(row, column); int minHeight = TextDrawing.getPreferredSize(font, "Mg").height; //$NON-NLS-1$ int height = TextDrawing.getPreferredSize(font, getPresentationText(row, column)).height; StdImage icon = row == null ? column.getIcon() : row.getIcon(column); if (icon != null) { int iconHeight = icon.getHeight(); if (height < iconHeight) { height = iconHeight; } } return minHeight > height ? minHeight : height; }
5831fbae-ea09-4c50-8f0a-4813e3f633e1
8
public void canDetectImplementor() { ClassInstrumentationCommand cic = new ClassInstrumentationCommand(); //cic.setIncludeClassRegEx("org.hsqldb.jdbc.jdbcStatement"); cic.setIncludeClassRegEx(ConnectionTestUtils.TEST_CLASS_TO_INSTRUMENT_1); IAgentCommand commandArray[] = { cic }; HostPort hostPort = new HostPort(ConnectionTestUtils.DEFAULT_HOST_1,ConnectionTestUtils.DEFAULT_PORT_1_INT); //Test will fail unless we wait for instrumentation to complete. IConnection c = null; try { latch = new CountDownLatch(1); DefaultCallback callback = new DefaultCallback() { @Override public void setProgress(Map<String, String> progress) { m_waitForInstrumentation = true; String result = progress.get("NUM_PROGRESS_DONE"); System.out.print("."); // kinda a live status update, filling screen with dots. if (result!=null && result.equals("true")) latch.countDown(); } }; /** * C O N N E C T */ c = DefaultConnectionList.getSingleton().connect(callback, hostPort, commandArray); //c = DefaultConnectionList.getSingleton().connect(null, hostPort, null); // may 15 2014 System.out.println("x1 ####@after connect"); System.out.println("x2 Connection [" + c.toString() + "]\n"); assertNotNull("Is the test program started? Didn't get a connection. [" + DefaultFactory.getFactory().getMessages().getTestSetupInstructions() + "]"); assertEquals("Didn't not connect successfully. [" + DefaultFactory.getFactory().getMessages().getTestSetupInstructions() + "]", true, c.isConnected()); //Thread.sleep(120000); if (m_waitForInstrumentation) { System.out.println("x4 Waiting for agent to finish instrumentation"); latch.await(); } System.out.println("x5 ####%instrumentation finished Connection [" + c.toString() + "]\n"); /** * V A L I D A T E * T R A C E * E V E N T S */ //dispEvents(c.getTraceEvents()); Thread.sleep(5000);//collect some events int traceEventCount = c.getTraceEvents().size(); System.out.println("Found [" + traceEventCount + "] events."); //assertEquals("Didn't find exepected number of java.sql.PreparedStatement events", 71, traceEventCount); //ITraceEvent event = c.getTraceEvents().get(0); c.disconnect(); } catch (ConnectionTimeout e) { e.printStackTrace(); fail("Received a connection timeout. Is the test program example.FirstTraceExample running? [" + e.getMessage() + "]"); } catch (ConnectionException e) { e.printStackTrace(); fail("Unknown connection error [" + e.getMessage() + "]"); } catch (BadCompletedRequestListener e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { latch.countDown(); if (c!=null) { c.disconnect(); System.out.println(" Connection list [" + DefaultConnectionList.getSingleton().size() + "]"); System.out.println("@@ 1 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); System.out.println(" Connection [" + c.toString() + "]\n"); System.out.println("** 2 *********************************************"); } } }
7b94cea2-88eb-4b73-9e4d-f2b827323bc1
9
private int stablePartition(int[] array, int[] temp, int lowindex, int highindex, boolean reversed) { Compare firstcond, secondcond; if (reversed){ firstcond = new Compare(Compare.type.GREATERTHAN); secondcond = new Compare(Compare.type.LESSTHAN); } else{ firstcond = new Compare(Compare.type.LESSTHAN); secondcond = new Compare(Compare.type.GREATERTHAN); } int pivot = 0; int midindex = (lowindex + highindex) /2; int median = getmedian(lowindex, highindex, midindex, array[lowindex], array[highindex], array[midindex]); int index = lowindex; for(int i = lowindex; i <= highindex; i++){ if (firstcond.compareto(array[i], array[median])){ temp[index] = array[i]; index++; } } for(int i = lowindex; i <= highindex; i++){ if (array[i] == array[median]){ if (median == i) pivot = index; temp[index] = array[i]; index++; } } for(int i = lowindex; i <= highindex; i++){ if (secondcond.compareto(array[i], array[median])){ temp[index] = array[i]; index++; } } for(int i = lowindex; i <= highindex; i++) array[i] = temp[i]; temp = null; return pivot; }
39e2a777-633e-4811-a3b2-6f9b66927e08
5
public void updateView(Tetromino tetromino){ for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { JLabel cell = (JLabel) getComponent(j * 4 + i); if(i < tetromino.getWidth() && j < tetromino.getHeight() && tetromino.hasSquareAt(i, j)){ cell.setBackground(tetromino.getColor()); }else{ cell.setBackground(Color.BLACK); } } } invalidate(); }
a5d03221-1aa6-47d5-8fcc-8044164f179d
1
public void initTiles() { tiles = new Tile[ROW * ROW]; for (int i = 0; i < tiles.length; i++) { tiles[i] = Tile.ZERO; } addTile(); addTile(); host.statusBar.setText(""); }
0be358bb-61be-4970-a174-14b4a4d7a8df
7
public static void main(String[] args) { final long startTime = System.currentTimeMillis(); final MFDFitnessFunction fitnessFunction = new MFDFitnessFunction(); final int[] symptoms = new int[NUMBER_OF_SYMPTOMS]; final StringBuilder sb = new StringBuilder(); final ArrayList<Chromosome> fittestChromosomes = new ArrayList<Chromosome>(); //DecimalFormat df = new DecimalFormat("##.###############"); //double totalReliability = 0.0; int firstReliability = 0; int secondReliability = 0; int thirdReliability = 0; // check all symptom sets for (int i = 1; i < 1024; i++) { // setup this symptom set sb.setLength(0); sb.append(Integer.toBinaryString(i)); while (sb.length() < 10) { sb.insert(0, 0); } for (int j = 0; j < NUMBER_OF_SYMPTOMS; j++) { symptoms[j] = Character.getNumericValue(sb.charAt(j)); } // setup fitness function for this symptom set fitnessFunction.setSymptoms(symptoms); // run an 10 iterations of the GA with this symptom set fittestChromosomes.clear(); int symptomSetIndex = i - 1; for (int j = 0; j < 10; j++) { SGA sga = new SGA(POPULATION_SIZE, NUMBER_OF_GENERATIONS, NUMBER_OF_DISEASES, CROSSOVER_PROBABILITY, MUTATION_PROBABILITY, fitnessFunction); sga.run(); //double fitness = Double.valueOf(df.format(sga.getFittestChromosome().getFitness())); double fitness = sga.getFittestChromosome().getFitness(); double tolerance = 0.000001; double diff1 = Math.abs(fitness - MFDFitnessFunction.firstBestFitnesses[symptomSetIndex]); double diff2 = Math.abs(fitness - MFDFitnessFunction.secondBestFitnesses[symptomSetIndex]); double diff3 = Math.abs(fitness - MFDFitnessFunction.thirdBestFitnesses[symptomSetIndex]); if (tolerance >= diff1) { firstReliability++; } else if (tolerance >= diff2) { secondReliability++; } else if (tolerance >= diff3) { thirdReliability++; } } //totalReliability += reliability; System.out.println(sb + " (" + i + ") : " + firstReliability + " ; " + secondReliability + " ; " + thirdReliability); //reliability = 0.0; } //System.out.println("Reliability : " + (totalReliability / 10230.0)); System.out.println(firstReliability + " => " + (float)(firstReliability / 10230) + "\n" + secondReliability + " => " + (float)(secondReliability / 10230) + "\n" + thirdReliability + " => " + (float)(thirdReliability / 10230)); System.out.println("Finished in: " + (System.currentTimeMillis() - startTime) + " milliseconds."); }
70fd8320-49ee-40e7-bc2d-dd8620214d8e
1
@RequestMapping("/listar") public ModelAndView listarProductos() { Stock stock = Stock.getInstance(); Map<String, Integer> mapStock = stock.obtenerStock(); Set<String> setStock = mapStock.keySet(); List<Producto> productList = new ArrayList<Producto>(); for (Iterator<String> iterator = setStock.iterator(); iterator.hasNext();) { String nombre = iterator.next(); Integer cantidad = mapStock.get(nombre); Producto otroProducto = new Producto(nombre, cantidad); productList.add(otroProducto); } Boolean hayProductos = (productList.size() >= 1); ModelMap model = new ModelMap(); model.put("productos", productList); model.put("hayProductos", hayProductos); return new ModelAndView("agregarProductos", model); }
7b4cb615-1520-4c7a-9a24-b44b921c16ef
4
private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger().warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } e.printStackTrace(); return false; } }
043e80a8-14e5-49e8-9422-dfc3b600d720
6
@Override public void run() { try { executing = true; // OK, we are running osCmd.start(); Thread.sleep(defaultWaitTime); // Allow some time for the thread to start // Wait for command to start while (!osCmd.isStarted() && isExecuting()) Thread.sleep(defaultWaitTime); // Wait for stdin to became available while ((osCmd.getStdin() == null) && isExecuting()) Thread.sleep(defaultWaitTime); // Now the command started executing started = true; synchronized (this) { osCmd.setObjetcToNotify(this); // Notify me when done (i.e. the command finished) while (isExecuting()) wait(defaultLoopWaitTime); } } catch (Throwable t) { error = t.toString(); t.printStackTrace(); // Something happened? => Stop this thread } finally { exitValue = osCmd.getExitValue(); close(); executing = false; started = true; } }
8a5e8246-3f1a-49b8-9d5c-3d95d138b6fb
5
public void save() { //Save markets //Clear the plugin pointer to null for( Market market : markets.values() ) market.setPlugin(null); try{ ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(Conf.dataFolder + "markets.bin")); oos.writeObject(markets); oos.flush(); oos.close(); getLogger().info("Saved markets.bin"); //Handle I/O exceptions }catch(Exception e){ getLogger().info("Could not write markets.bin, goodbye lovely data :("); } //Restore the plugin pointer for( Market market : markets.values() ) market.setPlugin(this); //Save revenue try{ ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(Conf.dataFolder + "revenue.bin")); oos.writeObject(revenue); oos.flush(); oos.close(); getLogger().info("Saved revenue.bin"); //Handle I/O exceptions }catch(Exception e){ getLogger().info("Could not write revenue.bin, goodbye lovely data :("); } //Save deliveries try{ ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(Conf.dataFolder + "deliveries.bin")); oos.writeObject(deliveries); oos.flush(); oos.close(); getLogger().info("Saved deliveries.bin"); //Handle I/O exceptions }catch(Exception e){ getLogger().info("Could not write deliveries.bin, goodbye lovely data :("); } }
a5d443b4-f26c-43da-a5a0-2048fecbd4a9
8
public static DHParameters getParams(int group) { BigInteger p = DHParameters.GROUP_2; BigInteger g = DHParameters.DH_G; if (group == 1) { p = DHParameters.GROUP_1; g = DHParameters.GROUP1_G; } else if (group == 2) p = DHParameters.GROUP_2; else if (group == 3) p = DHParameters.GROUP_5; else if (group == 14) p = DHParameters.GROUP_14; else if (group == 15) p = DHParameters.GROUP_15; else if (group == 16) p = DHParameters.GROUP_16; else if (group == 17) p = DHParameters.GROUP_17; else if (group == 18) p = DHParameters.GROUP_18; return new DHParameters(p, g, null); }
8aaaafd7-64c1-4cc7-9947-939eeed117c6
4
public boolean valido() { if (login == null || login.isEmpty()) { return false; } if (senha == null || senha.isEmpty()) { return false; } return true; }
4d5e285d-0d59-46dd-9a09-5ec0e5a99a1c
5
public SimulationMap(String mapName, int walkingDistancePerSec, int startId, Collection<Person> people, int dotsPerMeter, Collection<Sensor> sr, SQLiteConnection db){ this.mapName = mapName; this.people = people; this.sensors = sr; this.walkingSpeedPerSec = walkingDistancePerSec; this.dotsPerMeter = dotsPerMeter; this.startNodeId = startId; if(db != null) this.nodes = Node.getNodes(db); else nodes = new ArrayList<>(); objects = new ArrayList<>(); for(Node node: nodes){ if(node.id == startNodeId) startNode = node; if(!node.types.isEmpty()){ for(Appliance obj: node.types){ objects.add(obj); } } } this.items = new ArrayList<>(); this.runningTasks = new ArrayList<>(); }
4949a514-8a52-471a-b0b8-c190c575e4c5
0
private void initPopulation(){ IntStream.range(0, size) .forEach(_i -> individuals.add(makeRandomChromo.apply(rand))); }
8b27f1cc-2b68-4c14-8329-1bf297f94397
6
public ListNode swapPairs(ListNode head) { if (head == null) return null; if (head.next == null) return head; ListNode prev = null; ListNode slow = head; ListNode fast = head.next; while (fast != null && slow != fast) { slow.next = fast.next; fast.next = slow; if (prev == null) { prev = fast; head = prev; prev = prev.next; } else { prev.next = fast; prev = prev.next.next; } slow = slow.next; if (slow == null) break; fast = fast.next.next.next; } return head; }
99dba538-fb22-48db-b2d1-c696249b7b24
1
public void testConstructor_RI_RI7() throws Throwable { DateTime dt1 = new DateTime(2005, 7, 10, 1, 1, 1, 1); DateTime dt2 = new DateTime(2004, 6, 9, 0, 0, 0, 0); try { new MutableInterval(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} }
1e113652-c50d-4b54-83c7-3cabec018003
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PeriodHardConstraint other = (PeriodHardConstraint) obj; if (constraint != other.constraint) return false; if (e1Id != other.e1Id) return false; if (e2Id != other.e2Id) return false; return true; }
ecececa6-a9b6-4f8b-a3c0-8ba944e33e6e
1
@SuppressWarnings("unchecked") @Override public <T> T adaptTo(Class<T> type) { if(type.equals(NoteElement.class)) { return (T) this; } return null; }
3c925f1e-f100-4053-8d46-3989c9dc1059
8
private static String canonicalize(final SortedMap<String, String> sortedParamMap) { if (sortedParamMap == null || sortedParamMap.isEmpty()) { return ""; } final StringBuffer sb = new StringBuffer(100); for (Map.Entry<String, String> pair : sortedParamMap.entrySet()) { final String key = pair.getKey().toLowerCase(); if (key.equals("jsessionid") || key.equals("phpsessid") || key.equals("aspsessionid")) { continue; } if (sb.length() > 0) { sb.append('&'); } sb.append(percentEncodeRfc3986(pair.getKey())); if (!pair.getValue().isEmpty()) { sb.append('='); sb.append(percentEncodeRfc3986(pair.getValue())); } } return sb.toString(); }
768d566e-d9ca-43bd-a277-b9a1fffa17e3
6
public static void main( String[] argv ) { try { String[] stopMarks = new String[] { "%MARK_0%", "%MARK_A%", "%MARK_B%", "%MARK_C%" }; String data = stopMarks[0] + "This " + stopMarks[3] + " is a " + stopMarks[2] + " very simple " + stopMarks[1] + " test."; List<byte[]> stopMarkList = new ArrayList<byte[]>( stopMarks.length ); System.out.println( "Stop marks: " ); for( int i = 0; i < stopMarks.length; i++ ) { System.out.println( " [" + i + "] " + stopMarks[i] ); stopMarkList.add( stopMarks[i].getBytes(java.nio.charset.StandardCharsets.UTF_8.name()) ); } System.out.println( "\n" ); System.out.println( " data: " + data ); MultiStopMarkInputStream in = new MultiStopMarkInputStream( new java.io.ByteArrayInputStream(data.getBytes(java.nio.charset.StandardCharsets.UTF_8.name())), stopMarkList ); int i = 0; while( !in.eoiReached() && i < 10 ) { int b = -1; while( (b = in.read()) != -1 ) { System.out.print( (char)b ); } System.out.println( "" ); byte[] reachedStopMark = in.getReachedStopMark(); System.out.println( "Stop mark " + in.getReachedStopMarkIndex() + " found: " + (reachedStopMark==null?"null":new String(reachedStopMark)) ); in.continueStream(); i++; } } catch( IOException e ) { e.printStackTrace(); } }
0c2d0dd4-8721-402f-931f-d777453110fb
2
private void deleteContact() { if (ek != null) { int response = JOptionPane.showConfirmDialog(this, "M\u00F6chten Sie den Kontakt wirklich l\u00F6schen?"); if (response == JOptionPane.YES_OPTION) { ekd.delete(ek); displayFirst(); } } }
2a04b740-59de-498a-8850-bf0a774f11fd
1
private int max(Node node){ while (node.rightTree!=null) node=node.rightTree; return node.value; }
4e8b5718-27ad-451e-b4f4-c6e14cfba320
6
protected BulkBean buildGetBulkBean(Introspector is, Class<?> clazz, String[] fields, Class[] args) { if (fields.length != args.length) { throw new BeanMappingException("fields and args size is not match!"); } String[] getters = new String[fields.length]; String[] setters = new String[fields.length]; for (int i = 0; i < fields.length; i++) { String property = fields[i]; Class arg = args[i]; FastMethod setMethod = FastPropertySetExecutor.discover(is, clazz, property, arg); FastMethod getMethod = FastPropertyGetExecutor.discover(is, clazz, property); if (setMethod == null) { throw new BeanMappingException("class[" + clazz.getName() + "] field[" + property + "] arg[" + arg.getName() + "] set Method is not exist!"); } if (getMethod == null) { throw new BeanMappingException("class[" + clazz.getName() + "] field[" + property + "] get Method is not exist!"); } if (getMethod.getReturnType() != arg) { throw new BeanMappingException("class[" + clazz.getName() + "] field[" + property + "] getMethod does not match declared type"); } setters[i] = setMethod.getName(); getters[i] = getMethod.getName(); } bulkBean = BulkBean.create(clazz, getters, setters, args); return bulkBean; }
4927c64d-1bbc-4822-a6b4-98812369a2a5
6
@SuppressWarnings("unchecked") String getComponentsChapter(Collection<Class<?>> comps) { StringBuffer db = new StringBuffer(); // Model component db.append("<chapter>"); db.append("<title>" + b.getString("model") + "</title>"); Class mai = comps.iterator().next(); // the first component is top. db.append(classSection(mai)); db.append("</chapter>"); comps.remove(mai); // remove the main component Map<Package, List<Class<?>>> pmap = categorize(comps); List<Package> pl = new ArrayList<Package>(pmap.keySet()); Collections.sort(pl, new Comparator<Package>() { @Override public int compare(Package o1, Package o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); // Subcomponents. db.append("<chapter>"); db.append("<title>" + b.getString("sub") + "</title>"); for (Package p : pl) { db.append("<section>"); db.append("<title>'" + p.getName() + "'</title>"); List<Class<?>> co = pmap.get(p); Collections.sort(co, new Comparator<Class<?>>() { @Override public int compare(Class o1, Class o2) { return o1.getSimpleName().compareToIgnoreCase(o2.getSimpleName()); } }); for (Class c : co) { db.append(classSection(c)); } db.append("</section>"); } db.append("</chapter>"); return db.toString(); }
f488bad5-079c-47fb-9eae-bb853875a2a7
7
public XYSeries getPairwiseDifsDistribution() { ArrayList<Point2D> ser = new ArrayList<Point2D>(); int count = 0; int total = seqs.size()*(seqs.size()-1)/2; int step = total/10+1; int[] hist = new int[seqs.getMaxSeqLength()]; for (int i=0; i<seqs.size(); i++) { for(int j=i+1; j<seqs.size(); j++) { int difs = numDifs(seqs.get(i), seqs.get(j)); hist[difs]++; count++; } } int lowerCutoff = 0; while(lowerCutoff< hist.length && hist[lowerCutoff]==0) lowerCutoff++; int upperCutoff = hist.length-1; while(upperCutoff>lowerCutoff && hist[upperCutoff]==0) upperCutoff--; for(int i=lowerCutoff; i<=upperCutoff; i++) { ser.add(new Point2D.Double(i, hist[i])); } XYSeries cData = new XYSeries(ser); return cData; }
ce978ad2-1264-4f66-9b15-47bcf9f9b3dd
7
public JSONObject postAnswerTag(int USER_ID,int QUESTION_ID,String ANSWER) { try { Class.forName(JDBC_DRIVER); conn=DriverManager.getConnection(DB_URL,USER,PASS); stmt=conn.createStatement(); json=new JSONObject(); //String SQL="insert into ANSWERS(USER_ID,QUESTION_ID,ANSWER) values('"+USER_ID+"','"+QUESTION_ID+"','"+ANSWER+"')"; //int result=stmt.executeUpdate(SQL); //if(result>0) //{ //Calling the LocationBasedHandler's NewResponse method to notify() the uers. LocationBasedHandler object=new LocationBasedHandler(); int result=object.NewResponse(""+USER_ID,""+QUESTION_ID, ANSWER); object=null; if(result==1) { json.put(SUCCESS, 1); json.put(MESSAGE, "Insertion Successful"); String SQL="Select * from ANSWERS where QUESTION_ID="+QUESTION_ID; rs=stmt.executeQuery(SQL); if(rs.isBeforeFirst()) { JSONArray Answers=new JSONArray(); JSONObject answer; while(rs.next()) { answer=new JSONObject(); answer.put("ANSWER", rs.getString("ANSWER")); answer.put("ANSWER_ID", rs.getString("ANSWER_ID")); answer.put("RANK", rs.getInt("RANK")); Answers.add(answer); } json.put("ANSWERS", Answers); } }else { json.put(SUCCESS, 0); } rs.close(); stmt.close(); //Calling Mahesh Method Parser parseobject=new Parser(); parseobject.parseQuestionAnswer('a', USER_ID, ANSWER, Constants.PATH); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } //json.put(SUCCESS, 0); //json.put(MESSAGE, "Sorry, couldn't Process Request"); return(json); }
765cbdac-94d7-4171-ac68-94f3960dcec6
9
public void alarm () { long now=System.currentTimeMillis(); if (B.maincolor()>0) BlackRun=(int)((now-CurrentTime)/1000); else WhiteRun=(int)((now-CurrentTime)/1000); if (Col>0 && BlackTime-BlackRun<0) { if (BlackMoves<0) { BlackMoves=ExtraMoves; BlackTime=ExtraTime; BlackRun=0; CurrentTime=now; } else if (BlackMoves>0) { new Message(this,Global.resourceString("Black_looses_by_time_")); Timer.stopit(); } else { BlackMoves=ExtraMoves; BlackTime=ExtraTime; BlackRun=0; CurrentTime=now; } } else if (Col<0 && WhiteTime-WhiteRun<0) { if (WhiteMoves<0) { WhiteMoves=ExtraMoves; WhiteTime=ExtraTime; WhiteRun=0; CurrentTime=now; } else if (WhiteMoves>0) { new Message(this,Global.resourceString("White_looses_by_time_")); Timer.stopit(); } else { WhiteMoves=ExtraMoves; WhiteTime=ExtraTime; WhiteRun=0; CurrentTime=now; } } settitle(); }
b590d552-180e-4f45-8d18-66e71c5b0818
3
protected String getProcessingInstructionValue (Node contNode, String key) throws ParseException { String strValue = null; NodeList nl = contNode.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { String strTarget = ((ProcessingInstruction) nl.item(i)).getTarget(); if (strTarget.equals(key)) { strValue = ((ProcessingInstruction) nl.item(i)).getData(); // get value // remove the processing instruction Node parent = nl.item(i).getParentNode(); parent.removeChild(nl.item(i)); break; } } } return strValue; }
7d97d380-5a9d-48bd-815c-99ffb0c1a27d
8
public static String nthPowerString(int base, int power) { String nthPowerString = ""; int originalNumber; int calculatedNumber; int onesDigit; //the ones digit of calculatednumber String carryDigits = ""; //carry digits will be added at the end if (base < 10 && base > 0) { nthPowerString += base; // Takes care of power 1 if (power == 0) { } for (int i = 2; i <= power; i++) { //Start at power 2 // Multiply by the base all the way through the string for (int j = nthPowerString.length() - 1; j >= 0; j--) { originalNumber = (int) nthPowerString.charAt(j); originalNumber -= 48; //char numbers start at 48 calculatedNumber = originalNumber * 2; //next step if (calculatedNumber < 10) { //only one digit calculatedNumber += 48; //convert it to the char equiv nthPowerString = replaceCharAt(nthPowerString, j, (char) calculatedNumber); carryDigits += "0"; } else { //This means there is a carry onesDigit = calculatedNumber % 10; //get the first digit carryDigits = (calculatedNumber - onesDigit) / 10 + carryDigits; onesDigit += 48; // char equivalent nthPowerString = replaceCharAt(nthPowerString, j, (char) onesDigit); } //Add the nth string to the carry string } } } else if (base == 0) { return "0"; } else if (base == 1) { return "1"; } else { System.out.println("Cannot compute, base too large."); } return nthPowerString; }
abec3c7e-5d76-47b2-9f9b-e1f29c6723a6
3
public boolean canChunkExist(int var1, int var2) { byte var3 = 15; return var1 >= this.curChunkX - var3 && var2 >= this.curChunkY - var3 && var1 <= this.curChunkX + var3 && var2 <= this.curChunkY + var3; }
5d4ce8f9-f0e0-4902-8d08-144b5531e69a
0
public void tick() { }
89fc40d0-68ff-4d8e-8cc5-6d2da592807f
2
@Override public List Listar() { Session session = null; List<Equipo> equipo = null; try { session = NewHibernateUtil.getSessionFactory().openSession(); Query query = session.createQuery("from Equipo"); equipo = (List<Equipo>) query.list(); } catch (HibernateException e) { System.out.println(e.toString()); } finally { if (session != null) { // session.close(); } } return equipo; }
fcbbe855-5462-4a9d-a688-4bdd295cb8a8
5
public StaffListGUI() { //Get size of screen without taskbar screenSize = Toolkit.getDefaultToolkit().getScreenSize(); screenMax = Toolkit.getDefaultToolkit().getScreenInsets(bookDialog.getGraphicsConfiguration()); taskbarSize = screenMax.bottom; screenWidth = (int)screenSize.getWidth(); screenHeight = (int)screenSize.getHeight() - taskbarSize; //Fill container contentPane.setLayout(bookLayout); contentPane.add(backButton); contentPane.add(addButton); contentPane.add(deleteButton); contentPane.add(editButton); contentPane.add(listScrollPane); contentPane.add(searchLabel); contentPane.add(searchField); contentPane.add(bookBox); //Prepare frame components listField.setEditable(false); listField.setSelectionColor(selectionColor); searchField.setColumns(20); //Placement of components on screen bookLayout.putConstraint(SpringLayout.WEST, backButton, (int)(screenWidth * 0.01), SpringLayout.WEST, contentPane); bookLayout.putConstraint(SpringLayout.NORTH, backButton, (int)(screenHeight * 0.01), SpringLayout.NORTH, contentPane); bookLayout.putConstraint(SpringLayout.WEST, listScrollPane, (int)(screenWidth * 0.35), SpringLayout.WEST, contentPane); bookLayout.putConstraint(SpringLayout.NORTH, listScrollPane, (int)(screenHeight * 0.3703), SpringLayout.NORTH, contentPane); bookLayout.putConstraint(SpringLayout.WEST, addButton, (int)(screenWidth * 0.7), SpringLayout.WEST, contentPane); bookLayout.putConstraint(SpringLayout.NORTH, addButton, (int)(screenHeight * 0.41), SpringLayout.NORTH, contentPane); bookLayout.putConstraint(SpringLayout.WEST, deleteButton, (int)(screenWidth * 0.7), SpringLayout.WEST, contentPane); bookLayout.putConstraint(SpringLayout.NORTH, deleteButton, (int)(screenHeight * 0.46), SpringLayout.NORTH, contentPane); bookLayout.putConstraint(SpringLayout.WEST, editButton, (int)(screenWidth * 0.7), SpringLayout.WEST, contentPane); bookLayout.putConstraint(SpringLayout.NORTH, editButton, (int)(screenHeight * 0.51), SpringLayout.NORTH, contentPane); bookLayout.putConstraint(SpringLayout.WEST, searchLabel, (int)(screenWidth * 0.42), SpringLayout.WEST,contentPane); bookLayout.putConstraint(SpringLayout.NORTH, searchLabel, (int)(screenHeight * 0.33) , SpringLayout.NORTH, contentPane); bookLayout.putConstraint(SpringLayout.WEST, searchField, (int)(screenWidth * 0.45), SpringLayout.WEST,contentPane); bookLayout.putConstraint(SpringLayout.NORTH, searchField, (int)(screenHeight * 0.33) , SpringLayout.NORTH, contentPane); bookLayout.putConstraint(SpringLayout.WEST, bookBox, (int)(screenWidth * 0.6), SpringLayout.WEST,contentPane); bookLayout.putConstraint(SpringLayout.NORTH, bookBox, (int)(screenHeight * 0.33) , SpringLayout.NORTH, contentPane); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { MainGUI.switchToMenu(); } }); listField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { int offset = listField.viewToModel(e.getPoint()); int rowStart = Utilities.getRowStart(listField, offset); int rowEnd = Utilities.getRowEnd(listField, offset); listField.setSelectionStart(rowStart); listField.setSelectionEnd(rowEnd); selectedLine = listField.getText().substring(rowStart, rowEnd); int end = selectedLine.indexOf("|", 5); selectedLine = selectedLine.substring(5, end - 1); selectionMade = true; System.out.println(selectedLine); } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainGUI.switchToStaff(); forEdit = true; } }); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainGUI.switchToStaff(true); Staff staff = StaffDAO.getStaffByID(selectedLine); IDField.setText(staff.getLogin().getStaffID()); passwordField.setText(staff.getLogin().getPassword()); nameField.setText(staff.getName()); a = staff.getFunction(); firstNameField.setText(staff.getSurname()); StaffGUI.this.staffButton.setText("Save"); passwordChanged = false; } }); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(selectionMade == true) { StaffDAO.removeStaff(selectedLine); selectionMade = false; //Update list reset(); update(); } } }); searchField.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { reset(); String text = searchField.getText(); if(a==" ID") { if(listField.getText().equals("")){ staffList = StaffDAO.searchStaffByID(text); for(Staff s : staffList) { Login login = s.getLogin(); staffResults += " ID: " + login.getStaffID() + " || Surname: " + s.getSurname() + " || Name: " + s.getName() + " || Function: " + s.getFunction() + System.lineSeparator(); } listField.setText(staffResults); } } } }); }
0efd6290-4e4f-4784-8504-28d1e63475b8
2
@Override public void draw(Graphics g) { if(visible){ g.drawImage(background, rect.x, rect.y, null); for(GuiComponent c: components){ c.draw(g); } } }
a3253577-ed3c-4983-a278-93d87e0b0053
8
public boolean hasNext() { if (matcher == null) { return false; } if (delim != null || match != null) { return true; } if (matcher.find()) { if (returnDelims) { delim = input.subSequence(lastEnd, matcher.start()).toString(); } match = matcher.group(); lastEnd = matcher.end(); } else if (returnDelims && lastEnd < input.length()) { delim = input.subSequence(lastEnd, input.length()).toString(); lastEnd = input.length(); // Need to remove the matcher since it appears to automatically // reset itself once it reaches the end. matcher = null; } return delim != null || match != null; }
72a19e86-39b5-483b-8ffd-7fb7de00165c
1
public void addComp(JComponent... comp ) { JPanel shell = JComponentFactory.makePanel(JComponentFactory.HORIZONTAL); for(JComponent a : comp) shell.add(a); parts.add(shell); updateParts(); }
ced0d69d-ed63-4eaa-af3b-f182fe7f8d48
5
public boolean checkCollision(Player.Direction direction, int x, int y, int width, int height){ int xIndex = 0; int yIndex = 0; switch(direction){ case Up: xIndex = x / GRID_SIZE; yIndex = (y - height/2) / GRID_SIZE; break; case Down: xIndex = x / GRID_SIZE; yIndex = (y + height/2) / GRID_SIZE; break; case Left: xIndex = (x - width/2) / GRID_SIZE; yIndex = y / GRID_SIZE; break; case Right: xIndex = (x + width/2) / GRID_SIZE; yIndex = y / GRID_SIZE; break; } if(grid.get(yIndex).get(xIndex) == GridType.Wall) return true; return false; }
33da3f6e-162b-4c20-aaa5-fc7c47b50d8b
2
public static int getMstxInfoCount() { int result = 0; Connection con = null; Statement st = null; ResultSet rs = null; try { con = DBUtil.getConnection(); st = con.createStatement(); rs = st.executeQuery("select count(mid) from mstx_info"); if (rs.next()) { result = rs.getInt(1); } } catch (Exception e) { e.printStackTrace(); } return result; }
a91c77f2-0e55-43d6-9643-600dda184415
0
public ConnectionBundle() { chl = new ArrayList<ConnectionHandler>(); /** * Initially one party has access to the fields. */ accessSemaphore = new Semaphore(1); inputBuffer = new LinkedList<DCPackage>(); inputAvailable = new Semaphore(0); netStatBuffer = new LinkedList<NetStatPackage>(); statusAvailable = new Semaphore(0); connections = 0; activeConnections = 0; identifiedConnections = new HashMap<String, ConnectionHandler>(); currentRound = 0; }
640ada47-5347-4f22-9dd1-01fe081fded1
0
public String getTelephone() { return telephone; }
57822c6b-d555-416f-b6a3-c781af75f53a
0
public UDPClientThread(int size){ this.size=size; }
6640cd68-3005-479f-b34a-5005c294fb76
6
@EventHandler public void MagmaCubeFastDigging(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.getMagmaCubeConfig().getDouble("MagmaCube.FastDigging.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getMagmaCubeConfig().getBoolean("MagmaCube.FastDigging.Enabled", true) && damager instanceof MagmaCube && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, plugin.getMagmaCubeConfig().getInt("MagmaCube.FastDigging.Time"), plugin.getMagmaCubeConfig().getInt("MagmaCube.FastDigging.Power"))); } }
14118b68-8cf8-4f11-93bf-0d81cc6d821b
4
public void run() { try { if (BenchmarkClient.available.tryAcquire()){ Socket clientSocket = new Socket(hostname, portnumber); PrintStream out = new PrintStream(clientSocket.getOutputStream(), true); Scanner in = new Scanner(clientSocket.getInputStream()); out.println("hello world"); while (in.hasNextLine()){ if (in.nextLine().equals("HELLO WORLD")){ BenchmarkClient.count++; //BenchmarkClient.count.incrementAndGet(); } } in.close(); out.close(); clientSocket.close(); BenchmarkClient.available.release(); } } catch (IOException e) { e.printStackTrace(); } }
e1a96eba-95dc-4fd2-ac35-1186e67d3b93
0
public void showSplashScreen() { Dimension screenSize = tk.getScreenSize(); //setBackground(BORDERCOLOR); int w = imgWidth + (BORDERSIZE * 2); int h = imgHeight + (BORDERSIZE * 2); int x = (screenSize.width - w) / 2; int y = (screenSize.height - h) / 2; setBounds(x, y, w, h); setVisible(true); }
1054d1e7-818c-4ead-a278-e098b0b77037
0
public Transition getTransition(int row) { return transitions[row]; }
e16a350d-d804-44d3-a875-ea4072696b66
8
public String[] setListByType() { System.err.println("setListByType()"); if (typeIndex == 0 && Utils.sList != null) { String[] a = new String[Utils.sList.length-1]; for (int i = 1; i < Utils.sList.length; i++) { System.out.println("i=" + i); System.out.println(Utils.sList[i].getValue()); a[i-1] = Utils.sList[i].getValue(); } return a; } else if (typeIndex == 1 && Utils.rList != null) { String[] a = new String[Utils.rList.length-1]; for (int i = 1; i < Utils.rList.length; i++) { a[i-1] = Utils.rList[i].getValue(); } return a; } else if (typeIndex == 2 && Utils.cList != null) return Utils.cList; else return truc; }
c17fbeb6-32b4-4b28-8235-0f281af145e7
2
public void mysql2mongo(String src_db,String tar_db){ MySqlConnector mySqlConnector = new MySqlConnector(); mysql_conn = mySqlConnector.getConnection(src_db); PropertiesReader p = PropertiesReader.getInstance(); MongoConnector mongoConnector = new MongoConnector(); Mongo mongo = mongoConnector.getDb(); DB mongodb = mongo.getDB(tar_db); try{ for(String table_name : MySqlHelper.getTables(mysql_conn)){ ResultSet records = MySqlHelper.selectAll(mysql_conn,table_name); transfer(records,table_name,mongodb); } log.info(String.format("copy %s tables",table_count)); }catch (Exception e){ log.error(e); } finally { IOUtils.close(mysql_conn); mongo.close(); } }
eb877aa8-f02a-416e-a1cc-fb4eca73c64e
9
protected DropAction doAcceptDrop(Point p, DockingWindow window) { DropAction da = acceptChildDrop(p, window); if (da != null) return da; float f = isHorizontal() ? (float) p.y / getHeight() : (float) p.x / getWidth(); if (f <= 0.33f) { Direction splitDir = isHorizontal() ? Direction.UP : Direction.LEFT; return getSplitDropFilter().acceptDrop(new SplitDropInfo(window, this, p, splitDir)) ? split(window, splitDir) : null; } else if (f >= 0.66f) { Direction splitDir = isHorizontal() ? Direction.DOWN : Direction.RIGHT; return getSplitDropFilter().acceptDrop(new SplitDropInfo(window, this, p, splitDir)) ? split(window, splitDir) : null; } else { return getInteriorDropFilter().acceptDrop(new InteriorDropInfo(window, this, p)) ? createTabWindow(window) : null; } }
80b30786-8d6e-425a-ae53-80107af7b01a
7
public boolean setZombiePositions() { // TODO Auto-generated method stub for(int i = 0; i < zombieList.size(); i++) { //get posiiton point from zombie Point position = zombieList.get(i).getPosition(); //if the zombie tag didn't have an x and y if(position.x == -1 && position.y == -1) { //get all the possible tiles that the zombie can be placed in //DO NOT GENERATE EACH TIME, JUST REMOVE ZOMBIE ArrayList<Point> tileList = new ArrayList<>(); for (int y = 0; y < houseLength; y++) { for (int x = 0; x < houseWidth; x++) { if(tileLayout[x][y].getChar() == '.') { Point validTile = new Point(x,y); //put valid tile in list tileList.add(validTile); } } } //if no valid tiles if(tileList.size() == 0) return false; //pick a random tile int r = rand.nextInt(tileList.size()+1); //set position in zombie object zombieList.get(i).setPosition(tileList.get(r)); zombieList_backup.get(i).setPosition(tileList.get(r)); } } return true; }
c9669c67-da6e-4825-baf3-a3c2da283f9e
3
public String getTooltipExtraText(Province current) { if (!editor.Main.map.isLand(current.getId())) return ""; final String owner = mapPanel.getModel().getHistString(current.getId(), "owner"); if (owner == null || owner.length() == 0) return ""; return "Owned by: " + Text.getText(owner); }
9e8cc682-7337-4f05-837e-e2192705bfe0
2
public int countOccurrences(int target) { int answer; int index; answer = 0; for(index = 0; index < manyItems ; index++) { if(target == data[index]) { answer++; } } return answer; }
e767a3a8-3a87-47e3-8b1b-a5b1cd70c97c
0
public int getCoefiente() { return coefiente; }
ad758446-26b3-4493-9d1e-b772cfc1a21b
6
@PayloadRoot(localPart = REQUEST_LOCAL_NAME, namespace = NAMESPACE_URI) @ResponsePayload public AddListResponse processSubscription( @RequestPayload AddListRequest genericRequest) { try { logger.debug("Received subscription request"); try { logger.debug("Delegate to service"); logger.debug("GenericRequest size: " + genericRequest.getRecord().size()); for (Record record: genericRequest.getRecord()) { if (record.getSales() != null ) { commerceService.add(record.getSales()); } if (record.getInventory() != null ) { commerceService.add(record.getInventory()); } if (record.getOrder() != null ) { commerceService.add(record.getOrder()); } } } catch (Exception e) { logger.error("Unable to subscribe",e); // Return response AddListResponse response = new AddListResponse(); response.setCode("FAILURE"); response.setDescription("Unable to subscribe"); return response; } } catch (Exception e) { logger.error("Problem with subscription request"); // Return response AddListResponse response = new AddListResponse(); response.setCode("FAILURE"); response.setDescription("Problem with subscription request"); return response; } logger.debug("Success in subscribing"); AddListResponse response = new AddListResponse(); response.setCode("SUCCESS"); response.setDescription("User has been subscribed"); // Return response return response; }
2a20d664-718b-4439-a985-bce290dfe015
2
@Override public ArrayList<UsuarioBean> getPage(int intRegsPerPag, int intPage, ArrayList<FilterBean> hmFilter, HashMap<String, String> hmOrder) throws Exception { ArrayList<Integer> arrId; ArrayList<UsuarioBean> arrUsuario = new ArrayList<>(); try { oMysql.conexion(enumTipoConexion); arrId = oMysql.getPage("usuario", intRegsPerPag, intPage, hmFilter, hmOrder); Iterator<Integer> iterador = arrId.listIterator(); while (iterador.hasNext()) { UsuarioBean oUsuarioBean = new UsuarioBean(iterador.next()); arrUsuario.add(this.get(oUsuarioBean)); } oMysql.desconexion(); return arrUsuario; } catch (Exception e) { throw new Exception("UsuarioDao.getPage: Error: " + e.getMessage()); } }
afc696b1-2f7b-4b16-a87b-7018d2a090bd
0
public ClothHeadArmor() { this.name = Constants.CLOTH_HEAD_ARMOR; this.defenseScore = 11; this.money = 350; }