text
stringlengths
14
410k
label
int32
0
9
private String readFromFile() { /**This Method Reads from a specific file **/ String sourceContents = ""; try { URL fileLoc = new URL("http://www.digitalworlddevelopment.com/Java/content.txt"); String host=fileLoc.getHost(); URI fileName = fileLoc.toURI(); String Path = fileName.getPath(); System.out.println("host: "+host); System.out.println("Path: "+Path); /* PlainTextInputStream fileStream = (PlainTextInputStream) fileLoc.getContent(); BufferedReader dis = new BufferedReader(new InputStreamReader(fileStream)); ArrayList list = new ArrayList(); while(dis.read()>0){ String line = dis.readLine(); line += " \n"; sourceContents+= line; }//end while dis.close(); fileStream.close();*/ //fileStream.sourceContents = new String(); //sourceContents = (String) fileContents; //String inputFileName = fileLoc.openStream(); //Code to read from file File inputFile = new File(host+Path); FileInputStream in = new FileInputStream(inputFile); //InputStream in = fileLoc.openStream(); byte bt[] = new byte[(int)inputFile.length()]; in.read(bt); sourceContents = new String(bt); in.close(); } catch (java.io.IOException e) { JOptionPane.showMessageDialog(jScrollPaneText, "Error: " + e, "Applet Error", JOptionPane.ERROR_MESSAGE); } catch (URISyntaxException ex){ JOptionPane.showMessageDialog(jScrollPaneText, "Error: " + ex, "Applet Error", JOptionPane.ERROR_MESSAGE); } return sourceContents; }
2
public fightermakerView(SingleFrameApplication app) { super(app); current_move=null; current_frame=null; current_hitbox=null; red_hitboxes=new ArrayList<Hitbox>(); blue_hitboxes=new ArrayList<Hitbox>(); listOfMoves_main_file=null; listOfMoves_hitboxes_file=null; hitbox_color_selected=""; hitbox_index_selected=-1; frame_index_selected=-1; click_target_point="1"; click_target_flag=false; frame_title = "Rosalila engine hitboxes editor"; main_frame = new JFrame(frame_title); current_point_color = new Color(23,114,0); this.setFrame(main_frame); //bad code to remove warning java.util.logging.Logger logger = java.util.logging.Logger.getLogger(org.jdesktop.application.SessionStorage.class.getName()); logger.setLevel(java.util.logging.Level.OFF); initComponents(); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { busyIconIndex = 0; busyIconTimer.start(); } } else if ("done".equals(propertyName)) { busyIconTimer.stop(); } else if ("message".equals(propertyName)) { String text = (String)(evt.getNewValue()); messageTimer.restart(); } else if ("progress".equals(propertyName)) { } } }); JFrame mainFrame = fightermaker.getApplication().getMainFrame(); mainFrame.setTitle("Buurn baby!"); label_x1.setForeground(current_point_color); label_y1.setForeground(current_point_color); }
6
public int serve(HTTPServer.Request req, HTTPServer.Response resp) throws IOException { synchronized (mApp) { // Only allow one thread to touch app at a time. mApp.setRequest(new WikiRequest(req, mContainerPrefix)); try { WikiContext context = mApp.getContext(); if (req.getMethod().equals("POST")) { // Require form password for all posts, like toadlet framework. context.checkFormPassword(); } ChildContainerResult appResult = mApp.handle(context); // NOTE: We don't have to worry about the meta refresh here. // That is done for us in by HtmlResultFactory. resp.sendHeaders(200, appResult.getData().length, 0, // Send current date for Last-Modified header. null, // Don't send Etag header. appResult.getMimeType(), null /* No range. i.e. send everything. */); OutputStream body = resp.getBody(); try { body.write(appResult.getData()); } finally { body.close(); } return 0; } catch(AccessDeniedException accessDenied) { resp.sendError(403, accessDenied.getMessage()); return 0; } catch(NotFoundException notFound) { resp.sendError(404, notFound.getMessage()); return 0; } catch(RedirectException redirected) { resp.redirect(redirected.getLocation(), false); return 0; } catch(DownloadException forceDownload) { try { resp.getHeaders().add("Content-disposition", String.format("attachment; filename=%s", forceDownload.mFilename)); resp.sendHeaders(200, forceDownload.mData.length, -1, null, forceDownload.mMimeType, null); OutputStream body = resp.getBody(); if (body == null) { return 0; // hmmm... getBody() can return null. } try { body.write(forceDownload.mData); } finally { body.close(); } return 0; } catch (IOException ioe) { // Totally hosed. We already sent the headers so we can't send a response. ioe.printStackTrace(); return 0; } } catch(ChildContainerException serverError) { // This also handles ServerErrorException. resp.sendError(500, serverError.getMessage()); return 0; } } }
8
private void animateTexture(int textureId) { if (!lowMemory) { if (Rasterizer.textureLastUsed[17] >= textureId) { Background background = Rasterizer.textureImages[17]; int area = background.imageWidth * background.imageHeight - 1; int difference = background.imageWidth * animationTimePassed * 2; byte originalPixels[] = background.imagePixels; byte shiftedPixels[] = animatedPixels; for (int pixel = 0; pixel <= area; pixel++) shiftedPixels[pixel] = originalPixels[pixel - difference & area]; background.imagePixels = shiftedPixels; animatedPixels = originalPixels; Rasterizer.resetTexture(17); } if (Rasterizer.textureLastUsed[24] >= textureId) { Background background = Rasterizer.textureImages[24]; int area = background.imageWidth * background.imageHeight - 1; int difference = background.imageWidth * animationTimePassed * 2; byte originalPixels[] = background.imagePixels; byte shiftedPixels[] = animatedPixels; for (int pixel = 0; pixel <= area; pixel++) shiftedPixels[pixel] = originalPixels[pixel - difference & area]; background.imagePixels = shiftedPixels; animatedPixels = originalPixels; Rasterizer.resetTexture(24); } if (Rasterizer.textureLastUsed[34] >= textureId) { Background background = Rasterizer.textureImages[34]; int area = background.imageWidth * background.imageHeight - 1; int difference = background.imageWidth * animationTimePassed * 2; byte originalPixels[] = background.imagePixels; byte shiftedPixels[] = animatedPixels; for (int pixel = 0; pixel <= area; pixel++) shiftedPixels[pixel] = originalPixels[pixel - difference & area]; background.imagePixels = shiftedPixels; animatedPixels = originalPixels; Rasterizer.resetTexture(34); } } }
7
public void encode_file(String filename)throws FileNotFoundException, IOException { //C:\Users\Manu\Desktop\Workspace\IntelliJ\HuffmanCoding\src\test.txt //System.out.print("Enter the filepath: "); BufferedReader br= new BufferedReader(new FileReader(filename)); String line; while((line=br.readLine())!=null) input_string+=line; //ip_size=input_string.length()*2; int freq[] = new int[X]; pq=null; for(int i=0;i<input_string.length();i++) freq[input_string.charAt(i)]++; for(int i=0;i<X;i++) if(freq[i]>0) insert(new Pnode((char) i,freq[i],null,null)); while(count>1){ Pnode x1=delete(); Pnode x2=delete(); insert(new Pnode('\0',x1.freq + x2.freq,x1,x2)); } root=delete(); table = new String[X]; traverse(root,""); encoded_string = ""; for(int i=0;i<input_string.length();i++) encoded_string+=table[input_string.charAt(i)]; br.close(); }
6
public static ObjectType toFieldSignature(String sig) throws BadBytecode { try { return parseObjectType(sig, new Cursor(), false); } catch (IndexOutOfBoundsException e) { throw error(sig); } }
1
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((affected!=null) &&(affected instanceof MOB) &&(msg.amISource((MOB)affected)) &&(msg.targetMinor()==CMMsg.TYP_DAMAGE)) { final int damageType=Weapon.TYPE_NATURAL; if(msg.sourceMessage()!=null) msg.setSourceMessage(CMLib.combat().replaceDamageTag(msg.sourceMessage(), msg.value(), damageType, CMMsg.View.SOURCE)); if(msg.targetMessage()!=null) msg.setTargetMessage(CMLib.combat().replaceDamageTag(msg.targetMessage(), msg.value(), damageType, CMMsg.View.TARGET)); if(msg.othersMessage()!=null) msg.setOthersMessage(CMLib.combat().replaceDamageTag(msg.othersMessage(), msg.value(), damageType, CMMsg.View.OTHERS)); msg.setValue(0); } return super.okMessage(myHost,msg); }
7
protected void buttonActionPerformed(ActionEvent evt) { for(JTextComponent uiSource: uiSources) { if(uiSource.isFocusOwner()) { String text = uiSource.getText().trim(); JButton button = (JButton) evt.getSource(); String key = button.getText(); if(uiSource instanceof JFormattedTextField && (key.compareTo("9") > 0 || key.compareTo("0") < 0)) { break; } uiSource.setText(text + key); if(uiSource instanceof JFormattedTextField) { try { ((JFormattedTextField) uiSource).commitEdit(); ((JFormattedTextField) uiSource).setValue(((JFormattedTextField) uiSource).getValue()); } catch (ParseException e) { ((JFormattedTextField) uiSource).setValue(0); } } break; } } }
7
public void matchesInterface() { Filter isInterface = isInterface(); assert !isInterface.matches( DummyAnnotation.class ); assert isInterface.matches( Matcher.class ); }
0
@Override public void handleEvent(ERGameEvent e) { switch(e.eventType){ case ERGameEvent.EVENT_MESSAGE: EmptyRoom.logMessage(e.data[0]+": "+e.data[0].toString()); break; case ERGameEvent.EVENT_UPDATE: if(this.objects.containsKey( (e.data[0])) ){ objects.get( (e.data[0]) ).updateFromServer(e); } else{ objects.put( (Integer)(e.data[0]) , GameObject.makeFromEvent(e)); } break; case ERGameEvent.EVENT_DESTROY: objects.remove( (e.data[0]) ); break; case ERGameEvent.EVENT_INTERACT: //TODO event interactions;s break; default: System.err.println("can't parse event "+e.toString()); break; } }
5
void summary(String templateFile, String outputFile, boolean noCommas) { try { // Configure FreeMaker Configuration cfg = new Configuration(); // Specify the data source where the template files come from if (useLocalTemplate) cfg.setDirectoryForTemplateLoading(new File("./templates/")); // Use local 'template' directory else cfg.setClassForTemplateLoading(SnpEffCmdEff.class, "/"); // Use current directory in JAR file cfg.setObjectWrapper(new DefaultObjectWrapper()); // Specify how templates will see the data-model. This is an advanced topic... cfg.setLocale(java.util.Locale.US); if (noCommas) cfg.setNumberFormat("0.######"); // Create the root hash (where data objects are) HashMap<String, Object> root = summaryCreateHash(); // Get the template Template temp = cfg.getTemplate(templateFile); // Process the template Writer out = new OutputStreamWriter(new FileOutputStream(new File(outputFile))); temp.process(root, out); out.flush(); out.close(); } catch (IOException e) { error(e, "Error creating summary: " + e.getMessage()); } catch (TemplateException e) { error(e, "Error creating summary: " + e.getMessage()); } }
4
public static void addItemSomething(Item item){ if(item != null){ if(ItemStorageInventory.create().addItem(item)){ System.out.println("add "+ item.toString() + " successfully\n"); }else{ System.out.println("add "+ item.toString() + " failed\n"); } }else System.out.println("add item " + " failed\n"); }
2
public void setColor(int r, int c, char clr){ if(r >= size || c >= size || r < 0 || c < 0){ System.err.println("Invalid dimentions (" + r + "," + c + ") for size " + size); System.exit(0); } if(clr != '.') puzzle[r][c].color(clr); else puzzle[r][c].uncolor(); }
5
public void InicializaVerticesDoColider() { Colider colider = this.getColider(); getColider().setQuantDePontos(18); for (int i = 0; i < colider.pontos.length; i++) { colider.pontos[i] = new Point(); } colider.pontos[0].x = pos.x + 7; colider.pontos[0].y = pos.y + 30; colider.pontos[1].x = pos.x + 13; colider.pontos[1].y = pos.y + 19; colider.pontos[2].x = pos.x + 23; colider.pontos[2].y = pos.y + 13; colider.pontos[3].x = pos.x + 43; colider.pontos[3].y = pos.y + 11; colider.pontos[4].x = pos.x + 52; colider.pontos[4].y = pos.y + 10; colider.pontos[5].x = pos.x + 59; colider.pontos[5].y = pos.y + 11; colider.pontos[6].x = pos.x + 67; colider.pontos[6].y = pos.y + 12; colider.pontos[7].x = pos.x + 75; colider.pontos[7].y = pos.y + 17; colider.pontos[8].x = pos.x + 87; colider.pontos[8].y = pos.y + 22; colider.pontos[9].x = pos.x + 98; colider.pontos[9].y = pos.y + 43; colider.pontos[10].x = pos.x + 98; colider.pontos[10].y = pos.y + 53; colider.pontos[11].x = pos.x + 92; colider.pontos[11].y = pos.y + 69; colider.pontos[12].x = pos.x + 83; colider.pontos[12].y = pos.y + 81; colider.pontos[13].x = pos.x + 57; colider.pontos[13].y = pos.y + 88; colider.pontos[14].x = pos.x + 47; colider.pontos[14].y = pos.y + 88; colider.pontos[15].x = pos.x + 42; colider.pontos[15].y = pos.y + 87; colider.pontos[16].x = pos.x + 30; colider.pontos[16].y = pos.y + 87; colider.pontos[17].x = pos.x + 7; colider.pontos[17].y = pos.y + 64; for (Point ponto : colider.pontos) { colider.vertices.add(ponto); colider.forma.addPoint(ponto.x, ponto.y); } }
2
public void setColor(Color c) { garisson.setColor(c); if (WorldMap.getLastInstance() != null) { WorldMap.getLastInstance().colorChanged(this, c); } color = c; }
1
public Stat get(StatType s) { return stats.get(s); }
0
@Override public void run() { URLConnection conn = null; try { conn = prepareConnection(); prepareStream(conn); response.setStatus(DownloadResponseImpl.Status.IN_PROGRESS); try (InputStream inputStream = conn.getInputStream()) { byte[] tmpBuf = new byte[TMP_BUF_SIZE]; while (!Thread.currentThread().isInterrupted()) { int len = inputStream.read(tmpBuf); if (len == -1) { response.setStatus(DownloadResponseImpl.Status.FINISHED); break; } response.getStream().write(tmpBuf, 0, len); if (response.checkPaused(supportsRangedDownload(conn))) { // Should release the current thread and connection on pause return; } if (response.getStatus() == DownloadResponseImpl.Status.CANCELLED) { //Clean up already downloaded memory response.setStream(null); return; } } } } catch (IOException | InterruptedException e) { response.setStatus(DownloadResponseImpl.Status.FAILED); } finally { finalizeConnection(conn); } }
5
public Message RetrieveMessage(String value, Filter filter, Order order, boolean delete) throws IOException, QueueInexistentException, ClientInexistentException, UnspecifiedErrorException, InvalidHeaderException { this.sendMessage(new RetrieveMessageRequest(value, filter, order, delete)); ProtocolMessage message = this.getResponse(); if (message.getMessageType() == MessageType.REQUEST_RESPONSE) { RequestResponse rqMessage = (RequestResponse) message; switch (rqMessage.getStatus()) { case NO_MESSAGE: return null; case QUEUE_NOT_EXISTS: if (filter == Filter.QUEUE) throw new QueueInexistentException(value); else throw new UnexpectedResponseException(); case NO_CLIENT: if (filter == Filter.SENDER) throw new ClientInexistentException(value); else throw new UnexpectedResponseException(); case EXCEPTION: throw new UnspecifiedErrorException(); default: throw new UnexpectedResponseException(); } } else { RetrieveMessageResponse response = (RetrieveMessageResponse) message; return new Message(response.getMessageId(), response.getContext(), (byte)response.getPriority(), response.getMessageContent(), response.getSender(), response.getReceiver(), response.getQueue()); } }
7
public static List<Product> sort(List<Product> list) { ComparatorProduct comp = new ComparatorProduct(); Collections.sort(list, comp); return list; // 返回排序后的列表 }
0
public int[] listadoExtracciones() { ArrayList devolver = new ArrayList(); String[] nombre,campos; int[] solucion; campos = new String[]{"id_proyecto","nombre_proyecto"}; devolver = BDextracciones.mostrarDatos("proyecto", campos); solucion = new int[devolver.size()]; for(int i=0;i<devolver.size();i++) { nombre = (String[])devolver.get(i); solucion[i] = Integer.parseInt(nombre[0]); } return solucion; }
1
private void setHeldRsrceType() { switch (this.type) { case PROF_UNEMPLOYED: { this.heldRsrceType = Chunk.RSRCE_NOTHING; break; } case PROF_LUMBERJACK: { this.heldRsrceType = Chunk.RSRCE_WOOD; break; } } }
2
private String search(HttpServletRequest req) { String queryStr = req.getParameter("query"); if (queryStr == null) { queryStr = ""; } String limitStr = req.getParameter("limit"); int limit = 10; if (limitStr != null) { try { limit = Integer.parseInt(limitStr); } catch (NumberFormatException e) { LOG.severe("Failed to parse " + limitStr); } } List<Document> found = new ArrayList<Document>(); String outcome = null; try { // Rather than just using a query we build a search request. // This allows us to specify other attributes, such as the // number of documents to be returned by search. Query query = Query.newBuilder() .setOptions(QueryOptions.newBuilder() .setLimit(limit). // for deployed apps, uncomment the line below to demo snippeting. // This will not work on the dev_appserver. // setFieldsToSnippet("content"). build()) .build(queryStr); LOG.info("Sending query " + query); Results<ScoredDocument> results = INDEX.search(query); for (ScoredDocument scoredDoc : results) { User author = new User( getOnlyField(scoredDoc, "email", "user"), getOnlyField(scoredDoc, "domain", "example.com")); // Rather than presenting the original document to the // user, we build a derived one that holds author's nickname. List<Field> expressions = scoredDoc.getExpressions(); String content = null; if (expressions != null) { for (Field field : expressions) { if ("content".equals(field.getName())) { content = field.getHTML(); break; } } } if (content == null) { content = getOnlyField(scoredDoc, "content", ""); } Document derived = Document.newBuilder() .setId(scoredDoc.getId()) .addField(Field.newBuilder().setName("content").setText(content)) .addField(Field.newBuilder().setName("nickname").setText( author.getNickname())) .addField(Field.newBuilder().setName("published").setDate( scoredDoc.getOnlyField("published").getDate())) .build(); found.add(derived); } } catch (RuntimeException e) { LOG.log(Level.SEVERE, "Search with query '" + queryStr + "' failed", e); outcome = "Search failed due to an error: " + e.getMessage(); } req.setAttribute("found", found); return outcome; }
9
public double addPoint(Point p, double angle, double THRESHOLD2) { if (angle != ConnectedComponent.ANGLE_UNDEFINED) { // test point is not a corner double diff = angleDiff(angle, prevAngle); // if the sign of angle change is reversed if (sign(diff) != dirChange) { // corner detected if (accumChange >= THRESHOLD1) { return angleDiff(angle, approximateAngle()); } // reset cummulated results if (diff != 0) { accumChange = Math.abs(diff); dirChange = sign(diff); } } else { accumChange += Math.abs(diff); if (accumChange >= THRESHOLD2) return angleDiff(angle, approximateAngle()); } prevAngle = angle; } _prevEnd = _end; _end = p; return 0; }
5
public static void main(String[] args) { for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { System.out.print(i*j + " "); } System.out.println(); } }
2
public static void main(String[] args){ /* //Test Helper by creating few player objects Player p1 = Helper.generatePlayer("Canucks"); Player p2 = Helper.generatePlayer("Canucks"); Player p3 = Helper.generatePlayer("Canucks"); Player p4 = Helper.generatePlayer("Canucks"); p1.print(); p2.print(); p3.print(); p4.print(); */ //Test Helper to create an array list of players ArrayList<Player> playersList = new ArrayList<Player>(); for (int i = 0; i < 640; i++){ playersList.add(Helper.generatePlayer("Canucks")); } for (int i = 0; i < 640; i++){ playersList.get(i).print(); } //Test Helper to create a team Team team1 = Helper.generateTeam("Canucks"); team1.print(); Team team2 = Helper.generateTeam("Rangers"); team2.print(); //Now, let us use the array list created ABOVE TO DO SORTING for (int i = 0; i < 640; i++){ playersList.add(Helper.generatePlayer("Canucks")); } //Sort them using first names by insertion sort algorithm for (int currentIndex = 0; currentIndex < 640; currentIndex++){ int requiredIndex = currentIndex; for (int runningIndex = currentIndex; runningIndex < 640; runningIndex++){ if (playersList.get(runningIndex).getFirstName().compareToIgnoreCase(playersList.get(requiredIndex).getFirstName()) < 0){ requiredIndex = runningIndex; } } //Now swap the element at required index with the one at currentIndex Player temp = playersList.get(currentIndex); playersList.set(currentIndex, playersList.get(requiredIndex)); playersList.set(requiredIndex, temp); } for (int i = 0; i < 640; i++){ System.out.println(playersList.get(i).getFirstName() + " " + playersList.get(i).getLastName()); } }
7
@BeforeClass public static void setUpClass() throws Exception { ctx = new AnnotationConfigApplicationContext(ConnectionConfig.class); }
0
@Override public int hashCode() { return x + y; }
0
private void draw() { drawBackground(); drawWorld(); drawPlayer(); }
0
public void testBase64() { String source = "abcdefghijklmnopqrstuvwxyz"; String result = SecurityCoder.base64Encoder(source.getBytes()); byte[] data = SecurityCoder.base64Decoder(result); assertEquals(source, new String(data)); }
0
public static void safeClick(Selenium s, String path, UserSelection type) { if (s.isElementPresent(path)) { s.click(path); if (type.equals(UserSelection.ENDORSING)) { writer.write("Successfully ENDORSING for : " + safeGetText(s, "//*[@id='name']/h1/span/span[1]")); } else { writer.write("Successfuly Click " + safeGetText(s, path)); // writer.write("Successfuly Click Path: "+path); } } else { if (type.equals(UserSelection.ENDORSING)) { writer.write("Nothing to ENDORSING for : " + safeGetText(s, "//*[@id='name']/h1/span/span[1]")); } else { s.refresh(); s.waitForPageToLoad(loadingTimeOut); if (s.isElementPresent(path)) { s.click(path); }else{ writer.write("Error! Path:" + path + " is not found"); } } } }
4
public void render() { float x0 = x + Game.xScroll / 16; float y0 = y + Game.yScroll / 16; float x1 = x + 1 + Game.xScroll / 16; float y1 = y + 1 + Game.yScroll / 16; if (x1 < 0 || y1 < 0 || x0 > Component.width / 16 || y0 > Component.height / 16) return; Texture.tiles.bind(); glBegin(GL_QUADS); Renderer.quadData(x * size, y * size, halfSize, halfSize, color, xo + tileSprite[0], yo + tileSprite[1]); Renderer.quadData(x * size + 8, y * size, halfSize, halfSize, color, xo + tileSprite[2], yo + tileSprite[3]); Renderer.quadData(x * size + 8, y * size + 8, halfSize, halfSize, color, xo + tileSprite[4], yo + tileSprite[5]); Renderer.quadData(x * size, y * size + 8, halfSize, halfSize, color, xo + tileSprite[6], yo + tileSprite[7]); glEnd(); Texture.tiles.unbind(); }
4
public boolean equals(Object other) { if(other == null) { return false; } if(other == this) { return true; } if(!(other instanceof Artist)) { return false; } Artist otherArtist = (Artist)other; return (name.equals(otherArtist.getName())); }
3
public static String convertToJavaIdentifier(String string) { if (string == null || string.isEmpty()) { return new String(); } char[] ca = string.toCharArray(); StringBuilder sb = new StringBuilder(); for (char c : ca) { if (sb.length() == 0) { if (Character.isJavaIdentifierStart(c)) { sb.append(c); } } else { if (Character.isJavaIdentifierPart(c)) { sb.append(c); } } } return (sb.length() == 0 ? "" : ("$" + sb.toString())); }
7
public String getDirectionStr() { String dir = direction.name().toLowerCase(); switch(dir) { case "northwest": dir = "NW"; break; case "north": dir = "N"; break; case "northeast": dir = "NE"; break; case "south": dir = "S"; break; case "southwest": dir = "SW"; break; case "southeast": dir = "SE"; break; } return dir; }
6
public static void display_alll(List<Map<TableArticle, Integer>> list) { for(Map<?,?> m : list){ Entry<?,?> t = m.entrySet().iterator().next(); System.out.println( t.getKey().toString() + "\nx " + t.getValue().toString() ); } }
5
public Complex[] getData1i() { for(int i=0;i<count;i++){ double im = -x[i].im(); x[i].setIm(im); } setData1(x, power); fd1i = getData1(); for(int i=0;i<count;i++){ double re = fd1i[i].re(); double im = -fd1i[i].im(); fd1i[i].setRe(re/count); fd1i[i].setIm(im/count); } return fd1i; }
2
public static void main(String args[]) throws InterruptedException { String importantInfo[] = { "Each thread is assoceated with a instace of Thread.", "Thread can be created by Runnable object.", "Thread can also be created by subclassing the Thead class.", "Creating thread using Runnable is more flexible." }; for (int i = 0; i < importantInfo.length;i++) { //Pause for 4 seconds Thread.sleep(4000); //Print a message System.out.println(i+1+". "+importantInfo[i]); } }
1
public static void connection(String configfile) { ConfigGetDb getconfig = new ConfigGetDb(configfile); String driver = getconfig.driver; String url = getconfig.url; String uesr = getconfig.user; String password = getconfig.password; try { Class.forName(driver); logger.debug("Connection database url :" + url + "User :" + uesr); logger.info("Connection database Start"); conn = DriverManager.getConnection(url, uesr, password); logger.info("Connection database Successed"); } catch (Exception e) { logger.fatal(e); e.printStackTrace(); } }
1
public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; for(int i=0;i<n;i++){ a[i]=in.nextInt(); } int i = 0; while(i<a.length-1 && a[i+1]>=a[i]) i++; if(i==a.length-1){ System.out.println(0); return; } int ans = a.length-1-i; i++; while(i<a.length-1 && a[i+1]>=a[i]) i++; if(i==a.length-1 && a[i]<=a[0]) System.out.println(ans); else System.out.println(-1); }
8
public static void readMatrixBlocks(String path, HamaConfiguration conf, int rows, int cols, int blockSize, int lastI, List<Block> emptyBlocks) { SequenceFile.Reader reader = null; try { FileSystem fs = FileSystem.get(conf); VectorWritable row = new VectorWritable(); IntWritable i = new IntWritable(); for (Block b : emptyBlocks) { int bi = b.getI(); int bj = b.getJ(); reader = new SequenceFile.Reader(fs, new Path(path + bi + "_" + bj+".mat"), conf); while (reader.next(i, row)) { DoubleVector v = row.getVector(); for (int k = 0; k < v.getDimension(); k++) { b.setValue(i.get(), k, v.get(k)); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
6
private byte saveFile(InputStream is, String fullPath, long fileSize, long lastModifiedTime, boolean isDir, String realFileFullPath, TextProcessor textProcessor) throws Exception { byte message = DropboxConstants.NO_FILE_OPERATION; try { String filePath = fullPath.substring(0, fullPath.lastIndexOf(System.getProperty("file.separator"))); File copyFileDir = new File(filePath); File copyFileObj = new File(fullPath); File realFileObj = new File(realFileFullPath); if (isDir && !realFileObj.exists()) { // if this is an empty file dir and does not exist in this side copyFileObj.mkdirs(); copyFileObj.setLastModified(lastModifiedTime); message = DropboxConstants.ADD_DIR; } else { // copyFileDir is it's parent's dir path // ex: file fullpath: /home/chengren/1/2/3/4/5.txt (it's a non-existing file, and dir 1,2,3,4 do not exist either) // file.createNewFile() will report error is some dirs in the file path does not exist, // so here we need it's parentDirPath : /home/chengren/1/2/3/4 // then use mkdir to create this dir. copyFileDir.mkdirs(); copyFileDir.setLastModified(lastModifiedTime); } if(!isDir) { if (!realFileObj.exists()) { message = DropboxConstants.ADD_FILE; copyFileObj.createNewFile(); this.saveStreamDataToDiskFile(lastModifiedTime, fileSize, copyFileObj, textProcessor); } else if (realFileObj.lastModified() != lastModifiedTime) { message = DropboxConstants.UPDATE_FILE; this.saveStreamDataToDiskFile(lastModifiedTime, fileSize, copyFileObj, textProcessor); } else { is.skip(fileSize); } } else { is.skip(fileSize); } } catch (IOException ex) { message = DropboxConstants.FILE_OPERATION_FAIL; Logger.getLogger(DropboxFileTransferProtocolDeserializer.class.getName()).log(Level.SEVERE, null, ex); } return message; }
6
private long getDocCount(File file) { System.out.println("Counting documents in file ..."); long startTime = System.currentTimeMillis(); FileInputStream localFis = null; GZIPInputStream localGis = null; InputStreamReader localReader = null; BufferedReader localBuffer = null; long total = 0; try { localFis = new FileInputStream(file); if (file.getName().endsWith(".gz") || file.getName().endsWith("gzip")) { localGis = new GZIPInputStream(localFis); localReader = new InputStreamReader(localGis); } else { localReader = new InputStreamReader(localFis); } localBuffer = new BufferedReader(localReader); String s; while ((s = localBuffer.readLine()) != null) { total ++; } } catch (IOException ie) { ie.printStackTrace(); } finally { try { if (localBuffer != null) { localBuffer.close(); } if (localReader != null) { localReader.close(); } if (localGis != null) { localGis.close(); } if (localFis != null) { localFis.close(); } } catch (IOException ie) { ie.printStackTrace(); } } System.out.println("Counted " + total + " docs in " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds"); return total; }
9
public String getDataReg() throws SQLException, ClassNotFoundException { String sts = new String(); Connection conPol = conMgr.getConnection("PD"); if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } try { Statement stmt = conPol.createStatement(); String strQl = "SELECT MIN(datareg) AS dt_min, " + "MAX(datareg) as dt_max " + "FROM tb_assistec_rep;"; ResultSet rs = stmt.executeQuery(strQl); Calendar calMin = Calendar.getInstance(); Calendar calMax = Calendar.getInstance(); while (rs.next()) { calMin.setTimeInMillis(rs.getTimestamp("dt_min").getTime()); calMax.setTimeInMillis(rs.getTimestamp("dt_max").getTime()); while (calMax.compareTo(calMin) == 1) { sts = sts + "<option>" + (calMax.get(Calendar.MONTH) + 1) + "/" + calMax.get(Calendar.YEAR) + "</option>"; calMax.add(Calendar.MONTH, -1); } } } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } return sts; }
4
public static void resetIDtoZero(Class<? extends BaseEntity> clazz) { ID_MAP.put(clazz, new AtomicInteger(0)); }
1
public DHCPDetect(){ try { this.localIpAddress = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } serverIdentifier = null; // fill client identifier: HTYPE MACAddress clientIdentifier = new byte[1+LocalMacAddress.length]; clientIdentifier[0] = DHCPConstants.HTYPE_ETHER; for (int i=0; i<LocalMacAddress.length; i++) clientIdentifier[i+1] = LocalMacAddress[i]; }
2
public void setLatitude(double latitude) { this.latitude = latitude; }
0
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
9
public void visitJumpInsn(final int opcode, final Label label) { minSize += 3; if (opcode == GOTO || opcode == JSR) { maxSize += 5; } else { maxSize += 8; } if (mv != null) { mv.visitJumpInsn(opcode, label); } }
3
public void dispose () { try { _disposed = true; _socket.close(); } catch (Exception e) { // Do nothing. } }
1
public void update() { // so it is adding 1 to sAngle only if it hits 0 ant it hits 360 too //if (sAngle > 0 && fill < 270) if (sAngle > one && fill <= FILL) mM = 1; else if(sAngle <= one) mM = -1; // takes -1 to 45 and +2 to fill until 0 and 360 sAngle -= mM; // this keeps it 270; //fill += mM+mM; fill += 2*mM; if((x + xa + 300) < 0) xa = 1; if(x + xa + 320 > game.getWidth() - DIAMETER) xa = -1; if(y + ya + 200 < 0 ) ya = 1; if(y + ya + 230 > game.getHeight() - DIAMETER)ya = -1; //Righ 0 , 270 ,0 // up 90, 270, 90 // left 180, 270, 180 // down 270, 270, 270 x += xa; y += ya; }
7
private boolean isPossibleBlock(int[][] game, int x, int y, int number) { int x1 = x < 3 ? 0 : x < 6 ? 3 : 6; int y1 = y < 3 ? 0 : y < 6 ? 3 : 6; for (int yy = y1; yy < y1 + 3; yy++) { for (int xx = x1; xx < x1 + 3; xx++) { if (game[yy][xx] == number) return false; } } return true; }
7
private void backTrace(String word,String start,List<String> list){ if(word.equals(start)){ list.add(0,start); results.add(new ArrayList<String>(list)); list.remove(0); return; } list.add(0,word); if(map.get(word) != null) for(String s: map.get(word)) backTrace(s,start,list); list.remove(0); }
3
public void drawTail(Graphics g, GameObject front) { Image img = null; int x = getMotion().getX(); int y = getMotion().getY(); int fx = front.getMotion().getX(); int fy = front.getMotion().getY(); if (x == fx){ if (y < fy) img = imgTailDown; else if (y > fy) img = imgTailUp; } else if (y == fy){ if (x < fx) img = imgTailRight; else if (x > fx) img = imgTailLeft; } getSprite().setImage(img); }
6
public void sendObject(Object obj){ try{ b.writeObject(obj); }catch(Exception e){ e.printStackTrace(); } }
1
public boolean similar(Object other) { if (!(other instanceof JSONArray)) { return false; } int len = this.length(); if (len != ((JSONArray)other).length()) { return false; } for (int i = 0; i < len; i += 1) { Object valueThis = this.get(i); Object valueOther = ((JSONArray)other).get(i); if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { if (!((JSONArray)valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { return false; } } return true; }
8
@Override public void run() { long tc = 0; Transaction tx = graph.beginTx(); Iterable<Node> nodes = GlobalGraphOperations.at(graph).getAllNodes(); HashSet<Node> set = new HashSet<Node>(); for (Node u : nodes) { set.clear(); for (Relationship r : u.getRelationships(Direction.BOTH)) { Node v = r.getOtherNode(u); set.add(v); } for (Relationship r : u.getRelationships(Direction.BOTH)) { Node v = r.getOtherNode(u); for (Relationship r2 : v.getRelationships(Direction.BOTH)) { Node w = r2.getOtherNode(v); if (u.getId() < v.getId() && v.getId() < w.getId()) { if (set.contains(w)) tc++; } } } } tx.close(); System.out.println("Result : " + tc); }
7
public Team getOpposite(){ if(this == RED) return BLUE; else if(this == BLUE) return RED; else return NONE; }
2
public void write(int bits, int width) throws IOException { if (bits == 0 && width == 0) { return; } if (width <= 0 || width > 32) { throw new IOException("Bad write width."); } while (width > 0) { int actual = width; if (actual > this.vacant) { actual = this.vacant; } this.unwritten |= ((bits >>> (width - actual)) & BitInputStream.mask[actual]) << (this.vacant - actual); width -= actual; nrBits += actual; this.vacant -= actual; if (this.vacant == 0) { this.out.write(this.unwritten); this.unwritten = 0; this.vacant = 8; } } }
7
@EventHandler public void onEntityDeath(EntityDeathEvent event) { // do not act when disabled TODO, use unregister when available if ( !this.sheepFeedPlugin.isEnabled() ) { return; } Entity entity = event.getEntity(); if ( entity instanceof Sheep ) { this.sheepFeedPlugin.sheepDied((Sheep) entity); } }
2
public ArrayList<Prestamos> getPendientes(){ PreparedStatement ps; ArrayList<Prestamos> rows = new ArrayList<>(); try { ps = mycon.prepareStatement("SELECT DISTINCT Prestamos.*, Libros.nombre as lnombre, Usuarios.nombre as unombre FROM Prestamos, Libros, Usuarios WHERE Prestamos.id_libro = Libros.codigo AND Prestamos.id_usuario=Usuarios.codigo AND Prestamos.estado='pendiente'"); ResultSet rs = ps.executeQuery(); if(rs!=null){ try { Prestamos p; while(rs.next()){ p = new Prestamos( rs.getInt("id"), rs.getDate("fecha"), rs.getString("estado"), rs.getString("id_libro"), rs.getString("id_usuario") ); p.setNombreLibro(rs.getString("lnombre")); p.setNombreUsuario(rs.getString("unombre")); rows.add(p); } } catch (SQLException ex) { Logger.getLogger(Prestamos.class.getName()). log(Level.SEVERE, null, ex); } }else{ System.out.println("Total de registros encontrados es: 0"); } } catch (SQLException ex) { Logger.getLogger(PrestamosCRUD.class.getName()).log(Level.SEVERE, null, ex); } return rows; }
4
public void pastCrowl(){ DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Entity past_string = null; try { Key key = KeyFactory.createKey("past_string", "onlyOne"); past_string = datastore.get(key); } catch (Throwable t) { } past_string.setProperty("text",new Text(new Past().getPastString())); try{ if(false)datastore.put(past_string); }catch(Throwable t){} Queue queue = QueueFactory.getDefaultQueue(); queue.add(Builder.withUrl("/back").param("op","pastCrowl").method(Method.POST).countdownMillis(60000*30)); queue.add(Builder.withUrl("/sync").param("mode", "past").method(Method.GET).countdownMillis(30000)); queue.add(Builder.withUrl("/sync").param("mode", "ranking").method(Method.GET).countdownMillis(45000)); queue.add(Builder.withUrl("/sync").param("mode", "pair").method(Method.GET).countdownMillis(60000)); queue.add(Builder.withUrl("/ranking").param("c", "true").method(Method.GET).countdownMillis(90000)); queue.add(Builder.withUrl("/pair").param("c", "true").method(Method.GET).countdownMillis(120000)); }
3
@Override public void onLoadStateChange(LatestVersionListEvent event) { switch (event.getSource().getLoadState()) { case FAILED: status = Status.FAILED; break; case IDLE: status = Status.IDLE; break; case LOADED: status = Status.FOUND; boolean usingSnapshots = false; for (int i = 0; i < profile.allowedReleaseTypes.length; i++) { if (profile.allowedReleaseTypes[i].equals("snapshot")) { usingSnapshots = true; } } if (usingSnapshots) { version = MinecraftVersion.fromLatestSnapshot(); } else { version = MinecraftVersion.fromLatestRelease(); } if (version == null) { status = Status.FAILED; } else { versionName = version.getName(); } break; case LOADING: status = Status.IDLE; break; } for (IProfileUpdateListener listener : listeners) { listener.onProfileUpdate(new ProfileUpdateEvent(this)); } }
9
public static String unhtmlentities(String str) { //initialize html translation maps table the first time is called if (htmlentities_map.isEmpty()) { initializeEntitiesTables(); } StringBuilder buf = new StringBuilder(); for (int i = 0; i < str.length(); ++i) { char ch = str.charAt(i); if (ch == '&') { int semi = str.indexOf(';', i + 1); if ((semi == -1) || ((semi - i) > 7)) { buf.append(ch); continue; } String entity = str.substring(i, semi + 1); Integer iso; if (entity.charAt(1) == ' ') { buf.append(ch); continue; } if (entity.charAt(1) == '#') { if (entity.charAt(2) == 'x') { iso = Integer.valueOf(Integer.parseInt(entity.substring(3, entity.length() - 1), 16)); } else { iso = Integer.valueOf(entity.substring(2, entity.length() - 1)); } } else { iso = (Integer) unhtmlentities_map.get(entity); } if (iso == null) { buf.append(entity); } else { buf.append((char) (iso.intValue())); } i = semi; } else { buf.append(ch); } } return buf.toString(); }
9
public void testIsMatch_Partial() { // Year=2005, Month=7 (July), DayOfWeek=2 (Tuesday) Partial test = createYMDwPartial(ISO_UTC, 2005, 7, 2); LocalDate partial = new LocalDate(2005, 7, 5); assertEquals(true, test.isMatch(partial)); partial = new LocalDate(2005, 7, 4); assertEquals(false, test.isMatch(partial)); partial = new LocalDate(2005, 7, 6); assertEquals(false, test.isMatch(partial)); partial = new LocalDate(2005, 7, 12); assertEquals(true, test.isMatch(partial)); partial = new LocalDate(2005, 7, 19); assertEquals(true, test.isMatch(partial)); partial = new LocalDate(2005, 7, 26); assertEquals(true, test.isMatch(partial)); partial = new LocalDate(2005, 8, 2); assertEquals(false, test.isMatch(partial)); partial = new LocalDate(2006, 7, 5); assertEquals(false, test.isMatch(partial)); partial = new LocalDate(2005, 6, 5); assertEquals(false, test.isMatch(partial)); try { test.isMatch((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} }
1
public static void main(String[] args) { //OLD // List groceryList = new ArrayList(); // groceryList.add("Chocolate"); // groceryList.add("Milk"); // groceryList.add("Yogurt"); // groceryList.add("Graham crackers"); // // //had to cast prior to JDK5: // String item = (String)groceryList.get(1); // System.out.println(groceryList.size()); // groceryList.remove(2); // System.out.println(groceryList.size()); // // for(int i=0; i < groceryList.size(); i++){ // String s = (String)groceryList.get(i); // System.out.println(s); // } //NEW //after JDK5, you can specify object type in declaration List<String> groceryList = new ArrayList<String>(); //for JDK 7 only, this declaration is allowed: //List<String> groceryList = new ArrayList<>(); groceryList.add("Chocolate"); groceryList.add("Milk"); groceryList.add("Yogurt"); groceryList.add("Graham crackers"); groceryList.add("Milk"); //no casting needed for (String s : groceryList) { System.out.println(s); } System.out.println("-----------------------------------"); List<String> getTheseToo = new ArrayList<String>(); getTheseToo.add("Ice cream"); getTheseToo.add("Napkins"); for (String s : getTheseToo) { System.out.println(s); } System.out.println("-----------------------------------"); groceryList.addAll(getTheseToo); for (String s : groceryList) { System.out.println(s); } System.out.println("-----------------------------------"); groceryList.remove(4); groceryList.set(3, "Sprinkles"); for (String s : groceryList) { System.out.println(s); } //The following will swap 2 items in the list: item 5 (Napkins) is //stored in the String tmp; at index 5 the value is set to item 3 //(Sprinkles); tmp (Napkins) is then set at index 3. //Napkins is now #3 and Sprinkles is now #5 swap(groceryList, 5, 3); System.out.println("------After swap------------------------"); for (String s : groceryList) { System.out.println(s); } shuffle(groceryList, new Random()); System.out.println("------After shuffle---------------------"); for (String s : groceryList) { System.out.println(s); } Collections.sort(groceryList); System.out.println("------After sort---------------------"); for (String s : groceryList) { System.out.println(s); } Collections.reverse(groceryList); System.out.println("------After reverse---------------------"); for (String s : groceryList) { System.out.println(s); } Collections.shuffle(groceryList); System.out.println("------After collections shuffle---------------"); for (String s : groceryList) { System.out.println(s); } }
9
@Override public int getInput() { if(Keys.isDown(Keys.W)){return Keys.W;} if(Keys.isDown(Keys.S)){return Keys.S;} if(Keys.isDown(Keys.A)){return Keys.A;} if(Keys.isDown(Keys.D)){return Keys.D;} return -1; }
4
public void paintComponent(Graphics g) { super.paintComponent(g); if (_image != null) { if (!_autoSize) { g.drawImage(_image, _x, _y, _image.getWidth(null), _image.getHeight(null), null); } else { Graphics2D g2d = (Graphics2D) g; Double scaleWidth = new Double(getWidth()) / new Double(_image.getWidth(null)); Double scaleHeight = new Double(getHeight()) / new Double(_image.getHeight(null)); if (_keepAspect) { if (scaleWidth > scaleHeight) { scaleWidth = scaleHeight; } else { scaleHeight = scaleWidth; } } g2d.scale(scaleWidth, scaleHeight); g2d.drawImage(_image, _x, _y, null); } } }
4
public MonitoredOutputStream(OutputStream target, OutputStreamListener listener) { this.target = target; this.listener = listener; this.listener.start(); }
0
private static void createBombers(IBomber[] bombers, Match m, String[] args) throws IOException { ServerSocket socket = new ServerSocket(PORT_NO); for (int i = 0; i < bombersCount; i++) { String aiLocation = args[i]; bombers[i] = ProcessBotFactory.buildBomber(i, INITIAL_COUNT_OF_BOMBS, m, aiLocation); bombers[i].setSocket(socket.accept()); // In case one wants to play this interactively.... // bombers[i] = new MyBomber(i, INITIAL_COUNT_OF_BOMBS, m); } }
1
public void method() { try { System.out.println("Try 块开始 !"); // return; /** * * 如果这里是return时,运行结果如下: * Try 块开始 ! * 程序即将结束... ... ! * * 如果在try块中存在return语句,那么首先也需要将finally块中的代码执行 * 完毕,然后方法在返回 */ System.exit(0); /** * * System.exit(0);时 * * 系统java vm直接结束 运行结果如下: * * Try 块开始 ! * * 如果在try块中存在System.exit(0)语句,那么就不会执行finally块 * 中的代码,因为System.exit(0)会终止当前运行的java虚拟机,程序会在 * 虚拟机终止前结束执行。 * */ } catch(Exception e) { e.printStackTrace(); } finally { System.out.println("程序即将结束... ... !"); } System.out.println("方法正常结束 !"); }
1
public void incomingApdu(APDU apdu, Address address, OctetString linkService) throws BACnetException { // if (apdu.expectsReply() != npci.isExpectingReply()) // throw new MessageValidationAssertionException("Inconsistent message: APDU expectsReply="+ // apdu.expectsReply() +" while NPCI isExpectingReply="+ npci.isExpectingReply()); if (apdu instanceof ConfirmedRequest) { ConfirmedRequest confAPDU = (ConfirmedRequest) apdu; byte invokeId = confAPDU.getInvokeId(); if (confAPDU.isSegmentedMessage() && confAPDU.getSequenceNumber() > 0) // This is a subsequent part of a segmented message. Notify the waiting room. waitingRoom.notifyMember(address, linkService, invokeId, false, confAPDU); else { if (confAPDU.isSegmentedMessage()) { // This is the initial part of a segmented message. Go and receive the subsequent parts. WaitingRoomKey key = waitingRoom.enterServer(address, linkService, invokeId); try { receiveSegmented(key, confAPDU); } finally { waitingRoom.leave(key); } } // Handle the request. try { confAPDU.parseServiceData(); AcknowledgementService ackService = handleConfirmedRequest(address, linkService, invokeId, confAPDU.getServiceRequest()); sendResponse(address, linkService, confAPDU, ackService); } catch (BACnetErrorException e) { network.sendAPDU(address, linkService, new Error(invokeId, e.getError()), false); } catch (BACnetRejectException e) { network.sendAPDU(address, linkService, new Reject(invokeId, e.getRejectReason()), false); } catch (BACnetException e) { Error error = new Error(confAPDU.getInvokeId(), new BaseError((byte) 127, new BACnetError( ErrorClass.services, ErrorCode.inconsistentParameters))); network.sendAPDU(address, linkService, error, false); ExceptionDispatch.fireReceivedException(e); } } } else if (apdu instanceof UnconfirmedRequest) { UnconfirmedRequest ur = (UnconfirmedRequest) apdu; try { ur.getService().handle(localDevice, address, linkService); } catch (BACnetException e) { ExceptionDispatch.fireReceivedException(e); } } else { // An acknowledgement. AckAPDU ack = (AckAPDU) apdu; // Used for testing only. This is required to test the parsing of service data in an ack. // ((ComplexACK) ack).parseServiceData(); waitingRoom.notifyMember(address, linkService, ack.getOriginalInvokeId(), ack.isServer(), ack); } }
9
@Override public void setAbilityComponentCodedFromCodedPairs(PairList<String,String> decodedDV, AbilityComponent comp) { final String[] s=new String[6]; for(int i=0;i<6;i++) s[i]=decodedDV.get(i).second; if(s[0].equalsIgnoreCase("||")) comp.setConnector(AbilityComponent.CompConnector.OR); else comp.setConnector(AbilityComponent.CompConnector.AND); if(s[1].equalsIgnoreCase("held")) comp.setLocation(AbilityComponent.CompLocation.HELD); else if(s[1].equalsIgnoreCase("worn")) comp.setLocation(AbilityComponent.CompLocation.WORN); else if(s[1].equalsIgnoreCase("nearby")) comp.setLocation(AbilityComponent.CompLocation.NEARBY); else if(s[1].equalsIgnoreCase("onground")) comp.setLocation(AbilityComponent.CompLocation.ONGROUND); else comp.setLocation(AbilityComponent.CompLocation.INVENTORY); if(s[2].equalsIgnoreCase("consumed")) comp.setConsumed(true); else comp.setConsumed(false); comp.setAmount(CMath.s_int(s[3])); int depth=CMLib.materials().getResourceCode(s[4],false); if(depth>=0) comp.setType(AbilityComponent.CompType.RESOURCE, Integer.valueOf(depth)); else { depth=CMLib.materials().getMaterialCode(s[4],false); if(depth>=0) comp.setType(AbilityComponent.CompType.MATERIAL, Integer.valueOf(depth)); else comp.setType(AbilityComponent.CompType.STRING, s[4].toUpperCase().trim()); } comp.setMask(s[5]); }
9
public static Object[] getPropertyIds(Scriptable obj) { if (obj == null) { return ScriptRuntime.emptyArgs; } Object[] result = obj.getIds(); ObjToIntMap map = null; for (;;) { obj = obj.getPrototype(); if (obj == null) { break; } Object[] ids = obj.getIds(); if (ids.length == 0) { continue; } if (map == null) { if (result.length == 0) { result = ids; continue; } map = new ObjToIntMap(result.length + ids.length); for (int i = 0; i != result.length; ++i) { map.intern(result[i]); } result = null; // Allow to GC the result } for (int i = 0; i != ids.length; ++i) { map.intern(ids[i]); } } if (map != null) { result = map.getKeys(); } return result; }
9
public Enemy(int type, int rank) { ImageIcon i = new ImageIcon(this.getClass().getResource(zmbDown)); zombieDownImage = i.getImage(); ImageIcon i2 = new ImageIcon(this.getClass().getResource(zmbDown2)); zombieDownImage2 = i2.getImage(); ImageIcon i1 = new ImageIcon(this.getClass().getResource(zmbUp)); zombieUpImage = i1.getImage(); ImageIcon i11 = new ImageIcon(this.getClass().getResource(zmbUp2)); zombieUpImage2 = i11.getImage(); ImageIcon i3 = new ImageIcon(this.getClass().getResource(zmbRight)); zombieRightImage = i3.getImage(); ImageIcon i33 = new ImageIcon(this.getClass().getResource(zmbRight2)); zombieRightImage2 = i33.getImage(); ImageIcon i4 = new ImageIcon(this.getClass().getResource(zmbLeft)); zombieLeftImage = i4.getImage(); ImageIcon i44 = new ImageIcon(this.getClass().getResource(zmbLeft2)); zombieLeftImage2 = i44.getImage(); ImageIcon zdu = new ImageIcon(this.getClass().getResource(zmbDemonUp)); zombieDemonUpImage = zdu.getImage(); ImageIcon zdu2 = new ImageIcon(this.getClass().getResource(zmbDemonUp2)); zombieDemonUpImage2 = zdu2.getImage(); ImageIcon zdd = new ImageIcon(this.getClass().getResource(zmbDemonDown)); zombieDemonDownImage = zdd.getImage(); ImageIcon zdd2 = new ImageIcon(this.getClass().getResource(zmbDemonDown2)); zombieDemonDownImage2 = zdd2.getImage(); ImageIcon zdl2 = new ImageIcon(this.getClass().getResource(zmbDemonLeft2)); zombieDemonLeftImage2 = zdl2.getImage(); ImageIcon zdl = new ImageIcon(this.getClass().getResource(zmbDemonLeft)); zombieDemonLeftImage = zdl.getImage(); ImageIcon zdr2 = new ImageIcon(this.getClass().getResource(zmbDemonRight2)); zombieDemonRightImage2 = zdr2.getImage(); ImageIcon zdr = new ImageIcon(this.getClass().getResource(zmbDemonRight)); zombieDemonRightImage = zdr.getImage(); currentframe = 0; spriteTimer = System.nanoTime(); spriteDelay = 234; imageHeight = zombieDownImage.getHeight(null); imageWidth = zombieDownImage.getWidth(null); this.type = type; this.rank = rank; //basic enemy if (type == 1) { //color1 = Color.BLUE; if (rank == 1) { speed = 1; r = 25; health = 1; } if (rank == 2) { speed = 2; r = 25; health = 2; } } //zombie demon if (type == 2){ if (rank == 1){ speed = 2; health = 3; } if (rank == 2){ speed = 3; health = 3; } } //basic enemy upgraded x = Math.random() * GamePanel.WIDTH / 2 + GamePanel.WIDTH / 4; y = -r; double angle = Math.random() * 140 + 20; rad = Math.toRadians(angle); movementAngle = rad; dx = Math.cos(rad) * speed / 2; dy = Math.sin(rad) * speed / 2; ready = false; dead = false; }
6
public void startElement(String namespaceURI, String localName, String rawName, Attributes atts) throws SAXException { String k; if (insidePerson = (rawName.equals("author") || rawName .equals("editor"))) { //if start element is editor or author, then clear value string to store new name Value = ""; return; } if ((atts.getLength()>0) && ((k = atts.getValue("key"))!=null)) { key = k; recordTag = rawName; } if (insideDomain = (rawName.equals("crossref") || rawName.equals("journal"))) { publishDomain = ""; } }
6
public void addHit(Card x){ if (hit) { addCardtoHand(x); //Request card from dealer or dealer checks if player wants to hit I suppose. //Add card to hand runLogic(); } else if (!hit) { System.out.println("Error: Can't call addHit() if !hit! I'm not supposed to run!"); } }
2
public MockFacesContextFactory() { Class clazz = null; // Try to load the 1.2 version of our mock FacesContext class try { clazz = this.getClass().getClassLoader().loadClass("org.apache.shale.test.mock.MockFacesContext12"); constructor = clazz.getConstructor(facesContextSignature); jsf12 = true; } catch (NoClassDefFoundError e) { // We are not running on JSF 1.2, so go to our fallback clazz = null; constructor = null; } catch (ClassNotFoundException e) { // Same as above clazz = null; constructor = null; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new FacesException(e); } // Fall back to the 1.1 version if we could not load the 1.2 version try { if (clazz == null) { clazz = this.getClass().getClassLoader().loadClass("org.apache.shale.test.mock.MockFacesContext"); constructor = clazz.getConstructor(facesContextSignature); jsf12 = false; } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new FacesException(e); } }
7
private static final void handleDataDoubleEscapeTag(Tokeniser t, CharacterReader r, TokeniserState primary, TokeniserState fallback) { if (r.matchesLetter()) { String name = r.consumeLetterSequence(); t.dataBuffer.append(name.toLowerCase()); t.emit(name); return; } char c = r.consume(); switch (c) { case '\t': case '\n': case '\r': case '\f': case ' ': case '/': case '>': if (t.dataBuffer.toString().equals("script")) t.transition(primary); else t.transition(fallback); t.emit(c); break; default: r.unconsume(); t.transition(fallback); } }
9
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(AuthorizationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AuthorizationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AuthorizationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AuthorizationUI.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 AuthorizationUI().setVisible(true); } }); }
6
@Override public TileSet getBorderOf(int aX, int aY) { TileSet tiles = new TileSet(this); if (getTile(aX - 1, aY) != -1) tiles.add(Tile.create(aX - 1, aY)); if (getTile(aX + 1, aY) != -1) tiles.add(Tile.create(aX + 1, aY)); final int y = (aY + aX) % 2 == 0 ? aY + 1 : aY - 1; if (getTile(aX, y) != -1) tiles.add(Tile.create(aX, y)); return tiles; }
4
protected Constructor<? extends ConfigurationSerializable> getConstructor() { try { return clazz.getConstructor(Map.class); } catch (NoSuchMethodException ex) { return null; } catch (SecurityException ex) { return null; } }
3
public void loadComboBox() { for (Disc disc : Manager.getInstance().getDiscs().getDiscs()) { cbDiscs.addItem(disc.getName()); } }
1
public static String getCMD() { String ret = SystemInformation.getOSPath() + CMD_x86; if (!isX86() && FileUtil.control(SystemInformation.getOSPath().resolve(CMD_x64_wO_c))) { ret = SystemInformation.getOSPath() + CMD_x64; } return ret; }
2
public void kidChanged(TreeNodePageWrapper kidWrapper, String message, long value) { kidsInScanning = 0; kidsToSave = 0; for (@SuppressWarnings("unchecked") Enumeration<DefaultMutableTreeNode> children = children(); children.hasMoreElements();) { TreeNodePageWrapper kid = (TreeNodePageWrapper) children.nextElement(); if (kid.downloading || kid.downloadPageQ) kidsInScanning++; if (kid.mustSavePage || kid.saving) kidsToSave++; } }
5
private void firePlayerUpdate() { this.currentPlayer = (this.currentPlayer == CellState.PLAYER_ONE) ? CellState.PLAYER_TWO : CellState.PLAYER_ONE; this.eventSystem.queueEvent(new PlayerUpdateEvent(currentPlayer)); }
1
public String getColumnValue(String strColumnName,int intIndex){ int curColumnID=getColumnID(strColumnName); if(curColumnID==-1){ System.err.println("ERROR-Column Name not found = "+strColumnName); try { throw new Exception(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "ERROR-Column Name not found = "+strColumnName; } if ((intIndex>=0 && intIndex<ArrLRows.size())==false){ System.err.println("ERROR-Out of Range"); try { throw new Exception(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "ERROR-Out of Range"; } String TempString=ArrLRows.get(intIndex)[curColumnID].trim(); if(TempString==null){ TempString=""; }else if(TempString.equals("null")){ TempString=""; } //System.out.println(TempString); return TempString; }//end
7
void getAltLocLists() { if (!hasAlternateLocations()) return; String[] lists = new String[atomSetCount]; for (int i = 0; i < atomSetCount; i++) lists[i] = ""; for (int i = 0; i < atomCount; i++) { char id = atoms[i].alternateLocationID; if (id == '\0' || lists[atoms[i].atomSetIndex].indexOf(id) >= 0) continue; lists[atoms[i].atomSetIndex] += id; } for (int i = 0; i < atomSetCount; i++) if (lists[i].length() > 0) setAtomSetAuxiliaryInfo("altLocs", lists[i], i); }
7
public static BookStoreResult SendAndRecv(HttpClient client, ContentExchange exchange) throws BookStoreException { int exchangeState; try { client.send(exchange); } catch (IOException ex) { throw new BookStoreException( BookStoreClientConstants.strERR_CLIENT_REQUEST_SENDING, ex); } try { exchangeState = exchange.waitForDone(); // block until the response // is available } catch (InterruptedException ex) { throw new BookStoreException( BookStoreClientConstants.strERR_CLIENT_REQUEST_SENDING, ex); } if (exchangeState == HttpExchange.STATUS_COMPLETED) { try { BookStoreResponse bookStoreResponse = (BookStoreResponse) BookStoreUtility .deserializeXMLStringToObject(exchange .getResponseContent().trim()); if (bookStoreResponse == null) { throw new BookStoreException( BookStoreClientConstants.strERR_CLIENT_RESPONSE_DECODING); } BookStoreException ex = bookStoreResponse.getException(); if (ex != null) { throw ex; } return bookStoreResponse.getResult(); } catch (UnsupportedEncodingException ex) { throw new BookStoreException( BookStoreClientConstants.strERR_CLIENT_RESPONSE_DECODING, ex); } } else if (exchangeState == HttpExchange.STATUS_EXCEPTED) { throw new BookStoreException( BookStoreClientConstants.strERR_CLIENT_REQUEST_EXCEPTION); } else if (exchangeState == HttpExchange.STATUS_EXPIRED) { throw new BookStoreException( BookStoreClientConstants.strERR_CLIENT_REQUEST_TIMEOUT); } else { throw new BookStoreException( BookStoreClientConstants.strERR_CLIENT_UNKNOWN); } }
8
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); out = response.getWriter(); try { movieid = request.getParameter("movieid"); } catch (NumberFormatException ex) { movieid = null; } if (movieid != null) { try { conn = ds.getConnection(); movieid = movieid.replace("mid_", ""); statement = conn.prepareStatement("SELECT * FROM movies WHERE id = ?"); statement.setString(1, movieid); rs = statement.executeQuery(); rs.last(); int rows = rs.getRow(); if (rows > 0) { out.println("<div class=\"wrap\">"); rs.beforeFirst(); while(rs.next()){ out.println("<div class=\"list_item\">"); out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); out.println("<tr>"); out.println("<td rowspan=\"2\" valign=\"top\">"); out.println("<div class=\"image\">"); out.println(String.format("<a href=\"movie?id=%s\">", rs.getString(1))); out.println("<div>"); out.println(String.format("<img alt=\"\" title=\"\" src=\"%s\" />", rs.getString(5))); out.println("</div>"); out.println("</a>"); out.println("</div>"); out.println("</td>"); out.println("<td class=\"overview-top\">"); out.println(String.format("<h4><a href=\"movie?id=%s\" class=\"movie-title\">%s (%s)</a></h4>", rs.getString(1), rs.getString(2), rs.getString(3))); out.println("<div class=\"txt-block\">"); out.println("<h5>Movie ID:</h5>"); out.println(String.format("<span><span>%s</span></span>", rs.getString(1))); out.println("</div>"); out.println("<div class=\"txt-block\">"); out.println("<h5>Director:</h5>"); out.println(String.format("<span><span>%s</span></span>", rs.getString(4))); out.println("</div>"); out.println("<div class=\"txt-block\">"); out.println("<h5>Stars:</h5>"); PreparedStatement star_statement = conn.prepareStatement("SELECT s.id, s.first_name, s.last_name FROM stars s, stars_in_movies sim WHERE s.id = sim.star_id AND sim.movie_id = ?"); star_statement.setInt(1, rs.getInt(1)); ResultSet star_result = star_statement.executeQuery(); star_result.last(); int star_row = star_result.getRow(); int star_index = 0; star_result.beforeFirst(); while (star_result.next()) { star_index++; int star_id = star_result.getInt(1); String first_name = star_result.getString(2); String last_name = star_result.getString(3); out.print("<span><span><a href=\"star?id=" + star_id + "\">" + first_name + " " + last_name + "</a></span></span>"); if (star_index != star_row) out.print(", "); } out.println("</div>"); out.println("<div class=\"txt-block\">"); out.println("<h5>Genres:</h5>"); PreparedStatement genre_statement = conn .prepareStatement("SELECT g.* FROM genres g, genres_in_movies gim WHERE g.id = gim.genre_id AND gim.movie_id = ?"); genre_statement.setInt(1, rs.getInt(1)); ResultSet genre_result = genre_statement.executeQuery(); genre_result.last(); int genre_row = genre_result.getRow(); int genre_index = 0; genre_result.beforeFirst(); while (genre_result.next()) { genre_index++; int g_id = genre_result.getInt(1); String genre_name = genre_result.getString(2); out.print("<span><span><a href=\"result?by=genre&id=" + g_id + "&page=1&size=10&sort=title&order=asc\">" + genre_name + "</a></span></span>"); if (genre_index != genre_row) out.print(", "); } out.println("</div>"); out.println("</td>"); out.println("</tr>"); out.println("</table>"); out.println("</div>"); } out.println("</div>"); } conn.close(); } catch (SQLException e1) { } } out.close(); }
9
public boolean isOp() { return _prefix.indexOf('@') >= 0; }
0
public static void saveScene(int[][] array){ int totle = 0 ; File file = null ; file = new File("source/stages/"); totle = file.list().length + 1; String fileName = "stage" + totle ; File current = new File("source/stages/" + fileName +".txt") ; FileWriter out = null; try{ if( !current.exists()) current.createNewFile(); out = new FileWriter(current); for(int i = 0; i<array.length; i++){ for(int j = 0; j<array[i].length; j ++){ if( i <= 2) out.write(0 + ""); else out.write(array[i][j] + ""); } if( i != array[i].length - 1) out.write("\n"); } }catch(Exception e){ e.printStackTrace(); }finally{ try{ if( out != null) out.close(); }catch(Exception e){ System.out.println("关闭异常!"); } } System.out.println("游戏场景数据保存成功!"); }
8
public void switchNode(int value1, int value2) { if (value1 == value2) { return; } Node node1 = this.getNodeByValue(value1); Node node2 = this.getNodeByValue(value2); Node parent1 = node1.parent; Node parent2 = node2.parent; boolean isNode1LeftChild = node1 == parent1.leftChild; boolean isNode2LeftChild = node2 == parent2.leftChild; if (isNode1LeftChild) { parent1.leftChild = node2; } else { parent1.rightChild = node2; } // BUG3: forget to change the parent node2.parent = parent1; if (isNode2LeftChild) { parent2.leftChild = node1; } else { parent2.rightChild = node1; } node1.parent = parent2; }
3
@Override public void valueChanged(ListSelectionEvent e) { if (e.getSource() == orderingList) { // check if order list is empty if (orderingList.getSelectedIndex() > -1) { // separate the text in the selected list item String[] values = orderingList.getSelectedValue().split("\\t"); // call method to set the current combobox item according to the product name of the // selected list item setSelectedProductComboboxItem(values[0]); } removeButton.setEnabled(true); cancelButton.setEnabled(true); } }
2
public static void main(String[] args) throws Exception { if (args == null || args.length == 0) { testLocale(Locale.getDefault()); } else { String lang = null; String country = null; String variant = null; for (int i = 0; i < args.length; i++) { switch (i) { case 1: lang = args[i]; break; case 2: country = args[i]; break; case 3: variant = args[i]; break; } } final Locale locale; if (country == null) { locale = new Locale(lang.toLowerCase()); } else if (variant == null) { locale = new Locale(lang.toLowerCase(), country.toLowerCase()); } else { locale = new Locale(lang.toLowerCase(), country.toLowerCase(), variant); } testLocale(locale); } }
8
public ExtDecimal inc() { if (type == Type.NUMBER) { return add(ONE); } else if (type == Type.POSITIVEZERO) { return ONE; } else if (type == Type.NEGATIVEZERO) { return ONE; } else if (type == Type.INFINITY) { return INFINITY; } else if (type == Type.NEGATIVEINFINITY) { return NEGATIVEINFINITY; } else { throw new UnsupportedOperationException("Unknown type"); } }
5
@SuppressWarnings({"empty-statement", "CallToThreadDumpStack"}) private void miRecebimentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miRecebimentoActionPerformed if (recebimento != null && !recebimento.isVisible()) { deskPane.remove(recebimento); recebimento = null; } if (recebimento == null) { recebimento = new FrmRecebimento(this); Validacoes v = new Validacoes(); v.posicao(this, recebimento); deskPane.add(recebimento); try { recebimento.setSelected(true); } catch (PropertyVetoException ex) { ex.printStackTrace(); } } else { recebimento.toFront(); } }//GEN-LAST:event_miRecebimentoActionPerformed
4
public MiniSplash() { start = new ImageIcon("art/buttons/start_btn.jpg"); skip = new ImageIcon("art/buttons/skip_btn.jpg"); exit = new ImageIcon("art/buttons/exit_btn.jpg"); //eventually will be removed next = new ImageIcon("art/buttons/next_btn.jpg"); skipButton = new JButton(skip); try { binderBg = ImageIO.read(new File("art/classroom/splash.jpg")); bulletpoint = ImageIO.read(new File("art/classroom/bulletpoint.png")); } catch (IOException e) { e.printStackTrace(); } /* Game Key * 1 = Fruit * 2 = Warehouse * 3 = Sudoku * 4 = Tile Puzzle * 5 = Beer Pong */ Random generator = new Random(); game = generator.nextInt(5) + 1; // 1-5 //game = 3; //testing switch(game) { case 1: button = new JButton(start); break; case 2: button = new JButton(start); break; case 3: nxtScreen = true; button = new JButton(next); numScreen = 1; break; case 4: button = new JButton(start); break; case 5: button = new JButton(start); break; } finished = false; setLayout(null); add(button); if(nxtScreen) { add(skipButton); button.setBounds(150, 250, 100, 30); skipButton.setBounds(250, 250, 100, 30); skipButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { switchPanels(); } }); } else { button.setBounds(200, 250, 100, 30); } button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if(game == 3 && !finished) { numScreen++; finished = true; button.setIcon(start); repaint(); } else switchPanels(); } }); setBounds(26, 32, 550, 450); setVisible(true); }
9
public static boolean isValidPosition(int i, int j){ if(i < 4) return (j > -1 && j < 4); else if(i > 3 && i < 7) return (j > -1 && j < 3); else if(i > 6 && i < 9) return (j > -1 && j < 2); else if(i == 9) return (j == 0); else System.out.println("invalid Position dected. i="+i+", j="+j); return false; }
9
private static float calculateDividendPre(String ticker) { //DIVIDEND DUPLICATE COUNT NEEDS FIX HERE ArrayList<Float> dividends = new ArrayList<Float>(); float sum = 0; float dividend = 0; int dividendId = 82; for (Entry<Float, float[][]> ent : Database.DB_ARRAY.entrySet()) { float possibleDividend = ent.getValue()[Database.dbSet .indexOf(ticker)][dividendId]; if (possibleDividend > 0) { dividends.add(possibleDividend); sum += possibleDividend; } } if (sum > 0) { if (EarningsTest.singleton.averageDividend.isSelected()) dividend = sum / dividends.size(); else dividend = sum; } return dividend; }
4
public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
6