text
stringlengths
14
410k
label
int32
0
9
public boolean isChange() { return myChange; }
0
public double getSimilarity(String a, String b) { LinkedList<String> pairs1 = wordLetterPairs(a.toUpperCase()); LinkedList<String> pairs2 = wordLetterPairs(b.toUpperCase()); int intersection = 0; int union = pairs1.size() + pairs2.size(); for (int i = 0; i < pairs1.size(); i++) { Object pair1 = pairs1.get(i); for (int j = 0; j < pairs2.size(); j++) { Object pair2 = pairs2.get(j); if (pair1.equals(pair2)) { intersection++; pairs2.remove(j); break; } } } return (2.0 * intersection) / union; }
3
private void calculateBestTime(double recordBest, double newTime){ int secondsBehind; int secondsAhead; if(((recordBest <= 0)&&(newTime <= 0))||(newTime <= 0)) System.out.println("Invalid Time. \n"); else if (recordBest == 0) { System.out.println(+newTime + " Game Time \n"); System.out.println("New Record!"); } else if (recordBest < newTime) { secondsBehind = (int) (newTime - recordBest); System.out.println(+newTime + " Game Time \n"); System.out.println(+ secondsBehind+ " seconds behind the current record time. \n"); } else if (recordBest > newTime) { secondsAhead = (int) (recordBest - newTime); System.out.println(+newTime + " Game Time \n"); System.out.println("New Record! " +secondsAhead+ " seconds ahead of previous record time. \n"); } else if (recordBest == newTime) { System.out.println(+newTime + " Game Time \n"); System.out.println("Tied Game Record! \n"); } }
7
public String join(String separator) throws JSONException { int len = length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i += 1) { if (i > 0) { sb.append(separator); } sb.append(JSONObject.valueToString(this.myArrayList.get(i))); } return sb.toString(); }
2
@Override public void write(int b) throws IOException { // Debugger.println(2, "[DummyConnection] writing " + (char)b); if(dataSemaphore.availablePermits() > QUEUE_BUFFER_LIMIT) { throw new IOException("Buffer size limit reached!"); } else { synchronized(dataQueue) { dataQueue.add(b); dataSemaphore.release(); } } }
1
public static double svm_predict_probability(svm_model model, svm_node[] x, double[] prob_estimates) { if ((model.param.svm_type == svm_parameter.C_SVC || model.param.svm_type == svm_parameter.NU_SVC) && model.probA!=null && model.probB!=null) { int i; int nr_class = model.nr_class; double[] dec_values = new double[nr_class*(nr_class-1)/2]; svm_predict_values(model, x, dec_values); double min_prob=1e-7; double[][] pairwise_prob=new double[nr_class][nr_class]; int k=0; for(i=0;i<nr_class;i++) for(int j=i+1;j<nr_class;j++) { pairwise_prob[i][j]=Math.min(Math.max(sigmoid_predict(dec_values[k],model.probA[k],model.probB[k]),min_prob),1-min_prob); pairwise_prob[j][i]=1-pairwise_prob[i][j]; k++; } multiclass_probability(nr_class,pairwise_prob,prob_estimates); int prob_max_idx = 0; for(i=1;i<nr_class;i++) if(prob_estimates[i] > prob_estimates[prob_max_idx]) prob_max_idx = i; return model.label[prob_max_idx]; } else return svm_predict(model, x); }
8
public String getLibelle() { return libelle; }
0
public RequestsArray(int numberOfElements, float sDev) { this.meanBuyPrice = 1.0f; this.meanSellPrice = 1.0f; this.sDev = sDev; this.numberOfElements = numberOfElements; for(int i = 0; i<numberOfElements; i++){ float targetPrice; int sORb = rng.nextInt(2); if(sORb == 0){ targetPrice = (float)(((rng.nextGaussian())*sDev) + meanSellPrice); int ass = ((rng.nextInt(4)+1)); int aType = rng.nextInt(3); switch(aType){ case 0: Requests.add(new SellRequest("Pork Bellies", (targetPrice*1.28f), (ass*40000))); break; case 1: Requests.add(new SellRequest("Frozen Orange Juice Concentrate", (targetPrice*1.57f), (ass*15000))); break; case 2: Requests.add(new SellRequest("Soybeans", (targetPrice*14.05f), (ass*5000))); } } if(sORb == 1){ targetPrice = (float)(((rng.nextGaussian())*sDev)+ meanBuyPrice); int ass = ((rng.nextInt(4)+1)); int aType = rng.nextInt(3); switch(aType){ case 0: Requests.add(new BuyRequest("Pork Bellies", (targetPrice*1.28f), (40000*ass))); break; case 1: Requests.add(new BuyRequest("Frozen Orange Juice Concentrate", (targetPrice*1.57f), (ass*15000))); break; case 2: Requests.add(new BuyRequest("Soybeans", (targetPrice*14.05f), (ass*5000))); } } } lowestSellPrice(); highestBuyPrice(); }
9
public Movie registerMovie(Movie movie) { int index = movies.indexOf(movie); if (index == -1) { addMovie(movie); return movie; } else return movies.get(index); }
1
public static void main(String[] args) throws IOException { // TODO Auto-generated method stub System.out.println("Program Started"); //get config elements main_image_compressor m =new main_image_compressor(); //validate config elements if(!config_reader.validate_config(prop)) return ;//incorrect config //get list of files from the input folder : ArrayList<String> input_files=file_lister.list_files(prop.get(0),prop.get(1)); BufferedImage input_img;// = ImageIO.read(path); BufferedImage output_img = null; String f_name; String f_type; int h,w; int scaled_width,scaled_height; float aspect_ratio; int quality=Integer.parseInt(prop.get(4)); float q_value=((float)quality)/100; File output_file; ImageOutputStream ios; boolean small_img=false; System.out.println("Total number of files present in input directory : "+input_files.size()); for(String i:input_files) { //System.out.println(i); //individual files small_img=false; f_name=new File(i).getName().replace("."+prop.get(1),""); f_type=prop.get(3); //get image input_img=ImageIO.read(new File(i)); if(prop.get(5).contains("yes")) { //appply scaling ! //get image height & width h=input_img.getHeight(); w=input_img.getWidth(); aspect_ratio=w/(float)h; //call scale ! scaled_width=Integer.parseInt(prop.get(7)); if(scaled_width>w) { scaled_width=w; small_img=true; } if(prop.get(6).contains("yes")) { scaled_height=(int)(scaled_width/aspect_ratio); } else { scaled_height=Integer.parseInt(prop.get(8)); } if(scaled_height>h) { small_img=true; scaled_height=h; } output_img=scale(input_img,scaled_width,scaled_height); if(small_img) { //output_img=scale(input_img,scaled_width,scaled_height); System.out.println("input image : "+f_name+ " is already smaller than the required scaling width & height! "); //System.out.println(scaled_width+" "+scaled_height+" "+w+" "+h); //output_img=input_img; //continue; } } else if(prop.get(5).contains("no")) { // dont apply scaling! output_img=input_img; } //save the image ! ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName("jpg").next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(q_value); output_file=new File(prop.get(2)+File.separator+f_name+"."+f_type); ios = ImageIO.createImageOutputStream(output_file); writer.setOutput(ios); try { writer.write(null, new IIOImage(output_img, null, null), param); } catch (IIOException e) { //delete the files created if file is usupported ! output_file.delete(); System.out.println( "Unable to process the file! : "+f_name+"."+f_type); //System.out.println(f_type); //e.printStackTrace(); } } System.out.println("Program completed"); }
9
public T Abrir(Long id) { try { T obj = (T) manager.find(tipo, id); return obj; //abrir } catch (Exception ex) { return null; } }
1
public void appendPath(String p_addToPath) throws MalformedURIException { if (p_addToPath == null || p_addToPath.trim().length() == 0) { return; } if (!isURIString(p_addToPath)) { throw new MalformedURIException(Utils.messages.createMessage(MsgKey.ER_PATH_INVALID_CHAR, new Object[]{p_addToPath})); //"Path contains invalid character!"); } if (m_path == null || m_path.trim().length() == 0) { if (p_addToPath.startsWith("/")) { m_path = p_addToPath; } else { m_path = "/" + p_addToPath; } } else if (m_path.endsWith("/")) { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath.substring(1)); } else { m_path = m_path.concat(p_addToPath); } } else { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath); } else { m_path = m_path.concat("/" + p_addToPath); } } }
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MapKey other = (MapKey) obj; if (documentId != other.documentId) return false; if (term == null) { if (other.term != null) return false; } else if (!term.equals(other.term)) return false; return true; }
7
public static boolean isReservedOpenParen(String candidate) { int START_STATE = 0; int TERMINAL_STATE = 1; char next; if (candidate.length()!=1){ return false; } int state = START_STATE; for (int i = 0; i < candidate.length(); i++) { next = candidate.charAt(i); switch (state) { case 0: switch ( next ) { case '(': state++; break; default : state = -1; } break; } } if ( state == TERMINAL_STATE ) return true; else return false; }
5
@Override public int attack(double agility, double luck) { if(random.nextInt(100) < luck) { System.out.println("I just breathed darkness!"); return random.nextInt((int) agility) * 2; } return 0; }
1
public Kill04(String data){ if(!data.trim().equalsIgnoreCase("")){ String[] info = data.split(";"); String killer = info[0]; String victem = info[1]; int points = new Integer(info[2]); if(killer.equals(Main.playername)){ //Du hast jemand getötet String finalString = "You killed " + victem + "(" + points + ")"; Main.overlay.addToRender(new Text(finalString,(GAME_WIDTH / 2) - (Main.font.getWidth(finalString) / 2), GAME_HEIGHT/2,2000)); for(Enemy e: Main.enemies){ if(victem.equals(e.getName())){ e.die(); } } }else if(victem.equals(Main.playername)){ Main.player.die(); //Du wurdest getötet String finalString = "You've been killed by " + killer; Main.overlay.addToRender(new Text(finalString,(GAME_WIDTH / 2) - (Main.font.getWidth(finalString) / 2), GAME_HEIGHT/2,2000)); }else{ for(Enemy e: Main.enemies){ if(victem.equals(e.getName())){ e.die(); } } //Irgendwer hat irgendwen getötet Main.overlay.addToKillLog(killer,victem); } } }
7
private String readFile(File eventFile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(eventFile)); StringBuilder sBuilder = new StringBuilder(); try { String line = reader.readLine(); while (line != null) { sBuilder.append(line); line = reader.readLine(); } } finally { reader.close(); } return sBuilder.toString(); }
1
public static boolean isPrime( long x) { long max = (long)Math.sqrt(x); if( x ==2) { return true; } if( x % 2 ==0) { return false; } if( x <= 1) { return false; } for( int i = 2; i <= max; i++) { if( x % i ==0) { return false; } } return true; }
5
public boolean requiresVote(){ if(Plugin.getJobsConf().getBoolean(name + ".requires-vote")){ return true; }else{ return false; } }
1
public ArrayList getImages(String name) { ArrayList imsList = (ArrayList) imagesMap.get(name); if (imsList == null) { //EIError.debugMsg("No image(s) stored under " + name, EIError.ErrorLevel.Warning); return null; } EIError.debugMsg("Returning all images stored under " + name, EIError.ErrorLevel.Error); return imsList; }
1
public int HandleCollisionWithBullet(Bullet b) { ChainEnemyTailPiece iterator = mFirstTailPiece; while (iterator != null) { Vector2 intersection = iterator.GetBulletCollision(b); if (intersection != null) { int returnPoints = 0; if (b.IsAlive() && iterator.IsAlive() && iterator.GetNext() == null) { if (iterator == mFirstTailPiece) { Destroy(); returnPoints = 1000; } else { iterator.Destroy(); returnPoints = 50; } } b.SetPosition(intersection); b.Destroy(); return returnPoints; } iterator = iterator.GetNext(); } return 0; }
6
public static void main(String[] args) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); for (String line; (line = in.readLine())!= null; ) { int casos = Integer.parseInt(line); if(casos==0)break; courses = new String[casos]; popularity = new TreeMap<String, Integer>(); pop = new int[casos][5]; int max=Integer.MIN_VALUE; for (int c = 0; c < casos; c++) { line = in.readLine().trim(); StringTokenizer st = new StringTokenizer(line); for (int i = 0; i < pop[c].length; i++) pop[c][i]=Integer.parseInt(st.nextToken()); Arrays.sort(pop[c]); String key = Arrays.toString(pop[c]); if(popularity.get(key)==null) popularity.put(key, 1); else popularity.put(key, popularity.get(key)+1); int w = popularity.get(key); if( w > max ){ max = w; } courses[c] = Arrays.toString(pop[c]); } int cantEst=0; for (int c = 0; c < casos; c++) { if(popularity.get(courses[c])==max) cantEst++; } sb.append(cantEst+"\n"); } System.out.print(new String(sb)); }
8
public void calculateDayOfWeek(Calendar cal, Date currentTime) { Integer nextOccurence = null; for(int d : repeatDays) { cal.set(Calendar.DAY_OF_WEEK, d); if(cal.getTime().after(currentTime)) { nextOccurence = d; break; } } if(nextOccurence == null) { cal.add(Calendar.WEEK_OF_YEAR, 1); for(int d : repeatDays) { cal.set(Calendar.DAY_OF_WEEK, d); if(cal.getTime().after(currentTime)) { break; } } } }
5
private void stop() { if (isMovingRight() == false && isMovingLeft() == false) { speedX = 0; } if (isMovingRight() == false && isMovingLeft() == true) { moveLeft(); } if (isMovingRight() == true && isMovingLeft() == false) { moveRight(); } }
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(Imprimir_Acta_Notas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Imprimir_Acta_Notas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Imprimir_Acta_Notas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Imprimir_Acta_Notas.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 Imprimir_Acta_Notas().setVisible(true); } }); }
6
public void draw(Graphics g) { boolean selected = (needsHighlight() || sim.getPlotYElm() == this); Font f = new Font("SansSerif", selected ? Font.BOLD : 0, 14); g.setFont(f); g.setColor(selected ? selectColor : whiteColor); String s = (flags & FLAG_VALUE) != 0 ? getVoltageText(volts[0]) : "out"; FontMetrics fm = g.getFontMetrics(); if (this == sim.getPlotXElm()) { s = "X"; } if (this == sim.getPlotYElm()) { s = "Y"; } interpPoint(point1, point2, lead1, 1 - (fm.stringWidth(s) / 2 + 8) / dn); setBbox(point1, lead1, 0); drawCenteredText(g, s, x2, y2, true); setVoltageColor(g, volts[0]); if (selected) { g.setColor(selectColor); } drawThickLine(g, point1, lead1); drawPosts(g); }
7
* @param leftTransposed the left transpose MUM possibly null * @param rightTransposed the right transpose MUM possibly null * @return null or the best MUM */ private MUM getBest( MUM direct, MUM leftTransposed, MUM rightTransposed ) { MUM best = null; // decide which transpose MUM to use MUM transposed; if ( leftTransposed == null ) transposed = rightTransposed; else if ( rightTransposed == null ) transposed = leftTransposed; else if ( leftTransposed.compareTo(rightTransposed) > 0 ) transposed = leftTransposed; else transposed = rightTransposed; // decide between direct and transpose MUM if ( direct != null && transposed != null ) { int result = direct.compareTo( transposed ); // remember, we nobbled the compareTo method // to produce reverse ordering in the specials // treemap, so "less than" is actually longer if ( result == 0 || result < 0 ) best = direct; else best = transposed; } else if ( direct == null ) best = transposed; else best = direct; return best; }
8
public static SphericalCoordinate jauAtoiq(String type, double ob1, double ob2, Astrom astrom ) { char c; double c1, c2, sphi, cphi, ce, xaeo, yaeo, zaeo, v[] = new double[3], xmhdo, ymhdo, zmhdo, az, sz, zdo, refa, refb, tz, dref, zdt, xaet, yaet, zaet, xmhda, ymhda, zmhda, f, xhd, yhd, zhd, xpl, ypl, w; /* Coordinate type. */ c = type.charAt(0); /* Coordinates. */ c1 = ob1; c2 = ob2; /* Sin, cos of latitude. */ sphi = astrom.sphi; cphi = astrom.cphi; /* Standardize coordinate type. */ if ( c == 'r' || c == 'R' ) { c = 'R'; } else if ( c == 'h' || c == 'H' ) { c = 'H'; } else { c = 'A'; } /* If Az,ZD, convert to Cartesian (S=0,E=90). */ if ( c == 'A' ) { ce = sin(c2); xaeo = - cos(c1) * ce; yaeo = sin(c1) * ce; zaeo = cos(c2); } else { /* If RA,Dec, convert to HA,Dec. */ if ( c == 'R' ) c1 = astrom.eral - c1; /* To Cartesian -HA,Dec. */ v = jauS2c ( -c1, c2 ); xmhdo = v[0]; ymhdo = v[1]; zmhdo = v[2]; /* To Cartesian Az,El (S=0,E=90). */ xaeo = sphi*xmhdo - cphi*zmhdo; yaeo = ymhdo; zaeo = cphi*xmhdo + sphi*zmhdo; } /* Azimuth (S=0,E=90). */ az = ( xaeo != 0.0 || yaeo != 0.0 ) ? atan2(yaeo,xaeo) : 0.0; /* Sine of observed ZD, and observed ZD. */ sz = sqrt ( xaeo*xaeo + yaeo*yaeo ); zdo = atan2 ( sz, zaeo ); /* * Refraction * ---------- */ /* Fast algorithm using two constant model. */ refa = astrom.refa; refb = astrom.refb; tz = sz / zaeo; dref = ( refa + refb*tz*tz ) * tz; zdt = zdo + dref; /* To Cartesian Az,ZD. */ ce = sin(zdt); xaet = cos(az) * ce; yaet = sin(az) * ce; zaet = cos(zdt); /* Cartesian Az,ZD to Cartesian -HA,Dec. */ xmhda = sphi*xaet + cphi*zaet; ymhda = yaet; zmhda = - cphi*xaet + sphi*zaet; /* Diurnal aberration. */ f = ( 1.0 + astrom.diurab*ymhda ); xhd = f * xmhda; yhd = f * ( ymhda - astrom.diurab ); zhd = f * zmhda; /* Polar motion. */ xpl = astrom.xpl; ypl = astrom.ypl; w = xpl*xhd - ypl*yhd + zhd; v[0] = xhd - xpl*w; v[1] = yhd + ypl*w; v[2] = w - ( xpl*xpl + ypl*ypl ) * zhd; /* To spherical -HA,Dec. */ SphericalCoordinate co = jauC2s(v); /* Right ascension. */ co.alpha = jauAnp(astrom.eral + co.alpha); return co; /* Finished. */ }
8
public TreeNode buildTreeRec(int[] inorder, int[] postorder, int s1, int e1, int s2, int e2) { if(e1 == s1 && s2 == e2) return new TreeNode(inorder[s1]); if(postorder[e2] == inorder[s1]){ TreeNode root = new TreeNode(postorder[e2]); TreeNode right = buildTreeRec(inorder, postorder, s1+1, e1, e2-1-(e1-(s1+1)), e2-1); root.right = right; return root; } if(postorder[e2] == inorder[e1]){ TreeNode root = new TreeNode(postorder[e2]); TreeNode left = buildTreeRec(inorder, postorder, s1, e1-1, s2, e2-1); root.left = left; return root; } int i = s1; for(; i <= e1; ++i){ if(inorder[i] == postorder[e2]) break; } TreeNode root = new TreeNode(postorder[e2]); TreeNode left = buildTreeRec(inorder, postorder, s1, i-1, s2, s2+(i-1-s1)); root.left = left; TreeNode right = buildTreeRec(inorder, postorder, i+1, e1, e2-1-(e1-(i+1)), e2-1); root.right = right; return root; }
6
public void searchTitle(int docId,RandomAccessFile raf,long start,long end,boolean wikiflag, boolean titleflag) { //System.out.println(docId); long mid; String res; try { while(start<=end) { mid=(start+end)/2; raf.seek(mid); raf.readLine(); if((res=raf.readLine())!=null){ String[] tokens=res.split("#"); //System.out.println( tokens[0]); int comparison=Integer.parseInt(tokens[0]); if(comparison==docId) { if(!wikiflag && titleflag && tokens[1].contains("wiki")) break; System.out.println( docId+" "+tokens[1]); break; } else if(comparison<docId){ start=mid+1; } else { end=mid-1; } } else{ end=mid-1; } } } catch (Exception e) { e.printStackTrace(); } }
8
public boolean update() { x += dx; y += dy; if (x < -r || x > GamePanel.WIDTH + r || y < -r || y > GamePanel.HEIGHT + r) { return true; } return false; }
4
public int popFront() throws InvalidAccessException { if (this.head != null) { if (head.getVal() == Integer.MIN_VALUE) { int value = head.getList().popFront(); if (head.getList().peekFront() == Integer.MIN_VALUE) { DLNode temp = head; head = head.getNext(); temp.setNext(null); if (head != null) { head.setPrev(null); } } return value; } else { int val = head.getVal(); DLNode temp = head; head = head.getNext(); temp.setNext(null); if (head != null) { head.setPrev(null); } return val; } } throw new InvalidAccessException("Empty List"); }
5
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(shapeBuilderGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(shapeBuilderGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(shapeBuilderGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(shapeBuilderGUI.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 shapeBuilderGUI().setVisible(true); } }); }
6
@RequestMapping("/create") public String create(User user, Model model) { user = userRepository.save(user); model.addAttribute("user", user); return "users/form"; }
0
public Object getChild(Object parent, int index) { if (parent instanceof Page) { Page p = (Page)parent; if (index >= p.children.size()) { int j = index - p.children.size(); return p.names.get(j); } else { return p.children.get(index); } } else { return null; } }
2
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { // Start typing your Java solution below // DO NOT write main() function int n = num.length; Arrays.sort(num); Set<String> set = new HashSet<String>(); for (int i = 0; i < n - 3; i++) { for (int j = i + 1; j < n - 2; j++) { int expect = target - num[i] - num[j]; int l = j + 1; int r = n - 1; while (l < r) { int tmp = num[l] + num[r]; if (tmp == expect) { set.add(String.valueOf(num[i]) + "|" + String.valueOf(num[j]) + "|" + String.valueOf(num[l]) + "|" + String.valueOf(num[r])); l++; r--; } else if (tmp < expect) { l++; } else { r--; } } } } ArrayList<ArrayList<Integer>> array = new ArrayList<ArrayList<Integer>>(); for (String s : set) { String[] arr = s.split("\\|"); ArrayList<Integer> tmp = new ArrayList<Integer>(); for (int i = 0; i < 4; i++) { tmp.add(Integer.parseInt(arr[i])); } array.add(tmp); } return array; }
7
private void collectData(int team, String date) { try { // Name abfragen String qTeamname = "SELECT name FROM team WHERE id = " + team + ";"; String teamname = this.dbService.execScrollableQuery(qTeamname); //System.out.println(teamname); arffWriter.addAttribute("\"" + teamname + "\""); // ######################################################################################################## // ##################### Tore der letzten 5 Spiele vor mdate abgfragen ############################## // ######################################################################################################## String qTore = "CREATE OR REPLACE VIEW tore AS SELECT goalshome AS goals, mdate FROM blmatch WHERE home_team = " + team + " AND mdate < \'" + date + "\' UNION SELECT goalsguest AS goals, mdate FROM blmatch WHERE guest_team = " + team + " AND mdate < \'" + date + "\' ORDER BY mdate DESC FETCH FIRST 5 ROWS ONLY;"; dbService.execUpdate(qTore); String qSTore = "SELECT SUM (goals) FROM tore;"; String tore = dbService.execScrollableQuery(qSTore); if (tore == null) { tore = "0"; this.invalid++; } //System.out.println(tore); arffWriter.addAttribute(tore); // ######################################################################################################## // ##################### Gegentore der letzten 5 Spiele vor mdate abgfragen ############################## // ######################################################################################################## String qGgTore = "CREATE OR REPLACE VIEW ggtore AS SELECT goalsguest AS goals, mdate FROM blmatch WHERE home_team = " + team + " AND mdate < \'" + date + "\' UNION SELECT goalshome AS goals, mdate FROM blmatch WHERE guest_team = " + team + " AND mdate < \'" + date + "\' ORDER BY mdate DESC FETCH FIRST 5 ROWS ONLY;"; dbService.execUpdate(qGgTore); String qSGgSTore = "SELECT SUM (goals) FROM ggtore;"; String ggtore = dbService.execScrollableQuery(qSGgSTore); if (ggtore == null) ggtore = "0"; //System.out.println(ggtore); arffWriter.addAttribute(ggtore); // ######################################################################################################## // ##################### NIEDERLAGEN DER LETZTEN 5 SPIELE ABFRAGEN ###################################### // ######################################################################################################## //String qNiederlagen = "SELECT COUNT(*) FROM (SELECT * FROM v_matches WHERE team_id =" + winner + " AND mdate < \'" +date+ "\' ORDER BY mdate DESC FETCH FIRST 5 ROWS ONLY) AS abc WHERE goals < cgoals;"; String qNiederlagen = "SELECT COUNT(*) FROM (SELECT * FROM v_matches WHERE team_id = " + team + " AND mdate < \'" + date + "\' ORDER BY mdate DESC) AS abc WHERE goals < cgoals FETCH FIRST 5 ROWS ONLY;"; String niederlagen = dbService.execScrollableQuery(qNiederlagen); //System.out.println(niederlagen); arffWriter.addAttribute(niederlagen); // ######################################################################################################## // DURCHSCHNITTLICHE STEIGERUNG DER ANZAHL DER GESCHOSSENEN TORE // ######################################################################################################## int[] goals = new int[6]; int[] steigerung = new int[5]; int index = 0; for (int row = 5; row >= 0; row--) { String qgoals = "SELECT goals FROM v_matches WHERE team_id = " + team + " AND mdate < \'" + date + "\' ORDER BY mdate DESC FETCH FIRST 1 ROWS ONLY OFFSET " + row + ";"; goals[index] = dbService.execIntQuery(qgoals); if (goals[index] == -1) goals[index] = 0; index++; } for (int steig = 0; steig < steigerung.length; steig++) { steigerung[steig] = goals[steig + 1] - goals[steig]; } float total = 0; for (int steig = 0; steig < steigerung.length; steig++) { total += steigerung[steig]; } total = total / steigerung.length; arffWriter.addAttribute(total); // ######################################################################################################## // ############################# ANTEILIG GEWONNEN ###################################################### // ######################################################################################################## String qTotalGewonnen = "SELECT COUNT(*) FROM v_matches WHERE team_id = " + team + " AND goals > cgoals AND mdate > \'" + date + "\';"; int totalGewonnen = dbService.execIntQuery(qTotalGewonnen); String qTotalGames = "SELECT COUNT(*) FROM v_matches WHERE team_id = " + team + " AND mdate > \'" + date + "\';"; int totalGames = dbService.execIntQuery(qTotalGames); float rate = 0.0f; if (totalGames != 0) { rate = (float) totalGewonnen / (float) totalGames; } //System.out.println(rate); arffWriter.addAttribute(rate); // ######################################################################################################## // ############################# GOAL RATE ############################################################ // ######################################################################################################## String qAvgGoals = "SELECT AVG(goals) FROM (SELECT * FROM v_matches WHERE mdate < \'" + date + "\') AS abc WHERE team_id = 1;"; float avgGoals = dbService.execFloatQuery(qAvgGoals); //if (avgGoals == -1) avgGoals = 0; arffWriter.addAttribute(avgGoals); } catch (PSQLException e) { System.out.print("-"); } catch (SQLException e) { // e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }
9
public void replaySources() { Set<String> keys = sourceMap.keySet(); Iterator<String> iter = keys.iterator(); String sourcename; Source source; // loop through and cleanup all the sources: while (iter.hasNext()) { sourcename = iter.next(); source = sourceMap.get(sourcename); if (source != null) { if (source.toPlay && !source.playing()) { play(sourcename); source.toPlay = false; } } } }
4
public void hand(Point point){ if(selectedShape != null && (selectedShape.contains(point) || isResizing)){ isResizing = true; if(selectedTool == Tool.MOVE) moveShape(point); else resizeShape(point); } else { boolean found = false; for(int i = shapesList.size()-1; i >= 0 && !found; i--){ if(shapesList.get(i).contains(point)){ selectedShape = shapesList.get(i); found = true; } } if (!found){ selectedShape = null; } repaint(); } }
8
public void setColcheteE(TColcheteE node) { if(this._colcheteE_ != null) { this._colcheteE_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._colcheteE_ = node; }
3
private void runTest(Directory dir) throws Exception { // Run for ~1 seconds final long stopTime = System.currentTimeMillis() + 1000; SnapshotDeletionPolicy dp = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy()); final IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer(org.apache.lucene.util.Version.LUCENE_CURRENT), dp, IndexWriter.MaxFieldLength.UNLIMITED); // Force frequent flushes writer.setMaxBufferedDocs(2); final Thread t = new Thread() { @Override public void run() { Document doc = new Document(); doc.add(new Field("content", "aaa", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); do { for(int i=0;i<27;i++) { try { writer.addDocument(doc); } catch (Throwable t) { t.printStackTrace(System.out); fail("addDocument failed"); } if (i%2 == 0) { try { writer.commit(); } catch (Exception e) { throw new RuntimeException(e); } } } try { Thread.sleep(1); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } while(System.currentTimeMillis() < stopTime); } }; t.start(); // While the above indexing thread is running, take many // backups: do { backupIndex(dir, dp); Thread.sleep(20); if (!t.isAlive()) break; } while(System.currentTimeMillis() < stopTime); t.join(); // Add one more document to force writer to commit a // final segment, so deletion policy has a chance to // delete again: Document doc = new Document(); doc.add(new Field("content", "aaa", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.addDocument(doc); // Make sure we don't have any leftover files in the // directory: writer.close(); TestIndexWriter.assertNoUnreferencedFiles(dir, "some files were not deleted but should have been"); }
8
public ArrayList<String> parseTemplate(ArrayList<ArrayList<String>> data){ int position; ArrayList<String> newTemplate = new ArrayList<String>(); for(String line : template){ for(ArrayList<String> container : data){ position = line.indexOf(container.get(0)); if(position != -1){ line = line.substring(0, position + container.get(0).length() - 1) + container.get(1) + line.substring(position + container.get(0).length() + replacement.length() - 1, line.length()); } } newTemplate.add(line); } return newTemplate; }
3
public void addRow(Object[] array) { //data[rowIndex][columnIndex] = (String) aValue; try{ // add row to database EntityTransaction userTransaction = manager.getTransaction(); userTransaction.begin(); Audience newViewer = audienceService.createviewer((String) array[0], (String) array[1], (String) array[2], (String) array[3], (String) array[4]); userTransaction.commit(); // set the current row to rowIndex audienceResultList.add(newViewer); JOptionPane.showMessageDialog(window,"SignUp Successful","Confirm SignUP",JOptionPane.PLAIN_MESSAGE ); int row = audienceResultList.size(); int col = 0; // update the data in the model to the entries in array for (Object data : array) { setValueAt((String) data, row-1, col++); } numrows++; LoginGUI LGui = new LoginGUI(); LGui.showGUI(); } catch(Exception e){ JOptionPane.showMessageDialog(window,"Username already exits.Try a different Username","UserName Invalid",JOptionPane.PLAIN_MESSAGE ); //SignUpGUI gui1 = new SignUpGUI(); //gui1.showGUI(); } }
2
public void run() { // get line and buffer from ThreadLocals SourceDataLine line = (SourceDataLine)localLine.get(); byte[] buffer = (byte[])localBuffer.get(); if (line == null || buffer == null) { // the line is unavailable return; } // copy data to the line try { int numBytesRead = 0; while (numBytesRead != -1) { // if paused, wait until unpaused synchronized (pausedLock) { if (paused) { try { pausedLock.wait(); } catch (InterruptedException ex) { return; } } } // copy data numBytesRead = source.read(buffer, 0, buffer.length); if (numBytesRead != -1) { line.write(buffer, 0, numBytesRead); } } } catch (IOException ex) { ex.printStackTrace(); } }
7
public TestDriver(String[] args) { processProgramParameters(args); System.out.print("Reading Test Driver data..."); System.out.flush(); if (doSQL) parameterPool = new SQLParameterPool(new File(resourceDir), seed); else { if (updateFile == null) parameterPool = new LocalSPARQLParameterPool(new File( resourceDir), seed); else parameterPool = new LocalSPARQLParameterPool(new File( resourceDir), seed, new File(updateFile)); } System.out.println("done"); if (sparqlEndpoint != null && !multithreading) { if (doSQL) server = new SQLConnection(sparqlEndpoint, timeout, driverClassName); else { if ( sparqlEndpoint.startsWith("jena:") ) server = new LocalConnectionJena(sparqlEndpoint, sparqlUpdateEndpoint, defaultGraph, timeout); else if ( sparqlEndpoint.startsWith("sesame:") ) //server = new LocalConnectionSesame(sparqlEndpoint, defaultGraph, timeout); throw new UnsupportedOperationException("sesame: URLs not supported") ; else server = new SPARQLConnection(sparqlEndpoint, sparqlUpdateEndpoint, defaultGraph, timeout); } } else if (multithreading) { // do nothing } else { printUsageInfos(); System.exit(-1); } TestDriverShutdown tds = new TestDriverShutdown(this); Runtime.getRuntime().addShutdownHook(tds); }
8
public Integer getId() { return this.id; }
0
public static List<Interlocuteur> selectInterlocuteurByIdCommercial(int id) throws SQLException { String query = null; List<Interlocuteur> interlocuteur1 = new ArrayList<Interlocuteur>(); ResultSet resultat; query = "SELECT * from INTERLOCUTEUR where ID_COMMERCIAL = ? order by INTNOM asc "; PreparedStatement pStatement = (PreparedStatement) ConnectionBDD.getInstance().getPreparedStatement(query); pStatement.setInt(1, id); resultat = pStatement.executeQuery(); while (resultat.next()) { //System.out.println(resultat.getString("INTNOM")); Interlocuteur ii = new Interlocuteur(resultat.getInt("ID_INTERLOCUTEUR"),resultat.getInt("ID_COMMERCIAL"), resultat.getInt("ID_VILLE"), resultat.getInt("ID_SERVICE"), resultat.getString("INTNOM"), resultat.getString("INTPRENOM"), resultat.getString("INTEMAIL")); interlocuteur1.add(ii); } return interlocuteur1; }
1
public void onEnable(){ this.saveDefaultConfig(); log = this.getLogger(); Lang = this.getConfig().getString("language"); if (Lang.equals("en")){ chatname = "Game Server"; }else if(Lang.equals("ja")){ chatname = "ゲームサーバー"; }else{ log.info("[WARNING]" + Lang + " is not supported."); log.info("[WARNING]English(en) or Japanese(ja) Only."); log.info("[WARNING]言語設定" + Lang + "は使用できません"); log.info("[WARNING]英語(en)か日本語(ja)のみ対応しています。"); chatname = "Game Server"; } final String url = this.getConfig().getString("socketchaturl"); final String prefix = this.getConfig().getString("prefix"); final String pass = this.getConfig().getString("socket_pass"); getServer().getPluginManager().registerEvents(this, this); try { socket = new SocketIO(url); socket.connect(new IOCallback() { @Override public void onMessage(JSONObject json, IOAcknowledge ack) { try { } catch (JSONException e) { e.printStackTrace(); } } @Override public void onMessage(String data, IOAcknowledge ack) { } @Override public void onError(SocketIOException socketIOException) { log.info("[WARNING]Socket Error!"); socketIOException.printStackTrace(); } @Override public void onDisconnect() { log.info("[WARNING]SocketChat Disconnect!"); } @Override public void onConnect() { log.info("SocketChat Connect."); } @Override public void on(String event, IOAcknowledge ack, Object... args) { if (event.equals("log")){ final JSONObject jsondata = (JSONObject)args[0]; if (!jsondata.isNull("comment")){ String name = jsondata.getString("name"); if (jsondata.isNull("channel") && !name.equals(chatname)){ String comment = jsondata.getString("comment"); String ip = jsondata.getString("ip"); Bukkit.broadcastMessage(ChatColor.GREEN + "[" + prefix + "]" + ChatColor.WHITE + name + " : " + comment + " (" + ip + ")"); } } } } }); socket.emit("register", new JSONObject().put("mode", "client").put("lastid", 1)); socket.emit("inout", new JSONObject().put("name", chatname).put("pass", pass)); log.info("BukkitSocketChat has been enabled!"); } catch (MalformedURLException e1) { e1.printStackTrace(); log.info("[WARNING]BukkitSocketChat is Error!"); } }
8
protected void setInstancesFromDBaseQuery() { try { if (m_InstanceQuery == null) { m_InstanceQuery = new InstanceQuery(); } String dbaseURL = m_InstanceQuery.getDatabaseURL(); String username = m_InstanceQuery.getUsername(); String passwd = m_InstanceQuery.getPassword(); /*dbaseURL = (String) JOptionPane.showInputDialog(this, "Enter the database URL", "Query Database", JOptionPane.PLAIN_MESSAGE, null, null, dbaseURL);*/ DatabaseConnectionDialog dbd= new DatabaseConnectionDialog(null,dbaseURL,username); dbd.setVisible(true); //if (dbaseURL == null) { if (dbd.getReturnValue()==JOptionPane.CLOSED_OPTION) { m_FromLab.setText("Cancelled"); return; } dbaseURL=dbd.getURL(); username=dbd.getUsername(); passwd=dbd.getPassword(); m_InstanceQuery.setDatabaseURL(dbaseURL); m_InstanceQuery.setUsername(username); m_InstanceQuery.setPassword(passwd); m_InstanceQuery.setDebug(dbd.getDebug()); m_InstanceQuery.connectToDatabase(); if (!m_InstanceQuery.experimentIndexExists()) { System.err.println("not found"); m_FromLab.setText("No experiment index"); m_InstanceQuery.disconnectFromDatabase(); return; } System.err.println("found"); m_FromLab.setText("Getting experiment index"); Instances index = m_InstanceQuery.retrieveInstances("SELECT * FROM " + InstanceQuery.EXP_INDEX_TABLE); if (index.numInstances() == 0) { m_FromLab.setText("No experiments available"); m_InstanceQuery.disconnectFromDatabase(); return; } m_FromLab.setText("Got experiment index"); DefaultListModel lm = new DefaultListModel(); for (int i = 0; i < index.numInstances(); i++) { lm.addElement(index.instance(i).toString()); } JList jl = new JList(lm); jl.setSelectedIndex(0); int result; // display dialog only if there's not just one result! if (jl.getModel().getSize() != 1) { ListSelectorDialog jd = new ListSelectorDialog(null, jl); result = jd.showDialog(); } else { result = ListSelectorDialog.APPROVE_OPTION; } if (result != ListSelectorDialog.APPROVE_OPTION) { m_FromLab.setText("Cancelled"); m_InstanceQuery.disconnectFromDatabase(); return; } Instance selInst = index.instance(jl.getSelectedIndex()); Attribute tableAttr = index.attribute(InstanceQuery.EXP_RESULT_COL); String table = InstanceQuery.EXP_RESULT_PREFIX + selInst.toString(tableAttr); setInstancesFromDatabaseTable(table); } catch (Exception ex) { // 1. print complete stacktrace ex.printStackTrace(); // 2. print message in panel m_FromLab.setText("Problem reading database: '" + ex.getMessage() + "'"); } }
8
public boolean send(Msg msg_, int flags_) { // Drop the message if required. If we are at the end of the message // switch back to non-dropping mode. if (dropping) { more = msg_.has_more(); dropping = more; msg_.close (); return true; } while (active > 0) { if (pipes.get(current).write (msg_)) break; assert (!more); active--; if (current < active) Utils.swap (pipes, current, active); else current = 0; } // If there are no pipes we cannot send the message. if (active == 0) { ZError.errno(ZError.EAGAIN); return false; } // If it's final part of the message we can fluch it downstream and // continue round-robinning (load balance). more = msg_.has_more(); if (!more) { pipes.get(current).flush (); if (active > 1) current = (current + 1) % active; } return true; }
7
private char[] hashPassword(char[] password) throws CharacterCodingException { byte[] bytes = null; char[] result = null; String charSet = getProperty(PARAM_CHARSET); bytes = Utility.convertCharArrayToByteArray(password, charSet); if (md != null) { synchronized (md) { md.reset(); bytes = md.digest(bytes); } } String encoding = getProperty(PARAM_ENCODING); if (HEX.equalsIgnoreCase(encoding)) { result = hexEncode(bytes); } else if (BASE64.equalsIgnoreCase(encoding)) { result = base64Encode(bytes).toCharArray(); } else { // no encoding specified result = Utility.convertByteArrayToCharArray(bytes, charSet); } return result; }
3
public void commonTest() throws IOException { //Map<String, String> keys = new HashMap(); String requestBody; HttpResponse execute; ResponseHandler<String> handler; String response; post.setHeader("address", "192.168.50.174"); post.setHeader("port", "8100"); post.setHeader("command", "addShard"); requestBody = "Adding shard"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); System.out.println("Adding shard: " + response); for (int i = 0; i < 10; i ++){ post.setHeader("key", "key" + i); post.setHeader("value", "value" + i); post.setHeader("command", "add"); requestBody = "Adding value"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); assertEquals(response, "0"); } post.setHeader("command", "clear"); requestBody = "Clear Data Storage"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); assertEquals(response, "0"); post.setHeader("address", "192.168.50.174"); post.setHeader("port", "8200"); post.setHeader("command", "addShard"); requestBody = "Adding shard"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); System.out.println("Adding shard: " + response); for (int i = 0; i < 10; i ++){ post.setHeader("key", "key" + i); post.setHeader("value", "value" + i); post.setHeader("command", "add"); requestBody = "Adding value"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); assertEquals(response, "0"); } post.setHeader("command", "clear"); requestBody = "Clear Data Storage"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); assertEquals(response, "0"); post.setHeader("address", "192.168.50.187"); post.setHeader("port", "8100"); post.setHeader("command", "addShard"); requestBody = "Adding shard"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); System.out.println("Adding shard: " + response); for (int i = 0; i < 10; i ++){ post.setHeader("key", "key" + i); post.setHeader("value", "value" + i); post.setHeader("command", "add"); requestBody = "Adding value"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); assertEquals(response, "0"); } post.setHeader("command", "clear"); requestBody = "Clear Data Storage"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); assertEquals(response, "0"); post.setHeader("address", "192.168.50.187"); post.setHeader("port", "8200"); post.setHeader("command", "addShard"); requestBody = "Adding shard"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); System.out.println("Adding shard: " + response); for (int i = 0; i < 10; i ++){ post.setHeader("key", "key" + i); post.setHeader("value", "value" + i); post.setHeader("command", "add"); requestBody = "Adding value"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); assertEquals(response, "0"); } post.setHeader("command", "clear"); requestBody = "Clear Data Storage"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); handler = new BasicResponseHandler(); response = handler.handleResponse(execute); assertEquals(response, "0"); /*post.setHeader("address", "192.168.50.174"); post.setHeader("port", "8100"); post.setHeader("command", "addShard"); requestBody = "Adding shard"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); Handler = new BasicResponseHandler(); response = Handler.handleResponse(execute); System.out.println("Adding shard: " + response); post.setHeader("address", "192.168.50.174"); post.setHeader("port", "8200"); post.setHeader("command", "addShard"); requestBody = "Adding shard"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); Handler = new BasicResponseHandler(); response = Handler.handleResponse(execute); System.out.println("Adding shard: " + response); post.setHeader("address", "192.168.50.187"); post.setHeader("port", "8100"); post.setHeader("command", "addShard"); requestBody = "Adding shard"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); Handler = new BasicResponseHandler(); response = Handler.handleResponse(execute); System.out.println("Adding shard: " + response); post.setHeader("address", "192.168.50.187"); post.setHeader("port", "8200"); post.setHeader("command", "addShard"); requestBody = "Adding shard"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); Handler = new BasicResponseHandler(); response = Handler.handleResponse(execute); System.out.println("Adding shard: " + response); for (int i = 0; i < 1000; i ++){ String key = UUID.randomUUID().toString(); String value = "val" + i; keys.put(key, value); post.setHeader("key", key); post.setHeader("value", value); post.setHeader("command", "add"); requestBody = "Adding value"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); Handler = new BasicResponseHandler(); response = Handler.handleResponse(execute); assertEquals(response, "0"); } Set <String> keysSet = keys.keySet(); for (String key : keysSet){ post.setHeader("key", key); post.setHeader("value", keys.get(key) + "new"); post.setHeader("command", "edit"); requestBody = "editing value"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); Handler = new BasicResponseHandler(); response = Handler.handleResponse(execute); assertEquals(response, "0"); } for (String key : keysSet){ post.setHeader("key", key); post.setHeader("command", "get"); requestBody = "getting value"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); Handler = new BasicResponseHandler(); response = Handler.handleResponse(execute); assertEquals(response, keys.get(key) + "new"); } for (String key : keysSet){ post.setHeader("key", key); post.setHeader("command", "del"); requestBody = "deleting value"; post.setEntity(new StringEntity(requestBody)); execute = client.execute(httpHost, post); Handler = new BasicResponseHandler(); response = Handler.handleResponse(execute); assertEquals(response, "0"); }*/ }
4
private static CommandLine getCommandLine(String args[]) { HelpFormatter formatter = new HelpFormatter(); Options options = getOptions(args); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Error : " + e.getMessage()); formatter.printHelp("SortCompare", options, true); System.exit(1); } if (cmd.hasOption("h")) { formatter.printHelp("SortCompare", options, true); System.exit(0); } return cmd; }
2
public static ParticipantList getInstance() { return participantList; }
0
@Override public boolean equals(Object obj) { if(obj instanceof Pair) { Pair<?, ?> pair = (Pair<?, ?>) obj; return key.equals(pair.key) && value.equals(pair.value); } return super.equals(obj); }
6
public void render(float delta, SpriteBatch batch) { LevelGenerator.getInstance().generateLevel(this); for(Class cls : renderOrder){ if(cls == Rocket.class) { for (Entity rocket : levelEntities.get(cls)) { if (!isBulletInViewPort(rocket)) { rocket.markDeleted(); bum(rocket.getX(), rocket.getY() - 0.2f); } else { rocket.render(delta, batch); } } } else if (cls == OilField.class){ renderEntities(levelEntities.get(cls), delta, batch); president.render(delta, batch); } else { renderEntities(levelEntities.get(cls), delta, batch); } } for (Class entityClass: levelEntities.keySet()) { Entity temp = clearEntities(entityClass); while (temp != null) { levelEntities.get(entityClass).remove(temp); temp = clearEntities(entityClass); } } }
7
public void setAvalie(PExp node) { if(this._avalie_ != null) { this._avalie_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._avalie_ = node; }
3
private PageSpinner createSpinner() { PageSpinner s = new PageSpinner(); s.setPage(page); if (uid != null) { s.setUid(uid); uid = null; } connect(s); s.setMinimum(minimum); s.setMaximum(maximum); if (stepsize != 0) { s.setStepSize(stepsize); stepsize = 0; } s.setValue(value); s.putClientProperty("value", value); s.setName(changeName); s.setChangable(page.isEditable()); if (titleText != null) { s.setLabel(titleText); titleText = null; } else { s.setLabel(changeName); } if (toolTip != null) { s.setToolTipText(toolTip); toolTip = null; } s.autoSize(); if (disabledAtRun) { s.setDisabledAtRun(disabledAtRun); disabledAtRun = false; } if (disabledAtScript) { s.setDisabledAtScript(disabledAtScript); disabledAtScript = false; } if (script != null) { s.setScript(script); script = null; } changeName = null; return s; }
7
private File getNodeJsExecutableFile() { String nodePath = ""; // Loading the properties for the Runnable objects // Or trying to create them String nodeExecutablePath = properties.getProperty("nodePath"); File nodeExecutable = null; if (nodeExecutablePath != null) { nodeExecutable = new File(nodeExecutablePath); } if (nodeExecutable == null || !nodeExecutable.exists()) { // Trying to find the node.js executable without asking the user nodeExecutable = executableResolver.getFile(); // Last resort // Prompting the user for the executable is not found if(nodeExecutable == null) { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please provide the path to the node.js executable: "); try { nodeExecutable = new File(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } } if (nodeExecutable != null && nodeExecutable.exists()) { nodePath = nodeExecutable.getAbsolutePath(); } else { nodeExecutable = null; } properties.setProperty("nodePath", nodePath); return nodeExecutable; }
7
private void updateFilm(FilmBean film) { try { java.sql.Date date = new java.sql.Date(film.getReturnDate().getTime()); String queryString = "update filme set borowerID = ?, returnDate = '?', " + "renewal = ? where id = ? ;";; PreparedStatement statement = this.db.createStatement(queryString); statement.setInt(1, film.getBorrowerID()); statement.setDate(2, date); statement.setInt(3, film.getRenewals()); statement.setInt(4, film.getId()); statement.executeUpdate(); /* String sql = "update filme set borowerID = "+film.getBorrowerID()+", "+ "returnDate = '" + date.toString()+"', "+ "renewal = " + film.getRenewals() +" where id = "+film.getId()+" ;"; this.db.update(sql); */ } catch (SQLException ex) { Logger.getLogger(FilmothekModel.class.getName()).log(Level.SEVERE, null, ex); } }
1
public static boolean extractFromEmulator(CHREditorModel newModelRef, NES nes){ try { MemoryInterface mem = nes._memoryManager; // copy the nametable int len = newModelRef.getCHRModel().nameTableIndexes[0].length; byte nt[] = new byte[len]; for(int i=0;i<len;i++){ nt[i] = mem.getCHRMemory(0x2000 + i); } System.arraycopy(nt, 0, newModelRef.getCHRModel().nameTableIndexes[0],0,len); // copy the oam len = newModelRef.getCHRModel().oamValues[0].length; byte oam[] = new byte[len]; for(int i=0;i<len;i++){ oam[i] = mem.getCHRMemory(0x2400-len + i); } System.arraycopy(oam,0,newModelRef.getCHRModel().oamValues[0],0,len); // copy the palettes len = newModelRef.getCHRModel().imagePalette.length; byte pal[] = new byte[len]; for(int i=0;i<len;i++){ pal[i] = mem.getCHRMemory(0x3F00 + i); } System.arraycopy(pal, 0, newModelRef.getCHRModel().imagePalette,0,len); len = newModelRef.getCHRModel().spritePalette.length; pal = new byte[len]; for(int i=0;i<len;i++){ pal[i] = mem.getCHRMemory(0x3F10 + i); } System.arraycopy(pal, 0, newModelRef.getCHRModel().spritePalette,0,len); byte ctrlByte = nes._ppu.getPPUCTRLDirect(); boolean switchTiles = ((ctrlByte & 0x10) == 0x10); // copy the tiles len = newModelRef.getCHRModel().patternTable[0].length; byte tiles[] = new byte[len]; for(int i=0;i<len;i++){ tiles[i] = mem.getCHRMemory(0x0000 + i); } if(switchTiles) System.arraycopy(tiles,0,newModelRef.getCHRModel().patternTable[1],0,len); else System.arraycopy(tiles,0,newModelRef.getCHRModel().patternTable[0],0,len); len = newModelRef.getCHRModel().patternTable[1].length; tiles = new byte[len]; for(int i=0;i<len;i++){ tiles[i] = mem.getCHRMemory(0x1000 + i); } if(switchTiles) System.arraycopy(tiles,0,newModelRef.getCHRModel().patternTable[0],0,len); else System.arraycopy(tiles,0,newModelRef.getCHRModel().patternTable[1],0,len); } catch(Exception ex){ ex.printStackTrace(); } return true; }
9
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String tarefa = request.getParameter("tarefa"); if(tarefa == null) throw new IllegalArgumentException("Você esqueceu de passar a tarefa"); try{ String nomeDaClasse = "br.com.alura.gerenciador.web." + tarefa; Class<?> type = Class.forName(nomeDaClasse); Tarefa instancia = (Tarefa) type.newInstance(); String pagina = instancia.adiciona(request, response); request.getRequestDispatcher(pagina).forward(request, response); }catch(ServletException | ClassNotFoundException | InstantiationException | IllegalAccessException e){ throw new ServletException(e); } }
3
public String translate(Object o) { if (o == null) { return "null"; } Class objectClass = o.getClass(); if (objectClass.isArray() || o instanceof Object[]) { return translators.get(Object[].class).translate(o); } else { Translator lowestTranslator = null; System.out.println("Looking for best translator..."); while(lowestTranslator == null) { System.out.println("Checking " + objectClass); if(translators.containsKey(objectClass)) { lowestTranslator = translators.get(objectClass); System.out.println("lowestTranslator = " + lowestTranslator); } else { objectClass = objectClass.getSuperclass(); } } return lowestTranslator.translate(o); } }
5
private String processInput(String xmlString) { String requestType; //parse XML into DOM tree //getting parsers is longwinded but straightforward try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); //once you have parse just call parse. to parse a string vs. //a File requires using an InputSource. In any case result is //a DOM tree -- ie an instance of org.w3c.dom.Document Document document = builder.parse(new InputSource(new StringReader(xmlString))); //must invoke XML validator here from java. It is a major advantage //of using XML //assuming validated we continue to parse the data ... //always start by getting root element Element root = document.getDocumentElement(); //get the value of the id attribute requestType = root.getAttribute("type"); if (requestType.equalsIgnoreCase("move")) { String moveLocation; String player; Element locElement = (Element) document.getElementsByTagName("location").item(0); Element playerElement = (Element) document.getElementsByTagName("player").item(0); moveLocation = locElement.getFirstChild().getNodeValue(); player = playerElement.getFirstChild().getNodeValue(); //return moveLocation+" "+player; int moveInt = Integer.parseInt(moveLocation); boolean result = board.makeMove(moveInt, player); return marshalUpdate(board, result); } else if(requestType.equalsIgnoreCase("connect")) { return marshallConnect(); } else return null; } catch (Exception e) { System.out.print(e); return null; } }
3
protected void hudAreaText(HUDArea ha, String t) { if (ha.isInside(registry.getMousePosition()) && !t.isEmpty()) { registry.setStatusText(t); } }
2
@Override public String toString() { return "Fossils found!" + super.toString() + " Fossil=" + this.fossil + " SeenFossil=" + this.seenFossil; }
0
public static double calcArctg(double argument, double accuracy) { if (isNaN(argument) || isNaN(accuracy) || isInfinite(accuracy)) { return NaN; } if (isInfinite(argument)) { return (argument < 0) ? -PI / 2 : PI / 2; } if (abs(argument) >= 1) { return NaN; } final double sqrArg = pow(argument, 2); double prev = 0.0; double cur = argument; double numerator = argument; double result = argument; int i = 1; do { prev = cur; numerator *= sqrArg; cur = pow(-1, i) * numerator / ((i * 2) + 1); i++; result += cur; } while (abs(prev - cur) > accuracy && i < MAX_ITERATIONS); return result; }
8
public static void main(final 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(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GameFrame.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 GameFrame(args).setVisible(true); } }); }
6
public void draw(Graphics g){ int x = getX(); int y = getY(); int w = getW(); int h = getH(); if(w < 0){ x +=w; w *= -1; } if(h < 0){ y +=h; h *= -1; } Graphics2D g2 = (Graphics2D) g; if(getLinePattern()) g2.setStroke(new MyDashStroke(getLineWidth())); else g2.setStroke(new BasicStroke(getLineWidth())); if(getShadow()){ g2.setColor(Color.black); g2.fillOval(x+4, y+4, w, h); g2.setColor(Color.black); g2.drawOval(x+4, y+4, w, h); } g2.setColor(getFillColor()); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) getAlfa())); g2.fillOval(x, y, w, h); g2.setColor(getLineColor()); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) getAlfa())); g2.drawOval(x, y, w, h); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) 1)); super.draw(g2); }
4
* @param winner The <code>Unit</code> that looting. * @param loserId The id of the <code>Unit</code> that is looted. * @param loot The <code>Goods</code> to loot. * @return An <code>Element</code> encapsulating this action. */ public Element lootCargo(ServerPlayer serverPlayer, Unit winner, String loserId, List<Goods> loot) { LootSession session = TransactionSession.lookup(LootSession.class, winner.getId(), loserId); if (session == null) { return DOMMessage.clientError("Bogus looting!"); } if (!winner.hasSpaceLeft()) { return DOMMessage.clientError("No space to loot to: " + winner.getId()); } ChangeSet cs = new ChangeSet(); List<Goods> available = session.getCapture(); if (loot == null) { // Initial inquiry cs.add(See.only(serverPlayer), ChangePriority.CHANGE_LATE, new LootCargoMessage(winner, loserId, available)); } else { for (Goods g : loot) { if (!available.contains(g)) { return DOMMessage.clientError("Invalid loot: " + g.toString()); } available.remove(g); if (!winner.canAdd(g)) { return DOMMessage.clientError("Loot failed: " + g.toString()); } winner.add(g); } // Others can see cargo capacity change. session.complete(cs); cs.add(See.perhaps(), winner); sendToOthers(serverPlayer, cs); } return cs.build(serverPlayer); }
6
public boolean getFocused() { return focused; }
0
public synchronized boolean remover(int i) { try { new PesquisadorDAO().remover(list.get(i)); list = new PesquisadorDAO().listar(""); preencherTabela(); } catch (Exception e) { return false; } return true; }
1
static double[][] minor(double[][] A, int i, int j){ double[][] minor = new double[A.length-1][A.length-1]; int n = 0, m = 0; for(int k = 0; k < A.length; k++){ if(k == i) continue; for(int l = 0; l < A.length; l++){ if(l == j) continue; minor[n][m] = A[k][l]; m++; } n++; m = 0; } return minor; }
4
public Level(){ for(int x=0;x<SIZE;x++){ for(int y=0;y<SIZE;y++){ world[x][y] = TileType.STONE; } } System.out.println("Generating World..."); for(int i=0;i<rand.nextInt(SIZE/2);i++){ generateMineshaft(rand.nextInt(SIZE),rand.nextInt(SIZE)); } for(int i=0;i<rand.nextInt(SIZE)+10;i++){ generateCave(rand.nextInt(SIZE),rand.nextInt(SIZE)); } for(int i=0;i<rand.nextInt(SIZE);i++){ generateOres(rand.nextInt(SIZE),rand.nextInt(SIZE)); } generateTemple(rand.nextInt(SIZE-25),rand.nextInt(SIZE-25)); System.out.println("World Generated. Populating the world..."); populate(); setTileDamage(); p = new entity.Player(this); System.out.println("Population Complete. Level Generated."); }
5
@Override public void actionPerformed(ActionEvent e) { (Outliner.findReplace).show(); }
0
public CommandCwreload(CreeperWarningMain plugin) { this.plugin = plugin; }
0
private Node moveRedRight(Node h) { assert (h != null); assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); // flipColors(h); } return h; }
3
public Invoker(Object target) { invokeTarget = target; targetClass = (invokeTarget instanceof Class) ? (Class) invokeTarget : invokeTarget.getClass(); }
1
@Override public List<Ability> domainAbilities(final MOB M, final int domain) { final Vector<Ability> V=new Vector<Ability>(1); if(M!=null) { if(domain>Ability.ALL_ACODES) { for(final Enumeration<Ability> a=M.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null)&&((A.classificationCode()&Ability.ALL_DOMAINS)==domain)) { V.addElement(A); } } } else for(final Enumeration<Ability> a=M.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null)&&((A.classificationCode()&Ability.ALL_ACODES)==domain)) { V.addElement(A); } } } return V; }
8
public void RecibirArchivos() throws IOException{ int FILE_SIZE = 6022386; int bytesRead; int current = 0; FileOutputStream fos = null; BufferedOutputStream bos = null; Socket sock = null; try { sock = new Socket("localhost", 13267); System.out.println("Connecting..."); // receive file byte [] mybytearray = new byte [FILE_SIZE]; InputStream is = sock.getInputStream(); fos = new FileOutputStream("retornado.jpg"); bos = new BufferedOutputStream(fos); bytesRead = is.read(mybytearray,0,mybytearray.length); current = bytesRead; do { bytesRead = is.read(mybytearray, current, (mybytearray.length-current)); if(bytesRead >= 0) current += bytesRead; } while(bytesRead > -1); bos.write(mybytearray, 0 , current); bos.flush(); System.out.println("Files " + " downloaded (" + current + " bytes read)"); } finally { if (fos != null) fos.close(); if (bos != null) bos.close(); if (sock != null) sock.close(); } }
5
private Status.StoredFieldStatus testStoredFields(SegmentInfo info, SegmentReader reader, NumberFormat format) { final Status.StoredFieldStatus status = new Status.StoredFieldStatus(); try { if (infoStream != null) { infoStream.print(" test: stored fields......."); } // Scan stored fields for all documents for (int j = 0; j < info.docCount; ++j) { if (!reader.isDeleted(j)) { status.docCount++; Document doc = reader.document(j); status.totFields += doc.getFields().size(); } } // Validate docCount if (status.docCount != reader.numDocs()) { throw new RuntimeException("docCount=" + status.docCount + " but saw " + status.docCount + " undeleted docs"); } msg("OK [" + status.totFields + " total field count; avg " + format.format((((float) status.totFields)/status.docCount)) + " fields per doc]"); } catch (Throwable e) { msg("ERROR [" + String.valueOf(e.getMessage()) + "]"); status.error = e; if (infoStream != null) { e.printStackTrace(infoStream); } } return status; }
6
public static int rowMaxElem(double[][] a, int k) { int max = k; for (int i = k + 1; i < a.length; i++) { if (Math.abs(a[i][k]) > Math.abs(a[max][k])) max = i; } if (a[max][k] == 0) return -1; return max; }
3
private void btnSelecionaBancoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionaBancoActionPerformed JFileChooser flc = new JFileChooser(); flc.setMultiSelectionEnabled(false); flc.setFileFilter(new FileNameExtensionFilter("Banco de Dados \".gdb\" e \".fdb\"", new String[]{"gdb", "fdb"})); flc.setDialogTitle("Selecionar Banco de Dados"); boolean stop = false; while (stop != true) { if (flc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { if (!flc.getSelectedFile().getName().toLowerCase().endsWith(".gdb") && !flc.getSelectedFile().getName().toLowerCase().endsWith(".fdb")) { JOptionPane.showMessageDialog(null, "Arquivo não suportado!"); } else { txtCaminhoBanco.setText(flc.getSelectedFile().getAbsolutePath()); stop = true; } } else { stop = true; } } }//GEN-LAST:event_btnSelecionaBancoActionPerformed
4
public int[] getPoints(){ return points; }
0
@Override public boolean onCommand(CommandSender cs, Command cmd, String string, String[] args) { if (string.equalsIgnoreCase("SetLeapStick")) { if (cs.isOp() || cs.hasPermission("explosionman.SetLeapStick")) { if (args.length == 0) { cs.sendMessage(ChatColor.RED + "The proper usage is " + ChatColor.AQUA + "/SetLeapStick [id]"); } else if (args.length == 1) { try { Integer.parseInt(args[0]); } catch (NumberFormatException c) { cs.sendMessage(ChatColor.RED + "The proper usage is " + ChatColor.AQUA + "/SetLeapStick [id]"); return false; } MainClass.getConfig().set("leapstickid", Integer.parseInt(args[0])); MainClass.saveConfig(); cs.sendMessage(ChatColor.GOLD + "SET!"); } else if (args.length > 1) { cs.sendMessage(ChatColor.RED + "The proper usage is " + ChatColor.AQUA + "/SetLeapStick [id]"); } } else { cs.sendMessage(ChatColor.RED + "You do not have permission to use this command!"); } } return false; }
7
@Override public Object call() throws Exception { Thread.sleep(5000); totalMoney = new Integer(new Random().nextInt(10000)); System.out.println("您当前有" + totalMoney + "在您的私有账户中"); return totalMoney; }
0
private ActionListener research (final int i) { return new ActionListener() { public void actionPerformed (ActionEvent e) { if (researchupgrading.length() != 0) { JOptionPane.showMessageDialog(null, "You can only research one research at a time", "ERROR", JOptionPane.ERROR_MESSAGE); return; } if (i == 0 && checkresources(0, 0, 0, 0, 7 * (rml + 1))) { researchupgrading = "alloys"; researchingseconds = 65 * (rml + 1); gold -= 7 * (rml + 1); } else if (i == 1 && checkresources(0, 0, 0, 0, 5 * (rfl + 1))) { researchupgrading = "agriculture"; researchingseconds = 55 * (rfl + 1); gold -= 5 * (rfl + 1); } else if (i == 2 && checkresources(0, 0, 0, 0, 5 * (rql + 1))) { researchupgrading = "masonry"; researchingseconds = 55 * (rql + 1); gold -= 5 * (rql + 1); } else if (i == 3 && checkresources(0, 0, 0, 0, 3 * (rwl + 1))) { researchupgrading = "woodcraft"; researchingseconds = 45 * (rql + 1); gold -= 3 * (rwl + 1); } else return; researching = true; } }; }
9
@Override public void documentAdded(DocumentRepositoryEvent e) {}
0
public static String getURL(Object object) { String url = (String) HELP_MAP.get(object); if (url != null) return url; Class c = object instanceof Class ? (Class) object : object.getClass(); while (c != null) { url = (String) HELP_MAP.get(c); if (url != null) return url; url = "/DOCS/" + c.getName() + ".html"; if (c.getResource(url) != null) return url; c = c.getSuperclass(); } return null; }
5
public void pokazPracownikow() { try { ResultSet lista = zapytanie.executeQuery("SELECT * FROM pracownicy"); while (lista.next()) { System.out.println(LINIA); System.out.println("Id : " + lista.getInt("id_pracownika")); System.out.println("Imię : " + lista.getString("imie")); System.out.println("Nazwisko : " + lista.getString("nazwisko")); System.out.println("Wynagrodzenie : " + lista.getString("pensja")); System.out.println("Stanowisko : " + lista.getString("stanowisko")); System.out.println("Telefon : " + lista.getString("telefon")); if (lista.getString("stanowisko").equalsIgnoreCase("Dyrektor")) { System.out.println("Dodatek służbowy : " + lista.getString("dodatek")); System.out.println("Karta służbowa : " + lista.getString("karta_nr")); System.out.println("Limit kosztów : " + lista.getString("limit")); } else { System.out.println("Prowizja % : " + lista.getString("prowizja")); System.out.println("Limit prowizji : " + lista.getString("limit")); } System.out.println(LINIA); System.out.println("[Enter] - dalej"); System.out.println("[Q] - porzuć"); Scanner odczyt = new Scanner(System.in); String wybor = odczyt.nextLine(); System.out.println(wybor); while (!(wybor.equalsIgnoreCase("Q")) && !(wybor.equals(""))) { wybor = odczyt.nextLine(); } if (wybor.equalsIgnoreCase("Q")) { break; } } } catch (Exception e) { e.printStackTrace(); } }
6
public boolean equals(Object p_other) { boolean l_bRetVal = false; if ( p_other == null ) { l_bRetVal = false; } else if ( this == p_other ) { l_bRetVal = true; } else { ExecutionFilter l_theOther = (ExecutionFilter)p_other; l_bRetVal = (m_clientId == l_theOther.m_clientId && m_acctCode.equalsIgnoreCase( l_theOther.m_acctCode) && m_time.equalsIgnoreCase( l_theOther.m_time) && m_symbol.equalsIgnoreCase( l_theOther.m_symbol) && m_secType.equalsIgnoreCase( l_theOther.m_secType) && m_exchange.equalsIgnoreCase( l_theOther.m_exchange) && m_side.equalsIgnoreCase( l_theOther.m_side) ); } return l_bRetVal; }
8
public static void filledRectangle(double x, double y, double halfWidth, double halfHeight) { if (halfWidth < 0) throw new RuntimeException("half width can't be negative"); if (halfHeight < 0) throw new RuntimeException("half height can't be negative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*halfWidth); double hs = factorY(2*halfHeight); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); }
4
public String getCommand(int x) { String y; if (x == 1) { y = "attack"; } else if (x == 2) { y = "defend"; } else if (x == 3) { y = "cure"; } else if (x == 4) { y = "protect"; } else if (x == 5) { y = "reflect"; } else if (x == 6) { y = "rise"; } else if (x == 7) { y = "berserk"; } else { y = ""; } return y; }
7
public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Please provide a Bronto API token."); System.exit(0); } String token = args[0]; BrontoApiAsync client = new BrontoClientAsync(token, Executors.newCachedThreadPool()); String sessionId = client.login(); System.out.println("Successful login: " + sessionId); final MailListOperationsAsync listOps = new MailListOperationsAsync(client); ContactOperationsAsync contactOps = new ContactOperationsAsync(client); ObjectOperationsAsync<FieldObject> fieldOps = client.transportAsync(FieldObject.class); ObjectOperationsAsync<DeliveryObject> deliveryOps = client.transportAsync(DeliveryObject.class); ObjectOperationsAsync<HeaderFooterObject> headerFooterOps = client.transportAsync(HeaderFooterObject.class); ContactReadRequest activeContacts = new ContactReadRequest() .withIncludeLists(true) .withStatus(ContactStatus.ONBOARDING) .withEmail(FilterOperator.STARTS_WITH, "philip"); System.out.println("Reading active contacts"); contactOps.read(activeContacts, new CompletionHandler<ContactObject>(contactOps, activeContacts) { @Override public void readObjects(List<ContactObject> contacts) { for (ContactObject contact : contacts) { System.out.println(String.format("Contact %s: %s", contact.getId(), contact.getEmail())); for (String listId : contact.getListIds()) { System.out.println("\tList id: " + listId); } } } }); MailListReadRequest listRead = new MailListReadRequest(); System.out.println("Reading lists"); listOps.read(listRead, new CompletionHandler<MailListObject>(listOps, listRead) { @Override public void readObjects(List<MailListObject> lists) { for (MailListObject list : lists) { System.out.println(String.format("MailList %s: %s", list.getId(), list.getName())); } } }); FieldReadRequest fieldRead = new FieldReadRequest(); System.out.println("Reading fields"); fieldOps.read(fieldRead, new CompletionHandler<FieldObject>(fieldOps, fieldRead) { @Override public void readObjects(List<FieldObject> fields) { for (FieldObject field : fields) { System.out.println(String.format("Field %s: %s (%s)", field.getId(), field.getLabel(), field.getType())); } } }); DeliveryReadRequest deliveries = new DeliveryReadRequest() .withStatus(DeliveryStatus.SENT) .withDeliveryType(DeliveryType.NORMAL) .withIncludeRecipients(true); System.out.println("Reading sent bulk deliveries"); for (DeliveryObject delivery : deliveryOps.readAll(deliveries)) { System.out.println(String.format("Delivery %s: status %s went to:", delivery.getId(), delivery.getStatus())); for (DeliveryRecipientObject recipient : delivery.getRecipients()) { System.out.println(String.format("\t%s: %s", recipient.getId(), recipient.getType())); } } SOAPFault fault = SOAPFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createFault(); fault.setFaultString("Client received SOAP Fault from server: 246: This is my message"); SOAPFaultException exception = new SOAPFaultException(fault); BrontoClientException bce = new BrontoClientException(exception); System.out.println("BrontoClientException code is " + bce.getCode()); RetryLimitExceededException ree = new RetryLimitExceededException(bce); System.out.println("RetryLimitExceededException code is " + ree.getCode()); HeaderFooterReadRequest headerFooters = new HeaderFooterReadRequest().withIncludeContent(true); for (HeaderFooterObject headerFooter : headerFooterOps.readAll(headerFooters)) { System.out.println(String.format("Header/Footer %s (name: %s): " + "html:\n\t%s\ntext:\n\t%s\tHeader? - %b", headerFooter.getId(), headerFooter.getName(), headerFooter.getHtml(), headerFooter.getText(), headerFooter.isIsHeader())); } BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); if (reader.readLine() != null) { client.shutdown(); } }
9
public String getLowOrHighDate(String dateone, String datetwo, boolean highestDate) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = sdf.parse(dateone); Date date2 = sdf.parse(datetwo); if (date1.compareTo(date2) > 0) { if (!highestDate) { return datetwo; } else { return dateone; } } else if (date1.compareTo(date2) < 0) { if (highestDate) { return datetwo; } else { return dateone; } } else if (date1.compareTo(date2) == 0) { return dateone; } } catch (ParseException ex) { ex.printStackTrace(); } return dateone; }
6
public int sumNumbers(TreeNode root) { int sum = 0; if (root == null) return sum; Stack<TreeNode> sta = new Stack<TreeNode>(); // sta.push(root); TreeNode p = root; while (p != null || !sta.empty()) { while (p != null) { sta.push(p); p = p.left; } if (!sta.empty()) { p = sta.pop(); p=p.right; if(p==null) { int temp = 0; TreeNode t; for(TreeNode node:sta){ temp=temp*10+node.val; } sum += temp; // read stack and //sta.pop(); // stack pop() } } } return sum; }
7
public void actionPerformed(ActionEvent e) { if(e.getSource()==start) { stopflag=false; t=new Thread(this); t.start(); } else if(e.getSource()==stop) { stopflag=true; t=null; } }
2
public Bee(String name, Block[] rects, float x, float y) { this.beename = name; this.x = x; this.y = y; map = rects; try { bsprite = new SpriteSheet("src/Assets/beesheet.png", 128, 128); } catch (SlickException e) { e.printStackTrace(); } try { bsprite2 = new SpriteSheet("src/Assets/beesheet2.png", 128, 128); } catch (SlickException e) { e.printStackTrace(); } beeRight = new Animation(bsprite, 100); beeLeft = new Animation(bsprite2, 100); beeBoundingRect = new Rectangle(x,y, 128, 128); beeHitBox = new Rectangle(x,y,128,128); }
2
private Formatter initializeFormatter() { Formatter formatter; String format = this.configuration.getMessageFormat(); String separator = this.configuration.getMessageSeparator(); if (separator != null) { formatter = new SimpleFormatter(format, DISTANCE_CALLER_GIVE_FORMAT, separator); } else { formatter = new SimpleFormatter(format, DISTANCE_CALLER_GIVE_FORMAT); } return formatter; }
1
public void clear( final long fromIndex, final long toIndex ) { if ( fromIndex >= toIndex ) return; final long fromPos = getSetIndex( fromIndex ); final long toPos = getSetIndex( toIndex ); //remove all maps in the middle for ( long i = fromPos + 1; i < toPos; ++i ) m_sets.remove( i ); //clean two corner sets manually final BitSet fromSet = m_sets.get( fromPos ); final BitSet toSet = m_sets.get( toPos ); ///are both ends in the same subset? if ( fromSet != null && fromSet == toSet ) { fromSet.clear( getPos( fromIndex ), getPos( toIndex ) ); return; } //clean left subset from left index to the end if ( fromSet != null ) fromSet.clear( getPos( fromIndex ), fromSet.length() ); //clean right subset from 0 to given index. Note that both checks are independent if ( toSet != null ) toSet.clear( 0, getPos( toIndex ) ); }
6