method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
8675382b-bfb6-46cb-bfff-05e3611fc092
3
public static void main(String [] args) { //Start time long startTime = System.currentTimeMillis(); for( int c = 334; c < 1000; c++) { for( int a = 1; a < c; a++) { int b = 1000 - c - a; if( isPythagTriple(a,b,c)) { System.out.println(a + " , " + b + " , " + c); System.out.println( a * b * c); } } } //End time long endTime = System.currentTimeMillis(); //Calculate total time long totalTime = endTime - startTime; //Print time System.out.println("Time is: " + totalTime); }
e33684cc-6b4a-47fc-bf63-da7fae9ffe6c
9
public void changerDeVue(String nomVue){ System.out.println("GuiCR::changerDeVue()"); if(nomVue.equals("Liste visiteurs")){ this.vues.show(this.conteneur,nomVue) ; this.vueVisualiserVisiteurs.actualiser() ; } else if(nomVue.equals("Liste praticiens h�sitants")){ this.vues.show(this.conteneur,nomVue) ; this.vueVisualiserPraticiensHesitants.actualiser() ; } else if(nomVue.equals("Liste compte rendus")){ vueVisualiserCompteRendus = new VueListeCompteRendus(modele,controleur); this.conteneur.add(vueVisualiserCompteRendus,"Liste compte rendus"); this.vues.show(this.conteneur,nomVue) ; this.vueVisualiserCompteRendus.actualiser() ; } else if(nomVue.equals("Actualiser vue liste CR d'un visiteur")){ this.vues.show(this.conteneur,"Lite compte rendus") ; this.vueVisualiserCompteRendus.actualiser() ; } else if(nomVue.equals("Se Déconnecter")){ int boxDeconnexion = JOptionPane.showConfirmDialog(null, "Voulez-vous vous déconnecter?","Déconnexion",JOptionPane.YES_NO_OPTION); if(boxDeconnexion == JOptionPane.YES_OPTION){ this.menuRapports.setEnabled(false) ; this.itemSeConnecter.setEnabled(true) ; this.itemSeDeconnecter.setEnabled(false) ; this.vues.show(this.conteneur,"Accueil") ; } } else if(nomVue.equals("Connexion")){ this.vues.show(this.conteneur,"Accueil") ; JLabel matriculeLabel = new JLabel("Matricule : "); JTextField matriculeField = new JTextField(10); JLabel mdpLabel = new JLabel("Mot de Passe : "); JPasswordField mdpField = new JPasswordField(10); Object affichageBoxConnexion [] = {"Veuillez vous identifier", matriculeLabel, matriculeField, mdpLabel, mdpField}; Object options [] = {"Valider", "Annuler"}; int boxConnexion = JOptionPane.showOptionDialog(null,affichageBoxConnexion, "Identification", JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE,null,options,null); if(JOptionPane.OK_OPTION==boxConnexion){ boolean connexionOk = this.controleur.tenterConnexion(matriculeField.getText(),new String(mdpField.getPassword())) ; if(connexionOk){ this.menuRapports.setEnabled(true) ; this.itemSeConnecter.setEnabled(false) ; this.itemSeDeconnecter.setEnabled(true) ; JOptionPane.showMessageDialog(null, "Bienvenue."); } else { JOptionPane.showMessageDialog(null, "La connexion a échoué."); } } else { this.controleur.annulerConnexion() ; } } }
8c86b635-3a5f-428c-bdfc-8edc74997611
8
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); // Setup output stream PrintWriter out = response.getWriter(); // out.println("System is closed."); boolean isAuthorized = false; String requestURI = request.getRequestURI(); /* begin - process login */ if (requestURI.endsWith("login") && request.getHeader("Referer") != null) { /* init data */ String email = request.getParameter("loginEmail"); String password = request.getParameter("loginPassword"); if (password == null) { String random = Factory.md5(String.valueOf(System.currentTimeMillis())); password = random; } String rememberPassword = request.getParameter("rememberPassword"); if (rememberPassword == null) { rememberPassword = ""; } HttpSession session = request.getSession(true); if (email.matches("[a-z0-9_.]{2,77}[@]{1}[a-z0-9.]{4,45}[.]{1}[a-z]{2,4}")) session.setAttribute("email", email); if (this.authorize(email, password)) { isAuthorized = true; session.setAttribute("isAuthorized", isAuthorized); if (rememberPassword.equals("on")) { session.setMaxInactiveInterval(3600 * 24 * 7 * 2); } else { session.setMaxInactiveInterval(1800); } String message = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<message>\n" + "<loginStatus>Success</loginStatus>\n" + "</message>"; out.println(message); } else { String message = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<message>\n" + "<loginStatus>Email hoặc mật khẩu không chính xác</loginStatus>\n" + "</message>"; out.println(message); } } /* end - process login */ else if (requestURI.endsWith("logout")) { HttpSession session = request.getSession(true); session.setAttribute("isAuthorized", false); response.sendRedirect("index.jsp"); } else { response.sendRedirect("index.jsp"); } // Xác nhận Servlet đã chạy System.out.println("AuthorizationServlet ran."); }
1ca0da2b-ac20-470e-832a-aba114611fc0
6
public static void main(String[] args) { try { Socket s = null; for(int i = 0; i < Robot.robots.size(); i++) { try { SocketAddress local = new InetSocketAddress(InetAddress.getLocalHost(), CBCGUI.PORT + 1 + i); SocketAddress server = new InetSocketAddress(InetAddress.getLocalHost(), CBCGUI.PORT); s = new Socket(); s.bind(local); s.connect(server); break; } catch(BindException ex) { s = null; } } if(s == null) return; InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); for(int i; (i = is.read()) != -1;) { char c = (char) i; System.out.println(c); if(c == STATUS) os.write(ACTIVE); } } catch(IOException ex) { ex.printStackTrace(); } }
d1454f24-0e35-48cc-9cd2-02ed887dd4c8
9
private int GeneraNumero(int[][] matriz, int fila, int columna) { int resp = 0; boolean flag = false; //Genera lista para validar los numeros utilizados en el ciclo ReiniciarSecuencia(); do { boolean validaFila = true; boolean validaColumna = true; boolean validaCuadrante = true; resp = (int)(Math.random() * (10 - 1) + 1); //Chequea que el numero no se repita en los cuadrantes 3 x 3 if(!ValidaCuadrante(matriz, ObtieneCuadrante(fila, columna),resp)) validaCuadrante = false; else { //Chequea que el numero no se repita en la fila for(int i = 0;i < 9;i++) { if(matriz[i][columna]==resp) { validaColumna = false; } if(matriz[fila][i]==resp) { validaFila = false; } } } if(validaFila && validaColumna && validaCuadrante) flag = true; InsertaSecuencia(resp); //Si se han insertado todos los valores posibles se devuelve 0 if(ValidaSecuencia()) { flag = true; resp = 0; } } while (!flag); return resp; }
8f310646-a585-4cf5-bcbd-74f68e2d3775
6
@Override protected void onNotify(BTServerStateListener listener, int event, Object o) { if ((SERVER_STARTED & event)>0){ listener.serverStarted(); } if ((SERVER_ACCEPT & event)>0){ listener.serverAccept(); } if ((SERVER_STOPPED & event)>0){ listener.serverStopped(); } if ((SERVER_LISTENING & event)>0){ listener.serverListening(); } if ((SERVER_ERROR & event)>0){ listener.serverException((Exception) o); } if ((SERVER_WAITING & event)>0){ listener.serverWaiting(); } }
abf1920f-18bd-4b49-893e-41942ed07017
6
public static ACTIONS fromString(String strKey) { if (strKey.equalsIgnoreCase("ACTION_UP")) return ACTION_UP; else if (strKey.equalsIgnoreCase("ACTION_LEFT")) return ACTION_LEFT; else if (strKey.equalsIgnoreCase("ACTION_DOWN")) return ACTION_DOWN; else if (strKey.equalsIgnoreCase("ACTION_RIGHT")) return ACTION_RIGHT; else if (strKey.equalsIgnoreCase("ACTION_USE")) return ACTION_USE; else if (strKey.equalsIgnoreCase("ACTION_ESCAPE")) return ACTION_ESCAPE; else return ACTION_NIL; }
7354b1ff-833c-4797-ae67-b3189e95f6eb
2
public void addNotes(String note) { String eol = System.getProperty("line.seperator"); if(this.contactNotes==null || this.contactNotes.equals("")) { this.contactNotes = note; }else{ this.contactNotes = this.contactNotes + eol + note; } }
e8187bbc-015e-4fd9-8b36-8775e6c38e12
5
public Object [][] getDatos(){ Object[][] data = new String[getCantidadElementos()][colum_names.length]; //realizamos la consulta sql y llenamos los datos en "Object" try{ if (colum_names.length>=0){ r_con.Connection(); String campos = colum_names[0]; for (int i = 1; i < colum_names.length; i++) { campos+=","; campos+=colum_names[i]; } String consulta = ("SELECT "+campos+" "+ "FROM "+name_tabla); PreparedStatement pstm = r_con.getConn().prepareStatement(consulta); ResultSet res = pstm.executeQuery(); int i = 0; while(res.next()){ for (int j = 0; j < colum_names.length; j++) { data[i][j] = res.getString(j+1); } i++; } res.close(); } } catch(SQLException e){ System.out.println(e); } finally { r_con.cierraConexion(); } return data; }
16ebe61e-ae8a-4605-ba96-5be8a64ff601
1
public void poistaRivi(int rivi) { if (rivi >= 0) { elokuvalista.poista(rivi); this.fireTableDataChanged(); } }
783fb711-62a4-426a-bb26-41845ab1ab28
6
public static double dynamicallyEstimateInferenceCost(NamedDescription self) { { MemoizationTable memoTable000 = null; Cons memoizedEntry000 = null; Stella_Object memoizedValue000 = null; if (Stella.$MEMOIZATION_ENABLEDp$) { memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_DYNAMICALLY_ESTIMATE_INFERENCE_COST_MEMO_TABLE_000.surrogateValue)); if (memoTable000 == null) { Surrogate.initializeMemoizationTable(Logic.SGT_LOGIC_F_DYNAMICALLY_ESTIMATE_INFERENCE_COST_MEMO_TABLE_000, "(:MAX-VALUES 500 :TIMESTAMPS (:IMPLIES-PROPOSITION-UPDATE))"); memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_DYNAMICALLY_ESTIMATE_INFERENCE_COST_MEMO_TABLE_000.surrogateValue)); } memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), self, ((Context)(Stella.$CONTEXT$.get())), Stella.MEMOIZED_NULL_VALUE, null, -1); memoizedValue000 = memoizedEntry000.value; } if (memoizedValue000 != null) { if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) { memoizedValue000 = null; } } else { memoizedValue000 = IntegerWrapper.wrapInteger(LogicObject.applicableRulesOfDescription(self, Logic.KWD_BACKWARD, true).length()); if (Stella.$MEMOIZATION_ENABLEDp$) { memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000); } } { IntegerWrapper nofrules = ((IntegerWrapper)(memoizedValue000)); return (Stella.float_max(Logic.INFERABLE_PENALTY_COST * nofrules.wrapperValue, 1.0)); } } }
061b4c39-b84c-4932-8e9a-726a5dc7a1b3
6
public static ListNode alterList(ListNode head) { if (head == null || head.next == null) return head; //find the midpoint of the list ListNode p = head, q = head.next; while (q != null && q.next != null) { p = p.next; q = q.next.next; } q = p.next; p.next = null; //reverse the half of the list //Note that reverse list function is used from other solutions p = head; q = ReverseList.reverseList(q); //now merge both list nodes alternatively while (p != null && q != null) { ListNode t = p.next; ListNode s = q.next; p.next = q; q.next = t; p = t; q = s; } return head; }
92fbb9e3-7d82-4da6-9d1c-e0321c703ed5
7
@Override public void buildModel(Dataset dataset) { estimators = new DecisionTreeC45[estimatorCount]; estimatorWeight = new double[estimatorCount]; for(int i = 0; i < estimatorCount; i++) { estimators[i] = new DecisionTreeC45(); estimators[i].maxHeight = splitCount; estimators[i].needPrune = false; estimators[i].buildModel(dataset); double error = 0, sum = 0; for(int j = 0; j < dataset.data.size(); j++) { if(dataset.data.get(j).type != InstanceType.Train) continue; estimators[i].predict(dataset.data.get(j)); if(dataset.data.get(j).predict != dataset.data.get(j).target) error += dataset.data.get(j).weight; sum += dataset.data.get(j).weight; } double errorRate = error / sum; estimatorWeight[i] = Math.log((1-errorRate)/errorRate); for(int j = 0; j < dataset.data.size(); j++) { if(dataset.data.get(j).type != InstanceType.Train) continue; if(dataset.data.get(j).predict != dataset.data.get(j).target) dataset.data.get(j).weight *= Math.exp(estimatorWeight[i]/2); else dataset.data.get(j).weight /= Math.exp(estimatorWeight[i]/2); } System.out.println(estimatorWeight[i]); } }
d9bdf8e3-ca3f-4147-91b8-347a087bcc01
5
final void removeImageFetcher(Canvas canvas) { do { try { anInt7674++; if (canvas == aCanvas7626) throw new RuntimeException(); if (!aHashtable7577.containsKey(canvas)) break; Long var_long = (Long) aHashtable7577.get(canvas); anOpenGL7664.releaseSurface(canvas, var_long.longValue()); aHashtable7577.remove(canvas); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, "qo.AG(" + (canvas != null ? "{...}" : "null") + ')'); } break; } while (false); }
223f32af-11ef-43d8-8250-8c7819f207b9
2
public static ArrayList<QuizTakenRecord> getQuizHistoryByUserID(int userID) { ArrayList<QuizTakenRecord> records = new ArrayList<QuizTakenRecord>(); String statement = new String("SELECT * FROM " + DBTable + " WHERE userid = ?"); PreparedStatement stmt; try { stmt = DBConnection.con.prepareStatement(statement); stmt.setInt(1, userID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { Quiz quiz = Quiz.getQuizByQuizID(rs.getInt("qid")); User user = User.getUserByUserID(rs.getInt("userid")); QuizTakenRecord record = new QuizTakenRecord(rs.getInt("id"), quiz, user, rs.getLong("timespan"), rs.getDouble("score"), rs.getTimestamp("time"), rs.getBoolean("isfeedback"), rs.getBoolean("ispractice")); records.add(record); } rs.close(); Collections.sort(records, new RecordSortByTime()); return records; } catch (SQLException e) { e.printStackTrace(); } return null; }
7b329309-5805-4d77-9afd-911d5273c72a
8
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { int k = Integer.parseInt(line.trim()); Manacher m = new Manacher(in.readLine().trim()); int count = 0; for (int i = 0; i < m.p.length; i++) if (m.p[i] >= k && ((k % 2 == 0 && m.t[i] == '#') || (k % 2 == 1 && m.t[i] != '#'))) count++; out.append(count + "\n"); } System.out.print(out); }
3e8f096e-7d51-40cc-bce1-17013bfd3104
4
public static void initializeTranslates() { // Initialize the scaling translates Transform.scalingTranslates = new ArrayList<Double> (); int startTranslate = (int) Math.floor((Math.pow(2,Settings.startLevel)*Settings.getMinimumRange())-Wavelet.getSupport()[1]); int stopTranslate = (int) Math.ceil((Math.pow(2,Settings.startLevel)*Settings.getMaximumRange())-Wavelet.getSupport()[0]); for (double k = startTranslate; k <= stopTranslate; k++){ Transform.scalingTranslates.add(k); } // Initialize the wavelet translates if wavelets are being used if (Settings.waveletFlag) { Transform.waveletTranslates = new ArrayList<ArrayList<Double>> (); // Loop through resolutions for (double j = Settings.startLevel; j <= Settings.stopLevel; j++){ ArrayList <Double> jTranslates = new ArrayList<Double> (); startTranslate = (int) Math.floor((Math.pow(2, j)*Settings.getMinimumRange())-Wavelet.getSupport()[1]); stopTranslate = (int) Math.ceil((Math.pow(2, j)*Settings.getMaximumRange())-Wavelet.getSupport()[0]); for (double k = startTranslate; k <= stopTranslate; k++){ jTranslates.add(k); } Transform.waveletTranslates.add(jTranslates); } } initializePhiGrid(); } //end initializeTranslates
43ec6a3b-e83a-4ed2-bebf-26c2212fa80a
3
private void delCchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delCchButtonActionPerformed if(tablaCoches.getSelectedRow() >= 0){ askWind a = new askWind(new javax.swing.JFrame(),true,"Seguro que desea eliminar este vehiculo?"); a.setLocationRelativeTo(null); a.show(); if(a.getValue() == true){ try{ taller.eliminarCoche(coches.get(tablaCoches.getSelectedRow()).getMatricula()); initTablasCoches(); } catch(Exception e){ excepWind w = new excepWind(new javax.swing.JFrame(),true,e.getMessage()); w.show(); } } a.dispose(); } }//GEN-LAST:event_delCchButtonActionPerformed
c6b69caa-634f-42e4-a0ad-2ff940fa7a88
0
@Override public Integer getValue() { return this.value; }
1d95e64a-a7a1-44a5-9f27-c285d4e3c478
0
public CFPumpingLemmaChooser() { myList = new ArrayList(); //old languages myList.add(new AnBnCn()); myList.add(new WW()); myList.add(new AnBjAnBj()); myList.add(new NaNbNc()); myList.add(new NagNbeNc()); myList.add(new AiBjCk()); myList.add(new AnBn()); //new languages (JFLAP 6.2) myList.add(new AkBnCnDj()); myList.add(new WW1WrGrtrThanEq()); myList.add(new WW1WrEquals()); myList.add(new W1BnW2()); myList.add(new W1CW2CW3CW4()); myList.add(new W1VVrW2()); }
634c90ac-fae5-4533-ae32-e864d0961fad
6
private XTreeTry makeTryPosStarted(){ expect(XKeyword.TRY); XTreeScope resources; if(tokenOk(XTokenKind.KEYWORD, XKeyword.LBRAKET)){ startPosition(); tokenizer.next(); List<XTreeStatement> list = new ArrayList<XTreeStatement>(); list.add(makeExpr()); while(tokenOk(XTokenKind.KEYWORD, XKeyword.SEMICOLON)){ tokenizer.next(); list.add(makeExpr()); } expect(XKeyword.RBRAKET); resources = new XTreeScope(endPosition(), list); }else{ resources = null; } XTreeScope body = makeScope(); List<XTreeCatch> catches = new ArrayList<XTreeCatch>(); startPosition(); while(tokenOk(XTokenKind.KEYWORD, XKeyword.CATCH)){ tokenizer.next(); expect(XKeyword.LBRAKET); List<XTreeExpr> excType = new ArrayList<XTreeExpr>(); excType.add(makeExprPrefixSuffix(false)); while(tokenOk(XTokenKind.KEYWORD, XKeyword.OR)){ tokenizer.next(); excType.add(makeExprPrefixSuffix(false)); } XTreeIdent varName = null; if(!tokenOk(XTokenKind.KEYWORD, XKeyword.RBRAKET)){ varName = makeIdent(); } expect(XKeyword.RBRAKET); XTreeScope b = makeScope(); catches.add(new XTreeCatch(endPosition(), excType, varName, b)); startPosition(); } endPosition(); XTreeScope _finally; if(tokenOk(XTokenKind.KEYWORD, XKeyword.FINALLY)){ tokenizer.next(); _finally = makeScope(); }else{ _finally = null; } return new XTreeTry(endPosition(), resources, body, catches, _finally); }
0a5a0e98-228b-43bb-b34c-6f5467d26d26
3
public char skipTo(char to) throws JSONException { char c; try { int startIndex = this.index; reader.mark(Integer.MAX_VALUE); do { c = next(); if (c == 0) { reader.reset(); this.index = startIndex; return c; } } while (c != to); } catch (IOException exc) { throw new JSONException(exc); } back(); return c; }
c932a6a8-5bb0-420c-9ceb-2b02f136ad23
8
private static void StackWithArrayMenu(StackWithArray<Integer> StackWithArray){ System.out.println("What do you want to do ?"); System.out.println("1) pop"); System.out.println("2) top"); System.out.println("3) push"); System.out.println("4) print"); System.out.println("Enter your option"); try{ choose = in.nextInt(); switch (choose){ case 1: try{ start = System.nanoTime(); StackWithArray.pop(); end = System.nanoTime(); System.out.println("Pop lasted: " + (end - start)); break; }catch(Exception e){ break; } case 2: try{ start = System.nanoTime(); StackWithArray.top(); end = System.nanoTime(); System.out.println("Top lasted: " + (end - start)); break; }catch(Exception e){ break; } case 3 : try{ System.out.println("Insert the number to push: "); size = in.nextInt(); start = System.nanoTime(); StackWithArray.push(size); end = System.nanoTime(); System.out.println("Push lasted: " + (end - start)); break; }catch(Exception e){ break; } case 4 : System.out.println(StackWithArray.describe()); } System.out.println("Do you want to exit the Stack with array menu ? (Yes / No)"); exitStackWithArrayMenu(StackWithArray); }catch (Exception e){ System.out.println("Do you want to exit the Stack with array menu ? (Yes / No)"); exitStackWithArrayMenu(StackWithArray); } }
ba493c63-0fcb-4f43-beee-02abbd1eff86
9
* @param var2 The second list * @return result The difference of var1 and var2 */ static LinkedList<Integer> subtract(LinkedList<Integer>var1, LinkedList<Integer>var2){ LinkedList<Integer> result = new LinkedList<Integer>(); // If var1 has fewer digits than var2, var1 must be smaller than var2, so return 0 if(var1.size() < var2.size()){ result.add(0); return result; } Iterator<Integer> itr1 = var1.iterator(); Iterator<Integer> itr2 = var2.iterator(); int carrier = 0; // The carrier for a given digit in subtract operation // while var1 has the same number of digits as var2, subtract var2 from var1 digit by digit, from LSD to MSD while((itr1.hasNext())&&(itr2.hasNext())){ int x = itr1.next().intValue(); // The integer value of a digit in var1 int y = itr2.next().intValue(); // The integer value of a digit in var2 int diff = x - y + carrier; // The difference of the digit of var1 and var2, plus carrier if(diff < 0) { // If the difference is less than zero, borrow "1" from the next digit diff = diff + BASE; carrier = -1; } else { // Otherwise, set the carrier for the next digit as 0 carrier = 0; } result.add(diff); } // If var1 has more digits than var2, subtract var2 from var1 digit by digit, from LSD to MSD while(itr1.hasNext()){ int x = itr1.next().intValue(); int diff = x + carrier; if(diff < 0){ // If the difference is less than zero, borrow "1" from the next digit diff = diff + BASE; carrier = -1; } else{ // Otherwise, set the carrier for the next digit as 0 carrier = 0; } result.add(diff); } // If var1 is smaller than var2, return 0 if(carrier < 0) { result.clear(); result.add(0); } // Remove the leading zeros from the result while((result.getLast() == 0)&&(result.size() > 1)){ result.removeLast(); } return result; }
76dbf70e-9ca2-4d60-8e76-1630aa175947
1
public void update() { int current = currentQueue; currentQueue = (currentQueue + 1) % 2; eventQueues.get(currentQueue).clear(); ArrayDeque<IGameEvent> toEmpty = eventQueues.get(current); while(!toEmpty.isEmpty()) { IGameEvent event = toEmpty.pollFirst(); executeEvent(event); } }
2683330d-c710-44e9-80f9-8e03f7087810
2
private static void test_itostrb(TestCase t) { // Print the name of the function to the log pw.printf("\nTesting %s:\n", t.name); // Run each test for this test case int score = 0; for (int i = 0; i < t.tests.length; i += 2) { String exp = (String) t.tests[i]; int arg1 = (Integer) t.tests[i + 1]; String res = HW2Bases.itostrb(arg1); boolean cor = exp.equals(res); if (cor) { ++score; } pw.printf("%s(%8X): Expected: %31s Result: %31s Correct: %5b\n", t.name, arg1, exp, res, cor); pw.flush(); } // Set the score for this test case t.score = (double) score / (t.tests.length / 2); }
98d5eedf-9a52-4dea-9218-7255b7ab7d9a
0
public String getImageFile() { return filename; }
ef02aefb-35ca-4d9a-935b-783fa005ddda
6
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Search_Result other = (Search_Result) obj; if (!Objects.deepEquals(this.imageIds, other.imageIds)) { return false; } if (!Objects.deepEquals(this.imagePaths, other.imagePaths)) { return false; } if (!Objects.deepEquals(this.rowNumbers, other.rowNumbers)) { return false; } if (!Objects.deepEquals(this.fieldIds, other.fieldIds)) { return false; } return true; }
35457f02-1600-4003-a9a5-dd772c573dce
3
public void loadKompetenser() { PanelHelper.cleanPanel(kompetensHolderPanel); Dimension d = kompetensHolderPanel.getPreferredSize(); d.setSize(400, 10); kompetensHolderPanel.setPreferredSize(d); ArrayList<HashMap<String, String>> a1 = null; try { String query = "select KOMPETENSDOMAN.KID, HAR_KOMPETENS.KOMPETENSNIVA KOMPNIVA, PLATTFORM.PID from KOMPETENSDOMAN" + " join HAR_KOMPETENS on HAR_KOMPETENS.KID=KOMPETENSDOMAN.KID" + " join ANSTALLD on ANSTALLD.AID=HAR_KOMPETENS.AID" + " join PLATTFORM on PLATTFORM.PID=HAR_KOMPETENS.PID" + " where ANSTALLD.AID=" + selectedAnstalld; a1 = DB.fetchRows(query); } catch (InfException e) { e.getMessage(); } if (a1 != null) { //creates panels of the database results for (int i = 0; i < a1.size(); i++) { AnstalldKompetensShowUpdater kompShow = new AnstalldKompetensShowUpdater(new AnstalldKompPlattNiva(new Kompetensdoman(Integer.parseInt(a1.get(i).get("KID"))), new Plattform(Integer.parseInt(a1.get(i).get("PID"))), Integer.parseInt(a1.get(i).get("KOMPNIVA"))), selectedAnstalld, this); PanelHelper.addPanelToPanel(kompShow, kompetensHolderPanel, 350, 25); //make panels of the results d.setSize(d.getWidth(), (d.getHeight() + 30)); kompetensHolderPanel.setPreferredSize(d); } } }
42c53dfc-8cd7-4855-a3e6-b3dc94ba7c60
2
public void transformCode(BytecodeInfo bytecode) { this.bc = bytecode; calcLocalInfo(); if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_LOCALS) != 0) { GlobalOptions.err.println("Before Local Optimization: "); dumpLocals(); } stripLocals(); distributeLocals(); if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_LOCALS) != 0) { GlobalOptions.err.println("After Local Optimization: "); dumpLocals(); } firstInfo = null; changedInfos = null; instrInfos = null; paramLocals = null; }
6f0df848-7004-4d46-a05a-9d3f9a54da2c
3
public int insert(Funcao f) { Connection conn = null; PreparedStatement pstm = null; int retorno = -1; try { conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(INSERT, Statement.RETURN_GENERATED_KEYS); pstm.setString(1, f.getNome()); pstm.execute(); try (ResultSet rs = pstm.getGeneratedKeys()) { if (rs.next()) { retorno = (rs.getInt(1)); } } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Não foi possível efetuar a transação" + ex.getMessage()); } finally { try { ConnectionFactory.closeConnection(conn, pstm); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Erro ao fechar a conexão" + ex.getMessage()); } } return retorno; }
0d396a37-78c7-43b6-aeed-529880f903c4
5
@Override public void execute(String command) throws CommandExecutionException { System.out.println("Execution: " + command); Validate.notEmpty(command, "Command line must be not empty."); Process process = null; Throwable throwable = null; try { process = Runtime.getRuntime().exec(command); startReaderThread(process.getInputStream(), System.out, "STDOUT: "); startReaderThread(process.getErrorStream(), System.err, "STDERR: "); int returnCode = process.waitFor(); if (returnCode != 0) { throw new IllegalStateException(String.format("Command '%s' return %d\n", command, returnCode)); } } catch (IOException e) { throwable = e; throw new CommandExecutionException(e); } catch (InterruptedException e) { throwable = e; process.destroy(); throw new CommandExecutionException(e); } finally { try { closeProcessStreams(process); } catch (IOException e) { if (throwable == null) { throw new CommandExecutionException(e); } } } }
58ffbaa7-4edf-4a63-8946-03809ea91ec8
2
@Override public void atacar(){ if(!this.matriz[this.objectivo.x][this.objectivo.y].getOcupado()){ this.objectivo.x=0; this.objectivo.y=0; }else{ ImageIcon iconLogo = new ImageIcon(IMG.getImage(this.mainImg)); this.refLabel.setIcon(iconLogo); try{ this.matriz[this.objectivo.x][this.objectivo.y].recibirataque(this.daño); }catch(Exception e){System.out.println("Error aplicando el ataque");} } }
b76d74f9-8baa-43ca-8721-36ccbfe33b7c
7
@SuppressWarnings("unchecked") private void Help(StateInfo<T> u){ if(u==null) return; switch(u.state){ case StateInfo.IFlag: if(u.info instanceof IInfo) HelpInsert((IInfo<T>) u.info); break; case StateInfo.MARKED: if(u.info instanceof DInfo) HelpMarked((DInfo<T>)u.info); break; case StateInfo.DFlag: if(u.info instanceof DInfo){ HelpDelete((DInfo<T>)u.info); } break; } }
516625fe-dca0-4f8b-8c5b-4f96825743b2
0
public String getName() { return this.name; }
f2ba328c-67c0-42c4-93d6-38f7b4e51233
2
public int compare(Object o1, Object o2) { int prob_diff=((data)o2).get_probability()-((data)o1).get_probability(); if(prob_diff<0)return -1; if(prob_diff>0)return 1; return 0; }
dbd0efff-cca4-4613-bdf5-de76e3eed716
1
private void skip0(CSVParser csv, int lines) { try { csv.skipLines(lines); } catch (IOException ex) { throw new RuntimeException(ex); } }
a08e5f4b-f48b-4cf3-b098-6dd367189229
9
public void testRefTime() { ReferenceGroupSet ref = new ReferenceGroupSet(); for( int i = 0; i < 100000; i++ ) { switch( mRand.nextInt( 4 ) ) { case 0: { int c = mRand.nextInt( 10 ); int v = mRand.nextInt( 100 ); ref.add( c, v ); break; } case 1: { int c = mRand.nextInt( 10 ); int v = mRand.nextInt( 100 ); ref.remove( c, v ); break; } case 2: { int c = mRand.nextInt( 10 ); List<Integer> list = new ArrayList<Integer>( 8 ); for( int j = 0; j < 8; j++ ) { int v = mRand.nextInt( 100 ); list.add( v ); ref.add( c, v ); } break; } case 3: { int c = mRand.nextInt( 10 ); List<Integer> list = new ArrayList<Integer>( 8 ); for( int j = 0; j < 8; j++ ) { int v = mRand.nextInt( 100 ); list.add( v ); ref.remove( c, v ); } break; } case 4: { if( mRand.nextInt( 5 ) == 0 ) { int c = mRand.nextInt( 10 ); ref.clear( c ); } break; } } } }
75f9bacd-9bf2-426a-bb77-4cb8729525ce
6
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(GUIInfoPartidoJugado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUIInfoPartidoJugado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUIInfoPartidoJugado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUIInfoPartidoJugado.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 GUIInfoPartidoJugado().setVisible(true); } }); }
3c38d616-1c55-42ca-a54c-3f031722b7e1
9
@Test public void testLongWalkManager() throws IOException { int nvertices = 33333; LongWalkManager wmgr = new LongWalkManager(nvertices, 40000); int tot = 0; for(int j=877; j < 3898; j++) { wmgr.addWalkBatch(j, (j % 100) + 10); tot += (j % 100) + 10; } wmgr.initializeWalks(); assertEquals(tot, wmgr.getTotalWalks()); // Now get two snapshots WalkSnapshot snapshot1 = wmgr.grabSnapshot(890, 1300); for(int j=890; j <= 1300; j++) { WalkArray vertexwalks = snapshot1.getWalksAtVertex(j, true); assertEquals((j % 100) + 10, wmgr.getWalkLength(vertexwalks)); for(long w : ((LongWalkArray)vertexwalks).getArray()) { if (w != -1) assertEquals(false, wmgr.trackBit(w)); } } assertEquals(890, snapshot1.getFirstVertex()); assertEquals(1300, snapshot1.getLastVertex()); // Next snapshot should be empty WalkSnapshot snapshot2 = wmgr.grabSnapshot(890, 1300); for(int j=890; j <= 1300; j++) { WalkArray vertexwalks = snapshot2.getWalksAtVertex(j, true); assertNull(vertexwalks); } WalkSnapshot snapshot3 = wmgr.grabSnapshot(877, 889); for(int j=877; j <= 889; j++) { WalkArray vertexwalks = snapshot3.getWalksAtVertex(j, true); assertEquals((j % 100) + 10, wmgr.getWalkLength(vertexwalks)); } WalkSnapshot snapshot4 = wmgr.grabSnapshot(877, 889); for(int j=877; j <= 889; j++) { WalkArray vertexwalks = snapshot4.getWalksAtVertex(j, true); assertNull(vertexwalks); } WalkSnapshot snapshot5 = wmgr.grabSnapshot(1301, 3898); for(int j=1301; j < 3898; j++) { WalkArray vertexwalks = snapshot5.getWalksAtVertex(j, true); assertEquals((j % 100) + 10, wmgr.getWalkLength(vertexwalks)); } // wmgr.dumpToFile(snapshot5, "tmp/snapshot5"); WalkSnapshot snapshot6 = wmgr.grabSnapshot(1301, 3898); for(int j=1301; j < 3898; j++) { WalkArray vertexwalks = snapshot6.getWalksAtVertex(j, true); assertNull(vertexwalks); } /* Then update some walks */ long w = wmgr.encode(41, false, 0); wmgr.moveWalk(w, 76, false); w = wmgr.encode(88, false, 0); wmgr.moveWalk(w, 22098, true); WalkSnapshot snapshot7 = wmgr.grabSnapshot(76, 22098); WalkArray w1 = snapshot7.getWalksAtVertex(76, true); assertEquals(1, wmgr.getWalkLength(w1)); w = ((LongWalkArray)w1).getArray()[0]; assertEquals(41, wmgr.sourceIdx(w)); assertEquals(false, wmgr.trackBit(w)); WalkArray w2 = snapshot7.getWalksAtVertex(22098, true); w = ((LongWalkArray)w2).getArray()[0]; assertEquals(88, wmgr.sourceIdx(w)); assertEquals(true, wmgr.trackBit(w)); }
2c6e50dd-8d40-41b5-bb8f-2f937eece564
7
@Override public void processCommand(String command, Scanner sc) { switch (command) { case "-help": { getHelp(); break; } case "-expatt": { processExpAtt(sc); break; } case "-expst": { processExpSt(sc); break; } case "-cc": { createCourse(sc); break; } case "-cs": { createSession(sc); break; } case "-astc": { assignStudentToCourse(sc); break; } case "-setmark": { setMarks(sc); break; } default: System.out.println("Invalid command"); break; } }
efb4d7c3-623e-427c-9488-f7286dd43321
0
@Override public void windowDeactivated(WindowEvent arg0) { // TODO Auto-generated method stub }
63e04b4f-77b5-429a-9732-6a2ab74bcdbf
9
private void initConnection() { try { if (url.toURI().toString().contains("https")) { connection = (HttpsURLConnection) url.openConnection(); } else { connection = (HttpURLConnection) url.openConnection(); } } catch (IOException | URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (type == RequestType.POST) { connection.setRequestProperty("Content-Length", String.valueOf(body.length())); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } if (!referer.equals("")) { connection.setRequestProperty("Referer", referer); } connection.setRequestProperty("Connection", "keep-alive"); connection.setRequestProperty("DNT", "1"); connection.setRequestProperty("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3"); connection .setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0"); connection .setRequestProperty("Accept", "application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); connection.setRequestProperty("Accept-Encoding", "gzip, deflate"); try { setCookies(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (type == RequestType.GET) { try { ((HttpURLConnection) connection).setRequestMethod("GET"); connection.setDoOutput(false); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { ((HttpURLConnection) connection).setRequestMethod("POST"); connection.setDoOutput(true); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } } connection.setDoInput(true); connection.setUseCaches(true); connection.setRequestProperty("Host", url.getHost()); if (ref) { connection.setDoInput(false); } // try { // connection.setRequestProperty("Cookie", // URLEncoder.encode(cookies, "UTF-8")); // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } }
442fec6e-da41-428c-ac2f-76f10a933374
6
public void mouseClicked(MouseEvent me) { try { if (me.getSource() == jb_connexion) { login = jtf_login.getText(); password = String.valueOf(jpf_password.getPassword()); System.out.println("Email : "+login); System.out.println("MotDePasse : "+password); User u = null; Connection co = bs.getConnection(); System.out.println("avant IF"); if (User.checkPresence(bs,login,password)) { System.out.println("debut IF"); u = User.findByLogs(login,password,bs); groupe = UserType.findById(u.getId_ut(),bs).getName_ut(); System.out.println("OK : " + groupe); /**/ afficherMenuPrincipal(); setResizable(true); setExtendedState(MAXIMIZED_BOTH); /**/ } else { System.out.println("NON OK"); } } if (me.getSource() == jb_mdp_oublie) { /* * A COMPLETER : * interroger la base de données, * demander à l'élève de "prouver" son identité, * (question/réponse secrètes ?) * changer le mot de passe * et envoyer un mail à l'adresse associée * ou demander de changer le mot de passe */ if (SwingUtilities.isLeftMouseButton(me)) { // statement = connection.createStatement(); // query = "CREATE TABLE table_test (champ1_test VARCHAR(30) NOT NULL, champ2_test INTEGER, PRIMARY KEY (champ1_test))"; // statement.executeUpdate(query); // System.out.println("Creation reussie (create table)"); // query = "INSERT INTO table_test VALUES ('valeur numero 1',2)"; // statement.executeUpdate(query); // System.out.println("Enregistrement 1/2 reussi (insert v1)"); // query = "INSERT INTO table_test VALUES ('valeur numero 2',2)"; // statement.executeUpdate(query); // System.out.println("Enregistrement 2/2 reussi (insert v2)"); // query = "UPDATE table_test SET champ2_test = 1 WHERE champ1_test = 'valeur numero 1'"; // statement.executeUpdate(query); // System.out.println("Modification reussie (update v1)"); // query = "DELETE FROM table_test WHERE champ1_test = 'valeur numero 2'"; // statement.executeUpdate(query); // System.out.println("Effacement reussi (delete v2)"); } if (SwingUtilities.isRightMouseButton(me)) { // statement = connection.createStatement(); // query = "DROP TABLE table_test"; // statement.executeUpdate(query); // System.out.println("Suppression reussie (drop table)"); } } } // catch (SQLException sqle) // { // jl_message.setText("Mauvaise combinaison login/password"); // System.out.println("SQL Exception"); // sqle.printStackTrace(); // // } catch (Exception e) { System.out.println("Exception"); e.printStackTrace(); } }
29de397f-b365-418c-bc6d-8ccf978b25f2
1
public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }
71f4f5d4-0513-46a0-ba6f-8a5a7d38271d
2
private void initBorders() { for(int i = 0; i < height; i++) { grid[0][i] = new Fence(0, i, this); grid[width-1][i] = new Fence(width-1, i, this); } //Offset by 1 because corner for(int i = 1; i < width; i++) { grid[i][0] = new Fence(i, 0, this); grid[i][height-1] = new Fence(i, height-1, this); } }
86219f64-4f1f-4e27-9819-408ec4cf7cac
7
public Piece selectPieceJouable(int tour) { Position pos = null; Piece pieceSelected = null; boolean stop = false; do { pos = this.getCaseCliquee(); if(pos != null) if(this.E.getTableau()[pos.getI()][pos.getJ()] != null) if(((tour%2 != 0) && (this.E.getTableau()[pos.getI()][pos.getJ()].getCouleur() == "blanc")) || ((tour%2 == 0) && (this.E.getTableau()[pos.getI()][pos.getJ()].getCouleur() == "noir"))) { pieceSelected = this.E.getTableau()[pos.getI()][pos.getJ()]; stop = true; } } while(stop == false); return pieceSelected; }
f45dcd8f-4da3-450d-8947-cb6fd0679e98
4
public boolean doTransformations() { return ((initBlock == null && type == POSSFOR) || (initInstr == null && type == FOR)) && CreateForInitializer.transform(this, flowBlock.lastModified); }
06d0d6d2-5bc8-4a17-8602-631051d2f48c
1
private void initGUI() { try { { jPanelText = new JPanel(); getContentPane().add(jPanelText, BorderLayout.EAST); jPanelText.setPreferredSize(new java.awt.Dimension(343, 362)); } { jPanelLabel = new JPanel(); getContentPane().add(jPanelLabel, BorderLayout.WEST); jPanelLabel.setPreferredSize(new java.awt.Dimension(211, 162)); { jLabelDriver = new JLabel(); jPanelLabel.add(jLabelDriver); jLabelDriver.setText("DB Driver"); jLabelDriver.setPreferredSize(new java.awt.Dimension(190, 24)); jLabelDriver.setHorizontalTextPosition(SwingConstants.RIGHT); jLabelDriver.setHorizontalAlignment(SwingConstants.RIGHT); } { jLabelURL = new JLabel(); jPanelLabel.add(jLabelURL); jLabelURL.setText("DB URL"); jLabelURL.setPreferredSize(new java.awt.Dimension(190, 24)); jLabelURL.setHorizontalAlignment(SwingConstants.RIGHT); } { jLabelUN = new JLabel(); jPanelLabel.add(jLabelUN); jLabelUN.setText("UserName"); jLabelUN.setPreferredSize(new java.awt.Dimension(190, 24)); jLabelUN.setHorizontalAlignment(SwingConstants.RIGHT); } { jLabelPW = new JLabel(); jPanelLabel.add(jLabelPW); jLabelPW.setText("PassWord"); jLabelPW.setHorizontalAlignment(SwingConstants.RIGHT); jLabelPW.setPreferredSize(new java.awt.Dimension(190, 24)); } } { jTFDriver = new JTextField(); //getContentPane().add(jTFDriver, BorderLayout.CENTER); jPanelText.add(jTFDriver); jTFDriver.setText("com.mysql.jdbc.Driver"); jTFDriver.setPreferredSize(new java.awt.Dimension(340, 24)); } { jTFUrl = new JTextField(); jPanelText.add(jTFUrl); jTFUrl.setText("jdbc:mysql://localhost:3306/d000"); jTFUrl.setPreferredSize(new java.awt.Dimension(340, 24)); } { jTFName = new JTextField(); jPanelText.add(jTFName); jTFName.setText("root"); jTFName.setPreferredSize(new java.awt.Dimension(340, 24)); } { jTFPassword = new JTextField(); jPanelText.add(jTFPassword); jTFPassword.setText("123456"); jTFPassword.setPreferredSize(new java.awt.Dimension(340, 24)); } { jButtonOK = new JButton(); jPanelText.add(jButtonOK); jButtonOK.setText("OK"); jButtonOK.addActionListener(new OKButtonClick()); jButtonOK.setPreferredSize(new java.awt.Dimension(80, 24)); } { jButtonCancel = new JButton(); jPanelText.add(jButtonCancel); jButtonCancel.setText("Cancel"); jButtonCancel.addActionListener(new CancelButtonClick()); jButtonCancel.setPreferredSize(new java.awt.Dimension(80, 24)); } { this.setSize(550, 140); } setSize(600, 200); } catch (Exception e) { e.printStackTrace(); } }
49653029-84c0-44b3-a849-7b3845b0ff2d
8
public static MaplePacket updateParty(int forChannel, MapleParty party, PartyOperation op, MaplePartyCharacter target) { MaplePacketLittleEndianWriter mplew = new MaplePacketLittleEndianWriter(); mplew.writeShort(SendPacketOpcode.PARTY_OPERATION); switch (op) { case DISBAND: case EXPEL: case LEAVE: mplew.write(0xC); mplew.writeInt(40546); mplew.writeInt(target.getId()); if (op == PartyOperation.DISBAND) { mplew.write(0); mplew.writeInt(party.getId()); } else { mplew.write(1); if (op == PartyOperation.EXPEL) { mplew.write(1); } else { mplew.write(0); } mplew.writeMapleAsciiString(target.getName()); addPartyStatus(forChannel, party, mplew, false); // addLeavePartyTail(mplew); } break; case JOIN: mplew.write(0xF); mplew.writeInt(40546); mplew.writeMapleAsciiString(target.getName()); addPartyStatus(forChannel, party, mplew, false); // addJoinPartyTail(mplew); break; case SILENT_UPDATE: case LOG_ONOFF: mplew.write(0x7); mplew.writeInt(party.getId()); addPartyStatus(forChannel, party, mplew, false); break; } return mplew.getPacket(); }
925b039c-c843-453d-ad21-ca2c71d38a44
4
public <T extends Apple & Comparable<Apple>> Collection<? super T> getNewFilteredCollection( Collection<? extends T> collection, T element) { Collection<Apple> filtereCollection = new ArrayList<>(); for (T t : collection) { if (t.compareTo(element) > 0) { filtereCollection.add(t); } } return filtereCollection; }
1685cb9e-e171-4e9f-b2bf-5c5ae4138b23
4
public boolean saveFilesToDisk(String path) { for (MultipartFile mpf : files) { try { errorMsg += "\nFile saved to: " + path; File dest = new File(path, mpf.getOriginalFilename()); if (!dest.exists()) { dest.mkdirs(); } mpf.transferTo(dest); errorMsg += "File name: " + dest; } catch (IllegalStateException e) { errorMsg += "File uploaded failed:" + e.getMessage(); return false; } catch (IOException e) { errorMsg += "File uploaded failed:" + e.getMessage(); return false; } } return true; }
6a86082d-535f-400c-adff-e7b9f89967e1
2
public static <T> Constructor<T> getConstructorIfAvailable(Class<T> clazz, Class<?>... paramTypes) { Assert.notNull(clazz, "Class must not be null"); try { return clazz.getConstructor(paramTypes); } catch (NoSuchMethodException ex) { return null; } }
b5730e5a-c40e-4934-bf5b-ccb391f9be3f
0
public Integer getIdEntrada() { return idEntrada; }
63e12eba-a4b5-4ee0-b48c-dc48c4afe25e
5
public void setCount(int newHeadCount) { if (newHeadCount >= headCount) return; headCount = newHeadCount; if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_CONSTRS) != 0) { GlobalOptions.err.println("setCount: " + this + "," + newHeadCount); new Throwable().printStackTrace(GlobalOptions.err); } if (newHeadCount < headMinCount) { GlobalOptions.err .println("WARNING: something got wrong with scoped class " + clazzAnalyzer.getClazz() + ": " + headMinCount + "," + headCount); new Throwable().printStackTrace(GlobalOptions.err); headMinCount = newHeadCount; } if (ovListeners != null) { for (Enumeration enum_ = ovListeners.elements(); enum_ .hasMoreElements();) ((OuterValueListener) enum_.nextElement()) .shrinkingOuterValues(this, newHeadCount); } }
a98fcafc-0c4d-4e9b-bab1-12be3714e049
1
public SplashScreen() { Camera.get().addScreenEffect(new TintEffect(new Vector4f(0f, 0f, 0f, 0f), 1f, true, Tween.IN)); if(loadRandom) { loadRandomSplashes(); } else { loadSplashes(); } }
847f0cd5-1cb7-4956-af2a-b42d969636f9
7
public void handleWaves(int delta) { if (!wavesHaveBegun) { handleWaitForFirstWave(delta); return; } Wave currentWave = waves.get(waveIndex); currentWave.update(delta); if (currentWave.hasNextSpawn()) { spawnEnemy(currentWave.nextSpawn()); } if (currentWave.isFinished() && !isFinalWave()) { startNextWave(); } removeDeadEnemies(); if (currentWaveHasBeenCleared() && !hasGivenRewardForCurrentWave) { GamePlayState.giveRewardForWave(waveIndex + 1); hasGivenRewardForCurrentWave = true; if (isFinalWave()) { Game.winGame(); } } }
63000d68-32d6-4260-a937-8a6a354ec12b
4
public LatLong(double latitude, double longitude) { if (latitude > 90 || latitude < -90) { throw new IllegalArgumentException("Latitude:" + latitude +", is outside of acceptable values (-90<x<90)"); } else if (longitude < -180 || longitude > 180) { throw new IllegalArgumentException("Longitude :" + longitude +", is outside of acceptable values (-180<x<180)"); } this.latitude = latitude; this.longitude = longitude; }
4e975f71-289c-4566-9d4c-677a8b809735
3
@Override public LogicalArea findArea(Area area) { if (getAreas().contains(area)) return this; //in our area nodes else //in the subtree { for (int i = 0; i < getChildCount(); i++) { final LogicalArea ret = getChildArea(i).findArea(area); if (ret != null) return ret; } return null; } }
aea22840-2a3b-4c8a-a774-cb0255295a81
5
@Override public Exam get(String examId) { Exam.Builder examBuilder = new Exam.Builder(); try (Connection con = getConnection(); CallableStatement callableStatement = con.prepareCall(querySelectExamById)) { callableStatement.setNString(1, examId); try (ResultSet resultSet = callableStatement.executeQuery()) { if (resultSet.next()) { examBuilder = examBuilder.id(resultSet.getString(aliasExamId)) .name(resultSet.getString(aliasExamName)) .subject(new Subject.Builder().name(resultSet.getString(aliasSubjectName)).build()); LinkedHashMap<String, Question.Builder> questionBuilders = new LinkedHashMap<>(); do { String questionId = resultSet.getString(aliasQuestionId); Question.Builder questionBuilder = questionBuilders.get(questionId); if (questionBuilder == null) { String questionText = resultSet.getString(aliasQuestionText); questionBuilder = new Question.Builder().id(questionId).text(questionText); questionBuilders.put(questionId, questionBuilder); } questionBuilder.addAnswer( new Answer.Builder() .id(resultSet.getString(aliasAnswerId)) .text(resultSet.getString(aliasAnswerText)) .isCorrect(Integer.parseInt(resultSet.getString(aliasAnswerIsCorrect)) == 1) .build()); } while (resultSet.next()); for (Question.Builder builder : questionBuilders.values()) { examBuilder.addQuestion(builder.build()); } } } } catch (SQLException e) { logger.error("Failed to retrieve exam with examId {}", examId); throw new SphinxSQLException(e); } return examBuilder.build(); }
b28f26dc-5657-41d8-a28c-fab579464b12
4
public String checkNumber(int number) { if (number == 1) { return "Ace"; } else if (number == 11) { return "Jack"; } else if (number == 12) { return "Queen"; } else if (number == 13) { return "King"; } return null; }
446b540f-58f9-4089-81f5-13f6c2144f9f
6
@Override public boolean equals(Object o) { if (o == null) return false; if (o == this) return true; if (!(o instanceof Arbeitsplan)) return false; Arbeitsplan a = (Arbeitsplan) o; if(a.getId() != this.getId()) return false; if(a.getBauteilNr() != this.getBauteilNr()) return false; if(a.getNr() != this.getNr()) return false; return true; }
334ce507-ca22-42a3-97b6-f890c9ff7209
7
private void doSettings(int setting) { switch (setting) { case 0: File SettingsDirectory = new File("Settings/"); if (!SettingsDirectory.exists()) { SettingsDirectory.mkdir(); } break; //------------------------------------------------------------------------ case 1: File SavedDirectory = new File("Settings/SD.pmo"); if (SavedDirectory.exists()) { try { Scanner scan = new Scanner(SavedDirectory); fileDirectory = scan.nextLine(); scan.close(); } catch (Exception e) { //#DEBUG System.out.println("Insufficient Access to file! setting = 1"); } }//::End if(SavedDirectory) break; //------------------------------------------------------------------------ case 2: try { BufferedWriter bw = new BufferedWriter(new FileWriter("Settings/SD.pmo")); bw.write(fileDirectory); bw.close(); } catch (Exception e) { //#DEBUG System.out.println("Can't write to file! setting = 2"); } break; } }
3a1f47d5-b755-4c39-b804-b91cdc769778
7
private void formScreen(String action, Connection database, HttpSession session, HttpServletRequest request, PrintWriter webPageOutput) { int orderNumber=0; String orderName=""; Routines.tableStart(false,webPageOutput); if("Change Order".equals(action)) { try { Statement sql=database.createStatement(); ResultSet queryResult; queryResult=sql.executeQuery("SELECT PlayOrderNumber " + "FROM playorders " + "ORDER BY Sequence DESC"); int tempOrderNumber=0; while(queryResult.next()) { tempOrderNumber=queryResult.getInt(1); int currentSequence=0; if("true".equals(request.getParameter(String.valueOf(tempOrderNumber)))) { queryResult=sql.executeQuery("SELECT PlayOrderNumber,PlayOrderName " + "FROM playorders " + "WHERE PlayOrderNumber=" + tempOrderNumber); if(queryResult.first()) { orderNumber=queryResult.getInt(1); orderName=queryResult.getString(2); } else { Routines.writeToLog(servletName,"Unable to find order (" + tempOrderNumber + ")",false,context); } } } } catch(SQLException error) { Routines.writeToLog(servletName,"Unable to retrieve playorder: " + error,false,context); } Routines.tableHeader("Amend details of Order",2,webPageOutput); } if("New Order".equals(action)) { Routines.tableHeader("Enter details of new Order",2,webPageOutput); } Routines.tableDataStart(true,false,false,true,false,5,0,"scoresrow",webPageOutput); webPageOutput.print("Name"); Routines.tableDataEnd(false,false,false,webPageOutput); Routines.tableDataStart(true,false,false,false,false,75,0,"scoresrow",webPageOutput); webPageOutput.print("<INPUT TYPE=\"TEXT\" NAME=\"orderName\" SIZE=\"10\" MAXLENGTH=\"10\" VALUE=\"" + orderName + "\">"); Routines.tableDataEnd(false,false,true,webPageOutput); Routines.tableEnd(webPageOutput); webPageOutput.println(Routines.spaceLines(1)); Routines.tableStart(false,webPageOutput); Routines.tableHeader("Actions",1,webPageOutput); Routines.tableDataStart(true,true,false,true,false,0,0,"scoresrow",webPageOutput); if("New Order".equals(action)) { webPageOutput.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Store New Order\" NAME=\"action\">"); } else { webPageOutput.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Store Changed Order\" NAME=\"action\">"); } webPageOutput.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Cancel\" NAME=\"action\">"); Routines.tableDataEnd(false,false,true,webPageOutput); Routines.tableEnd(webPageOutput); webPageOutput.println("<INPUT TYPE=\"hidden\" NAME=\"jsessionid\" VALUE=\"" + session.getId() + "\">"); webPageOutput.println("<INPUT TYPE=\"hidden\" NAME=\"orderNumber\" VALUE=\"" + orderNumber + "\">"); webPageOutput.println("</FORM>"); }
c74c4cef-be98-42d8-bf89-e63698a2d7db
9
private void growRegionSeeds(){ int remainingSpaces = countSpaces(); while (remainingSpaces > 0){ Region r = regions.get((int) (Math.random() * regions.size())); Tile t = r.getTiles().get((int) (Math.random() *r.getTiles().size()) ); Tile nt = null; int x = t.getX(); int y = t.getY(); /* * The if structure below will take the random region tile and attempt to "grow" it. * it does this by testing if the tile to the west, east, south, or north are currently null. * If this is the case it will add it to the region. */ if (x != 0 && tiles[x - 1][y] == null){ nt = new Tile(x - 1, y, TILE_ID); r.addTile(nt); tiles[x-1][y] = nt; TILE_ID ++; remainingSpaces --; } else if (x != size - 1 && tiles[x + 1][y] == null){ nt = new Tile(x + 1, y, TILE_ID); r.addTile(nt); tiles[x+1][y] = nt; TILE_ID ++; remainingSpaces --; } else if (y != size - 1 && tiles[x][y + 1] == null){ nt = new Tile(x, y + 1, TILE_ID); r.addTile(nt); tiles[x][y+1] = nt; TILE_ID ++; remainingSpaces --; } else if (y != 0 && tiles[x][y - 1] == null){ nt = new Tile(x, y - 1, TILE_ID); r.addTile(nt); tiles[x][y - 1] = nt; remainingSpaces --; TILE_ID ++; } } // Regions are now successfully created, time to create the territories in a similar manner PathGenerator.setTiles(tiles, size); generateTerritorySeeds(); }
fe25c7ad-6fcb-4133-8ea1-505a39e7e04e
2
@Override protected Void doInBackground() throws Exception { final int BUFFER_SIZE = 10000; Client client = new Client(BUFFER_SIZE, BUFFER_SIZE); client.getKryo().register(PacketLogin.class); client.getKryo().register(PacketLoginResponse.class); client.getKryo().register(PacketRequestCaptcha.class); client.getKryo().register(PacketCaptchaImage.class); client.getKryo().register(byte[].class); client.getKryo().register(PacketRegister.class); client.getKryo().register(PacketRegistered.class); client.getKryo().register(PacketFilesListRequest.class); client.getKryo().register(PacketFilesList.class); client.getKryo().register(String[].class); client.getKryo().register(PacketChangePassword.class); client.getKryo().register(PacketChangePasswordResponse.class); client.addListener(new Listener() { @Override public void received(Connection connection, Object object) { if (object instanceof PacketChangePasswordResponse) { PacketChangePasswordResponse response = (PacketChangePasswordResponse) object; publish(new ChangePasswordState(response.isSuccess)); connection.close(); } } }); client.start(); try { client.connect(5000, Constants.SERVER_HOST, Constants.SERVER_PORT); } catch (Exception e) { e.printStackTrace(); return null; } PacketChangePassword pcp = new PacketChangePassword(); pcp.username = this.username; pcp.session = this.session; pcp.newPassword = this.newPassword; client.sendTCP(pcp); return null; }
c87f420c-c950-42f9-b4d7-3c46aa2c51af
6
@Override public void update(GameState state) { pos.add(vel, state.seconds); if (pos.x < 0 || pos.x > AsteroidsGame.WIDTH || pos.y < 0 || pos.y > AsteroidsGame.HEIGHT) { expire(); } // TODO Coll Detection for (int j = 0; j < AsteroidsGame.enemies.size(); j++) { if (getBoundary().intersects(AsteroidsGame.enemies.get(j).getBoundary())) { AsteroidsGame.particles.add(new SmokeParticle((float)getBoundary().getCenterX(), (float)getBoundary().getCenterY(), 12, 500, 1.0f, Color.YELLOW)); expire(); // TODO dependent on bullet dmg AsteroidsGame.enemies.get(j).dealDmg(dmg); } } }
efc452e1-a774-4d5b-9c65-c42c6a07c60b
0
public void setNilai(String nilai) { this.nilai = nilai; }
356a755e-2221-40f7-930d-a49a66696bc6
3
private Music loadMusic(String path) throws SlickException { if (path == null || path.length() == 0) throw new SlickException("Sound resource has invalid path"); Music music = null; try { music = new Music(path); } catch (SlickException e) { throw new SlickException("Could not load sound", e); } return music; }
01d98501-5b31-4c9e-9e39-68a4b91cea03
0
@Override public long getIdleTimeout() { return idleTimeout; }
51c8ed12-808d-478b-8f89-019c554cc414
4
public static int fieldNum(String name) { int fieldNum = 0; if (name.equals("LOF.GENE")) return fieldNum; fieldNum++; if (name.equals("LOF.GENEID")) return fieldNum; fieldNum++; if (name.equals("LOF.NUMTR")) return fieldNum; fieldNum++; if (name.equals("LOF.PERC")) return fieldNum; fieldNum++; return -1; }
5031cf07-f7b8-40ac-9bd4-5ef1d141b94e
8
public String generateXML() { // Fisierul XML se va genera intr-un folder separat de cel cu executabilele String thisXMLPath = getXMLFolder() + "\\" + getName() + id + ".xml"; // Se ia fiecare parametru si se trece in tag-uri File file = new File(thisXMLPath); try { file.createNewFile(); } catch (IOException ex) { Logger.getLogger(Operation.class.getName()).log(Level.SEVERE, null, ex); } BufferedWriter writer; try { writer = new BufferedWriter(new FileWriter(file)); // Se urmareste structura documentului // Tag-ul task writer.write("<" + getRootElement() + ">"); writer.newLine(); writer.write('\t'); writer.write("<" + getRootDescription() + ">"); // Descrierea executabilului for (Map.Entry<String, String> entry : getDescription().entrySet()) { writer.newLine(); writer.write('\t'); writer.write('\t'); writer.write("<" + entry.getKey() + ">" + entry.getValue() + "</" + entry.getKey() + ">"); } writer.newLine(); writer.write("</" + getRootDescription() + ">"); // Lista de parametri for (SimpleTypeParameter param : getParameters()) { // Daca elementul e de tip simplu if (!(param instanceof ComplexTypeParameter)) { writer.newLine(); writer.write('\t'); writer.write("<" + param.getName() + ">"); writer.write(param.getValue()); writer.write("</" + param.getName() + ">"); } // Daca este element de tip complex else { writer.newLine(); writer.write('\t'); ComplexTypeParameter complexParam = (ComplexTypeParameter) param; // Tag-ul writer.write("<" + complexParam.getName()); // Atributele ArrayList<Attribute> attributes = complexParam .getAttributes(); for (Attribute attribute : attributes) { /* * Daca valoarea atributului nu este nula, inseamna ca: * 1. este required * 2. nu este required, dar valoarea lui a fost completata in fereastra de parametri */ if (attribute.getValue() != null) { writer.write(" " + attribute.getName() + "=" + "\"" + attribute.getValue() + "\""); } } writer.write(">"); /* * Se scrie valoarea efectiva a parametrului; * daca tag-ul e de tip empty, atunci inseamna ca valoarea e null si nu se afiseaza nimic */ if (complexParam.getValue() != null) { writer.write(complexParam.getValue()); } writer.write("</" + complexParam.getName() + ">"); } } writer.newLine(); writer.write("</" + getRootElement() + ">"); writer.close(); } catch (IOException ex) { Logger.getLogger(Operation.class.getName()).log(Level.SEVERE, null, ex); } return thisXMLPath; }
ae0e089f-8c55-4f21-8632-ad4ae513f59b
3
@Override public void assignValue(Designator d, BasicBlock cur, BasicBlock join, Environment env, Value newVal) throws Exception { if(global) { used = true; Adda ad = new Adda(getGBP(), getAddr(d)); cur.addInstruction(ad); Store st = new Store(d.getVarName(), ad, newVal); cur.addInstruction(st); if(join != null) { join.addAtEndBeforeBranch(new Kill(d.getVarName())); } } else { Identifier var = d.getVarName(); Value old = env.get(var); // generate a move instruction to indicate the value assignment Move move = new Move(newVal); cur.addInstruction(move); env.put(var, move); // get the variable reference to replace old references with Value replaceWith = env.get(var); if(join != null) { join.addPhi(var, old, replaceWith); } } }
755ba5e5-40d9-4f2a-becb-a1e8fd1e81a2
3
private void borrarFichero(File dir, int i) { File[] files = dir.listFiles(); if (files != null) { for (File f : files) { if (f.isDirectory()) { borrarFichero(f, i); } else { f.delete(); } } } dir.delete(); darCarpetas(i); }
46111268-12ed-4dc6-8891-f9078c270718
1
static void init(){ SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); try { startDay= sdf.parse("1900-01-01 00:00:00.000"); endDay= sdf.parse("2001-12-04 00:00:00.000"); } catch (ParseException e) { e.printStackTrace(); } }
274bb376-2990-42b5-be9f-13bfb91c95a9
6
public static void main(String[] args) { try { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File(ClassLoader.getSystemResource(runXMLAUTHORITY).getFile()); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); for (String warning : warnings) { System.out.println("Warning:" + warning); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XMLParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
4640b457-c8c9-492d-abe0-30b66b14ca27
2
public static String getPopulation(String date, String state, String gender) { DB db = _mongo.getDB(DATABASE_NAME); DBCollection coll = db.getCollection(COLLECTION_POPULATION); BasicDBObject query = new BasicDBObject(); query.put("year", "" + getYear(date)); DBCursor cur = coll.find(query); DBObject doc = null; if (cur.hasNext()) { doc = cur.next(); if (gender == null) gender = GENDER_ALL; return getValue(doc, state, gender); } return ""; }
c3bce6bf-7860-43e5-a89c-bc68c77e4cf6
7
@SuppressWarnings("serial") public MvcView(MvcModel model, JFrame Frame) { // add a property change listener to the model to listen and // respond to changes in the model's state model.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // if the state change is the one we're interested in... if (evt.getPropertyName().equals(MvcModel.STATE)) { stateField.setText(evt.getNewValue().toString()); } } }); startButton = new JButton(new AbstractAction("Start") { public void actionPerformed(ActionEvent ae) { if (control != null) { if (this.getValue(NAME) == "Start") { this.putValue(Action.NAME, "Stop"); pauseButton.setEnabled(true); control.startButtonActionPerformed(ae); } else if (this.getValue(NAME) == "Stop") { this.putValue(Action.NAME, "Start"); pauseButton.setEnabled(false); pauseButton.getAction().putValue(Action.NAME, "Pause"); control.stopButtonActionPerformed(ae); } else { System.out.println("StartFAIL"); } } } }); pauseButton = new JButton(new AbstractAction("Pause") { public void actionPerformed(ActionEvent ae) { if (control != null) { if (this.getValue(NAME) == "Pause") { this.putValue(Action.NAME, "Resume"); control.pauseButtonActionPerformed(ae); } else if (this.getValue(NAME) == "Resume") { this.putValue(Action.NAME, "Pause"); control.startButtonActionPerformed(ae); } else { System.out.println("PauseFAIL"); } } } }); pane = new JLayeredPane(); pane.setPreferredSize(Frame.getMaximumSize()); pane.add(stateControlPanel(), JLayeredPane.DEFAULT_LAYER, 0); this.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); this.setLayout(new BorderLayout()); }
215700ba-495e-4ada-b69c-bf23a4200b82
0
@After public void tearDown() { }
2cafc014-4b82-40a1-b1a5-38a907f896b4
4
private int minBest(int i, int j, int k){ double di = fitness.get(i); double dj = fitness.get(j); double dk = fitness.get(k); if(di <= dj && di <= dk){ return i; }else if(dj <= di && dj <= dk){ return j; }else{ return k; } }
68f797c2-317a-4db0-8e84-ca37ae1f5239
7
public void beginTurn() { if (!autoGame) { autoGame = true; for (int i = 0; i < numPlayers; i++) { if (!players[i].isAI() && players[i].isLiving()) autoGame = false; } } playerPnlHash.get(activePlayer).setActive(true); int troopCount = Math.max(map.getTerritoryCount(activePlayer) / 3, 3); log(activePlayer.name + " gets " + troopCount + " troops for " + map.getTerritoryCount(activePlayer) + " territories."); int extra = 0; if (activePlayer.hasSet()) extra += playSet(); troopCount += extra; state = State.DEPLOY; conqueredTerritory = false; fromTerrit = null; toTerrit = null; actionBtn.setText("End Attacks"); actionBtn.setEnabled(false); autoPlayBtn.setEnabled(true); Continent[] conts = map.getContinents(); for (Continent cont : conts) { if (cont.hasContinent(activePlayer)) { troopCount += cont.getBonus(); log(activePlayer.name + " gets " + cont.getBonus() + " troops for holding " + cont.name + "."); } } activePlayer.updateStats(Player.BONUS, troopCount - extra); message(activePlayer.name + ", you have " + troopCount + " troops to place."); deployNum = troopCount; }
a3ee834f-b1c4-466d-b63f-41fb3b793b10
0
public int getSequence() { return this._sequence; }
58225295-707c-4ec3-81b6-74da39a7e49d
5
@Override public boolean processBuffer() { // Stream buffers can only be queued for streaming sources: if( errorCheck( channelType != SoundSystemConfig.TYPE_STREAMING, "Buffers are only processed for streaming sources." ) ) return false; // Make sure we have a SourceDataLine: if( errorCheck( sourceDataLine == null, "SourceDataLine null in method 'processBuffer'." ) ) return false; if( streamBuffers == null || streamBuffers.isEmpty() ) return false; // Dequeue a buffer and feed it to the SourceDataLine: SoundBuffer nextBuffer = streamBuffers.remove( 0 ); sourceDataLine.write( nextBuffer.audioData, 0, nextBuffer.audioData.length ); if( !sourceDataLine.isActive() ) sourceDataLine.start(); nextBuffer.cleanup(); nextBuffer = null; return true; }
0fb62556-da9a-4a74-9c9c-243abac46eac
9
protected void recoverStatements() { class MethodVisitor extends ASTVisitor { public ASTVisitor typeVisitor; TypeDeclaration enclosingType; // used only for initializer TypeDeclaration[] types = new TypeDeclaration[0]; int typePtr = -1; public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { typePtr = -1; return true; } public boolean visit(Initializer initializer, MethodScope scope) { typePtr = -1; return true; } public boolean visit(MethodDeclaration methodDeclaration,Scope scope) { typePtr = -1; return true; } public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) { return this.visit(typeDeclaration); } public boolean visit(TypeDeclaration typeDeclaration, Scope scope) { return this.visit(typeDeclaration); } private boolean visit(TypeDeclaration typeDeclaration) { if(this.types.length <= ++this.typePtr) { int length = this.typePtr; System.arraycopy(this.types, 0, this.types = new TypeDeclaration[length * 2 + 1], 0, length); } this.types[this.typePtr] = typeDeclaration; return false; } public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { this.endVisitMethod(constructorDeclaration, scope); } public void endVisit(MethodDeclaration methodDeclaration, Scope scope) { this.endVisitMethod(methodDeclaration, scope); } private void endVisitMethod(AbstractMethodDeclaration methodDeclaration, Scope scope) { TypeDeclaration[] foundTypes = null; // int length = 0; // if(this.typePtr > -1) { // length = this.typePtr + 1; // foundTypes = new TypeDeclaration[length]; // System.arraycopy(this.types, 0, foundTypes, 0, length); // } ReferenceContext oldContext = Parser.this.referenceContext; Parser.this.recoveryScanner.resetTo(methodDeclaration.bodyStart, methodDeclaration.bodyEnd); Scanner oldScanner = Parser.this.scanner; Parser.this.scanner = Parser.this.recoveryScanner; Parser.this.parseStatements( methodDeclaration, methodDeclaration.bodyStart, methodDeclaration.bodyEnd, foundTypes, compilationUnit); Parser.this.scanner = oldScanner; Parser.this.referenceContext = oldContext; // for (int i = 0; i < length; i++) { // foundTypes[i].traverse(typeVisitor, scope); // } } public void endVisit(Initializer initializer, MethodScope scope) { TypeDeclaration[] foundTypes = null; int length = 0; if(this.typePtr > -1) { length = this.typePtr + 1; foundTypes = new TypeDeclaration[length]; System.arraycopy(this.types, 0, foundTypes, 0, length); } ReferenceContext oldContext = Parser.this.referenceContext; Parser.this.recoveryScanner.resetTo(initializer.bodyStart, initializer.bodyEnd); Scanner oldScanner = Parser.this.scanner; Parser.this.scanner = Parser.this.recoveryScanner; Parser.this.parseStatements( this.enclosingType, initializer.bodyStart, initializer.bodyEnd, foundTypes, compilationUnit); Parser.this.scanner = oldScanner; Parser.this.referenceContext = oldContext; for (int i = 0; i < length; i++) { foundTypes[i].traverse(typeVisitor, scope); } } } class TypeVisitor extends ASTVisitor { public MethodVisitor methodVisitor; TypeDeclaration[] types = new TypeDeclaration[0]; int typePtr = -1; public void endVisit(TypeDeclaration typeDeclaration, BlockScope scope) { endVisitType(); } public void endVisit(TypeDeclaration typeDeclaration, ClassScope scope) { endVisitType(); } private void endVisitType() { this.typePtr--; } public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) { return this.visit(typeDeclaration); } public boolean visit(TypeDeclaration typeDeclaration, ClassScope scope) { return this.visit(typeDeclaration); } private boolean visit(TypeDeclaration typeDeclaration) { if(this.types.length <= ++this.typePtr) { int length = this.typePtr; System.arraycopy(this.types, 0, this.types = new TypeDeclaration[length * 2 + 1], 0, length); } this.types[this.typePtr] = typeDeclaration; return true; } public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { if(constructorDeclaration.isDefaultConstructor()) return false; constructorDeclaration.traverse(methodVisitor, scope); return false; } public boolean visit(Initializer initializer, MethodScope scope) { methodVisitor.enclosingType = this.types[typePtr]; initializer.traverse(methodVisitor, scope); return false; } public boolean visit(MethodDeclaration methodDeclaration, Scope scope) { methodDeclaration.traverse(methodVisitor, scope); return false; } } if (false) { MethodVisitor methodVisitor = new MethodVisitor(); TypeVisitor typeVisitor = new TypeVisitor(); methodVisitor.typeVisitor = typeVisitor; typeVisitor.methodVisitor = methodVisitor; if(this.referenceContext instanceof AbstractMethodDeclaration) { ((AbstractMethodDeclaration)this.referenceContext).traverse(methodVisitor, (Scope)null); }else if(this.referenceContext instanceof CompilationUnitDeclaration) { CompilationUnitDeclaration compilationUnitDeclaration=(CompilationUnitDeclaration)this.referenceContext; if (compilationUnitDeclaration.statements!=null) for (int i = 0; i < compilationUnitDeclaration.statements.length; i++) { if( compilationUnitDeclaration.statements[i] instanceof AbstractMethodDeclaration) ((AbstractMethodDeclaration)compilationUnitDeclaration.statements[i] ).traverse(methodVisitor, (Scope)null); } } else if(this.referenceContext instanceof TypeDeclaration) { TypeDeclaration typeContext = (TypeDeclaration)this.referenceContext; int length = typeContext.fields.length; for (int i = 0; i < length; i++) { final FieldDeclaration fieldDeclaration = typeContext.fields[i]; switch(fieldDeclaration.getKind()) { case AbstractVariableDeclaration.INITIALIZER: methodVisitor.enclosingType = typeContext; ((Initializer) fieldDeclaration).traverse(methodVisitor, (MethodScope)null); break; } } } } else { CompilationUnitDeclaration compilationUnitDeclaration=(CompilationUnitDeclaration)this.referenceContext; ReferenceContext oldContext = Parser.this.referenceContext; int start = compilationUnitDeclaration.sourceStart; int end = compilationUnitDeclaration.sourceEnd; Parser.this.recoveryScanner.resetTo(start, end); Scanner oldScanner = Parser.this.scanner; Parser.this.scanner = Parser.this.recoveryScanner; /* unit creation */ this.referenceContext = this.compilationUnit = compilationUnitDeclaration= new CompilationUnitDeclaration( this.problemReporter, compilationUnitDeclaration.compilationResult, end); Parser.this.parseStatements( compilationUnitDeclaration, start, end, null, compilationUnit); Parser.this.scanner = oldScanner; Parser.this.referenceContext = oldContext; } }
67f4dce5-b317-40b0-aac2-cdbf10d6aa4d
1
@Override public void update(long deltaMs) { if(spawned) { checkBossStatus(); } else { spawnBoss(); } }
7faa2990-f361-4552-8968-9382a63f6196
6
public KladrComboBoxModel(String code, Integer type){ Kladr kladr = new Kladr(); LinkedHashMap<String, String> subjects = null; if(code == null){ subjects = kladr.getSubjects(); }else if(type == KladrComboBoxModel.REGION){ subjects = kladr.getRegions(code); }else if(type == KladrComboBoxModel.CITY){ subjects = kladr.getCities(code); }else if(type == KladrComboBoxModel.MICROREGIONS){ subjects = kladr.getMicroRegions(code); }else if(type == KladrComboBoxModel.STREET){ subjects = kladr.getStreets(code); } int i = 0; for(String k: subjects.keySet()){ data.add(new Subject( subjects.get(k), k )); i++; } }
f28900e6-941f-4658-a3a9-dd3766891956
6
public int run() { Utils.setConsoleTitle(log.localize("interactive.cmd.title")); log.println("interactive.header", se.getFactory().getEngineName(), se.getFactory().getEngineVersion()); se.put(XScriptLang.ENGINE_ATTR_INTERACTIVE, true); se.put(XScriptLang.ENGINE_ATTR_SOURCE_FILE, ".interactive"); @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); while(se.isRunning()){ log.print("interactive.cmd.prfix"); log.flush(); String script = sc.nextLine(); script = script.trim(); if(script.equals("exit")){ return Utils.OK; }else if(script.equals("help")){ log.println("msg.help"); continue; } while(!finished(script)){ log.print("interactive.cmd.resume"); log.flush(); script += "\n"+sc.nextLine(); } try { Object ret = se.eval(script); ret = ((Invocable)se).invokeFunction("__builtin__.___str__", ret); log.rawprintln(XUtils.getString(se, (XValue)ret)); } catch (ScriptException e) { log.rawprintln(Kind.ERROR, e.getMessage()); } catch (NoSuchMethodException e) {} } log.flush(); return (Integer)se.get(XScriptLang.ENGINE_ATTR_EXIT_STATE); }
9cecf695-0577-4dfb-8081-9ff8b80fdabc
6
public static Stella_Object accessSavedInferenceLevelProofAdjunctSlotValue(SavedInferenceLevelProofAdjunct self, Symbol slotname, Stella_Object value, boolean setvalueP) { if (slotname == Logic.SYM_LOGIC_SAVED_INFERENCE_LEVEL) { if (setvalueP) { self.savedInferenceLevel = ((InferenceLevel)(value)); } else { value = self.savedInferenceLevel; } } else if (slotname == Logic.SYM_LOGIC_INFERENCE_LEVEL) { if (setvalueP) { self.inferenceLevel = ((InferenceLevel)(value)); } else { value = self.inferenceLevel; } } else if (slotname == Logic.SYM_LOGIC_DOWN_FRAME) { if (setvalueP) { self.downFrame = ((ControlFrame)(value)); } else { value = self.downFrame; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + slotname + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } return (value); }
5603ee0c-0df3-4852-86d4-918a4f602621
9
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equalsIgnoreCase("settag")){ if (sender instanceof Player){ if (args.length==1){ if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){ if(args[0].equals("clear") == false){ tag.put(sender.getName(), (args[0])); sender.sendMessage("Your radio tag is now " + tag.get(sender.getName())); return true; }else{ tag.put(sender.getName(), null); sender.sendMessage("Your tag has been cleared"); return true; } }else{ sender.sendMessage("You must have a radio in hand to set your tag"); return true; } }else{ sender.sendMessage("Need 1 argument!"); return false; } }else{ sender.sendMessage("You must be a player to use this command"); return true; } } if(cmd.getName().equalsIgnoreCase("gettag")){ if(sender instanceof Player){ if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){ if(tag.get(sender.getName()) != null){ sender.sendMessage("Your tag is " + tag.get(sender.getName())); return true; }else{ sender.sendMessage("You don't have a tag right now"); return true; } }else{ sender.sendMessage("You must have a radio in your hand to check your tag"); return true; } }else{ sender.sendMessage("You must be a player to use this command"); return true; } } return false; }
ad9bf205-5cd0-488c-812a-6a46b951dc48
3
@Raw public Weapon getNextWeapon() throws IllegalStateException { if (currentWeaponIndex == -1 && weaponList.size() == 0) throw new IllegalStateException("Next Weapon isn't available since the list doesn't contain any weapons."); if (currentWeaponIndex == weaponList.size() - 1) return weaponList.get(0); else return weaponList.get(currentWeaponIndex + 1); }
c8de15b2-46dc-40b7-aa77-81815475d5a0
8
public static boolean fileprocess(String downloadpath, String filepath, String []paras, String sn){ int errorcode=0;// print error code in the final output file; int errornum = 13; String result=""; File downloadfile = new File(downloadpath+"\\humid_test.txt"); File outputfile = new File(filepath); double value =0; String line=""; ArrayList <String> content = new ArrayList<String>(); try { BufferedReader br = new BufferedReader(new FileReader(downloadfile)); while ((line=br.readLine())!=null){ content.add(line); } br.close(); downloadfile.delete(); double lower_bound=Double.parseDouble(paras[0]); double upper_bound=Double.parseDouble(paras[1]); if (content.size()!=1){ result = "FAILED"; errorcode=3; } else{ value=Double.parseDouble(content.get(0)); if (value>=lower_bound){ if (value<=upper_bound){ result="PASS"; } else { result = "FAILED"; errorcode =2; } } else{ result = "FAILED"; errorcode=1; } } } catch (IOException e) { e.printStackTrace(); } catch (NumberFormatException ex){ result = "FAILED"; errorcode = 0; } try { BufferedWriter bw = new BufferedWriter(new FileWriter(outputfile,true)); bw.write("Humidity="+value+"\r\n"); System.out.println("Humidity="+value); bw.write("Humidity_Result="+result+"\r\n"); System.out.println("Humidity_Result="+result); if (result.equals("FAILED")){ NumberFormat nf = NumberFormat.getIntegerInstance(); nf.setMinimumIntegerDigits(2); bw.write("Error_Code= "+nf.format(errornum)+nf.format(errorcode)+"\r\n"); System.out.println("Error_Code="+nf.format(errornum)+nf.format(errorcode)); } bw.flush(); bw.close(); }catch (Exception e){ e.printStackTrace(); } return true; }
b5fb432f-44da-4d16-ac62-68f01654e2dd
8
private String readIACSETerminatedString(int maxlength) throws IOException { int where = 0; char[] cbuf = new char[maxlength]; char b = ' '; boolean cont = true; do { int i; i = rawread(); switch (i) { case IAC: i = rawread(); if (i == SE) { cont = false; } break; case -1: return (new String("default")); default: } if (cont) { b = (char) i; // Fix for overflow wimpi (10/06/2004) if ((b == '\n') || (b == '\r') || (where == maxlength)) { cont = false; } else { cbuf[where++] = b; } } } while (cont); return (new String(cbuf, 0, where)); }// readIACSETerminatedString
0f00538f-4ab9-4926-8877-fe9f48782c75
5
protected static Object getter(Object obj, String type, String attr) { Class<?> c = obj.getClass(); Method method = null; if (type.equals("boolean")) { try { method = c.getMethod("is" + attr); } catch (Exception e) { LOG.error("没有这个方法is" + attr + "或者因为安全问题无法访问", e); } } else { try { method = c.getMethod("get" + attr); } catch (Exception e) { LOG.error("没有这个方法get" + attr + "或者因为安全问题无法访问", e); } } try { obj = method.invoke(obj); } catch (Exception e) { LOG.error("调用方法" + method.getName() + "时发生异常", e); } return obj; }
711413bb-30f5-4aa5-8bd2-0509c73c2afd
0
public void setDest(String dest){ this.dest = dest; }
c27ddcf5-2ade-4c06-b285-9c1af6684e58
7
public boolean additionalStrictCheck() { for (GridElement ge : g) { if (ge instanceof Cell) { Cell cell = (Cell) ge; if (cell.getDigit() != -1) { if (cell.countYesEdges() != cell.getDigit()) { iV = cell.getY(); jV = cell.getX(); message = "Cell at row " + iV + " column " + jV + ": incorrect number of edges around"; return false; } } } if (ge instanceof Vertex) { Vertex vertex = (Vertex) ge; if (vertex.countYesEdges() != 2 && vertex.countYesEdges() != 0) { iV = vertex.getY(); jV = vertex.getX(); message = "Vertex at row " + iV + " column " + jV + ": incorrect number of edges around"; return false; } } } return true; }
cfd168ea-e05a-4a94-82e1-15226516685b
1
public static double getSumValue(HashMap<String, Double> map) { Double count = 0.0D; List list = new LinkedList(map.entrySet()); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); count += map.get(entry.getKey()); } return count; }
01a3d1dd-11ef-46fc-b28d-268c3e65c395
2
public static void main(String[] args) { //Set Used Queues values to False for(int k = 0;k<=5;k++) { usedQueues[k] = false; usedStatusArea[k] = false; usedConnectionThread[k] = false; usedUploadQueues[k] = false; usedUploadStatusArea[k] = false; usedUploadConnectionThread[k] = false; } //Populate JTextAres and Queues Arrays for(int k = 0;k<=5;k++) { JTextArea dev = new JTextArea(); statusFields[k] = dev; JTextArea dev1 = new JTextArea(); uploadStatusFields[k] = dev1; LinkedList<Integer> queue = new LinkedList<Integer>(); queues[k] = queue; LinkedList<Integer> queue1 = new LinkedList<Integer>(); uploadQueues[k] = queue1; } //Build and create Welcome Screen javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JPanel p = new JPanel(null); wG = new WelcomeGUI(p); wG.setVisible(true); } }); //Create DB Helper Object dbHelper = new DatabaseHelper(); }
ee43c018-c121-429d-86e8-f046e5222c63
9
@Override public void map(LongWritable id, Text line, OutputCollector<IntWritable, Text> out, Reporter reporter) throws IOException { // Get Name and Text of document contents = line.toString().split("\\|",2); words = contents[1].split("\\s+"); // Process for document names and contents that are not empty (or just a space) if (contents[0].length() > 1 && contents[1].length() > 1){ wordCounts = new HashMap<String, Double>(); double tf = 0; double idf = 0; maxWordCount = 0; tfidf = new HashMap<String, Double>(); int count; double documentCount = (double) docFrequency.getDocumentCount(); // Process each word to get totals for (int i = 0; i < words.length; i++){ word = words[i]; if (wordCounts.containsKey(word)){ wordCounts.put(word, wordCounts.get(word) + 1.0); } else { wordCounts.put(word, 1.0); } } // Get highest word count in the document for (double value : wordCounts.values()){ maxWordCount = Math.max(maxWordCount, value); } // Process each unique word to get tfidf for (int i = 0; i < words.length; i++){ word = words[i]; if (word.trim().length() > 1){ count = docFrequency.getCount(word); if (count == 0){ count = 1; } idf = Math.log(documentCount / (double) count); tf = 0.5 + (0.5 * wordCounts.get(word) / maxWordCount); tfidf.put(word, tf * idf); } } // Optional Steps: // Sort tfidf // Cut to top K (maybe) // Get reducer key based on title key = new IntWritable(); key.set(contents[0].toLowerCase().trim().charAt(0)); // Create tfidf string sb = new StringBuilder(wordCounts.size()); sb.append(contents[0].toLowerCase().trim()); sb.append("|"); for (String key : tfidf.keySet()){ sb.append(key); sb.append(":"); sb.append(tfidf.get(key)); sb.append(","); } tfidfString = sb.toString(); // Emit title + tfidf string //System.out.println(tfidfString); out.collect(key, new Text(tfidfString)); } }
ae462fbc-db31-405a-aa14-f0c1079f1701
5
public static void newStartMenu(Game game, Screen parent, PokeInstance pokemon) { try { pokemonStatusMenuClass.getConstructors()[0].newInstance(game, parent, pokemon); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } }
cfd837a6-a800-4316-8680-cf4bc2c23d2d
7
public void start() throws Exception { _unavailable=0; super.start(); if (!javax.servlet.Servlet.class .isAssignableFrom(_class)) { Exception ex = new IllegalStateException("Servlet "+_class+ " is not a javax.servlet.Servlet"); super.stop(); throw ex; } _config=new Config(); if (_runAs!=null) _realm=_httpHandler.getHttpContext().getRealm(); if (javax.servlet.SingleThreadModel.class .isAssignableFrom(_class)) _servlets=new Stack(); if (_initOnStartup) { _servlet=(Servlet)newInstance(); try { initServlet(_servlet,_config); } catch(Throwable e) { _servlet=null; _config=null; if (e instanceof Exception) throw (Exception) e; else if (e instanceof Error) throw (Error)e; else throw new ServletException(e); } } }