text
stringlengths
14
410k
label
int32
0
9
public boolean func_para_num_wrong(String func_name,int number){ int num = gt.function_table.function_name.size(); for (int i = 0; i < num; i++) { if (gt.function_table.function_name.get(i).toString().equals(func_name)) { int n =(Integer)gt.function_table.function_parameter_num.get(i); if(n!=number)return true; } } return false; }
3
public int characterAt(int at) throws JSONException { int c = get(at); if ((c & 0x80) == 0) { return c; } int character; int c1 = get(at + 1); if ((c1 & 0x80) == 0) { character = ((c & 0x7F) << 7) | c1; if (character > 0x7F) { return character; } } else { int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF && (character < 0xD800 || character > 0xDFFF)) { return character; } } throw new JSONException("Bad character at " + at); }
8
private int minPathSumMN(int m, int n, int[][] s, int[][]grid){ if(m == 0 && n == 0 ){ return grid[0][0]; } else if(m == 0){ if(s[m][n-1] != -1){ s[m][n] = s[m][n-1] + grid[m][n]; } else{ s[m][n] = minPathSumMN(m, n-1, s, grid) + grid[m][n]; } } else if(n == 0){ if(s[m-1][n] != -1){ s[m][n] = s[m-1][n] + grid[m][n]; } else{ s[m][n] = minPathSumMN(m-1, n, s, grid) + grid[m][n]; } } else{ if(s[m][n-1] == -1){ s[m][n-1] = minPathSumMN(m, n-1, s, grid); } if(s[m-1][n] == -1){ s[m-1][n] = minPathSumMN(m-1, n, s, grid); } int min = s[m][n-1] <= s[m-1][n] ? s[m][n-1] : s[m-1][n]; s[m][n] = min + grid[m][n]; } return s[m][n]; }
9
@Override public void mouseDragged(MouseEvent mouse) { Tool tool = controls.getTool(); if (begin == null && selectedMessage == null) { graph.canvas.offX = oldOffX + (mouse.getX() - preClickX); graph.canvas.offY = oldOffY + (mouse.getY() - preClickY); GUI.gRepaint(); return; } if (tool.type == ToolType.move) { for (Vertex vertex : graph.vertices) { if (!vertex.equals(begin) && vertex .isNearPoint(mouseGetX(mouse), mouseGetY(mouse), begin.getRadius())) { return; } } begin.move(mouseGetX(mouse), mouseGetY(mouse)); GUI.gRepaint(); } else { xlast = mouseGetX(mouse); ylast = mouseGetY(mouse); GUI.gRepaint(); } }
6
public static void killMetaInf () { File inputFile = new File(Settings.getSettings().getInstallPath() + "/" + ModPack.getSelectedPack().getDir() + "/minecraft/bin", "minecraft.jar"); File outputTmpFile = new File(Settings.getSettings().getInstallPath() + "/" + ModPack.getSelectedPack().getDir() + "/minecraft/bin", "minecraft.jar.tmp"); try { JarInputStream input = new JarInputStream(new FileInputStream(inputFile)); JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile)); JarEntry entry; while ((entry = input.getNextJarEntry()) != null) { if (entry.getName().contains("META-INF")) { continue; } output.putNextEntry(entry); byte buffer[] = new byte[1024]; int amo; while ((amo = input.read(buffer, 0, 1024)) != -1) { output.write(buffer, 0, amo); } output.closeEntry(); } input.close(); output.close(); if (!inputFile.delete()) { Logger.logError("Failed to delete Minecraft.jar."); return; } outputTmpFile.renameTo(inputFile); } catch (FileNotFoundException e) { Logger.logError("Error while killing META-INF", e); } catch (IOException e) { Logger.logError("Error while killing META-INF", e); } }
6
public static String getLongestPalindrome(String s){ char[] T = preProcess(s).toCharArray(); int n = T.length; int[] P = new int[n]; int C = 0, R = 0; for (int i = 1; i < n-1; i++) { int i_mirror = 2*C - i; // equals to i' = C - (i-C) if ( i < R ) { P[i] = Math.min(R-i, P[i_mirror]); } else{ P[i] = 0; } // Attempt to expand palindrome centered at i while( T[i+1+P[i]] == T[i-1-P[i]] ) P[i]++; // if palindrome centered at i expand past R // adjust center based on expanded palindrome if ( debug ) { System.out.println("i="+i +", P[i]="+P[i] + ", R="+R); } if ( i + P[i] > R) { C = i; R = i + P[i]; if ( debug ){ System.out.println("Updated C="+C +", R="+R); } } } int maxLen = 0; int centerIndex = 0; for (int i = 1; i < n-1 ; i++) { if (P[i] > maxLen) { maxLen = P[i]; centerIndex = i; } } if ( debug ){ System.out.println("centerIndex: " + centerIndex); System.out.println("maxLen: " + maxLen); } int beginIndex = (centerIndex-1-maxLen)/2; return s.substring(beginIndex, beginIndex+maxLen); }
9
public boolean hasPermission(CommandSender sender, String permission) { if( sender instanceof ConsoleCommandSender ) return true; // from here forward it must be a player object to pass if( !(sender instanceof Player) ) return false; Player p = (Player) sender; if( usePermissions && vaultPerms != null ) return vaultPerms.has(p, permission); else if( p.isOp() ) return true; else return false; }
5
public static boolean validClass(Class<?> clazz) { try { Method serialize = clazz.getDeclaredMethod("serialize"); if (!serialize.getReturnType().equals(String.class)) { System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because it does not return a String"); return false; } if (!Modifier.isPublic(serialize.getModifiers())) { System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because the method 'serialize' is not public"); return false; } if (!Modifier.isStatic(serialize.getModifiers())) { System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because the method 'serialize' is static"); return false; } Method deserialize = clazz.getDeclaredMethod("deserialize", String.class); if (!deserialize.getReturnType().equals(clazz)) { System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' does not return the class '" + clazz.getCanonicalName() + "'"); return false; } if (!Modifier.isStatic(deserialize.getModifiers())) { System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is not static"); return false; } if (!Modifier.isPublic(deserialize.getModifiers())) { System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is not public"); return false; } } catch (NoSuchMethodException e) { System.out.println("Class '" + clazz.getCanonicalName() + "' does not have either the serialize and/or deserialize method(s)"); return false; } return true; }
8
public int placeWords(String matchString, String[] matchWords){ int n = matchString.length(); int m = 0; for(int i=0; i<n; i++){ if(m<matchWords[i].length()) m = matchWords[i].length(); } int min = Integer.MAX_VALUE; for(int i=0; i<m; i++){ int cost = 0; int length = 0; for(int j=0; j<n; j++){ int start = Math.min(i, matchWords[j].length()-1); for(int e=start; e>=0; e--){ if(matchWords[j].charAt(e) == matchString.charAt(j)){ cost+=i-e; length++; break; } } } if(length == n) min = Math.min(min, cost); } if(min==Integer.MAX_VALUE) return -1; else return min; }
8
public synchronized void m4t2() { int i = 5; while (i-- > 0) { System.out.println(Thread.currentThread().getName() + " : " + i); try { Thread.sleep(500); } catch (InterruptedException ie) { } } }
2
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; Room R=CMLib.map().roomLocation(target); if(R==null) R=mob.location(); if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; // now see if it worked final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),auto?"":L("^S<S-NAME> speak(s) and gesture(s) to <T-NAMESELF>.^?")); if(R.okMessage(mob,msg)) { R.send(mob,msg); R.show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> seem(s) much more likeable!")); beneficialAffect(mob,target,asLevel,0); } } else return beneficialVisualFizzle(mob,target,L("<S-NAME> incant(s) gracefully to <T-NAMESELF>, but nothing more happens.")); // return whether it worked return success; }
9
private static void getConfigLocations(File dir, String curPath, String cfgFileName, String filePrefix, List<String> files, boolean isFullPath) { String[] fileNames = dir.list(); if (fileNames == null) return; String filePath = dir.getPath(); for (int i = 0, len = fileNames.length; i < len; i++) { if (fileNames[i].equals(".") || fileNames[i].equals("..")) continue; if (fileNames[i].startsWith(cfgFileName) && fileNames[i].endsWith(".xml")) { if (isFullPath) files.add(filePath + "/" + fileNames[i]); else files.add(filePrefix + curPath + "/" + fileNames[i]); continue; } File file = new File(filePath + "/" + fileNames[i]); if (file.isDirectory()) { // recursion getConfigLocations(file, curPath + "/" + fileNames[i], cfgFileName, filePrefix, files, isFullPath); } } }
8
public void initMatrix() { set0ButtonActionPerformed(null); float m[][] = filter.getMatrix(); int size = m[0].length; int start_position = 0; switch(size) { case 3 : start_position = 2; jComboBox1.setSelectedIndex(0); break; case 5 : start_position = 1; jComboBox1.setSelectedIndex(1); break; case 7 : start_position = 0; jComboBox1.setSelectedIndex(2); break; } windowSizeListValueChanged(null); for(int r = start_position; r < start_position + size; r++) for(int c = start_position; c < start_position + size; c++) { Float float_value = new Float(m[r - start_position][c - start_position]); String s = null; // Get rid of trailing zeroes if(float_value.floatValue() == float_value.intValue()) s = float_value.intValue() + ""; else s = float_value.floatValue() + ""; textArray[r][c].setText(s); } }
6
public void copyDataFrom(CPColorBmp bmp) { if (bmp.width != width || bmp.height != height) { width = bmp.width; height = bmp.height; data = new int[width * height]; } System.arraycopy(bmp.data, 0, data, 0, data.length); }
2
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed Desktop dt = Desktop.getDesktop(); try { dt.open( new File("help.html") ); } catch (IOException e) {//exception handling? } }//GEN-LAST:event_jMenuItem4ActionPerformed
1
public static final ISignature getInstance(String ssa) { if (ssa == null) { return null; } ssa = ssa.trim(); ISignature result = null; if (ssa.equalsIgnoreCase(Registry.DSA_SIG) || ssa.equals(Registry.DSS_SIG)) { result = new DSSSignature(); } else if (ssa.equalsIgnoreCase(Registry.RSA_PSS_SIG)) { result = new RSAPSSSignature(); } else if (ssa.equalsIgnoreCase(Registry.RSA_PKCS1_V1_5_SIG)) { result = new RSAPKCS1V1_5Signature(); } return result; }
5
public int getACC() { return acc; }
0
protected Behaviour getNextStep() { if (actor.mind.home() == newHome) return null ; if (verbose) I.sayAbout(actor, "Getting next site action ") ; if (! newHome.inWorld()) { if (! canPlace()) { abortBehaviour() ; return null ; } final Tile goes = actor.world().tileAt(newHome) ; final Action sites = new Action( actor, Spacing.nearestOpenTile(goes, actor), this, "actionSiteHome", Action.LOOK, "Siting home" ) ; sites.setProperties(Action.RANGED) ; return sites ; } final Action finds = new Action( actor, newHome, this, "actionFindHome", Action.LOOK, "Finding home" ) ; return finds ; }
4
private void generarArchivoAutomata() { FileWriter archivoAutomata = null; PrintWriter pw = null; this.nombreAutomata = "AFN_TXT\\" + JOptionPane.showInputDialog("Por favor, indique el nombre del archivo que almacena al automata")+".txt"; try { archivoAutomata = new FileWriter(nombreAutomata); pw = new PrintWriter(archivoAutomata); for (int i = 0; i < automataFormateado.size(); i++) { pw.println(automataFormateado.get(i)); } } catch (IOException ex) { Logger.getLogger(AFN.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (null != archivoAutomata) { archivoAutomata.close(); JOptionPane.showMessageDialog(null, "El archivo " + nombreAutomata + " se gener\u00f3 satisfactoriamente"); } } catch (Exception e2) { e2.printStackTrace(); } } }
4
public Integer next() { current++; return current - 1; }
0
public void register(Object value) { if (JSONzip.probe) { int integer = find(value); if (integer >= 0) { JSONzip.log("\nDuplicate key " + value); } } if (this.length >= this.capacity) { compact(); } this.list[this.length] = value; this.map.put(value, new Integer(this.length)); this.uses[this.length] = 1; if (JSONzip.probe) { JSONzip.log("<" + this.length + " " + value + "> "); } this.length += 1; }
4
public void actionPerformed(ActionEvent e) { // Reset all labels userView.lblUserName.setText("* User Name"); userView.lblUserName.setForeground(Color.BLACK); userView.lblPassword.setText("* Password"); userView.lblPassword.setForeground(Color.BLACK); userView.lblFirstName.setText("* First Name"); userView.lblFirstName.setForeground(Color.BLACK); userView.lblLastName.setText("* Last Name"); userView.lblLastName.setForeground(Color.BLACK); userView.lblEmailAddress.setText("* Email"); userView.lblEmailAddress.setForeground(Color.BLACK); // TODO sanitize all input String userName = userView.txtUserName.getText(); if (userName.isEmpty()) { userView.lblUserName.setText("User Name is blank"); userView.lblUserName.setForeground(Color.RED); return; } else if (dbHandle.validUser(userName)) { userView.lblUserName.setText("User Name is not available"); userView.lblUserName.setForeground(Color.RED); return; } char[] password = userView.txtPass.getPassword(); char[] rePass = userView.txtRePass.getPassword(); // TODO the password should probably be verified so that it is secure if (password.length == 0) { userView.lblPassword.setText("Password is blank"); userView.lblPassword.setForeground(Color.RED); return; } if (!Arrays.equals(password, rePass)) { userView.lblPassword.setText("Password fields must match"); userView.lblPassword.setForeground(Color.RED); return; } String firstName = userView.txtFirstName.getText(); if (firstName.isEmpty()) { userView.lblFirstName.setText("Please enter your first name"); userView.lblFirstName.setForeground(Color.RED); return; } String lastName = userView.txtLastName.getText(); if (lastName.isEmpty()) { userView.lblLastName.setText("Please enter your last name"); userView.lblLastName.setForeground(Color.RED); return; } // TODO when sanitizing the email address - make sure that it passes a regex for email String emailAdd = userView.txtEmail.getText(); if (emailAdd.isEmpty()) { userView.lblEmailAddress.setText("Please enter your email address"); userView.lblEmailAddress.setForeground(Color.RED); return; } // Passed all tests - get a password salt, encrypt the password, and insert the user PasswordEncrypt pass = new PasswordEncrypt(); String salt = null; try { salt = pass.getSalt(); } catch (Exception a) { } String encPassword = pass.getSecurePassword(new String(password), salt); dbHandle.insertNewUser(userName, encPassword, salt, firstName, lastName, emailAdd); userView.setVisible(false); //you can't see me! userView.dispose(); //Destroy the JFrame object // mController.goodUser(userName); }
8
@Override public List<Integer> sort() { int i, j, k, h, x; int[] spalten = { 271, 111, 41, 13, 4, 1 }; for (k = 0; k < 6; k++) { h = spalten[k]; // Sortiere die "Spalten" mit Insertionsort for (i = h; i < list.size(); i++) { x = list.get(i); j = i; while (j >= h && list.get(j - h) > x) { list.set(j, list.get(j - h)); j = j - h; } list.set(j, x); } } return list; }
4
@Override public boolean isDataFlavorSupported(DataFlavor flavor) { DataFlavor[] flavors = getTransferDataFlavors(); for (int i = 0; i < flavors.length; i++) { if (flavors[i] != null && flavors[i].equals(flavor)) { return true; } } return false; }
3
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)); }
9
private int amtBet(int minBet, int maxBet){ double betAmt = 0; //Decide if its worth being aggressive if(match.tableCards.size()==0){ if(match.abs_prob_win < AGGRESSION_THRESHOLD){ return -1; }else{ betAmt = match.abs_prob_win*match.pot; } }else if(match.tableCards.size()==3){ if(opponent.bluffMetric(1) > 50){ betAmt = (opponent.bluffMetric(1)/50)*AGGRESSION_FACTOR*match.abs_prob_win*match.pot; }else{ return -1; } }else if(match.tableCards.size()==4){ if(opponent.bluffMetric(2) > 50){ betAmt = (opponent.bluffMetric(1)/50)*AGGRESSION_FACTOR*AGGRESSION_FACTOR*match.abs_prob_win*match.pot; }else{ return -1; } }else if(match.tableCards.size()==5){ if(opponent.bluffMetric(2) > 50){ betAmt = (opponent.bluffMetric(1)/50)*AGGRESSION_FACTOR*AGGRESSION_FACTOR*AGGRESSION_FACTOR*match.abs_prob_win*match.pot; }else{ return -1; } } betAmt += (betAmt/10)*Math.random() - (betAmt/20); //add some noise to confuse machine learning return (int) Math.round(betAmt); }
8
public void service(){ while(true){ Socket socket = null; try { socket = serverSocket.accept(); System.out.println("New connections accepted" + socket.getInetAddress() + " : " + socket.getPort()); Thread.sleep(5000); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }finally{ if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
5
public static void parse(String t, int lineNum) { acceptingStates = new ArrayList<String>(); if (lineNum == NFA.STATES.lineNum()) { numStates = Integer.parseInt(t); } else if (lineNum == NFA.LANGUAGE.lineNum()) { language = t; } else if (lineNum == NFA.CARDINALITY.lineNum()) { numAcceptingStates = Integer.parseInt(t); } else if (lineNum > NFA.CARDINALITY.lineNum() && isMoreAcceptingStates()) { acceptingStates.add(t); statesRead++; } else if (lineNum > NFA.CARDINALITY.lineNum() && !isMoreAcceptingStates() && !startStateFound()) { startState = t; startStateFound = true; } else if (lineNum > (NFA.CARDINALITY.lineNum() + numStates) +1) { String[] transition = new String[3]; transition = t.split(" "); String c = transition[0]; String w = transition[1]; String n = transition[2]; transitionFunctions.put(Collections.unmodifiableList(Arrays.asList(c,w)), n); } }
9
public int getValue() { return value; }
0
public RandomListNode copyRandomList(RandomListNode head) { if(head == null) return null; else{ RandomListNode headNew = copyNext(head);; copyRandom(headNew,head); return headNew; } }
1
public static void main(String[] args) { // abort program if correct number of command-line argument is not given if ( args.length != 1 ){ System.out.println(args.length); System.out.println("Usage : RunZeroGameSolver output.dat"); System.exit(0); } final int m0 = 2; final int increment = 1; final int nRepeat = 10; // number of repeated calculations for better statistical average final int maxM = 15; final double max = 1.0; // maximum element value final double delta = 0.1; // error parameter for MW method File output = new File(args[0]); try { PrintStream ps = new PrintStream(output); ps.println("# Value of zero-sum games computed from Linear programming approach " + "and Multiplicative-Weights-Update approach"); ps.println("#m(matrix size) value(LP) value(MW) comp_time_avg(LP) " + "comp_time_avg(MW) comp_time_max(LP) comp_time_max(MW)"); for ( int m = m0; m < maxM; m++ ){ double dTLP = 0.0; // computing time of LP approach double dTMW = 0.0; // computing time of MW approach double valLP = 0.0; // value computed from LP double valMW = 0.0; // value computed from MW double maxTimeLP = 0.0; // maximum computing time using LP double maxTimeMW = 0.0; // maximum computing time using MW for ( int r = 0; r < nRepeat; r++ ){ double[][] A = ZeroSumGame.genGame(m, m, max); // Linear-Programming approach (deterministic algorithm) long tiL = System.nanoTime(); LPSolver solL = new LPSolver(A); long tfL = System.nanoTime(); dTLP += (double)(tfL-tiL)/(1000000.0); valLP += solL.getValue(); if ( (double)(tfL-tiL) > maxTimeLP ) maxTimeLP = (double)(tfL-tiL); // Multiplicative weights update approach (approximate algorithm) long tiM = System.nanoTime(); MWSolver solM = new MWSolver(A, delta); long tfM = System.nanoTime(); dTMW += (double)(tfM-tiM)/(1000000.0); valMW += solM.getValue(); if ( (double)(tfM-tiM) > maxTimeMW ) maxTimeMW = (double)(tfM-tiM); } ps.println(String.format("%d %f %f %fms %fms %fms %fms", m, valLP/(double)nRepeat, valMW/(double)nRepeat, dTLP/(double)nRepeat, dTMW/(double)nRepeat, maxTimeLP/1000000.0, maxTimeMW/1000000.0 )); } ps.close(); } catch ( IOException ex ){ System.out.println("Cannot write into file " + args[0]); } }
6
public static boolean Pase(Cancha cancha, int equipoA, int jugadorA, int jugadorR,int equipoD,int jugadorD, Pelota pelota){ float pase=cancha.getEquipoX(equipoA).getJugadorX(jugadorA).getPase(); pase=pase*Factorf.factorF(); //se multiplican datos por valores aleatorios float bloque=(Factorf.factorF())* (cancha.getEquipoX(equipoD).getJugadorX(jugadorD).getBloqueo()); // obtienen posiciones de jugadores int[] posJug1=new int[2]; int[] posJug2=new int[2]; float disJug, paseFinal; posJug1[0]=cancha.getEquipoX(equipoA).getJugadorX(jugadorA).getPosX(); posJug1[1]=cancha.getEquipoX(equipoA).getJugadorX(jugadorA).getPosY(); posJug2[0]=cancha.getEquipoX(equipoA).getJugadorX(jugadorR).getPosX(); posJug2[1]=cancha.getEquipoX(equipoA).getJugadorX(jugadorR).getPosY(); //calculo distancia entre jugadores disJug=(float)(Math.sqrt(Math.pow(posJug2[0]-posJug1[0], 2)+Math.pow(posJug2[1]-posJug1[1], 2))); paseFinal=pase-disJug; if(paseFinal>0 && cancha.getEquipoX(equipoA).getJugadorX(jugadorA).isTieneBalon() ){ //condicion para realizar pase if(paseFinal-bloque<=0){ pelota.setPosX(cancha.getEquipoX(equipoD).getJugadorX(jugadorD).getPosX()); pelota.setPosY(cancha.getEquipoX(equipoD).getJugadorX(jugadorD).getPosY()); pelota.setPosecion(true);//probalbemente cambie a quien tiene el balon cancha.getEquipoX(equipoA).getJugadorX(jugadorA).setTieneBalon(false); cancha.getEquipoX(equipoD).getJugadorX(jugadorD).setTieneBalon(true); cancha.getEquipoX(equipoD).setAtacante(); // System.out.println("te quitaron el balon"); }else{ if((paseFinal-bloque>=disJug)){ pelota.setPosX(cancha.getEquipoX(equipoA).getJugadorX(jugadorR).getPosX()); pelota.setPosY(cancha.getEquipoX(equipoA).getJugadorX(jugadorR).getPosY()); pelota.setPosecion(true);//probalbemente cambie a quien tiene el balon cancha.getEquipoX(equipoA).getJugadorX(jugadorA).setTieneBalon(false); cancha.getEquipoX(equipoA).getJugadorX(jugadorR).setTieneBalon(true); cancha.getEquipoX(equipoA).setAtacante(); }else{ if((paseFinal-bloque)>(1/2*disJug)){ cancha.getEquipoX(equipoA).getJugadorX(jugadorA).setTieneBalon(false); pelota.setPosX( (int)(Math.random()*(cancha.getEquipoX(equipoA).getJugadorX(jugadorR).getPosX()+5)+(cancha.getEquipoX(equipoA).getJugadorX(jugadorR).getPosX()-5)) ); pelota.setPosY( (int)(Math.random()*(cancha.getEquipoX(equipoA).getJugadorX(jugadorR).getPosY()+5)+(cancha.getEquipoX(equipoA).getJugadorX(jugadorR).getPosY()-5)) ); pelota.setPosecion(false); }else{ cancha.getEquipoX(equipoA).getJugadorX(jugadorA).setTieneBalon(false); pelota.setPosX((int)(Math.random()*(cancha.getEquipoX(equipoD).getJugadorX(jugadorD).getPosX()+5)+(cancha.getEquipoX(equipoD).getJugadorX(jugadorD).getPosX()-5)) ); //revisar para calculo de matriz con centro en jugador que defiende pelota.setPosY((int)(Math.random()*(cancha.getEquipoX(equipoD).getJugadorX(jugadorD).getPosY()+5)+(cancha.getEquipoX(equipoD).getJugadorX(jugadorD).getPosY()-5))); pelota.setPosecion(false); } } } return true; }else{ return false; } }
5
private void destroyNeighbors(Brick[][] array, int y, int x) { triggerPower(powers[y][x]); array[y][x].blowUp(); if (isBlockAbove(array, y, x)) { if (array[y - 1][x].getType() == BrickType.EXPLOSIVE) { // above explosive? destroyNeighbors(array, y - 1, x); } array[y - 1][x].blowUp(); score += 100; triggerPower(powers[y - 1][x]); } if (isBlockBelow(array, y, x)) { if (array[y + 1][x].getType() == BrickType.EXPLOSIVE) { destroyNeighbors(array, y + 1, x); } array[y + 1][x].blowUp(); score += 100; triggerPower(powers[y + 1][x]); } if (isBlockLeft(array, y, x)) { if (array[y][x - 1].getType() == BrickType.EXPLOSIVE) { destroyNeighbors(array, y, x - 1); } array[y][x - 1].blowUp(); score += 100; triggerPower(powers[y][x - 1]); } if (isBlockRight(array, y, x)) { if (array[y][x + 1].getType() == BrickType.EXPLOSIVE) { destroyNeighbors(array, y, x + 1); } array[y][x + 1].blowUp(); score += 100; triggerPower(powers[y][x + 1]); } }
8
public String getWebPage() { return WebPage; }
0
private void updateStateFound(List<Keyword> keywords, List<String> terms) { for (Keyword kw: keywords) { for (DialogState d : kw.getReference()) { if (d.getCurrentState() == Start.S_USER_FOUND) { getCurrentSession().setCurrentUser(new User((UserData)(kw.getKeywordData().getDataReference().get(0)))); getCurrentSession().getCurrentUser().getUserData().setLastAccess(new Date()); getCurrentSession().getCurrentUser().getUserData().writeFile(); Main.giveMain().setUserLoggedIn(true); return; } } } DialogManager.giveDialogManager().setInErrorState(true); //Jumping due to keyword }
3
private final String getChunk(String s, int slength, int marker) { StringBuilder chunk = new StringBuilder(); char c = s.charAt(marker); chunk.append(c); marker++; if (isDigit(c)) { while (marker < slength) { c = s.charAt(marker); if (!isDigit(c)) break; chunk.append(c); marker++; } } else { while (marker < slength) { c = s.charAt(marker); if (isDigit(c)) break; chunk.append(c); marker++; } } return chunk.toString(); }
5
File getFile() { return file == newFile ? null : file; }
1
@Test public void getListProductPreferredAllClients() { Map<Client, List<Product>> currentList = null; Product book = new Product("Book", 1234, 2.30, 100); Product table = new Product("Table", 4321, 3.00, 100); Product printer = new Product("Printer", 4321, 3.00, 100); facade.addProduct(book); facade.addProduct(table); facade.addProduct(printer); Client client1 = new Client("Diego", "111", "[email protected]", 18, 11, 1988); Client client2 = new Client("Ayla", "222", "[email protected]", 18, 11, 1988); facade.addClient(client1); facade.addClient(client2); try { Thread.sleep(3000); } catch (InterruptedException e) { e.getMessage(); } facade.addPreferencesClient(client1, book); facade.addPreferencesClient(client1, table); facade.addPreferencesClient(client2, printer); try { Thread.sleep(3000); } catch (InterruptedException e) { e.getMessage(); } facade.getListProductPreferredAllClients(copyAllClientsPreferences); try { currentList = copyAllClientsPreferences.take(); } catch (InterruptedException e) { e.getMessage(); } assertEquals(2, currentList.size()); assertTrue(currentList.get(client1).contains(book)); assertFalse(currentList.get(client1).contains(printer)); assertTrue(currentList.containsKey(client2)); assertEquals(2, currentList.get(client1).size()); assertEquals(1, currentList.get(client2).size()); }
3
AIMove onTestPuckFriction(AIHockeyist hockeyist) { AIManager manager = AIManager.getInstance(); AIRectangle rink = manager.getRink(); int currentTick = manager.getCurrentTick(); AIPuck puck = manager.getPuck(); AIMove move = new AIMove(); if (manager.isPuckOwner(hockeyist)) { if (hockeyist.distanceTo(rink.origin) < 3 * AIHockeyist.RADIUS) { if (hockeyist.getSpeedScalar() < 0.04) { AIPoint target = new AIPoint(rink.getRight(), hockeyist.getY()); // AIPoint.sum(rink.origin, rink.size) double angle = hockeyist.angleTo(target); if (abs(angle) < 0.01) { //move.setAction(ActionType.STRIKE); if (hockeyist.getLastAction() == ActionType.SWING && currentTick - hockeyist.getLastActionTick() > 11) { move.setAction(ActionType.STRIKE); } else { move.setAction(ActionType.SWING); } } else { move.setTurn(angle); } } else { move.setSpeedUp(0); } } else { move = AIGo.to(hockeyist, rink.origin); } } else { if (puck.getSpeedScalar() > 1) return new AIMove(); move = AIGo.to(hockeyist, puck.getLocation()); if (hockeyist.isInStickRange(puck)) { move.setAction(ActionType.TAKE_PUCK); } } return move; }
8
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) // override protection plugins public void onBlockBreak(final BlockBreakEvent broken) { if (broken instanceof KioskRemove) return; if (!Kiosk.SIGN_BLOCKS.contains(broken.getBlock().getTypeId())) return; final Sign state = (Sign) broken.getBlock().getState(); if (!this.hasTitle(state)) return; final Function function = this.getFunction(state); if (function == null) { Main.courier.send(broken.getPlayer(), "unknownFunction", state.getLine(1)); broken.setCancelled(true); state.update(); return; } if (!function.canUse(broken.getPlayer())) { Main.courier.submit(new Sender(broken.getPlayer()), function.draftDenied()); broken.setCancelled(true); state.update(); return; } this.dispatch(broken.getPlayer(), state); // manually process block break to avoid other plugins responding to event broken.setCancelled(true); state.setType(Material.AIR); state.update(true); broken.getBlock().getWorld().dropItemNaturally(broken.getBlock().getLocation(), new ItemStack(Material.SIGN)); }
5
public void info() { List<Host> newList = new ArrayList<Host>(network_.size()); for (Host host : network_) { try { newList.add(simulation_.info(host)); } catch (CommunicationException e) { logger_.warn("{}", e.getMessage()); } } network_ = newList; if (network_.isEmpty()) { System.out.println("No hosts are present in the network."); } for (Host host : network_) { System.out.println("[" + host.getHostPath() + "] " + host + ":" + host.getPort()); } }
4
public static long runQuery(final String query, final PrintStream p, final DBHandle handle) throws SQLException { final Statement stmt = handle.createReadStatement(); final RSIterator source = new RSIterator(stmt.executeQuery(query)); final String sep = "\t"; boolean first = true; long rowNum = 0; while(source.hasNext()) { final BurstMap row = source.next(); if(first) { boolean firstCol = true; for(final String ki: row.keySet()) { if(firstCol) { firstCol = false; } else { p.print(sep); } //final TypeInfo columnInfo = source.getJavaClassName(ki); p.print(TrivialReader.safeStr(ki) /* + ":" + columnInfo.sqlColumnType */); } p.println(); first = false; } boolean firstCol = true; for(final String ki: row.keySet()) { if(firstCol) { firstCol = false; } else { p.print(sep); } final String vi = row.getAsString(ki); p.print(TrivialReader.safeStr(vi)); } p.println(); ++rowNum; // System.out.println(row); } stmt.close(); return rowNum; }
6
public void closePopUp() { Parent parentRoot = ((Stage) stage.getOwner()).getScene().getRoot(); if (parentRoot instanceof StackPane) { ((StackPane) parentRoot).getChildren().remove(mask); } stage.close(); }
1
public void morrisTraverse(TreeNode root) { while (root != null) { if (root.getLeft() == null) { System.out.println(root.getData()); root = root.getRight(); } else { TreeNode ptr = root.getLeft(); while (ptr.getRight() != null && ptr.getRight() != root) ptr = ptr.getRight(); if (ptr.getRight() == null) { ptr.setRight(root); root = root.getLeft(); } else { ptr.setRight(null); System.out.println(root.getData()); root = root.getRight(); } } } }
5
protected void buildClassifierWithWeights(Instances data) throws Exception { Instances trainData, training; double epsilon, reweight; Evaluation evaluation; int numInstances = data.numInstances(); Random randomInstance = new Random(m_Seed); // Initialize data m_Betas = new double [m_Classifiers.length]; m_NumIterationsPerformed = 0; // Create a copy of the data so that when the weights are diddled // with it doesn't mess up the weights for anyone else training = new Instances(data, 0, numInstances); // Do boostrap iterations for (m_NumIterationsPerformed = 0; m_NumIterationsPerformed < m_Classifiers.length; m_NumIterationsPerformed++) { if (m_Debug) { System.err.println("Training classifier " + (m_NumIterationsPerformed + 1)); } // Select instances to train the classifier on if (m_WeightThreshold < 100) { trainData = selectWeightQuantile(training, (double)m_WeightThreshold / 100); } else { trainData = new Instances(training, 0, numInstances); } // Build the classifier if (m_Classifiers[m_NumIterationsPerformed] instanceof Randomizable) ((Randomizable) m_Classifiers[m_NumIterationsPerformed]).setSeed(randomInstance.nextInt()); m_Classifiers[m_NumIterationsPerformed].buildClassifier(trainData); // Evaluate the classifier evaluation = new Evaluation(data); evaluation.evaluateModel(m_Classifiers[m_NumIterationsPerformed], training); epsilon = evaluation.errorRate(); // Stop if error too small or error too big and ignore this model if (Utils.grOrEq(epsilon, 0.5) || Utils.eq(epsilon, 0)) { if (m_NumIterationsPerformed == 0) { m_NumIterationsPerformed = 1; // If we're the first we have to to use it } break; } // Determine the weight to assign to this model m_Betas[m_NumIterationsPerformed] = Math.log((1 - epsilon) / epsilon); reweight = (1 - epsilon) / epsilon; if (m_Debug) { System.err.println("\terror rate = " + epsilon +" beta = " + m_Betas[m_NumIterationsPerformed]); } // Update instance weights setWeights(training, reweight); } }
8
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed if (jTable1.getSelectedRow()==-1) { JOptionPane.showMessageDialog(this, "Select a search item to check in"); return; } if (jTable1.getSelectedRowCount() > 1) { JOptionPane.showMessageDialog(this, "Error. Multiple items selected"); return; } int row = jTable1.getSelectedRow(); if(jTable1.getValueAt(row, 0)== null) { JOptionPane.showMessageDialog(this, "Search and choose an item to return back"); return; } try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library_management", "root", "welcome6" ); String s2 = "update book_loans set date_in = ? where loan_id= ? and date_in IS NULL "; PreparedStatement pst2 = conn.prepareStatement( s2 ); java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime()); pst2.setTimestamp(1,date); pst2.setObject(2,jTable1.getValueAt(row, 0)); int x = pst2.executeUpdate(); if (x==1) { JOptionPane.showMessageDialog(this, "Successfully checked in"); jButton2.doClick();} conn.close(); } catch(SQLException ex) { System.out.println("Error in connection: " + ex.getMessage()); } catch (ClassNotFoundException ex) { System.out.println("Class not found:" + ex.getMessage()); } }//GEN-LAST:event_jButton4ActionPerformed
6
private void createGui() { sendButton.setText(settings.getLanguage().getLabel("button_send")); outputTextArea.setEditable(false); setInputsEnabled(false); JPanel inputPanel = new JPanel(); inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS)); JScrollPane inputScrollPane = new JScrollPane(inputTextArea); inputScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); inputPanel.add(inputScrollPane); inputPanel.add(sendButton); JScrollPane outputScrollPane = new JScrollPane(outputTextArea); outputScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); textAreSplitPane.setLeftComponent(outputScrollPane); textAreSplitPane.setRightComponent(inputPanel); JPanel participantsPanel = new JPanel(new BorderLayout()); JScrollPane participantsScrollPane = new JScrollPane(participantsJList); participantsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); participantsLabel = new JLabel(settings.getLanguage().getLabel("label_participants")); participantsPanel.add(participantsLabel, BorderLayout.NORTH); participantsPanel.add(participantsScrollPane, BorderLayout.CENTER); mainSplitPane.setLeftComponent(textAreSplitPane); mainSplitPane.setRightComponent(participantsPanel); add(mainSplitPane); }
0
public synchronized void runTask(Runnable task) { if (!isAlive) { throw new IllegalStateException(); } if (task != null) { taskQueue.add(task); notify(); } }
2
public String getParameterString(){ String retString = super.getParameterString(); try{ if(sourceText!=null) retString+="&sourceText="+sourceText; if(cQuery!=null) retString+="&cquery="+URLEncoder.encode(cQuery,"UTF-8"); if(xPath!=null) retString+="&xpath="+URLEncoder.encode(xPath,"UTF-8"); } catch(UnsupportedEncodingException e ){ retString = ""; } return retString; }
4
private boolean calulateBrightnessContrast(ij.process.ImageProcessor ip) { boolean brightnesscontrast = false; int w = ip.getWidth(); int h = ip.getHeight(); //set image as current window ImagePlus bc_imp; bc_imp = WindowManager.getCurrentImage(); //calculate histogram values int []hist = new int[256]; for (int i=0; i<256; i++) { hist[i] = 0; } for (int x=0; x<w; x++) { for (int y=0; y<h; y++) { int [] piksels = bc_imp.getPixel(x,y); int gray_value = (piksels[0]+piksels[1]+piksels[2])/3; hist[(int)gray_value] += 1; } } //find max value in histogram int max_hist_value = 0; for (int i=0; i<255; i++) { if (max_hist_value < hist[i]) { max_hist_value = hist[i]; } } //calc 5 most highest or lowest frequencies int sum_first = 0; int sum_last = 0; for (int i=0; i<5; i++) { sum_first += hist[i]; sum_last += hist[255-i]; } //decide what to do int perc_of_max = max_hist_value/51; if ((sum_first <perc_of_max) ||(sum_last <perc_of_max)) { brightnesscontrast = true; } Window_Closer Wind_Clow = new Window_Closer(); Wind_Clow.run(argument); return brightnesscontrast; }
8
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Square other = (Square) obj; if (this.xmin != other.xmin) { return false; } if (this.xmax != other.xmax) { return false; } if (this.ymin != other.ymin) { return false; } if (this.ymax != other.ymax) { return false; } return true; }
6
public String strStr(String haystack, String needle) { // Start typing your Java solution below // DO NOT write main() function assert (haystack != null && needle != null); if (needle.length() == 0) { return haystack; } int i = 0; while (i < haystack.length()) { if (haystack.length() - i < needle.length()) { break; } if (haystack.charAt(i) == needle.charAt(0)) { int j = i; while (j - i < needle.length() && haystack.charAt(j) == needle.charAt(j - i)) { j++; } if (j - i == needle.length()) { return haystack.substring(i); } } i++; } return null; }
8
public static boolean existeUsuario(String username) { username = username.trim(); Connection conn = null; PreparedStatement stmt = null; boolean existe = false; try { conn = model.ConexionMySQL.darConexion(); stmt = conn.prepareStatement("SELECT count(*) as count from usuario where username=?"); stmt.setString(1, username); ResultSet result = stmt.executeQuery(); while (result.next()) { int val = Integer.parseInt(result.getString("count")); if (val > 0) { existe = true; } } } catch (SQLException e) { } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { } } if (conn != null) { try { conn.close(); } catch (SQLException ex) { } } } return existe; }
7
public Authentication(AdminClient parent) { super("resources/UmbrellaSignIn.png"); this.parent = parent; this.parent.setTitle("Authentication"); if(AdminClient.client == null) { try { AdminClient.client = new Client("127.0.0.1", 1234); }catch (IOException e) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new SwitchServerWindow(); } }); } } //Window's components. this.setSize(new Dimension(800, 600)); this.setLayout(null); RotatingComponent rc = new RotatingComponent("resources/UmbrellaLogo.png", 95, 97, 255, 255, 0.5); authPanel = new GradientPanel(new Color(173, 173, 173), new Color(78, 78, 78)); authPanel.setBounds(425, 200, 300, 58); authPanel.setLayout(null); authPanel.setBorder(BorderFactory.createLineBorder(new Color(60, 10, 11), 1)); AdminClient.serverLocator.setEnabled(true); shacker = new Shaker(authPanel); tfUserName.setBorder(BorderFactory.createLineBorder(new Color(123, 0, 1), 2)); pfPassword.setBorder(BorderFactory.createLineBorder(new Color(123, 0, 1), 2)); lUserName.setBounds(70, 8, 40, 23); //lUserName.setBorder(BorderFactory.createLineBorder(Color.BLACK)); lPassword.setBounds(15, lUserName.getY() + lUserName.getHeight() - 4, 100, 25); //lPassword.setBorder(BorderFactory.createLineBorder(Color.BLACK)); authPanel.add(lUserName); authPanel.add(lPassword); tfUserName.setBounds(lUserName.getX() + lUserName.getWidth(), 8, 145, lUserName.getHeight() - 3); pfPassword.setBounds(lUserName.getX() + lUserName.getWidth(), lPassword.getY() + 4, tfUserName.getWidth(), tfUserName.getHeight() + 2); authPanel.add(tfUserName); authPanel.add(pfPassword); progress = new SpinningWheel(5, 0, 20, 55); progress.setVisible(false); correct = new JBackgroundedPanel("resources/Correct.png", 5, 0, 20, 20); correct.setVisible(false); error = new JBackgroundedPanel("resources/Error.png", 5, 0, 20, 20); error.setVisible(false); bSignIn.setIcon(new ImageIcon(Utilities.resizeImage(20, 20, "resources/NextButton.png"))); bSignIn.setBounds(5, 23, bSignIn.getIcon().getIconWidth(), bSignIn.getIcon().getIconHeight()); bSignIn.setBorderPainted(false); bSignIn.setContentAreaFilled(false); bSignIn.setFocusable(false); JPanel panelAux = new JPanel(); panelAux.setLayout(null); panelAux.setBounds(tfUserName.getX() + tfUserName.getWidth() + 5, lUserName.getY(), 50, 50); panelAux.setOpaque(false); panelAux.add(correct); panelAux.add(error); panelAux.add(progress); panelAux.add(bSignIn); authPanel.add(panelAux); this.add(rc); this.add(authPanel); //Component's listeners tfUserName.addFocusListener(this); pfPassword.addFocusListener(this); tfUserName.getDocument().addDocumentListener(this); bSignIn.addActionListener(this); pfPassword.addKeyListener(this); }
2
public static void main(String[] args) { try { Sys.savePID(new ClinicClient().getPidFile()); Log.init(); App form = new App(); form.setUploadRunnable(new Runnable() { @Override public void run() { try { Application.upload(); } catch (Exception e) { Log.write(e); } } }); form.setUpdateRunnable(new Runnable() { @Override public void run() { try { Runtime.getRuntime().exec( Sys.getStartJarCommand(new ClientUpdater().getFile().getName()) + " --force" ); } catch (Exception e) { Log.write(e); } } }); new Thread(new Runnable() { @Override public void run() { long lastModified = 0; while (true) { try { File filesDirectory = new File(config.getPath()); long directoryModified = filesDirectory.lastModified(); if (lastModified < directoryModified) { lastModified = directoryModified; Log.write(Message.MESSAGE_DIRECTORY_MODIFIED); Application.upload(); } Thread.sleep(300000); } catch (Exception e) { Log.write(e); } } } }).start(); new Thread(new Runnable() { @Override public void run() { try { Application.configure(); while (true) { Log.write(Message.MESSAGE_SEND_PING); ApiClient.getInstance().ping(Config.VERSION); Thread.sleep(86400 * 1000); } } catch (InterruptedException e) { Log.write(e); } catch (Exception e) { Log.write(e); } } }).start(); } catch (Exception e) { Log.write(e); } }
9
private String joinTypeToString(QbJoinType joinType) { switch (joinType) { case DEFAULT: return ""; case LEFT_OUTER: return "LEFT OUTER"; case RIGHT_OUTER: return "RIGHT OUTER"; case INNER: case OUTER: case LEFT: case RIGHT: default: return joinType.toString(); } }
7
private void processPaging(MapHttpServletRequest request) { String path = request.getRequestURI(); int index = path.lastIndexOf("/page/"); if (index != -1) { String url = path.substring(0, index); String[] elements = path.substring(index + 6).split("/"); if (elements.length < 1 || elements.length > 2) { return; } int page = -1; int size = -1; try { page = Integer.parseInt(elements[0]); if (elements.length > 1) { size = Integer.parseInt(elements[1]); } } catch (NumberFormatException ex) { // Not correct paging format, maybe it is something else return; } if (page > -1) { request.setAttribute(AttributeNames.PAGING, page); } if (size > -1) { request.setAttribute(AttributeNames.PAGING_SIZE, size); } if (url.equals("")) { url = "/"; } path = url; request.setRequestURI(path); } }
8
public DefaultParser(final String fileName) throws DaoException { super(); file = DefaultParser.class.getResourceAsStream(fileName); if (file == null) { throw new DaoException("file not found:" + fileName); } }
1
private void bump(int x, int y){ int[][] bumpvals = {new int[] {2,3,4,5}, new int[] {6, 7, 8, 9}, new int[] {10,11,12,13}, new int[] {14,15,16,17}, new int[] {18,19,20,21}}; for(int i = 0 ; i< bumpvals.length; i++){ for(int j : bumpvals[i]){ if(j == terrain[x][y]){ switch(i){ case 0: bumpKey(); break; case 1: bumpDoor(); break; case 2: bumpSword(); break; case 3: bumpDragon(); break; case 4: bumpPrincess(); break; } } } } }
8
public Node execute (SearchProblemInterface problem) { Node result = null, node, shallowestNode = null; resetStatistics(); openlist.add(initialNode(problem)); /* Loop until openlist is empty, search is cancelled, or * solution is found. */ while (true) { node = openlist.poll(); if (node == null) { result = shallowestNode; break; // Open list empty, no solution found. } if (isCancelled) { result = null; break; // Search cancelled. } updateNofNodesVisited(node); currentDepth = Math.max(currentDepth, node.depth); if (!depthlimit.belowLimit(node)) { /* Depth limit reached. */ nofNodesPruned++; if (shallowestNode == null || node.totalcost < shallowestNode.totalcost) { shallowestNode = node; } } else if (problem.isSolution(node.state)) { /* Solution found. */ result = node; break; // Solution found. } else if (closedlist.contains(node.state)) { /* State already seen. */ nofClosedListHits++; } else { /* State not yet seen, not a solution, below limit. */ closedlist.add(node.state); List<Node> children = node.expand(problem); openlist.addAll(children); } } openlist.clear(); closedlist.clear(); return result; }
8
public static void main(String[] args) { long SEED = 287848937; int NumberOfPackets = 10 ; //************************* double mean = 10;//2.9; //************************* System.out.println("Packets arrival distributions: "); //for packet times delivery, seed to keep the same number Random rnd = new Random(SEED); //defaults to 1 unless packet count > 1 int NumberOfTimesPacketsAreDeliverd = 1; //or else the random will be 0 if(NumberOfPackets > 1) { do{ NumberOfTimesPacketsAreDeliverd = rnd.nextInt(NumberOfPackets+1); } while(NumberOfTimesPacketsAreDeliverd == 0); } System.out.println("NumberOfTimesPacketsAreDeliverd: "+NumberOfTimesPacketsAreDeliverd); //based on the number of packets, a random number is chosen for the //number of times packet delivery happens ExponentialDistribution arrivalAmounts= new ExponentialDistribution(NumberOfTimesPacketsAreDeliverd,SEED); //********************************** arrivalAmounts.SetMean(mean); //********************************** arrivalAmounts.SetNumebrOfPackets(NumberOfPackets); arrivalAmounts.getDistribution(); /* System.out.println("Arrival Patterns"); ExponentialDistribution arrivalPattern= new ExponentialDistribution(NumberOfTimesPacketsAreDeliverd); int packetAmt; while((packetAmt = arrivalAmounts.getNumber()) != -1) { arrivalPattern.SetNumebrOfPackets(packetAmt); arrivalPattern.SetMean(mean); arrivalPattern.getDistribution(); arrivalPattern.remove(); } */ }
2
public void createEmpire() { beginGame(); properEmpire(); initializeTime(); EmpireDrawer.createDrawableEmpire(); SoundsOfEmpire.playBackgroundMusic(); createBarbarianMotherfuckers(); while(true) { if(Empire.getInstance().SETTLEMENTS.size() >0) { } else { break; } try { Thread.sleep(1000); } catch(Exception ex) { ex.printStackTrace(); } } endGame(); }
3
public int threeSumClosest(int[] num, int target) { Arrays.sort(num); int n = num.length; if(n < 3) { int sum = 0; for(int i : num) { sum+=i; } return sum; } int closest = 0; for(int i=0; i<3; i++){ closest+=num[i]; } for(int i=0; i<=n-3; i++) { int a = num[i]; int start = i+1; int end = n-1; while(start < end) { int b = num[start]; int c = num[end]; if(a+b+c==target) { return target; } else if(a+b+c > target) { end--; } else { start ++; } if(Math.abs(a + b + c - target) < Math.abs(closest-target)) { closest = a + b + c; } } } return closest; }
8
private void seleccionarArchivos() { int resultado = selectorArchivo.showOpenDialog(this); if (resultado == JFileChooser.CANCEL_OPTION) return; File archivo = selectorArchivo.getSelectedFile(); if (archivo.isDirectory()) explorador = new ExploradorRecursivoArchivos(EXTENSIONES_TODAS); else { // Si es un archivo de audio, intentar recuperar // información if (esDeTipo(EXTENSIONES_AUDIO, archivo.toString())) { // Verificar que el archivo no se encuentre // registrado if (biblio.noEsta(archivo.toString(), BD_ARCHIVO)) { // Escoger el tipo de archivo que se desea // construir directorMedios.setArchivoMultimedia(archivoAudio); // Construir el archivo directorMedios.buildArchivo(archivo.toString()); // Obtener objeto con los datos del archivo medio = directorMedios.getArchivo(); // Enviar archivo al objeto que lo guardará // persistentemente biblio.aniadirArchivo(medio); } else if (DEBUG)// Si el archivo ya esta System.out.println("NO hago nada porque ya estas: " + archivo.toString()); }// imagen? if (esDeTipo(EXTENSIONES_IMAGEN, archivo.getName())) { // TODO capturar datos de la imagen if (biblio.noEsta(archivo.getName(), BD_ARCHIVO)) { directorMedios.setArchivoMultimedia(archivoImagen); directorMedios.buildArchivo(archivo.getName()); medio = directorMedios.getArchivo(); biblio.aniadirArchivo(medio); } else if (DEBUG)// Si el archivo ya esta System.out.println("NO hago nada porque ya estas: " + archivo.getName()); } } actualizarTabla(); }
8
public static <E extends Comparable<? super E>> Node<E> partitionList(Node<E> head, E value) { Node<E> oh = null; Node<E> ot = null; Node<E> h = null; Node<E> t = null; Node<E> curr = head; while (curr != null) { if (curr.data.compareTo(value) < 0) { if (oh == null) { oh = new Node<E>(curr.data); h = oh; } else { h.next = new Node<E>(curr.data); h = h.next; } } else { if (ot == null) { ot = new Node<E>(curr.data); t = ot; } else { t.next = new Node<E>(curr.data); t = t.next; } } curr = curr.next; } if (h != null) { h.next = ot; return oh; } else { return ot; } }
6
public Usuario Logar(String Email, String Senha) throws SQLException, excecaoLogin { Usuario userLogado = new Usuario(); LoginDAO LoginDAO = new LoginDAO(); userLogado = LoginDAO.selectLogin(Email, Senha); if (userLogado == null) { throw new excecaoLogin(); } else { return userLogado; } }
1
private static int partition(int[] arr, int left, int right) { int pivot = arr[left]; // any number while (left < right) { while (left < right && arr[right] > pivot) { right--; } if (left < right) { arr[left++] = arr[right]; } while (left < right && arr[left] <= pivot) { left++; } if (left < right) { arr[right--] = arr[left]; } } return left; }
7
@Override public Position getNextPosition() { if(reader == null) { if(super.getParamString().equals("")) { reader = PositionFileIO.getPositionFileReader(null); } else { reader = PositionFileIO.getPositionFileReader(super.getParamString()); } } return PositionFileIO.getNextPosition(reader); }
2
public boolean matches( Class<?> clazz ) { return this.a.matches( clazz ) && this.b.matches( clazz ); }
2
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { if (IOHandler.this.master.isInterrupted() && !method.equals(this.interruptMethod)) { if (Thread.currentThread() != IOHandler.this.master) { throw new InterruptedException(); } return null; } if (IOHandler.this.guiReal == null) { return null; } return method.invoke(IOHandler.this.guiReal, args); }
4
private void botonEliminarEliminarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonEliminarEliminarProductoActionPerformed // TODO add your handling code here: Producto p = controlador.buscarProducto(txtCodigoEliminarProducto.getText()); if (p != null) { int respuesta = JOptionPane.showConfirmDialog(dlgEliminarProducto, "¿Está seguro de que desea eliminar este producto?", "Confirmación para la eliminación", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (respuesta == JOptionPane.OK_OPTION) { Pedido actual = controlador.getPedidoActual(); if (actual == null || !actual.getProductos().contains(p)) { controlador.eliminarProducto(p); } else { mostrarMensajeError("Error: el producto que está tratando de eliminar se encuentra en el pedido actual"); } } } panelDatosEliminacionPedido.setText(""); txtCodigoEliminarProducto.setText(""); botonEliminarEliminarProducto.setEnabled(false); dlgEliminarProducto.setVisible(false); }//GEN-LAST:event_botonEliminarEliminarProductoActionPerformed
4
public static int countOccurrencesOf(String str, String sub) { if (str == null || sub == null || str.length() == 0 || sub.length() == 0) { return 0; } int count = 0; int pos = 0; int idx; while ((idx = str.indexOf(sub, pos)) != -1) { ++count; pos = idx + sub.length(); } return count; }
5
private void isGameStable() { if (play.getGameStatus().equals(GameResult.GameStable)) engine.startDay(); if (play.getGameStatus().equals(GameResult.MafiaWins)) engine.endGame(GameResult.MafiaWins); if (play.getGameStatus().equals(GameResult.VillagerWins)) engine.endGame(GameResult.VillagerWins); }
3
@Override protected boolean xhas_in () { // We may already have a message pre-fetched. if (prefetched) return true; // Try to read the next message to the pre-fetch buffer. prefetched_msg = xxrecv (ZMQ.ZMQ_DONTWAIT); if (prefetched_msg == null && ZError.is(ZError.EAGAIN)) return false; prefetched = true; return true; }
3
public int getInt(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); } }
2
public synchronized boolean use(String openerSQL) { if((!inUse)&&(ready())&&(!isProbablyDead())) { lastError=null; try { myPreparedStatement=null; sqlserver=true; myStatement=myConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); } catch(final SQLException e) { if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SQLERRORS)) Log.errOut("DBConnection",e); myConnection=null; failuresInARow++; sqlserver=false; return false; } sqlserver=false; try { if(!openerSQL.equals("")) { lastSQL=openerSQL; lastQueryTime=System.currentTimeMillis(); myStatement.executeUpdate(openerSQL); } } catch(final SQLException e) { if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SQLERRORS)) { Log.errOut("DBConnection","Error use: "+openerSQL); Log.errOut("DBConnection",e); } return false; // not a real error?! } lastPutInUseTime=System.currentTimeMillis(); inUse=true; return true; } return false; }
8
public void connect() { try { Connection c = DriverManager.getConnection( "jdbc:hsqldb:file:C:\\Users\\school\\Ninak+katen\\repo\\sytossCinemaTraining\\cinemaBom\\cinema.db;ifexists=true", "SA", ""); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
1
public void debugOutput(String filePrefix) { File topicFolder = new File(filePrefix + "topicAssignment"); if (!topicFolder.exists()) { System.out.println("creating directory" + topicFolder); topicFolder.mkdir(); } File childTopKStnFolder = new File(filePrefix + "topKStn"); if (!childTopKStnFolder.exists()) { System.out.println("creating top K stn directory\t" + childTopKStnFolder); childTopKStnFolder.mkdir(); } File stnTopKChildFolder = new File(filePrefix + "topKChild"); if (!stnTopKChildFolder.exists()) { System.out.println("creating top K child directory\t" + stnTopKChildFolder); stnTopKChildFolder.mkdir(); } int topKStn = 10; int topKChild = 10; for (_Doc d : m_trainSet) { if (d instanceof _ParentDoc) { printParentTopicAssignment(d, topicFolder); } else if (d instanceof _ChildDoc) { printChildTopicAssignment(d, topicFolder); } // if(d instanceof _ParentDoc){ // printTopKChild4Stn(topKChild, (_ParentDoc)d, stnTopKChildFolder); // printTopKStn4Child(topKStn, (_ParentDoc)d, childTopKStnFolder); // } } String parentParameterFile = filePrefix + "parentParameter.txt"; String childParameterFile = filePrefix + "childParameter.txt"; printParameter(parentParameterFile, childParameterFile, m_trainSet); // printTestParameter4Spam(filePrefix); String similarityFile = filePrefix + "topicSimilarity.txt"; discoverSpecificComments(similarityFile); printEntropy(filePrefix); printTopKChild4Parent(filePrefix, topKChild); printTopKChild4Stn(filePrefix, topKChild); printTopKChild4StnWithHybrid(filePrefix, topKChild); printTopKChild4StnWithHybridPro(filePrefix, topKChild); printTopKStn4Child(filePrefix, topKStn); }
6
private static final InetAddress getLoopBackAddress() { try { return InetAddress.getByName(null); } catch (UnknownHostException uhe) { // This can't occur, as the loopback address is always valid. Log.error(uhe); return null; } }
1
public static boolean isValidPresenceValue(int presence) { switch(presence) { case AWAY: case ONLINE: case HIDEN: case BUSY: case ROBOT: return true; default: return false; } }
5
@Test public void TestOptions() { ArgSet a1 = new ArgSet("nooption -o --option -op -- - -"); assertTrue(a1.hasArg()); assertFalse(a1.hasAbbArg()); assertFalse(a1.hasOptionArg()); a1.pop(); assertFalse(a1.hasOptionArg()); assertTrue(a1.hasAbbArg()); assertTrue(a1.fetchAbbr().equals('o')); assertTrue(a1.hasOptionArg()); assertFalse(a1.hasAbbArg()); assertTrue(a1.fetchOption().equals("option")); assertFalse(a1.hasAbbArg()); assertFalse(a1.hasOptionArg()); assertTrue(a1.pop().equals("-op")); assertFalse(a1.hasAbbArg()); assertFalse(a1.hasOptionArg()); a1.pop(); assertFalse(a1.hasAbbArg()); assertFalse(a1.hasOptionArg()); a1.pop(); assertFalse(a1.hasAbbArg()); assertFalse(a1.hasOptionArg()); a1.pop(); }
0
private void initFrames(CtClass clazz, MethodInfo minfo) throws BadBytecode { if (frames == null) { frames = ((new Analyzer())).analyze(clazz, minfo); offset = 0; // start tracking changes } }
1
public ListIterator listIterator(final int startIndex) { if (startIndex < 0 || startIndex > instructionCount) throw new IllegalArgumentException(); return new ListIterator() { Instruction instr = get0(startIndex); Instruction toRemove = null; int index = startIndex; public boolean hasNext() { return index < instructionCount; } public boolean hasPrevious() { return index > 0; } public Object next() { if (index >= instructionCount) throw new NoSuchElementException(); index++; toRemove = instr; instr = instr.nextByAddr; // System.err.println("next: "+toRemove.getDescription()); return toRemove; } public Object previous() { if (index == 0) throw new NoSuchElementException(); index--; instr = instr.prevByAddr; toRemove = instr; // System.err.println("prev: "+toRemove.getDescription()); return toRemove; } public int nextIndex() { return index; } public int previousIndex() { return index - 1; } public void remove() { if (toRemove == null) throw new IllegalStateException(); // System.err.println("remove: "+toRemove.getDescription()); instructionCount--; if (instr == toRemove) instr = instr.nextByAddr; else index--; toRemove.removeInstruction(BytecodeInfo.this); toRemove = null; } public void add(Object o) { instructionCount++; index++; // System.err.println("add: " // +((Instruction)o).getDescription() // +" after "+instr.prevByAddr // .getDescription()); instr.prevByAddr.appendInstruction((Instruction) o, BytecodeInfo.this); toRemove = null; } public void set(Object o) { if (toRemove == null) throw new IllegalStateException(); // System.err.println("replace "+toRemove.getDescription() // +" with " // +((Instruction)o).getDescription()); toRemove.replaceInstruction((Instruction) o, BytecodeInfo.this); if (instr == toRemove) instr = (Instruction) o; toRemove = (Instruction) o; } }; }
8
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.WHITE); Rectangle2D.Double background = new Rectangle2D.Double(0, 0, Main.WINDOW_SIZE.width, Main.WINDOW_SIZE.height); g2.fill(background); g2.draw(background); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { this.tileList[i][j].draw(g2); if(this.unitList[i][j] != null) { try { this.unitList[i][j].draw(g2, this.unitList[i][j].getUnitName()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
4
private void nodeId(String s,int t) { nextToken("error occurred in node_id"); if (m_st.ttype == '}') { //creates a node if t is zero if (t == 0) { m_nodes.addElement(new InfoObject(s)); } m_st.pushBack(); } else if (m_st.ttype == '-') { nextToken("error occurred checking for an edge"); if (m_st.ttype == '>') { edgeStmt(s); } else { System.out.println("error occurred checking for an edge"); } } else if (m_st.ttype == '[') { //creates a node if t is zero and sends it to attr if (t == 0) { m_nodes.addElement(new InfoObject(s)); attrList((InfoObject)m_nodes.lastElement()); } else { attrList((InfoObject)m_edges.lastElement()); } } else if (m_st.sval != null) { //creates a node if t is zero if (t == 0) { m_nodes.addElement(new InfoObject(s)); } m_st.pushBack(); } else { System.out.println("error occurred in node_id"); } }
8
public PDALambdaTransitionChecker() { super(); }
0
protected static List<Block> mergeBlocks(final List<Block> blocks, final List<PartitioningMath.Partition> partitions, final Set<LinkDigest> survivors) { final List<Block> merged = new ArrayList<Block>(); for (PartitioningMath.Partition partition : partitions) { if (partition.getStart() == partition.getEnd()) { merged.add(blocks.get(partition.getStart())); continue; } final ArrayList<LinkDigest> digests = new ArrayList<LinkDigest>(); for (int index = partition.getStart(); index <= partition.getEnd(); index++) { digests.addAll(blocks.get(index).getDigests()); } List<LinkDigest> filtered = new ArrayList<LinkDigest>(); for (LinkDigest digest : digests) { if (!survivors.contains(digest)) { //System.out.println("DROPPED: " + digest); continue; } filtered.add(digest); survivors.remove(digest); // i.e. no duplicates. } merged.add(new Block(filtered)); } return merged; }
5
public void setCars(List<Car> cars) { this.cars = cars; }
0
private static boolean processArgs(Option option) throws IOException, InterruptedException { if (option.isDecodeurl() == false && option.getNbThreads() > 0 && option.isCheckOnly() == false && OptionFlags.getInstance().isMetadata() == false) { return multithread(option); } for (String s : option.getResult()) { if (option.isDecodeurl()) { final Transcoder transcoder = TranscoderUtil.getDefaultTranscoder(); System.out.println("@startuml"); System.out.println(transcoder.decode(s)); System.out.println("@enduml"); } else { final FileGroup group = new FileGroup(s, option.getExcludes(), option); for (File f : group.getFiles()) { try { final boolean error = manageFileInternal(f, option); if (error) { return true; } } catch (IOException e) { e.printStackTrace(); } } } } return false; }
9
public void close(boolean fuse) { PluginVars.commu_mode.remove(this.editing); this.editing.closeInventory(); if(fuse) { if(!this.editing.isOnline()) { this.returnCards(); return; } else if(!this.receiver.isOnline()) { this.editing.sendMessage("Player " + this.receiver.getDisplayName() + ChatColor.WHITE + " has gone offline"); this.returnCards(); return; } if(this.recipe.size() > 4 || this.recipe.size() < 3) { this.editing.sendMessage("You must use 3 or 4 cards in a commu fusion!"); this.returnCards(); return; } else { if(this.editing.getLocation().distance(this.receiver.getLocation()) > 6.0d) { this.editing.sendMessage("MISS!"); this.editing.sendMessage("Player " + this.receiver.getDisplayName() + " has gone out of reach."); this.returnCards(); return; } this.editing.getWorld().playSound(this.editing.getLocation(), Sound.FIREWORK_BLAST, 1.0f, 1.0f); this.receiver.getWorld().playSound(this.receiver.getLocation(), Sound.FIREWORK_BLAST, 1.0f, 1.0f); try { int result = this.fuse(); Main.giveReward(this.receiver, result); this.receiver.sendMessage("Commu Fusion: " + Card.fromId(result).name); this.editing.sendMessage(ChatColor.GREEN + "SUCCESS!!!"); } catch (NoCardCreatedException e) { this.editing.sendMessage(ChatColor.RED + "FAILED!!!\n" + ChatColor.YELLOW + "\nNo card created."); } } } else { this.editing.sendMessage("Cancelled fusion"); this.returnCards(); } }
7
public int nombreKamonInitial(int nbjoueur){ int nbkamons = 0; if(nbjoueur == 2){ nbkamons = 12; } if(nbjoueur == 3){ nbkamons = 10; } if(nbjoueur == 4){ nbkamons = 8; } return nbkamons; }
3
private ArrayList<String> getclashedModules(String name) { // String part is module ID that it's clashed with, integer is how many // students take that module. try{ openDatabase(); }catch(Exception e){} String query = "SELECT name FROM t8005t2 .modules WHERE ID IN (SELECT ForeignID FROM t8005t2 .clashedModules WHERE moduleID IN (SELECT ID FROM t8005t2 .modules WHERE name= '" + name + "'))"; ArrayList<String> clashedModules = new ArrayList<String>(); try { stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String foreignID = rs.getString("name"); clashedModules.add(foreignID); } } catch (Exception e) { System.err.println("Problem executing getclashedModules query"); System.err.println(e.getMessage()); } try{ closeDatabase(); }catch(Exception e){} return clashedModules; }
4
private static BitVector algoritam2(SATFormula formula) { BitVector vector = new BitVector(formula.getNumberOfVariables()); for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) { SATFormulaStats vstat = new SATFormulaStats(formula); vstat.setAssignment(vector, true); if (vstat.isSatisfied()) { System.out.println("Zadovoljivo: " + vector); return vector; } BitVectorNGenerator generator = new BitVectorNGenerator(vector); MutableBitVector[] neighborhood = generator.createNeighborhood(); int size = neighborhood.length; int[] fitness = new int[size]; int max = 0; for (int j = 0; j < size; j++) { SATFormulaStats st = new SATFormulaStats(formula); st.setAssignment(neighborhood[j], true); fitness[j] = st.getNumberOfSatisfied(); if (st.isSatisfied()) { System.out.println("Zadovoljivo: " + neighborhood[j].toString()); return neighborhood[j]; } if (max < fitness[j]) { max = fitness[j]; } } if (max < vstat.getNumberOfSatisfied()) { System.out.println("Neuspjeh! Lokalni optimum!"); return null; } List<MutableBitVector> solutions = new ArrayList<>(); for (int j = 0; j < size; j++) { if (fitness[j] >= max) { solutions.add(neighborhood[j]); } } int rand = new Random().nextInt(solutions.size()); vector = solutions.get(rand); } System.out.println("Neuspjeh! Prekoračen broj dozvoljenih iteracija!"); return null; }
8
public void setBedCount(int bedCount) throws CarriageException { if (bedCount < 0) { throw new CarriageException("Beds count is under zero"); } this.bedCount = bedCount; }
1
public static boolean isExist(int number, int counter){ int x = 0; while(x < counter){ if(number == randlist[x]){ return false; } x++; } return true; }
2
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if (GuildUtils.czyGraczMaGildie(sender.getName()) == true) { if (GuildUtils.czyGraczJestOwnerem(sender.getName(), GuildUtils.dajGildieGracza(sender.getName())) == false) { if (args.length == 0) { sender.sendMessage(ChatColor.RED+"Aby potwierdzic opuszczenie gildii wpisz /opusc potwierdz"); } else if (args.length == 1) { if (args[0].equalsIgnoreCase("potwierdz")) { Bukkit.broadcastMessage(ChatColor.YELLOW+sender.getName()+ChatColor.DARK_GREEN+" opuscil gildie "+ChatColor.YELLOW+GuildUtils.dajGildieGracza(sender.getName())+ChatColor.DARK_GREEN+"!"); try{ Connection conn = DriverManager.getConnection(GuildUtils.ip, GuildUtils.login, GuildUtils.haslo); Statement st = conn.createStatement(); try{ st.execute("DELETE FROM players WHERE Nick='"+sender.getName()+"'"); conn.close(); }catch (SQLException e){ e.printStackTrace(); System.out.println("Cos sie zepsulo ;/"); sender.sendMessage(ChatColor.RED+"Wystapil problem podczas tworzenia gidii, zglos to zdarzenie administratorowi"); } }catch (SQLException e){ System.out.println("Uwaga!!!! Mamy problem z polaczeniem!!!!"); sender.sendMessage(ChatColor.RED+"Wystapil problem podczas tworzenia gildii, zglos to zdarzenie administratorowi"); } Bufor.budujListeGraczy(); } else { sender.sendMessage(ChatColor.RED+"Aby potwierdzic opuszczenie gildii wpisz /opusc potwierdz"); } } else { sender.sendMessage(ChatColor.RED+"Niepoprawne uzycie"); } } else { sender.sendMessage(ChatColor.RED+"Jestes wlascicielem gildii!"); } } else { sender.sendMessage(ChatColor.RED+"Nie masz gildii!"); } return false; }
7
public static int generateResult(Bean beanobj) throws NullPointerException, SQLException { int total=0; try { con = DBConnection.getConnection(); //String query1 = "select question.answer,testresult.capturedanswer from question,testresult,test where test.testid='"+beanobj.getTestid()+"'and test.questionid=question.questionid and testresult.questionid=question.questionid and testresult.studentid='"+beanobj.getStudentid()+"'"; String query1="select question.answer,testresult.capturedanswer from question,testresult where testresult.testid='"+beanobj.getTestid()+"' and testresult.studentid='"+beanobj.getStudentid()+"' and testresult.questionid=question.questionid"; String query2 = "insert into result1(testid,studentid,score,schoolid,average) values(?,?,?,?,?)"; st = con.createStatement(); rs=st.executeQuery(query1); /*if(rs.next()){ i=1; }*/ while(rs.next()){ i=1; System.out.println(rs.getString(1)); System.out.println(rs.getString(2)); if(rs.getString(1).equalsIgnoreCase(rs.getString(2))) { System.out.println("answer is correct give 1 mark"); total++; } else { System.out.println("answer is not correct give 0 mark"); //total=total+0; } } System.out.println(total); pt = con.prepareStatement(query2); int avg1=(total*100); int avg=avg1/10; System.out.println(avg); pt.setString(1, beanobj.getTestid()); pt.setString(2, beanobj.getStudentid()); pt.setInt(3,total); pt.setString(4,beanobj.getSchoolid()); pt.setFloat(5,avg); pt.executeUpdate(); con.commit(); } catch (Exception e) { i=10; return i; } finally { con.close(); } return total; }
3
@Override public void saveTroubleTicket(TroubleTicket troubleticket) { int ID = troubleticket.getID(); String userName = troubleticket.getUserName(); String callerName = troubleticket.getCallerName(); String description = troubleticket.getDescription(); String dateTime = troubleticket.getDateTime(); if (userName == null) { userName = ""; } if (callerName == null) { callerName = ""; } if (description == null) { description = ""; } if (dateTime == null) { dateTime = ""; } try { // Execute insert or update query executor.executeQuery( "INSERT INTO troubletickets (ID, userName, callerName, description, dateTime)" + "VALUES (" + ID + ", '" + userName + "', '" + callerName + "', '" + description + "', '" + dateTime + "')" + "ON DUPLICATE KEY UPDATE" + " userName = '" + userName + "'," + " callerName = '" + callerName + "'," + " description = '" + description + "'," + " dateTime = '" + dateTime + "'"); } catch (ExecutorException e) { e.printStackTrace(); } System.out.println( "INSERT INTO troubletickets (ID, userName, callerName, description, dateTime)" + "VALUES (" + ID + ", '" + userName + "', '" + callerName + "', '" + description + "', '" + dateTime + "')" + "ON DUPLICATE KEY UPDATE" + " userName = '" + userName + "' AND" + " callerName = '" + callerName + "' AND" + " description = '" + description + "' AND" + " dateTime = '" + dateTime + "'"); }
5
private void addVariable(String variable) { myVariables.add(variable); }
0
public static void main(String[] args){ //the best input in the command line is : 1440 900 filename 6 3.75 Thread main = Thread.currentThread(); System.out.println(main); if(args.length!=6&&args.length!=5&&args.length!=3&&args.length!=0&&args.length!=2){ System.err.println("i need either three or five or six or 7 command line arguements 1: image width 2: image height 3: file name 4: aspect ratio width 5: aspect ratio height 6:light weight"); System.err.println("~note~ you do not need to add a .ppm to your filename"); System.err.println("the best command line arguements are : 1440 900 filename 6 3.75 : at least it is for me since my screen resolution is 1440*900"); return; } else { int width=800; int height=600; String filenameinput="scene.ssf",filename="ray"; int AAF=1;//this is the anti aliasing factor. values above 4ish create a very blurred image. for best results use 2 or 3. If you want no AA, then use 1. double topAspect=-1;//top aspect and side aspect allow you to change the aspect ratio of your image. This is the same concept as tv screens, standard output is 4:3 and widescreen is 16:9 and for widescreen computer monitors it is 16:10 or 8:5 double sideAspect=-1;//larger numbers here pan the camera out, while smaller ones zoom it in if(args.length==2){ width=Integer.parseInt(args[0]); height = Integer.parseInt(args[1]); } if(args.length==3){ width= Integer.parseInt(args[0]); height = Integer.parseInt(args[1]); filename=args[2]; } if(args.length==5){ width= Integer.parseInt(args[0]); height = Integer.parseInt(args[1]); filename=args[2]; topAspect=Double.parseDouble(args[3]); sideAspect=Double.parseDouble(args[4]); } if(args.length==6){ width= Integer.parseInt(args[0]); height = Integer.parseInt(args[1]); filename=args[2]; topAspect=Double.parseDouble(args[3]); sideAspect=Double.parseDouble(args[4]); filenameinput=args[5]; } RayTracer rt = new RayTracer(width, height, filename, topAspect, sideAspect,AAF,filenameinput); rt.createImage(); rt.waitForThreadsToFinish(main); rt.print(); } }
9