method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
9d233887-d188-4ab6-a17a-d6b32bc4fa22
8
public void SelecteerSBox(int keuze, int rij, int kolom) { switch(keuze){ case 0: resultaatSBox[eersteIndex] = Matrices.sBox1[rij][kolom]; eersteIndex++; break; case 1: resultaatSBox[eersteIndex] = Matrices.sBox2[rij][kolom]; eersteIndex++; break; case 2: resultaatSBox[eersteIndex] = Matrices.sBox3[rij][kolom]; eersteIndex++; break; case 3: resultaatSBox[eersteIndex] = Matrices.sBox4[rij][kolom]; eersteIndex++; break; case 4: resultaatSBox[eersteIndex] = Matrices.sBox5[rij][kolom]; eersteIndex++; break; case 5: resultaatSBox[eersteIndex] = Matrices.sBox6[rij][kolom]; eersteIndex++; break; case 6: resultaatSBox[eersteIndex] = Matrices.sBox7[rij][kolom]; eersteIndex++; break; case 7: resultaatSBox[eersteIndex] = Matrices.sBox8[rij][kolom]; eersteIndex++; break; } }
ea0c8e49-c709-44d4-978f-430eddac93d0
0
public static void main(String[] args) { boolean isLocal = "windows".equals(OS); System.out.println(isLocal); }
db05b7e8-e978-4ca9-83de-3a43b4215d28
8
public final WaiprParser.statdefs_return statdefs() throws RecognitionException { WaiprParser.statdefs_return retval = new WaiprParser.statdefs_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token char_literal36=null; Token char_literal38=null; ParserRuleReturnScope statdef35 =null; ParserRuleReturnScope statdef37 =null; CommonTree char_literal36_tree=null; CommonTree char_literal38_tree=null; RewriteRuleTokenStream stream_17=new RewriteRuleTokenStream(adaptor,"token 17"); RewriteRuleTokenStream stream_IE=new RewriteRuleTokenStream(adaptor,"token IE"); RewriteRuleSubtreeStream stream_statdef=new RewriteRuleSubtreeStream(adaptor,"rule statdef"); try { dbg.enterRule(getGrammarFileName(), "statdefs"); if ( getRuleLevel()==0 ) {dbg.commence();} incRuleLevel(); dbg.location(36, 0); try { // C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:36:9: ( statdef ( ',' statdef )* ';' -> ( statdef )* ) dbg.enterAlt(1); // C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:36:11: statdef ( ',' statdef )* ';' { dbg.location(36,11); pushFollow(FOLLOW_statdef_in_statdefs253); statdef35=statdef(); state._fsp--; stream_statdef.add(statdef35.getTree());dbg.location(36,19); // C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:36:19: ( ',' statdef )* try { dbg.enterSubRule(10); loop10: while (true) { int alt10=2; try { dbg.enterDecision(10, decisionCanBacktrack[10]); int LA10_0 = input.LA(1); if ( (LA10_0==17) ) { alt10=1; } } finally {dbg.exitDecision(10);} switch (alt10) { case 1 : dbg.enterAlt(1); // C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:36:20: ',' statdef { dbg.location(36,20); char_literal36=(Token)match(input,17,FOLLOW_17_in_statdefs256); stream_17.add(char_literal36); dbg.location(36,24); pushFollow(FOLLOW_statdef_in_statdefs258); statdef37=statdef(); state._fsp--; stream_statdef.add(statdef37.getTree()); } break; default : break loop10; } } } finally {dbg.exitSubRule(10);} dbg.location(36,34); char_literal38=(Token)match(input,IE,FOLLOW_IE_in_statdefs262); stream_IE.add(char_literal38); // AST REWRITE // elements: statdef // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.tree = root_0; RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); root_0 = (CommonTree)adaptor.nil(); // 36:38: -> ( statdef )* { dbg.location(36,41); // C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:36:41: ( statdef )* while ( stream_statdef.hasNext() ) { dbg.location(36,41); adaptor.addChild(root_0, stream_statdef.nextTree()); } stream_statdef.reset(); } retval.tree = root_0; } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { // do for sure before leaving } dbg.location(36, 48); } finally { dbg.exitRule(getGrammarFileName(), "statdefs"); decRuleLevel(); if ( getRuleLevel()==0 ) {dbg.terminate();} } return retval; }
fc19b411-b2e2-49cf-a5de-752c00d32be2
3
@Test public void putGetSize() { HugeMapBuilder<HandTypesKey, HandTypes> dummy = new HugeMapBuilder<HandTypesKey, HandTypes>() {{ allocationSize = 64 * 1024; setRemoveReturnsNull = true; }}; HandTypesMap map = new HandTypesMap(dummy); HandTypesKeyImpl key = new HandTypesKeyImpl(); HandTypesImpl value = new HandTypesImpl(); long start = System.nanoTime(); final int size = 5000000; for (int i = 0; i < size; i += 2) { put(map, key, value, i, false); put(map, key, value, i, true); } for (int i = 0; i < size; i += 2) { get(map, key, i, false); get(map, key, i, true); } for (Map.Entry<HandTypesKey, HandTypes> entry : map.entrySet()) { assertEquals(entry.getKey().getInt(), entry.getValue().getInt()); assertEquals(entry.getKey().getBoolean(), entry.getValue().getBoolean()); } long time = System.nanoTime() - start; System.out.printf("Took an average of %,d ns to write/read", time / size); System.out.println(Arrays.toString(map.sizes())); System.out.println(Arrays.toString(map.capacities())); }
90801b25-0ac5-4559-aee8-221c2a343b6b
2
@Override public boolean removeAll( Collection<?> collection ) { boolean changed = false; for (Object element : collection) { changed |= remove( element ); } return changed; }
5a56414d-8f76-4010-af75-527164fc1a9e
9
public static char findFirstNonRepeatingChar(String stream) { LinkedListNode head = null; LinkedListNode tail = null; boolean[] repeating = new boolean[256]; LinkedListNode[] nodes = new LinkedListNode[256]; for (int i=0; i<stream.length(); i++) { if (repeating[stream.charAt(i)] == false) { if (nodes[stream.charAt(i)] != null) { LinkedListNode n = nodes[stream.charAt(i)]; if (head == n) { head = head.getNext(); } if (tail == n) { tail = tail.getPrev(); } if (n.getNext() != null) { n.getNext().setPrevious(n.getPrev()); } if (n.getPrev() != null) { n.getPrev().setNext(n.getNext()); } repeating[stream.charAt(i)] = true; nodes[stream.charAt(i)] = null; } else { LinkedListNode temp = new LinkedListNode(stream.charAt(i)); temp.setNext(null); temp.setPrevious(null); if (head == null) { head = temp; tail = temp; } else { tail.setNext(temp); temp.setPrevious(tail); tail = temp; } nodes[stream.charAt(i)] = tail; } } } if (head != null) return (char)head.getData(); return ' '; }
8c4f9395-b988-4e6b-9bc1-b541a2ebfe7d
3
@Override public void setVolume(int soundID, int volume) { //Clamp the volume between 0-100 if(volume > 100) volume = 100; if(volume < 0) volume = 0; //Convert it to a float between 0.0f and 1.0f float convertedVolume = ((float)(volume/100)); //Set the volume if(this.soundMap.containsKey(soundID)) { this.setVolumeChecked(soundID, convertedVolume); } }
2d533bd5-ec15-4c24-a8ab-766b4633d026
2
public int score(Collection<String> names) { int sum = 0; for( String name : names ) { if( rankByName.get(name) == null ) throw new RuntimeException("Error: Entry '" + name + "' not found!"); sum += rankByName.get(name); } return sum; }
aa2286e1-0bcd-41e8-a63e-14686f5d3bf8
5
public boolean set_hhmm(String hhmm) { if(hhmm.matches("\\d\\d\\d\\d")) { int h= (byte)Integer.parseInt(hhmm.substring(0, 2)); int m= (byte)Integer.parseInt(hhmm.substring(2, 4)); if(h>=0 && h<24 && m>=0 && m<60) { this.hour=(byte) h; this.minute=(byte) m; return true; } } return false; }
d437c9ea-448d-4e7a-9137-ce23c83d2375
8
private Statement statement() throws RequiredTokenException { enterRule(NonTerminal.STATEMENT); Statement statement = null; if(firstSetSatisfied(NonTerminal.VARIABLE_DECLARATION)) try { statement = variable_declaration(); } catch (SymbolRedefinitionException e) { statement = new Error( e.DuplicateToken.getLineNumber(), e.DuplicateToken.getCharPos(), String.format("Attempted to redefine symbol \"%s\".", e.DuplicateToken.getLexeme())); } else if(firstSetSatisfied(NonTerminal.CALL_STATEMENT)) try { statement = call_statement(); } catch (UnresolvableSymbolException e) { statement = new Error( e.UnresolvedToken.getLineNumber(), e.UnresolvedToken.getCharPos(), String.format("Unable to resolve symbol \"%s\".", e.UnresolvedToken.getLexeme())); } else if(firstSetSatisfied(NonTerminal.ASSIGNMENT_STATEMENT)) statement = assignment_statement(); else if(firstSetSatisfied(NonTerminal.IF_STATEMENT)) statement = if_statement(); else if(firstSetSatisfied(NonTerminal.WHILE_STATEMENT)) statement = while_statement(); else if(firstSetSatisfied(NonTerminal.RETURN_STATEMENT)) statement = return_statement(); else { statement = new Error( reader.token().getLineNumber(), reader.token().getCharPos(), String.format("First set unsatisfied for non-terminal of kind \"%s\".", reader.token().getKind())); } exitRule(); return statement; }
d7b3017c-1c85-4077-a075-800efa9bd2c8
8
protected void updateWeather() { if (!this.worldProvider.hasNoSky) { if (this.lastLightningBolt > 0) { --this.lastLightningBolt; } this.prevRainingStrength = this.rainingStrength; if (this.worldInfo.isRaining()) { this.rainingStrength = (float)((double)this.rainingStrength + 0.01D); } else { this.rainingStrength = (float)((double)this.rainingStrength - 0.01D); } if (this.rainingStrength < 0.0F) { this.rainingStrength = 0.0F; } if (this.rainingStrength > 1.0F) { this.rainingStrength = 1.0F; } this.prevThunderingStrength = this.thunderingStrength; if (this.worldInfo.isThundering()) { this.thunderingStrength = (float)((double)this.thunderingStrength + 0.01D); } else { this.thunderingStrength = (float)((double)this.thunderingStrength - 0.01D); } if (this.thunderingStrength < 0.0F) { this.thunderingStrength = 0.0F; } if (this.thunderingStrength > 1.0F) { this.thunderingStrength = 1.0F; } } }
7e8b8abd-0b78-4bca-ae89-82fd44fae3a3
9
public ArrayList<LazyDocument> documentFor(Filer filer, TypeElement classDeclaration) throws SAXParseException { String viewName = classDeclaration.getSimpleName() + ".ui.xml"; Collection<? extends AnnotationMirror> mirrors = classDeclaration.getAnnotationMirrors(); for (AnnotationMirror mirror : mirrors) { if (((TypeElement) mirror.getAnnotationType().asElement()).getQualifiedName().toString() .equals("com.guit.client.ViewTemplate")) { Map<? extends ExecutableElement, ? extends AnnotationValue> values = mirror.getElementValues(); for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : values .entrySet()) { viewName = (String) entry.getValue().getValue(); break; } break; } } String basePackage = classDeclaration.getQualifiedName().toString(); basePackage = basePackage.substring(0, basePackage.lastIndexOf(".")); ArrayList<LazyDocument> documents = new ArrayList<LazyDocument>(); // Try to locate in the same package locateFile(filer, basePackage, viewName, documents); if (documents.size() == 0) { throw new RuntimeException("The view '" + classDeclaration.getQualifiedName() + ".ui.xml' was not found"); } return documents; }
f8fcdb81-df3d-4e06-8dcf-c42cb817f0c3
4
public PaintMessage getMessage(String string) { Scanner s = new Scanner(string); PaintMessage message = null; switch (PaintMessageType.valueOf(s.next())) { case LINE: message = new LineMessage(s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt()); break; case SHAPE: message = new ShapeMessage(Shape.valueOf(s.next()), s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt(), Boolean.valueOf(s.next())); break; case CLEAR: message = new ClearMessage(); break; case BUCKET_FILL: message = new BucketFillMessage(s.nextInt(), s.nextInt(), s.nextInt()); break; } return message; }
659c2b8a-7954-44fd-89d7-13876f9d63b2
4
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((datum == null) ? 0 : datum.hashCode()); result = prime * result + nummer; result = prime * result + plaatsen; result = prime * result + ((prijs == null) ? 0 : prijs.hashCode()); result = prime * result + ((titel == null) ? 0 : titel.hashCode()); result = prime * result + ((uitvoerders == null) ? 0 : uitvoerders.hashCode()); return result; }
b6a12533-a1cd-4b0d-b640-2d863845ae5d
3
public synchronized void lock(){ while(locked){ try{ if(this.thread != Thread.currentThread()) wait(); else break; }catch(Exception e){} } this.thread = Thread.currentThread(); locked = true; }
98c9be77-4e1f-47eb-8d90-eebc91fedeec
6
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if(isSelected) { setForeground(table.getSelectionForeground()); setBackground(table.getSelectionBackground()); }else{ setForeground(table.getForeground()); setBackground(table.getBackground()); } // 非表示レコードの文字色変更 int disableCol = recTable.getColumnModel().getColumnIndex(SearchPage.COL_LABEL_DISABLE); if (Boolean.parseBoolean(String.valueOf(recTable.getValueAt(row, disableCol)))) { if (isSelected) { setForeground(Color.GRAY); } else { setForeground(Color.LIGHT_GRAY); } } if (value instanceof Boolean) { if (column == disableCol) { // チェックボックス返却 JCheckBox obj = new JCheckBox(null, null, ((Boolean)table .getValueAt(row, column)).booleanValue()); if (isSelected) { obj.setBackground(table.getSelectionBackground()); } else { obj.setBackground(table.getBackground()); } obj.setHorizontalAlignment(CENTER); return obj; } } return this; } } /** * ペインマウスリスナー * PackageViewPanelのインナークラス */ class PaneMouseListener extends MouseAdapter { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); // 右リリースの場合 if (SwingUtilities.isRightMouseButton(e)) { recListPopup(e); } }
2bab5629-d854-4c92-94a2-979d82ac8a77
2
public static void deleteDir(File dir) { for(File file : dir.listFiles()) { if(file.isDirectory()) { deleteDir(file); continue; } file.delete(); } dir.delete(); }
f86d29b7-65cc-46fa-bef9-20c318cb28d7
1
private String formatTD(String content) { String buf = ""; int idx = 0; int aStart = 0; int aEnd = -5; int i=0; while (content.indexOf("<td", idx) != -1) { i++; aStart = content.indexOf("<td", idx); aStart = content.indexOf(">", aStart)+1; //buf += content.substring(aEnd+5, aStart); aEnd = content.indexOf("</td>", aStart); buf += " | "+content.substring(aStart, aEnd); idx = aEnd; } //buf += content.substring(aEnd+5); return buf; }
846336da-7b7d-4890-80cc-3d9e8eb6c546
5
public void put(K key, V value) { int internalKey = generateKey(key); if (array[internalKey] == null) { Bag<K, V> bag = new Bag<>(key, value, internalKey); array[internalKey] = bag; } else { int count = 0; while (array[internalKey] != null && count < size) { internalKey++; count++; if (internalKey == size) { internalKey = 0; } } if (count == size) { //throw new NoSuchMethodError("Resizing of the hashmap"); } else { Bag<K, V> bag = new Bag<K, V>(key, value, internalKey); array[internalKey] = bag; } } }
0e35e4da-40be-4c8b-8961-b9268fc541ac
3
public Object[] conectarOlib(String url, String titleno) throws ClassNotFoundException, SQLException { // retorna un arreglo con 2 arreglos en su interior [ [arreglo 1] , [arreglo 2] ] // arreglo 1: arreglo de cadenas [nombres de archivo] // arreglo 2: arreglo de cadenas [cadenas con dublin core] Class.forName("oracle.jdbc.driver.OracleDriver"); Connection conn = DriverManager.getConnection(url, usuario, contraseña); conn.setAutoCommit(false); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); //consulta (restringida a pdfs por politica de biblioteca) //String consulta= "select count ('a') from titleobjs t_o, titles t, objects o, mediatps m where t_o.titleno = t.titleno and t_o.objectno = o.objectno and t.mediatp = m.mediatp and t.titleno = " + articleno + " and lower(o.locator) like '%.pdf' UNION select count(*) from titleobjs t_o, titles t, objects o, mediatps m where t_o.titleno = t.titleno and t_o.objectno = o.objectno and t.mediatp = m.mediatp and t.titleno = " + articleno + " and lower(o.locator) like '%.pdf'"; String consulta= "select count ('a') from titles t, mediatps m where t.mediatp = m.mediatp and t.titleno = " + titleno + " UNION select count(*) from titles t, mediatps m where t.mediatp = m.mediatp and t.titleno = " + titleno + " "; //System.out.println("conectarOlib"+ consulta); ResultSet rsetA = stmt.executeQuery(consulta); int filas = 0; while (rsetA.next()) { filas += rsetA.getInt(1); } rsetA.close(); //consulta (restringida a pdfs politica de biblioteca) //consulta = "select distinct replace(o.locator,'http://www.icesi.edu.co/esn/contenido/pdfs/',''), '<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?><dublin_core>' ||' <dcvalue element=\"title\" qualifier=\"none\">'||t.title||decode(t.subtitle,null,null,' : '||t.subtitle)||'</dcvalue>' ||decode(t.isbn,null,null,' <dcvalue element=\"identifier\" qualifier=\"isbn\">'||t.isbn||'</dcvalue>') ||'<dcvalue element=\"identifier\" qualifier=\"other\">'||t.titleno||'</dcvalue>' ||fbib_dc_autores(t.titleno) ||fbib_dc_abstract(t.titleno) ||' <dcvalue element=\"language\" qualifier=\"iso\">es</dcvalue>' ||' <dcvalue element=\"date\" qualifier=\"accessioned\">'||to_char(nvl(fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>' ||' <dcvalue element=\"date\" qualifier=\"available\">'||to_char(nvl(fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>'||' <dcvalue element=\"date\" qualifier=\"issued\">'||to_char(nvl(fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>' ||fbib_dc_altertitulo(t.titleno) ||fbib_dc_publicador(t.titleno) ||fbib_dc_subject(t.titleno) ||fbib_dc_sponsors(t.titleno) ||fbib_dc_type(t.titleno) ||' </dublin_core>' dc_info from titleobjs t_o, titles t, objects o, mediatps m where t_o.titleno = t.titleno and t_o.objectno = o.objectno and t.mediatp = m.mediatp and t.articleno = "+ articleno +" and lower(o.locator) like '%.pdf' UNION select distinct replace(o.locator,'http://www.icesi.edu.co/esn/contenido/pdfs/',''), '<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?><dublin_core>' ||' <dcvalue element=\"title\" qualifier=\"none\">'||t.title||decode(t.subtitle,null,null,' : '||t.subtitle)||'</dcvalue>' ||decode(t.isbn,null,null,' <dcvalue element=\"identifier\" qualifier=\"isbn\">'||t.isbn||'</dcvalue>') ||'<dcvalue element=\"identifier\" qualifier=\"other\">'||t.titleno||'</dcvalue>' ||fbib_dc_autores(t.titleno) ||fbib_dc_abstract(t.titleno) ||' <dcvalue element=\"language\" qualifier=\"iso\">es</dcvalue>' ||' <dcvalue element=\"date\" qualifier=\"accessioned\">'||to_char(nvl(fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>' ||' <dcvalue element=\"date\" qualifier=\"available\">'||to_char(nvl(fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>'||' <dcvalue element=\"date\" qualifier=\"issued\">'||to_char(nvl(fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>' ||fbib_dc_altertitulo(t.titleno) ||fbib_dc_publicador(t.titleno) ||fbib_dc_subject(t.titleno) ||fbib_dc_sponsors(t.titleno) ||fbib_dc_type(t.titleno) ||' </dublin_core>' dc_info from titleobjs t_o, titles t, objects o, mediatps m where t_o.titleno = t.titleno and t_o.objectno = o.objectno and t.mediatp = m.mediatp and t.titleno = "+ articleno +" and lower(o.locator) like '%.pdf'"; //consulta = "select distinct replace(o.locator,'http://www.icesi.edu.co/esn/contenido/pdfs/',''), '<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?><dublin_core>' ||' <dcvalue element=\"title\" qualifier=\"none\">'||t.title||decode(t.subtitle,null,null,' : '||t.subtitle)||'</dcvalue>' ||decode(t.isbn,null,null,' <dcvalue element=\"identifier\" qualifier=\"isbn\">'||t.isbn||'</dcvalue>') ||'<dcvalue element=\"identifier\" qualifier=\"other\">'||t.titleno||'</dcvalue>' ||olib.fbib_dc_autores(t.titleno) ||olib.fbib_dc_abstract(t.titleno) ||' <dcvalue element=\"language\" qualifier=\"iso\">es</dcvalue>' ||' <dcvalue element=\"date\" qualifier=\"accessioned\">'||to_char(nvl(olib.fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>' ||' <dcvalue element=\"date\" qualifier=\"available\">'||to_char(nvl(olib.fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>'||' <dcvalue element=\"date\" qualifier=\"issued\">'||to_char(nvl(olib.fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>' ||olib.fbib_dc_altertitulo(t.titleno) ||olib.fbib_dc_publicador(t.titleno) ||olib.fbib_dc_subject(t.titleno) ||olib.fbib_dc_sponsors(t.titleno) ||olib.fbib_dc_type(t.titleno) ||' </dublin_core>' dc_info from titleobjs t_o, titles t, objects o, mediatps m where t_o.titleno = t.titleno and t_o.objectno = o.objectno and t.mediatp = m.mediatp and t.articleno = "+ articleno +" and lower(o.locator) like '%.pdf' UNION select distinct replace(o.locator,'http://www.icesi.edu.co/esn/contenido/pdfs/',''), '<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?><dublin_core>' ||' <dcvalue element=\"title\" qualifier=\"none\">'||t.title||decode(t.subtitle,null,null,' : '||t.subtitle)||'</dcvalue>' ||decode(t.isbn,null,null,' <dcvalue element=\"identifier\" qualifier=\"isbn\">'||t.isbn||'</dcvalue>') ||'<dcvalue element=\"identifier\" qualifier=\"other\">'||t.titleno||'</dcvalue>' ||olib.fbib_dc_autores(t.titleno) ||olib.fbib_dc_abstract(t.titleno) ||' <dcvalue element=\"language\" qualifier=\"iso\">es</dcvalue>' ||' <dcvalue element=\"date\" qualifier=\"accessioned\">'||to_char(nvl(olib.fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>' ||' <dcvalue element=\"date\" qualifier=\"available\">'||to_char(nvl(olib.fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>'||' <dcvalue element=\"date\" qualifier=\"issued\">'||to_char(nvl(olib.fbibbus_fecha_pub(t.titleno),sysdate),'yyyy-mm-dd')||'</dcvalue>' ||olib.fbib_dc_altertitulo(t.titleno) ||olib.fbib_dc_publicador(t.titleno) ||olib.fbib_dc_subject(t.titleno) ||olib.fbib_dc_sponsors(t.titleno) ||olib.fbib_dc_type(t.titleno) ||' </dublin_core>' dc_info from titleobjs t_o, titles t, objects o, mediatps m where t_o.titleno = t.titleno and t_o.objectno = o.objectno and t.mediatp = m.mediatp and t.titleno = "+ articleno +" and lower(o.locator) like '%.pdf'"; /*Gavarela: La consulta original sacaba todo el dublin core en una sola columna, * esto generaba problemas ya que el límite de retorno de un VARCHAR2 es de 4000, * por eso se partió el dublin core en 3 columnas, dejando la descripción como columna aparte*/ /*"SELECT DISTINCT REPLACE(o.locator, 'http://www.icesi.edu.co/esn/contenido/pdfs/', '')" + ",'<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><dublin_core>' || "+ "' <dcvalue element=\"title\" qualifier=\"none\">' || t.title || decode(t.subtitle, NULL, NULL, ' : ' || t.subtitle) || '</dcvalue>' ||"+ " decode(t.isbn, NULL, NULL, ' <dcvalue element=\"identifier\" qualifier=\"isbn\">' || t.isbn || '</dcvalue>') || "+ "'<dcvalue element=\"identifier\" qualifier=\"other\">' || t.titleno || '</dcvalue>' || "+"olib.fbib_dc_autores(t.titleno)" + ", olib.fbib_dc_abstract(t.titleno)|| "+ "' <dcvalue element=\"identifier\" qualifier=\"OLIB\">http://biblioteca2.icesi.edu.co/cgi-olib?infile=details.glu&loid=' || t.titleno || '</dcvalue>' ||" + "' <dcvalue element=\"language\" qualifier=\"iso\">spa</dcvalue>' || "+ "' <dcvalue element=\"date\" qualifier=\"available\">' || "+ " to_char(nvl(olib.fbibbus_fecha_pub(t.titleno), sysdate), 'yyyy-mm-dd') || '</dcvalue>' || "+ "' <dcvalue element=\"date\" qualifier=\"issued\">' || to_char(nvl(olib.fbibbus_fecha_pub(t.titleno), sysdate), 'yyyy-mm-dd') || '</dcvalue>' ||"+ " olib.fbib_dc_altertitulo(t.titleno) || decode(t.isbn, NULL, NULL, '<dcvalue element=\"pubplace\" qualifier=\"none\">' || tp.pubplace || '</dcvalue>') ||"+ " olib.fbib_dc_publicador(t.titleno) || olib.fbib_dc_subject(t.titleno) || olib.fbib_dc_sponsors(t.titleno) || olib.fbib_dc_type(t.titleno) || "+ "' </dublin_core>' dc_info" + " FROM titleobjs t_o, titles t, objects o, mediatps m, titlepub tp" + " WHERE t_o.titleno = t.titleno" + " AND t_o.objectno = o.objectno" + " AND t.mediatp = m.mediatp" + //" AND t.articleno = "+ articleno + " AND t.titleno = "+ articleno + " AND tp.titleno = "+ articleno + " AND LOWER(o.locator) LIKE '%.pdf'" + " UNION" +*/ /*" SELECT DISTINCT REPLACE(o.locator, 'http://www.icesi.edu.co/esn/contenido/pdfs/', '')" + ", '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><dublin_core>' || ' <dcvalue element=\"title\" qualifier=\"none\">' || t.title || decode(t.subtitle, NULL, NULL, ' : ' || t.subtitle) || '</dcvalue>' || decode(t.isbn, NULL, NULL, ' <dcvalue element=\"identifier\" qualifier=\"isbn\">' || t.isbn || '</dcvalue>') || '<dcvalue element=\"identifier\" qualifier=\"other\">' || t.titleno || '</dcvalue>' || olib.fbib_dc_autores(t.titleno)" + ", olib.fbib_dc_abstract(t.titleno) || ' <dcvalue element=\"identifier\" qualifier=\"OLIB\">http://biblioteca2.icesi.edu.co/cgi-olib?infile=details.glu&loid=' || t.titleno||'</dcvalue>' ||" + "'<dcvalue element=\"language\" qualifier=\"iso\">es</dcvalue>' || '</dcvalue>' || ' <dcvalue element=\"date\" qualifier=\"available\">' || to_char(nvl(olib.fbibbus_fecha_pub(t.titleno), sysdate), 'yyyy-mm-dd') || '</dcvalue>' || ' <dcvalue element=\"date\" qualifier=\"issued\">' || to_char(nvl(olib.fbibbus_fecha_pub(t.titleno), sysdate), 'yyyy-mm-dd') || '</dcvalue>' || olib.fbib_dc_altertitulo(t.titleno) || decode(t.isbn, NULL, NULL, '<dcvalue element=\"pubplace\" qualifier=\"none\">' || tp.pubplace || '</dcvalue>') || olib.fbib_dc_publicador(t.titleno) || olib.fbib_dc_subject(t.titleno) || olib.fbib_dc_sponsors(t.titleno) || olib.fbib_dc_type(t.titleno) || ' </dublin_core>' dc_info" + " FROM titleobjs t_o, titles t, objects o, mediatps m, titlepub tp" + " WHERE t_o.titleno = t.titleno" + " AND t_o.objectno = o.objectno" + " AND t.mediatp = m.mediatp" + " AND t.titleno = "+ articleno + " AND tp.titleno = "+ articleno + " AND LOWER(o.locator) LIKE '%.pdf'";*/ consulta = " SELECT DISTINCT " + "'<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><dublin_core>' || ' <dcvalue element=\"title\" qualifier=\"none\">' || t.title || decode(t.subtitle, NULL, NULL, ' : ' || t.subtitle) || '</dcvalue>' || decode(t.isbn, NULL, NULL, ' <dcvalue element=\"identifier\" qualifier=\"isbn\">' || t.isbn || '</dcvalue>') || '<dcvalue element=\"identifier\" qualifier=\"other\">' || t.titleno || '</dcvalue>' || olib.fbib_dc_autores(t.titleno)" + " || ' <dcvalue element=\"identifier\" qualifier=\"OLIB\">http://biblioteca2.icesi.edu.co/cgi-olib?oid=' || t.titleno||'</dcvalue>' ||" + "'<dcvalue element=\"language\" qualifier=\"iso\">spa</dcvalue>' || ' <dcvalue element=\"date\" qualifier=\"available\">' || to_char(nvl(olib.fbibbus_fecha_pub(t.titleno), sysdate), 'yyyy-mm-dd') || '</dcvalue>' || ' <dcvalue element=\"date\" qualifier=\"issued\">' || to_char(nvl(olib.fbibbus_fecha_pub(t.titleno), sysdate), 'yyyy-mm-dd') || '</dcvalue>' || olib.fbib_dc_altertitulo(t.titleno) || decode(t.isbn, NULL, NULL, '<dcvalue element=\"pubplace\" qualifier=\"none\">' || tp.pubplace || '</dcvalue>') || olib.fbib_dc_subject(t.titleno) || " +"'<dcvalue element=\"format\" qualifier=\"none\">PDF</dcvalue>' || '<dcvalue element=\"format\" qualifier=\"medium\">Digital</dcvalue>' || '<dcvalue element=\"relation\" qualifier=\"hasversion\">publishedVersion</dcvalue>' || " +"'<dcvalue element=\"coverage\" qualifier=\"none\">Cali de Lat: 03 24 00 N degrees minutes Lat: 3.4000 decimal degrees Long: 076 30 00 W degrees minutes Long: -76.5000 decimal degrees.</dcvalue>' || " +"'<dcvalue element=\"rights\" qualifier=\"accessRights\">openAccess</dcvalue>' || " +" olib.fbib_dc_contributors(t.titleno) || olib.fbib_dc_departament(t.titleno) || olib.fbib_dc_faculty(t.titleno) dc_info , " +" olib.fbib_dc_type_title(t.titleno) || " +"'<dcvalue element=\"format\" qualifier=\"mimetype\">Application PDF</dcvalue>' || " +"'<dcvalue element=\"publisher\" qualifier=\"none\">Universidad Icesi</dcvalue>' || " +" olib.fbib_dc_pubplace(t.titleno) || " +" olib.fbib_dc_format_extent(t.titleno) dc_info1 , " +" olib.fbib_dc_abstract(t.titleno) || " + "' </dublin_core>' " + " FROM titles t, mediatps m, titlepub tp" + " WHERE t.mediatp = m.mediatp" + " AND t.titleno = "+ titleno + " AND tp.titleno = "+ titleno ; //System.out.println(consulta); ResultSet rset = stmt.executeQuery(consulta); String dir[] = new String[filas]; String dublin[] = new String[filas]; int cont = 0; while (rset.next()) { /*String dc = rset.getString(2); dc += rset.getString(3); dc += rset.getString(4);*/ String dc= rset.getString(1); dc+= rset.getString(2); dc += rset.getString(3); //AQUI MACHETE! :) EN CASO DE QUE LA CONSULTA RETORNE UNA CADENA HEXADECIMAL /*if (!dc.startsWith("<")) { int a = dc.indexOf("x"); if (a != -1) { dc = dc.substring(a + 1); dc = convertToUnicodeString(dc); } }*/ //Reemplasar caracter '%' por 'Porciento' y '&' por 'y' (causan problemas en la importacion) //dc = dc.replace("&", "&amp;"); //dc = dc.replace("%", "porciento"); //dir[cont] = rset.getString(1); dublin[cont] = dc; cont++; } stmt.close(); /* Se recorre el arreglo de archivos de tipo pdf que contiene el directorio */ for(int i=0; i< archivos.length; i++) { dir[i]= archivos[i]; } Object[] resultado = new Object[2]; resultado[0] = dir; resultado[1] = dublin; return resultado; }
31b3ce0a-01dd-4226-be2a-04b30dbff92f
1
public void render(Graphics g) { Graphics2D g2d = (Graphics2D) g; AffineTransform transformation = new AffineTransform(); //rotiere den Vogel transformation.translate(x, y); try { double xOrient = (double)direction.getY(); double yOrient = (double)direction.getX(); double pos = Math.atan2(xOrient, yOrient)+Math.PI / 2; transformation.rotate(pos); g2d.setTransform(transformation); } catch (Exception e) { // TODO: handle exception } // zeichne das Dreieck g2d.setColor(color); g2d.fillPolygon(triangle); }
271bc9d1-3ad8-43e2-8e1e-f3ffdbb72dec
9
@Override public void setValueAt(Object o, int row, int col) { Order or = info.get(row); switch (col) { case 0 : or.getOrderName(); break; case 1 : or.getDueDate(); break; case 2 : or.getSleeve().getMaterial().getName(); break; case 3 : or.getSleeve().getThickness(); break; case 4 : or.getSleeve().getCircumference(); break; case 5 : or.getWidth(); break; case 6 : or.getQuantity(); break; // case 7 : or.getConductedQuantity(); break; case 8 : or.getStatus(); break; case 9 : or.isUrgent(); break; } }
3d7241e4-2a85-41cf-9519-bd8cb9d7a750
8
private JPanel setupControlPanel() { JPanel controlPanel = new JPanel(); controlPanel.setBorder(new TitledBorder("Controls")); GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); controlPanel.setLayout(gbl); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.ipady = 0; gbc.ipadx = 0; gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; // a special controls mode panel if (setupDragAndDrop) { JPanel panel00 = setupControlMode(); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbl.setConstraints(panel00, gbc); controlPanel.add(panel00); } // next row gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; { // To DO: change setupControls here... JPanel panel01 = setupControls(nameTableRegions[0], "Name Table"); final JCheckBox oamCB = new JCheckBox("Show OAM Grid"); oamCB.setSelected(nameTableRegions[0].getShowOAMGrid()); oamCB.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { nameTableRegions[0].setShowOAMGrid(oamCB.isSelected()); for (int i = 0; i < nameTableRegions.length; i++) { nameTableRegions[i].notifyDisplayInterfaceUpdated(); } } }); panel01.add(oamCB); { JPanel spinnerPanel = new JPanel(); spinnerPanel.setLayout(new FlowLayout()); final JSpinner spinner = new JSpinner(); Integer value = new Integer(nameTableRegions[0].getScale()); Integer min = new Integer(NameTablePanel.MIN_SCALE); Integer max = new Integer(NameTablePanel.MAX_SCALE); Integer step = new Integer(1); SpinnerNumberModel spinnerModel = new SpinnerNumberModel(value, min, max, step); spinner.setModel(spinnerModel); spinner.setToolTipText("Scale for the Name Table"); spinner.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { int newVal = ((Integer) spinner.getModel().getValue()).intValue(); for (int i = 0; i < nameTableRegions.length; i++) { nameTableRegions[i].setScale(newVal); } } }); spinnerPanel.add(new JLabel("Scale:")); spinnerPanel.add(spinner); panel01.add(spinnerPanel); } gbl.setConstraints(panel01, gbc); controlPanel.add(panel01); } if (editorRegion != null) { gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; JPanel panel11 = setupControls(editorRegion, "Entry Editor"); gbl.setConstraints(panel11, gbc); controlPanel.add(panel11); } gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 1; { JPanel panel02 = setupControls(patternTableRegions[0], "Background Pattern Table"); ButtonGroup buttonGroup = new ButtonGroup(); JRadioButton b1 = new JRadioButton("Background Palette"); buttonGroup.add(b1); panel02.add(b1); JRadioButton b2 = new JRadioButton("Sprite Palette"); buttonGroup.add(b2); panel02.add(b2); buttonGroup.setSelected(b1.getModel(), true); b1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { patternTableRegions[0].setPaletteType(0); } } }); b2.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { patternTableRegions[0].setPaletteType(1); } } }); gbl.setConstraints(panel02, gbc); controlPanel.add(panel02); } gbc.gridx = 1; gbc.gridy = 2; { JPanel panel12 = setupControls(patternTableRegions[1], "Sprite Pattern Table"); ButtonGroup buttonGroup = new ButtonGroup(); JRadioButton b1 = new JRadioButton("Background Palette"); buttonGroup.add(b1); panel12.add(b1); JRadioButton b2 = new JRadioButton("Sprite Palette"); buttonGroup.add(b2); panel12.add(b2); buttonGroup.setSelected(b2.getModel(), true); b1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { patternTableRegions[1].setPaletteType(0); } } }); b2.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { patternTableRegions[1].setPaletteType(1); } } }); gbl.setConstraints(panel12, gbc); controlPanel.add(panel12); } // put it in the top left corner (when scaling) JPanel daOtherPanel = new JPanel(); daOtherPanel.setLayout(new BorderLayout()); daOtherPanel.add(controlPanel, BorderLayout.NORTH); JPanel daPanel = new JPanel(); daPanel.setLayout(new BorderLayout()); daPanel.add(daOtherPanel, BorderLayout.WEST); return daPanel; }
187ca12b-6a50-4dba-8c84-354e0956715b
8
public void Play() { while (game.getGameState() != GameState.Ending) { switch (game.getGameState()) { case MainMenu: visualiser.sayHello(); String[] names = visualiser.getNames(); game.getPlayers()[0].setName(names[0]); game.getPlayers()[1].setName(names[1]); game.setGameState(GameState.Fight); break; case Fight: MoveAttributes ma;// = new MoveAttributes(); while ((game.getPlayers()[0].getHp() > 0) && (game.getPlayers()[1].getHp() > 0)) { game.setCurrentPlayer(); //get player parameters and visualise if (game.getPlayers()[game.getCurrentPlayer()].getStatus() != Status.Stunned) { visualiser.printWhiteSpaces(2); visualiser.outStatus(game.getPlayers()[game.getCurrentPlayer()], game.getPlayers()[game.anotherPlayer()]); //setting move parameteres ma = visualiser.getMove(); game.getPlayers()[game.getCurrentPlayer()].setMove(new Move(new Defense(ma.getDefenseTarget()), new Attack(ma.getAttackTarget(), ma.getAttackType()))); visualiser.printWhiteSpaces(2); } if (game.getPlayers()[game.anotherPlayer()].getStatus() != Status.Stunned) { visualiser.outStatus(game.getPlayers()[game.anotherPlayer()], game.getPlayers()[game.getCurrentPlayer()]); ma = visualiser.getMove(); game.getPlayers()[game.anotherPlayer()].setMove(new Move(new Defense(ma.getDefenseTarget()), new Attack(ma.getAttackTarget(), ma.getAttackType()))); visualiser.printWhiteSpaces(2); } //process move and visualise it visualiser.outMoveResult(game.evaluateMove()); } game.setGameState(GameState.Ending); break; case Ending: break; } } visualiser.printWhiteSpaces(2); visualiser.outWinner(game.getPlayers()[game.getCurrentPlayer()].getName()); }
599b8430-e750-45fb-9411-2b3017911d43
1
public String properties() { String gasString = ""; if(isGas()) gasString = " gas"; return protons+" "+getSymbol()+" "+getName()+gasString+" Mass: "+getMass()+" Density: "+getDensity(); }
f120cf73-16bd-4a07-88ca-b3be308aa105
0
private void ExitbuttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ExitbuttonMouseClicked // TODO add your handling code here: dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); System.exit(0); }//GEN-LAST:event_ExitbuttonMouseClicked
6644b385-13a0-4ed3-b81d-9d24e470645a
4
public Matrix getD () { Matrix X = new Matrix(n,n); double[][] D = X.getArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { D[i][j] = 0.0; } D[i][i] = d[i]; if (e[i] > 0) { D[i][i+1] = e[i]; } else if (e[i] < 0) { D[i][i-1] = e[i]; } } return X; }
323958fd-04ba-43d0-b8e2-253e0ef4ff3f
3
private void trigger(){ Set<String> fileSignatureSet = filePathModifiedTimeMap.keySet(); for ( String fileSignature : fileSignatureSet ){ File file = new File(fileSignature); long currentLastModifiedTime = file.lastModified(); Long lastestLastModifiedTime = filePathModifiedTimeMap.get(fileSignature); // if different, invoke onChanged method if( lastestLastModifiedTime!=null && currentLastModifiedTime != lastestLastModifiedTime ){ ResourceUpdaterListener listener = listenerMap.get(fileSignature); listener.onChanged(); logger.info("Reloading the resource. signature = "+listener.signature()); filePathModifiedTimeMap.put(fileSignature, currentLastModifiedTime); logger.info("Reload the resource successfully. signature = "+listener.signature()); } } }
5b89611c-17be-43d8-b44a-050a0d311b05
1
public static void closeConnection(){ try { conn.close(); } catch (SQLException e) { System.out.println("error closing connection within process class"); e.printStackTrace(); } }
4c38ac14-7654-4a93-9968-6e1d8d3ca1ea
9
public int alphaBetaSearchResult(int depth, int alpha, int beta) { if (isTerminalState()) return heuristicFunctionValueOfGivenBlock(lastMoveMadeInBlockNumber); else if (depth == 0) return heuristicFunctionValueOfGame(); List <Integer> listOfEmptyCells = getBlock(nextMoveInBlockNumber).getListOfBestMovesForThisCell(whoHasNextMove); if (!isOpponentPlaying()) { for (int emptyCell : listOfEmptyCells) { // Expand this game state Game expandedState = new Game(this, whoHasNextMove); expandedState.setMove(whoHasNextMove, nextMoveInBlockNumber, emptyCell); int alphaValue = expandedState.alphaBetaSearchResult(depth - 1, alpha, beta); if (alphaValue > alpha) alpha = alphaValue; if (alpha >= beta) return alpha; } return alpha; } else { for (int emptyCell : listOfEmptyCells) { Game expandedState = new Game(this, whoHasNextMove); expandedState.setMove(whoHasNextMove, nextMoveInBlockNumber, emptyCell); int betaValue = expandedState.alphaBetaSearchResult(depth - 1, alpha, beta); if (betaValue < beta) beta = betaValue; if (beta <= alpha) return beta; } return beta; } }
4b85d507-819e-4846-9fea-59a30ed306f5
1
static void openURL (String url) throws IOException, URISyntaxException{ Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.BROWSE)){ desktop.browse(new URI(url) ); }else showMessage(("Error")); }
4efa3005-bb0d-49a6-b7c5-0e40acc27f6e
4
private void readtRNS() throws IOException { switch (colorType) { case COLOR_GREYSCALE: checkChunkLength(2); transPixel = new byte[2]; readChunk(transPixel, 0, 2); break; case COLOR_TRUECOLOR: checkChunkLength(6); transPixel = new byte[6]; readChunk(transPixel, 0, 6); break; case COLOR_INDEXED: if(palette == null) { throw new IOException("tRNS chunk without PLTE chunk"); } paletteA = new byte[palette.length/3]; Arrays.fill(paletteA, (byte)0xFF); readChunk(paletteA, 0, paletteA.length); break; default: // just ignore it } }
cbba3560-4485-4518-8581-d14260357919
3
public void deleteCommand() { try{ int choice = JOptionPane.showConfirmDialog(rootPane, "Are you sure you want to delete " + currentRunway.getId() + "?" + "\n This will also delete all glider and winch positions associated with this runway.", "Delete Runway", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (choice == 0){ DatabaseUtilities.DatabaseEntryDelete.DeleteEntry(currentRunway); objectSet.clearRunway(); JOptionPane.showMessageDialog(rootPane, currentRunway.toString() + " successfully deleted."); parent.update("2"); this.dispose(); } }catch (ClassNotFoundException e2) { JOptionPane.showMessageDialog(rootPane, "Error: No access to database currently. Please try again later.", "Error", JOptionPane.INFORMATION_MESSAGE); }catch (Exception e3) { } }
babf0b19-4352-4ad3-b56b-8a4432071a5a
8
@Override public ImmutableValue<Boolean> evaluate(Context context) { // destacando variaveis Value[] values = new Value[variables.length]; for (int i = 0; i < variables.length; i++) { Expression variable = variables[i]; values[i] = variable.evaluate(context); } // destacando o iterador Object target = list.evaluate(context).get(); Iterator it = (target instanceof Iterable) ? ((Iterable) target).iterator() : (Iterator) target; // aplicando o padrao while (it.hasNext()) { Object current = it.next(); // avancando as variaveis for (int i = 0; i < (values.length - 1); i++) { values[i].set(values[i + 1].get()); } values[values.length - 1].set(current); boolean valid = (Boolean) body.evaluate(context).get(); if (!valid) { return new ImmutableValue<Boolean>(false); } } // esgotando as variaveis for (int j = 0; j < values.length - 1; j++) { // avancando as variaveis for (int i = 0; i < (values.length - 1); i++) { values[i].set(values[i + 1].get()); } values[values.length - 1].set(null); boolean valid = (Boolean) body.evaluate(context).get(); if (!valid) { return new ImmutableValue<Boolean>(false); } } return new ImmutableValue<Boolean>(true); }
29317770-407e-49c8-b975-ded5efd9d479
1
@Test public void testTimeStep_MEAN_MONTHLY_1year() throws Exception { printDebug("----------------------------"); printDebug("MEAN_MONTHLY 1 year: " + this.toString()); printDebug("----------------------------"); CSTable t = DataIO.table(r, "obs"); Assert.assertNotNull(t); // 1 YEAR Date start = Conversions.convert("1981-1-01", Date.class); Date end = Conversions.convert("1981-12-31", Date.class); //System.out.println("Start = " + start.toString() + "; End = " + end.toString()); double[] obsval = DataIO.getColumnDoubleValuesInterval(start, end, t, "runoff[0]", DataIO.MEAN_MONTHLY); //System.out.println("# values = " + obsval.length); Assert.assertTrue(obsval.length == 12); //Values computed directly from .csv file double[] goldenVal = new double[12]; goldenVal[0] = 2430 / 31.0; goldenVal[1] = 3897 / 28.0; goldenVal[2] = 4587 / 31.0; goldenVal[3] = 14840 / 30.0; goldenVal[4] = 21287 / 31.0; goldenVal[5] = 11096 / 30.0; goldenVal[6] = 3048 / 31.0; goldenVal[7] = 2187 / 31.0; goldenVal[8] = 1345 / 30.0; goldenVal[9] = 1893 / 31.0; goldenVal[10] = 8457 / 30.0; goldenVal[11] = 13534 / 31.0; for (int i = 0; i < obsval.length; i++) { printDebug("obs[" + i + "] = " + obsval[i] + ";\tGolden = " + goldenVal[i]); } Assert.assertArrayEquals(goldenVal, obsval, 0); }
6624d61b-0207-449b-8d2c-a69349d3f0b7
2
public void releaseAllKeys() { for(int i = 0; i < buttons.length; i++) { buttons[i] = false; } for(int j = 0; j < upButtons.length; j++) { upButtons[j] = false; } }
d4a41764-6865-4c32-ac81-4d0a10dc7bf4
5
public static String to_booleanString(String str) { if (str == null) return null; String[] trueValues = new String[] {"true","True","Yes","yes","1","-1","yep","supported"}; String[] falseValues = new String[] {"false","no","False","No","0","nope","not supported","not_supported"}; //ArrayList<String> trueValues = new ArrayList<String>(); for (int i=0; i < trueValues.length; i++) { if (str.equals(trueValues[i])) return "1"; } for (int i=0; i < falseValues.length; i++) { if (str.equals(falseValues[i])) return "0"; } return null; }
7e269b3d-207b-47b4-91c0-581db60f1cf2
0
private ImageProcessor hMinima(ImageProcessor ip, int m){ ip.invert(); ImageProcessor ip1 = ip.duplicate(); ip1.subtract(m); GreyscaleReconstruct_ gr = new GreyscaleReconstruct_(); Object[] result = gr.exec(new ImagePlus("temp", ip), new ImagePlus("temp1", ip1), "null", true, false); ip.invert(); return ((ImagePlus) result[1]).getProcessor(); //call matlab }
50a8eab1-9d35-4a1a-bfc1-3f1850ba8fa1
8
public void render(Graphics g, Camera camera) { int x0 = camera.x >> 4; int x1 = (camera.x + camera.width + 16) >> 4; int y0 = camera.y >> 4; int y1 = (camera.y + camera.height + 16) >> 4; for (int y = y0; y < y1; y++) { for (int x = x0; x < x1; x++) { if (x >= 0 && y >= 0 && x < width && y < height) { if (world[x][y] != null) { world[x][y].render(x, y, g); } } } } for (int i = 0; i <= entities.size() - 1; i++) { Entity e = entities.get(i); e.render(g, camera); } }
642267c8-2140-48a7-a79d-210f9113ff36
5
static final void method1005(byte byte0, boolean flag) { if (TraversalMap.aByteArrayArrayArray976 == null) { TraversalMap.aByteArrayArrayArray976 = new byte[4][104][104]; } if (!flag) { return; } for (int i = 0; i < 4; i++) { for (int j = 0; j < 104; j++) { for (int k = 0; k < 104; k++) { TraversalMap.aByteArrayArrayArray976[i][j][k] = byte0; } } } }
978e83be-98b8-47e7-929d-08d7d49d6d73
6
private static DecimalImpl divByInt(final long d1Base, final int d1Factor, final long d2Base) { if (d1Factor < 0) { final long scaledBase = d1Base * DPU.getScale(-d1Factor); final long base = scaledBase / d2Base; final long remainder = scaledBase % d2Base; if (0 != remainder) { final int factorLimit = DPU.findFactorByLimit(base); if (factorLimit > 0) { final int factor = factorLimit + d1Factor; final long scaledRemainder = remainder * DPU.getScale(factor); final long remainderBase; if (DPU.isSameMulSign(remainder, DPU.getScale(factor), scaledRemainder)) { remainderBase = scaledRemainder / d2Base; } else { remainderBase = remainder / (d2Base / DPU.getScale(factor)); } return safegetInstance(base * DPU.getScale(factor) + remainderBase, factor); } } return getInstance(base, 0); } else { final long base = d1Base / d2Base; final long remainder = d1Base % d2Base; if (0 != remainder) { final int factorLimit = DPU.findFactorByLimit(Math.abs(base)); final int factorDiff = factorLimit - d1Factor; if (factorDiff > 0) { final long remainderBase = remainder * DPU.getScale(factorDiff) / d2Base; return safegetInstance(base * DPU.getScale(factorDiff) + remainderBase, factorLimit); } } return getInstance(base, d1Factor); } }
2b55c8bd-935d-4fa4-960d-82ea95f5f767
8
@Override public void paintComponent(Graphics g) { super.paintComponent(g); // Offset used by the image, as well as their "highlighted" buttons. Point offsetHead = new Point(10, 25); Point offsetMiddle = new Point(235, 30); // Sinleton to load the images only once. Placing this in the // Constructor will fail to load the images to begin with - Java bug? if(imageWiiHead == null) { try { imageWiiHead = ImageIO.read(getClass().getResource("/Resources/wiiremote_head.png")); imageWiiMiddle = ImageIO.read(getClass().getResource("/Resources/wiiremote_middle.png")); } catch (IOException ex) { } } g.drawImage(imageWiiHead, offsetHead.x, offsetHead.y, null); g.drawImage(imageWiiMiddle, offsetMiddle.x, offsetMiddle.y, null); // Color of the highlighted buttons: g.setColor(Color.decode("0x5b7886")); // This routine should highlight any button currently pressed. if(isLeft) drawSquare(g, 42, 95, offsetHead); // left if(isRight) drawSquare(g, 95, 95, offsetHead); // right if(isUp) drawSquare(g, 68, 68, offsetHead); // up if(isDown) drawSquare(g, 68, 122, offsetHead); // down if(isMinus) drawCircle(g, 23, 23, offsetMiddle); // - button if(isPlus) drawCircle(g, 111, 23, offsetMiddle); // + button }
d71adfa6-9207-4038-ab14-3939df1dddb9
6
@Override public double calculate(Map<? extends Number, ? extends Number> weightedSet, double extremalLevel) { assert extremalLevel >= -1 && extremalLevel <= 1; // используя гравитационное расширение нечетких сравнений найдем центр тяжести всей совокупности. double sumOfRectifications = 0; for (Map.Entry<? extends Number, ? extends Number> entry : weightedSet.entrySet()) { sumOfRectifications += entry.getKey().doubleValue() * entry.getValue().doubleValue(); } double mediana = sumOfRectifications / weightedSet.size(); // сравнивая медиану с искомым вертикальным уровнем, должны получить, что уровень сильно больше , // тоесть n ( mediana. verticalLevel) = 0.5 // возьмем простое сравнение n(a, b) = (b - a) / (a^2 + b^2)^0.5 // есть решение на бумажке return mediana * (8 + Math.sqrt(28)) / 6; }
6ddb9274-b36c-42e0-ae09-cb9dcbefcb65
1
public static int parse(String methods) { int httpMethods = 0; String[] items = methods.split("\\|"); for (String item : items) { item = item.trim(); httpMethods = httpMethods | HttpMethods.getMethod(item); } return httpMethods; }
91fe3b4d-591e-4501-a2ad-89ac180e43fd
1
public void initialize(ConstPool cp, CodeAttribute attr) { if (constPool != cp) newIndex = 0; }
7d9dd72d-e350-46b2-9049-a86f7bfef00e
0
@Override public void windowActivated(WindowEvent e) { }
37644691-dc03-456a-9a3e-6379aa4cb090
6
private static Attack createAttack(Element type){ Element attackElement = (Element)type.getElementsByTagName("attack").item(0); if(attackElement == null){ return null; } SoundWrapper attackSound = ResourceLoader.createSound(attackElement.getAttribute("sound"), Float.parseFloat(attackElement.getAttribute("soundVolume"))); String attackType = attackElement.getAttribute("type"); Attack attack = null; int baseDamage = Integer.parseInt(attackElement.getAttribute("baseDamage")); int randomDamage = Integer.parseInt(attackElement.getAttribute("randomDamage")); int cooldown = Integer.parseInt(attackElement.getAttribute("cooldown")); if(attackType.equals("MELEE")){ attack = new Attack(baseDamage, randomDamage, cooldown, attackSound); }else if(attackType.equals("RANGED") || attackType.equals("RANGED_ACTION")){ double range = Double.parseDouble(attackElement.getAttribute("range")); int projectileSize = Integer.parseInt(attackElement.getAttribute("projectileSize")); Color projectileColor; if(attackElement.hasAttribute("projectileColor")){ projectileColor = getColorFromString(attackElement.getAttribute("projectileColor")); }else{ projectileColor = getColorFromStrings( attackElement.getAttribute("projectileColorR"), attackElement.getAttribute("projectileColorG"), attackElement.getAttribute("projectileColorB") ); } double projectileSpeed = Double.parseDouble(attackElement.getAttribute("projectileSpeed")); SoundWrapper sound = ResourceLoader.createSound( attackElement.getAttribute("sound"), Float.parseFloat(attackElement.getAttribute("soundVolume"))); if(attackType.equals("RANGED")){ attack = new RangedAttack(baseDamage, randomDamage, cooldown, range, projectileSize, projectileColor, projectileSpeed, sound); }else{ Element effectElement = (Element) attackElement.getElementsByTagName("effect").item(0); Effect effect = new EffectFactory().createEffect(effectElement); attack = new RangedActionAttack(baseDamage, randomDamage, cooldown, range, projectileSize, projectileColor, projectileSpeed, effect, sound); } }else{ new Exception("Unknown attackType-value in XML").printStackTrace(); } return attack; }
ff045283-5385-4c8e-8f48-3e98b431ea54
5
public boolean isMobAllowed(final EntityType type) { return type == EntityType.SPIDER || type == EntityType.CAVE_SPIDER || type == EntityType.SKELETON || type == EntityType.CREEPER || type == EntityType.PIG_ZOMBIE || type == EntityType.ZOMBIE; }
c0d39194-a327-4e1b-93bd-ac84f93f374c
7
private int getIssueCycle2(int[][] schedule, int instructionNumber) { FunctionType function = executed.get(instructionNumber).getFunction(); int cycle = schedule[instructionNumber - 1][0] + 1; if (function.ordinal() >= configuration.length - 1) return cycle; int minCycle = schedule[instructionNumber - 1][3]; int stations = 0; for (int j = instructionNumber - 1; j > -1; j--) { if (function == executed.get(j).getFunction() && cycle >= schedule[j][0] && cycle < schedule[j][3]) { stations++; if (minCycle > schedule[j][3]) { minCycle = schedule[j][3]; } } } int allStations = configuration[function.ordinal() + 1][0] * configuration[function.ordinal() + 1][1]; return (stations >= allStations)? minCycle : cycle; }
91e0b8e8-25ce-4ec2-bb8e-99feb57e6296
1
public static void connectToDB () { try { Driver driver = (Driver) Class.forName("org.sqlite.JDBC").newInstance(); DriverManager.registerDriver(driver); } catch (Exception ex) { ex.printStackTrace(); } }
cc6e85ff-1ec5-403d-b635-ba4217f4d8cd
8
private void habilitarMenuPerfil(Vector<Vector<Integer>>moduloTarea){ habilitarMenu(false); for(Component cMenu:jMenuBar1.getComponents()){ for(Vector<Integer>modulo:moduloTarea){ if(cMenu.getName().equals("M"+modulo.get(0))){ cMenu.setEnabled(true); } } JMenu maux=(JMenu)cMenu; for(int i=0;i<maux.getItemCount();i++){ for(Vector<Integer>modulo:moduloTarea){ if(maux.getItem(i).getName().equals("M"+modulo.get(0))){ maux.getItem(i).setEnabled(true); } for(int z=1;z<modulo.size();z++){ if(maux.getItem(i).getName().equals("T"+modulo.get(0)+modulo.get(z))) maux.getItem(i).setEnabled(true); } } // menu interno que tiene menu } } }
d3f6f3a4-b8a4-4829-9155-01b32a54053b
0
public JoinIterator(Iterable<T> outer, Iterable<TInner> inner, Selector<T, TKey> outerKeySelector, Selector<TInner, TKey> innerKeySelector, Joint<T, TInner, TResult> joint, Comparator<TKey> comparator) { this._outer = outer.iterator(); this._inner = inner; this._innerKeySelector = innerKeySelector; this._outerKeySelector = outerKeySelector; this._joint = joint; this._comparator = comparator; }
329e14fd-dc84-4b74-bc56-c1d654dc65b0
9
@Override public void checkedDoPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (isLoggedIn(req.getSession())) forceLogOut(req, resp); String userName = req.getParameter("username"); String name = req.getParameter("name"); // String name = "Jisan Mahmud"; String password = req.getParameter("password"); String password2 = req.getParameter("password2"); String email = req.getParameter("email"); Date dob = parseDateString(req.getParameter("dob")); String sex = req.getParameter("sex"); if (email != null) email = email.toLowerCase(); if (!UserModel.userNameAvailable(userName)) { SimpleFeedbackPageLoader .showSimpleFeedbackPage( req, resp, "Error", "Username unavailable", "Sorry. This username is already taken or invalid. Please choose something else"); } else if (!passwordIsInCorrectFormat(password)) { SimpleFeedbackPageLoader .showSimpleFeedbackPage(req, resp, "Error", "Password too short", "Password too short. Please choose a password of at least length 5"); } else if (!passwordsMatch(password, password2)) { SimpleFeedbackPageLoader.showSimpleFeedbackPage(req, resp, "Error", "Password mismatch", "Passwords didn't match. Feel up again"); } else if (!UserModel.emailAvailableForNewUser(email)) { SimpleFeedbackPageLoader.showSimpleFeedbackPage(req, resp, "Error", "Email already used", "This email is invalid or have already been used"); } else if (!dateOfBirthIsValid(dob)) { SimpleFeedbackPageLoader.showSimpleFeedbackPage(req, resp, "Error", "Invalid date of birth", "Date of birth year should be between 1900 and 2006"); } else { try { if (UserModel.createNewUser(userName, name, password, dob, sex, email)) { SimpleFeedbackPageLoader .showSimpleFeedbackPage(req, resp, "Account created", "Account created", "Your account has been created. Please log in to continue"); } else throw new SQLException(); } catch (SQLException ex) { SimpleFeedbackPageLoader .showSimpleFeedbackPage(req, resp, "Error", "Account creation failed", "Sorry. Your account could not be created. Please try again later."); } } }
b08a1590-8c7b-4242-9175-8645c5202027
3
public void loadAllObjects() { ResultSet data = query(QueryGen.selectAllObjects()); while (iterateData(data)) { ChunkyObject obj = (ChunkyObject) createObject(getString(data, "type")); if (obj == null) { Logging.warning("Created " + getString(data, "type") + " is null"); continue; } try { obj.setId(getString(data, "id")).load(getString(data, "data")); } catch (JSONException e) { Logging.severe(e.getMessage()); } } }
d4583fc8-a3e0-4a19-8c67-4cdfa95a009d
9
public boolean isPalindrome(String s) { int b = 0, e = s.length()-1; while(b <= e) { char x = s.charAt(b); char y = s.charAt(e); if (isCharacter(x) && isCharacter(y) && !isSame(x,y)) return false; else if (isCharacter(x) && isCharacter(y) && isSame(x,y)) { ++b; --e; } else { if (!isCharacter(x)) ++b; if (!isCharacter(y)) --e; } } return true; }
b1035dae-0ced-4ef3-b01d-d9cbaff3b6f0
0
public void die() { alive = false; }
6e4d0b8e-e8ce-4aaa-adbf-f2db1986dab9
4
@Override public Object solve() { int count = 0; int weekday = 2; // 1 - 7 mapping to Mon - Sun, 1st Jan 1901 is a Tuesday for (int year = 1901; year <= 2000; year++) { for (int month = 0; month < 12; month++) { if (weekday == 7) { count++; } weekday += getDaysInMonth(month, year) % 7; if (weekday > 7) { weekday -= 7; } } } return count; }
3e3ada3d-4d34-4063-98b5-c803119a3e27
0
public final Set<Token.Kind> firstSet() { return firstSet; }
2845a0fe-b6ee-4b3b-ba53-1808e1e10e89
7
private String dayOfWeek(int dayOfWeek) { String day; switch (dayOfWeek) { case 1: day = "Sun"; break; case 2: day = "Mon"; break; case 3: day = "Tues"; break; case 4: day = "Wed"; break; case 5: day = "Thurs"; break; case 6: day = "Fri"; break; case 7: day = "Sat"; break; default: day = ""; } return day; }
de3704f8-14dc-48cb-a9fd-cff9bedee59f
9
public void search (BayesNet bayesNet, Instances instances) throws Exception { m_random = new Random(m_nSeed); // determine base scores double [] fBaseScores = new double [instances.numAttributes()]; double fCurrentScore = 0; for (int iAttribute = 0; iAttribute < instances.numAttributes(); iAttribute++) { fBaseScores[iAttribute] = calcNodeScore(iAttribute); fCurrentScore += fBaseScores[iAttribute]; } // keep track of best scoring network double fBestScore = fCurrentScore; BayesNet bestBayesNet = new BayesNet(); bestBayesNet.m_Instances = instances; bestBayesNet.initStructure(); copyParentSets(bestBayesNet, bayesNet); double fTemp = m_fTStart; for (int iRun = 0; iRun < m_nRuns; iRun++) { boolean bRunSucces = false; double fDeltaScore = 0.0; while (!bRunSucces) { // pick two nodes at random int iTailNode = Math.abs(m_random.nextInt()) % instances.numAttributes(); int iHeadNode = Math.abs(m_random.nextInt()) % instances.numAttributes(); while (iTailNode == iHeadNode) { iHeadNode = Math.abs(m_random.nextInt()) % instances.numAttributes(); } if (isArc(bayesNet, iHeadNode, iTailNode)) { bRunSucces = true; // either try a delete bayesNet.getParentSet(iHeadNode).deleteParent(iTailNode, instances); double fScore = calcNodeScore(iHeadNode); fDeltaScore = fScore - fBaseScores[iHeadNode]; //System.out.println("Try delete " + iTailNode + "->" + iHeadNode + " dScore = " + fDeltaScore); if (fTemp * Math.log((Math.abs(m_random.nextInt()) % 10000)/10000.0 + 1e-100) < fDeltaScore) { //System.out.println("success!!!"); fCurrentScore += fDeltaScore; fBaseScores[iHeadNode] = fScore; } else { // roll back bayesNet.getParentSet(iHeadNode).addParent(iTailNode, instances); } } else { // try to add an arc if (addArcMakesSense(bayesNet, instances, iHeadNode, iTailNode)) { bRunSucces = true; double fScore = calcScoreWithExtraParent(iHeadNode, iTailNode); fDeltaScore = fScore - fBaseScores[iHeadNode]; //System.out.println("Try add " + iTailNode + "->" + iHeadNode + " dScore = " + fDeltaScore); if (fTemp * Math.log((Math.abs(m_random.nextInt()) % 10000)/10000.0 + 1e-100) < fDeltaScore) { //System.out.println("success!!!"); bayesNet.getParentSet(iHeadNode).addParent(iTailNode, instances); fBaseScores[iHeadNode] = fScore; fCurrentScore += fDeltaScore; } } } } if (fCurrentScore > fBestScore) { copyParentSets(bestBayesNet, bayesNet); } fTemp = fTemp * m_fDelta; } copyParentSets(bayesNet, bestBayesNet); } // buildStructure
288ca153-d132-4dec-818e-45130a38acb8
8
public static int getLevenshteinDistance(String first, String second) { if (first.equals(second)) return 0; if (first.length() == 0) return second.length(); if (second.length() == 0) return first.length(); int[] previousRow = new int[second.length() + 1]; int[] currentRow = new int[second.length() + 1]; for (int i = 0; i < previousRow.length; i++) previousRow[i] = i; for (int i = 0; i < first.length(); i++) { currentRow[0] = i + 1; for (int j = 0; j < second.length(); j++) { int cost = (first.charAt(i) == second.charAt(j)) ? 0 : 1; currentRow[j + 1] = min(currentRow[j] + 1, previousRow[j + 1] + 1, previousRow[j] + cost); } for (int j = 0; j < previousRow.length; j++) previousRow[j] = currentRow[j]; } return currentRow[second.length()]; }
773dcb5f-200f-46f4-98c7-cff5128af1ea
1
public void addNode(int pos, long nodeId) { if (poligons.size() > pos) nodes.get(pos).add(nodeId); }
bd95c721-bdbc-49aa-a493-df88d9114160
4
public static void showRevealedBoard(BoardModel boardModel) { System.out.print(" "); for (int i = 0; i < boardModel.getBoardWidth(); i++) { System.out.print(" " + i); } System.out.println(""); System.out.println(" -----------------------"); for (int i = 0; i < boardModel.getBoardWidth(); i++) { System.out.print(i + " | "); for (int j = 0; j < boardModel.getBoardHeight(); j++) { System.out.print(boardModel.getPosition(i, j).getContent() + " "); } System.out.println("| " + i); } System.out.println(" -----------------------"); System.out.print(" "); for (int i = 0; i < boardModel.getBoardWidth(); i++) { System.out.print(" " + i); } System.out.println(""); }
ff2bb298-4891-46e2-b0c3-f82635fbf327
1
@Override public URI getResourceIdentity() { try { return new URI(context() + name()); } catch (URISyntaxException e) { e.printStackTrace(); return null; } }
f939ddba-90c9-4783-bbfe-2c52522be3e8
4
public static void main(String[] args) { char again; do{ // The main loop, everything is called from here. double[] u = new double[3], v = new double[3],w; print("Enter a vector in R" + "\u00b3"+": "); for(int i = 0; i < 3; i++) u[i] = scan.nextDouble(); print("Enter a second vector in R" + "\u00b3"+": "); for(int i = 0; i < 3; i++) v[i] = scan.nextDouble(); w = crossProduct(u,v); print("The cross product is: "); print(w); print("\nContinue?(Y/N): "); again = scan.next().charAt(0); }while(again == 'y' || again == 'Y'); return; }
f956aa64-8f62-46ec-9b43-67b350ba2fae
4
public void sort(){ java.util.Stack<Integer> spare_stack=new java.util.Stack<Integer>(); while(!this.stack.empty()){ int current=this.stack.pop(); while(!spare_stack.empty() && spare_stack.peek()>current){ this.stack.push(spare_stack.pop()); } spare_stack.push(current); } while(!spare_stack.empty()){ this.stack.push(spare_stack.pop()); } }
3990e882-4502-45b1-8e93-c7c197009543
3
public boolean isValidBST(TreeNode root) { if(null != root) { List<Integer> list = new ArrayList<Integer>(); travelTree(root, list); for(int i=0; i<list.size()-1; i++) { if(list.get(i) >= list.get(i+1)){ return false; } } } return true; }
c9fed1ef-337f-40dd-b274-32771ab1f130
6
public void update(int delta) { for (Building b : buildings) { if (b.getStatus()) { b.setBuildingtimeLeft(b.getBuildingtimeLeft() - delta); } if (b.getBuildingtimeLeft() <= 0) { b.upgrade(); } } for (Building b : buildings) { if (b instanceof ProductionBuilding) { b.setTimeLeft(b.getTimeLeft()-delta); if (b.getTimeLeft() <= 0) { changeGold(((ProductionBuilding) b).getGoldProcuction()); changeFood(((ProductionBuilding) b).getFoodProduction()); b.setTimeLeft(1000); } } } }
27b96950-8e5d-4dd7-a601-472f3db03a71
6
protected void processInput(String userInput) { if (userInput.equals("!end")) { exit = true; try { stdIn.close(); } catch (IOException e) { logger.error("coulden't get inputstream"); } // propper shutdown of the ExecutorService Main_Client.clientExecutionService.shutdown(); // Disable new tasks // from being // submitted try { // Wait a while for existing tasks to terminate if (!Main_Client.clientExecutionService.awaitTermination(3, TimeUnit.SECONDS)) { Main_Client.clientExecutionService.shutdownNow(); // Cancel // currently // executing // tasks // Wait a while for tasks to respond to being cancelled if (!Main_Client.clientExecutionService.awaitTermination(3, TimeUnit.SECONDS)) System.err.println("Pool did not terminate"); } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted Main_Client.clientExecutionService.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } client.shutdown(); exit = true; } else { String[] commandArray = userInput.split(" "); if (commandArray[0].equals("!login")) { userInput += " " + udpPort; /* try { UDPSocket.username = commandArray[1]; } catch (ArrayIndexOutOfBoundsException e) { }*/ } logger.debug("sending TCP- message: " + userInput); out.println(userInput); out.flush(); } }
224b15ea-46a9-4d71-ac83-74ab443640a6
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (ip == null) { if (other.ip != null) return false; } else if (!ip.equals(other.ip)) return false; if (nickname == null) { if (other.nickname != null) return false; } else if (!nickname.equals(other.nickname)) return false; return true; }
a3b0e307-cb42-4901-a10d-409d52407481
0
public String getContacter() { return contacter; }
84ac1a39-096c-4a9f-9eef-3f70be99e75f
2
public void characters(char[] ch, int s, int len) { String content = new String(ch, s, len); if(content.length() != 0) { if(Debug.debugLevel() >= 5) { Debug.println("Characters received:", 5); Debug.println(" Characters: " + content, 5); Debug.println("End of characters.", 5); Debug.println("Adding content...", 5); } elements.get(elements.size() - 1).addText(content); } }
1acea8e1-8e2b-45b5-a7e9-313e1d3f2d6c
4
public static void main(String[] args) { //Test: CreateBlackBox Circuit c1 = new Circuit(); int number1 = 0; int number2 = 0; Scanner scan = new Scanner(System.in); System.out.println("Length of binary numbers:"); int amount = Integer.parseInt(scan.nextLine()); BlackBox tester = CreateBlackBox.rippleAdder(amount); CreateBlackBox.wireUp(tester, c1); c1.powerUp(); System.out.println("Give the first binary number:"); String first = scan.nextLine(); for (int i=0; i<amount; i++) { number1 += Math.pow(2.0, i*1.0)* Integer.parseInt("" + first.charAt(amount - i - 1)); if (i==0) { c1.makeAction(1, Integer.parseInt("" + first.charAt(amount - i - 1))); } else { c1.makeAction(i * 4 + 3, Integer.parseInt("" + first.charAt(amount - i - 1))); } } System.out.println("Give the second binary number:"); String second = scan.nextLine(); for (int i=0; i<amount; i++) { number2 += Math.pow(2.0, i*1.0)* Integer.parseInt("" + second.charAt(amount - i - 1)); if (i==0) { c1.makeAction(3, Integer.parseInt("" + second.charAt(amount - i - 1))); } else { c1.makeAction(i * 4 + 5, Integer.parseInt("" + second.charAt(amount - i - 1))); } } System.out.println(""+number1+" + "+number2+" ="); c1.displayCircuit(); /* //Test: Circuit() Circuit c2 = new Circuit(); Wire wire0 = new Wire(); Wire wire1 = new Wire(); Wire wire2 = new Wire(); Wire wire3 = new Wire(); Wire wire4 = new Wire(); Wire wire5 = new Wire(); Wire wire6 = new Wire(); Wire wire7 = new Wire(); Wire wire8 = new Wire(); Wire[] wires0 = new Wire[1]; wires0[0] = wire0; Wire[] wires1 = new Wire[1]; wires1[0] = wire1; Wire[] wires2 = new Wire[1]; wires2[0] = wire2; Wire[] wires3 = new Wire[1]; wires3[0] = wire3; Wire[] wires4 = new Wire[1]; wires4[0] = wire4; Wire[] wires5 = new Wire[1]; wires5[0] = wire5; Wire[] wires6 = new Wire[1]; wires6[0] = wire6; Wire[] wires7 = new Wire[1]; wires7[0] = wire7; Wire[] wires8 = new Wire[1]; wires8[0] = wire8; Wire[] wires35 = new Wire[2]; wires35[0] = wire3; wires35[1] = wire5; Wire[] wires67 = new Wire[2]; wires67[0] = wire6; wires67[1] = wire7; Element batt0 = new Battery(wires0); batt0.setCircuit(c2); Element batt1 = new Battery(wires2); batt1.setCircuit(c2); Element batt2 = new Battery(wires4); batt2.setCircuit(c2); Element switch0 = new Switch(wires0,wires1); switch0.setCircuit(c2); Element switch1 = new Switch(wires2,wires3); switch1.setCircuit(c2); Element switch2 = new Switch(wires4,wires5); switch2.setCircuit(c2); Element not0 = new NotGate(wires1,wires6); not0.setCircuit(c2); Element or0 = new OrGate(wires35,wires7); or0.setCircuit(c2); Element and0 = new AndGate(wires67,wires8); and0.setCircuit(c2); Element light0 = new Light(wires8); light0.setCircuit(c2); c2.elements.add(batt0); c2.elements.add(batt1); c2.elements.add(batt2); c2.elements.add(switch0); c2.elements.add(switch1); c2.elements.add(switch2); c2.elements.add(not0); c2.elements.add(or0); c2.elements.add(and0); c2.elements.add(light0); c2.wires.add(wire0); c2.wires.add(wire1); c2.wires.add(wire2); c2.wires.add(wire3); c2.wires.add(wire4); c2.wires.add(wire5); c2.wires.add(wire6); c2.wires.add(wire7); c2.wires.add(wire8); c2.powerUp(); c2.makeAction(3,0); c2.makeAction(4,1); c2.makeAction(5,1); c2.displayCircuit(); //Test: newInstance() BlackBox fullAdder = (BlackBox) CreateBlackBox.fullAdder().newInstance(); BlackBox rippleAdder = new BlackBox(); rippleAdder.addElement(fullAdder); Battery b0 = new Battery(); Battery b1 = new Battery(); Battery b2 = new Battery(); Switch sw0 = new Switch(); Switch sw1 = new Switch(); Switch sw2 = new Switch(); Light li0 = new Light(); Light li1 = new Light(); Wire w1 = new Wire(); Wire w2 = new Wire(); Wire w3 = new Wire(); Wire w4 = new Wire(); Wire w5 = new Wire(); Wire w6 = new Wire(); Wire w7 = new Wire(); Wire w8 = new Wire(); b0.setOutput(0, w1); b1.setOutput(0, w2); b2.setOutput(0, w3); sw0.setInput(0, w1); sw1.setInput(0, w2); sw2.setInput(0, w3); sw0.setOutput(0, w4); sw1.setOutput(0, w5); sw2.setOutput(0, w6); li0.setInput(0, w7); li1.setInput(0, w8); rippleAdder.setInput(0, w4); rippleAdder.setInput(1, w5); rippleAdder.setInput(2, w6); rippleAdder.setOutput(0, w7); rippleAdder.setOutput(1, w8); Circuit c3 = new Circuit(); b0.setCircuit(c3); b1.setCircuit(c3); b2.setCircuit(c3); sw0.setCircuit(c3); sw1.setCircuit(c3); sw2.setCircuit(c3); li0.setCircuit(c3); li1.setCircuit(c3); rippleAdder.setCircuit(c3); c3.elements.add(b0); c3.elements.add(b1); c3.elements.add(b2); c3.elements.add(sw0); c3.elements.add(sw1); c3.elements.add(sw2); c3.elements.add(rippleAdder); c3.elements.add(li0); c3.elements.add(li1); c3.wires.add(w1); c3.wires.add(w2); c3.wires.add(w3); c3.wires.add(w4); c3.wires.add(w5); c3.wires.add(w6); c3.wires.add(w7); c3.wires.add(w8); c3.powerUp(); c3.makeAction(3,1); c3.makeAction(4,1); c3.makeAction(5,0); c3.displayCircuit(); */ }
e8bb1fbd-f1e4-4c3c-b88c-db06d303b85b
6
@EventHandler public void WitchStrength(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getWitchConfig().getDouble("Witch.Strength.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getWitchConfig().getBoolean("Witch.Strength.Enabled", true) && damager instanceof Witch && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, plugin.getWitchConfig().getInt("Witch.Strength.Time"), plugin.getWitchConfig().getInt("Witch.Strength.Power"))); } }
4325377b-31ae-49a0-987e-fbddd1e52727
8
private void verbindeNachbarn(int x, int y) { //Nord if(istGueltigePosition(x, y - 1) && existiertRaumAnPosition(x, y - 1)) { _raumArray[x][y].verbindeZweiRaeume(TextVerwalter.RICHTUNG_NORDEN, _raumArray[x][y - 1], TextVerwalter.RICHTUNG_SUEDEN); } //Ost if(istGueltigePosition(x + 1, y) && existiertRaumAnPosition(x + 1, y)) { _raumArray[x][y].verbindeZweiRaeume(TextVerwalter.RICHTUNG_OSTEN, _raumArray[x + 1][y], TextVerwalter.RICHTUNG_WESTEN); } //Süd if(istGueltigePosition(x, y + 1) && existiertRaumAnPosition(x, y + 1)) { _raumArray[x][y].verbindeZweiRaeume(TextVerwalter.RICHTUNG_SUEDEN, _raumArray[x][y + 1], TextVerwalter.RICHTUNG_NORDEN); } //West if(istGueltigePosition(x - 1, y) && existiertRaumAnPosition(x - 1, y)) { _raumArray[x][y].verbindeZweiRaeume(TextVerwalter.RICHTUNG_WESTEN, _raumArray[x - 1][y], TextVerwalter.RICHTUNG_OSTEN); } }
d9c26e2b-2bbe-4459-ac68-98b493cb7871
3
public void closeBraceContinue() { if ((Options.outputStyle & Options.BRACE_AT_EOL) != 0) print("} "); else { println("}"); if ((Options.outputStyle & Options.BRACE_FLUSH_LEFT) == 0 && currentIndent > 0) untab(); } }
0077f256-fa22-4de2-8bdc-9670518a5a38
4
private Entity readFromFile(int pos) { ObjectInputStream ois = null; Entity rslt = null; try { ois = new ObjectInputStream(new FileInputStream(file)); for (int i = 0; i < pos; i++) { ois.readObject(); } rslt = (Entity) ois.readObject(); } catch (Exception ex) { Logger.getLogger(FileStorage.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ois != null) { ois.close(); } } catch (IOException ex) { Logger.getLogger(FileStorage.class.getName()).log(Level.SEVERE, null, ex); } return rslt; } }
96b01572-8d2d-4f72-ab22-d22cfb24832f
5
public void compileSource(String source){ //1.创建需要动态编译的代码字符串 //2.将预动态编译的代码写入文件中1:创建临时目录2:写入临时文件 File dir=new File("../webapps/JudgeOnLine/temp");//tomcat里工程下的临时目录 String className = source.substring(source.indexOf("public class") + 13,source.indexOf("{")).toString();//获取类名字符串 //如果/temp目录不存在创建temp目录 if(!dir.exists()){ dir.mkdir(); } try { FileOutputStream err = new FileOutputStream("../webapps/JudgeOnLine/temp/err.txt"); FileWriter writer=new FileWriter(new File(dir,className + ".java")); writer.write(source);//将字符串写入文件中 writer.flush(); writer.close(); //3:取得当前系统java编译器 JavaCompiler javaCompiler=ToolProvider.getSystemJavaCompiler(); //4:获取一个文件管理器StandardJavaFileManage StandardJavaFileManager javaFileManager=javaCompiler.getStandardFileManager(null, null, null); //5.文件管理器根与文件连接起来 Iterable it=javaFileManager.getJavaFileObjects(new File(dir,className + ".java")); //建立一个信息收集器 DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>(); //创建编译的任务 CompilationTask task=javaCompiler.getTask(null, javaFileManager,collector,Arrays.asList("-d","../webapps/JudgeOnLine/temp"), null, it); //执行编译 Boolean result = task.call(); //获取信息 List<Diagnostic<? extends JavaFileObject>> diagnostics = collector.getDiagnostics(); for(Diagnostic<? extends JavaFileObject> d : diagnostics){ System.out.println("Line Number->" + d.getLineNumber()); System.out.println("Message->"+ d.getMessage(Locale.ENGLISH)); System.out.println("Source->" + d.getCode()); System.out.println(d.getKind() + "\n" ); } javaFileManager.close(); System.out.println("result" + result); } catch (Exception e) { e.printStackTrace(); } finally { } /*File file = new File("D:\\RuntimeInput.java"); Reader reader = null; StringBuffer contents = new StringBuffer(); try { System.out.println("以字符为单位读取文件内容,一次读一个字节:"); // 一次读一个字符 reader = new InputStreamReader(new FileInputStream(file)); int tempchar; while ((tempchar = reader.read()) != -1) { // 对于windows下,\r\n这两个字符在一起时,表示一个换行。 // 但如果这两个字符分开显示时,会换两次行。 // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。 if (((char) tempchar) != '\r') { contents.append(tempchar); System.out.print((char) tempchar); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } String code = contents.toString();*/ //return "ok"; }
14349cd9-5944-456e-be41-d9e0fca9e24e
7
private String unitConver(int len) { String reVal; switch(len) { case 2: reVal = "十";break; case 3: reVal = "百";break; case 4: reVal = "千";break; case 5: reVal = "万";break; case 6: reVal = "十";break; case 7: reVal = "百";break; case 8: reVal = "千";break; default: reVal = ""; } return reVal; }
dc6226a4-52a2-4f05-b24c-05a9f7534574
2
public void setCurrent(long current) { this.current = current; if (current > this.total) this.total = current; if (this.job != null) this.job.updateProgress(); }
cadcd452-991b-4601-b3e8-ae64f5dd457e
3
public Prime(int n) { max = n; bitSet = new BitSet(max + 1); bitSet.set(0, 2, false); bitSet.set(2, max, true); for (long i = 2; i * i <= max; ++i) { if (isPrime((int) i)) { for (long j = i * i; j <= max; j += i) { bitSet.set((int) j, false); } } } primeCount = bitSet.cardinality(); }
5e010b0f-98fa-46d7-85b4-1da7c0cc697c
3
public void write(List<String> csvStrings, String fileNameDestination) throws IOException { File file = new File(fileNameDestination); logger.info("outfilename=" + fileNameDestination); if ( !file.exists()) { file.createNewFile(); } FileWriter fileWriter = new FileWriter(file, false); fileWriter.write(""); //clear file content fileWriter.close(); fileWriter = new FileWriter(file, true); PrintWriter printWriter = new PrintWriter(fileWriter); for (String row : csvStrings) { printWriter.println(row); logger.info("row added to output: " + row); } try { printWriter.close(); fileWriter.close(); } catch (IOException e) { logger.error("Writer could not be closed."); } }
6aa28796-e98b-4a4b-9de3-671fbe111cba
9
public static void connectToChatRoom(String cHost, int cPort) throws IOException { Socket joinedClient =null; BufferedReader in; PrintWriter out = null; try { joinedClient = new Socket(cHost, cPort); } catch (IOException e) { System.out.println("Could not connect to peer "); return; } try { joinedClient.setSoTimeout(30000); } catch (SocketException se) { System.err.println("Unable to set socket connection timeout "); } try { out = new PrintWriter(joinedClient.getOutputStream(), true); in = new BufferedReader( new InputStreamReader(joinedClient.getInputStream())); } catch (IOException e) { System.err.println(e); return; } BufferedReader standardIn = new BufferedReader(new InputStreamReader( System.in)); System.out.println("Input '/exit' to disconnect or quit the chatroom\nInput a message to send data to chatroom:"); String inMessage2; String outMessage2; while (true) { try { if (in.ready()) { inMessage2 = in.readLine(); if (inMessage2.equals("Dics_From_Chat")) { System.out.println("A user has disconnected."); } else { System.out.println(inMessage2); } } else if (standardIn.ready()) { outMessage2 = standardIn.readLine(); if (outMessage2.equals("/exit")) { System.out.println("Disconnecting from chatroom."); out.println("Dics_From_Chat"); break; } else { out.println(outMessage2); } } } catch (SocketException SE) { // Disconnect clients System.out.println("Connection timed out, standby "); joinedClient.close(); } } }
54aeabfc-2ffc-4bc3-b383-ef85f13731c4
6
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case boardPackage.BOARD__COUNTRIES: return getCountries(); case boardPackage.BOARD__BORDERS: return getBorders(); case boardPackage.BOARD__CONTINENTS: return getContinents(); case boardPackage.BOARD__ADDITIONAL_TROOPS: return getAdditionalTroops(); case boardPackage.BOARD__CARDS: return getCards(); case boardPackage.BOARD__INITIAL_TROOPS: return getInitialTroops(); } return super.eGet(featureID, resolve, coreType); }
553df11c-a60b-41e8-a333-120e8df71e64
5
public void connect() throws RemoteException { try { registry = LocateRegistry.getRegistry(ipAddress, portNumber); } catch (RemoteException ex) { System.out.println("Client: Cannot locate registry"); System.out.println("Client: RemoteException: " + ex.getMessage()); registry = null; } if (registry != null) { } else { System.out.println("Client: Cannot locate registry"); System.out.println("Client: Registry is null pointer"); } if (registry != null) { try { ieffect = (IEffectenbeurs) registry.lookup(bindingName); } catch (RemoteException | NotBoundException ex) { ieffect = null; } if (ieffect != null) { } else { System.out.println("Client: Effectenbeur is null pointer"); } } }
f83d2043-2d56-4b4e-90fb-12ddfc95d944
7
public int candy(int[] ratings) { if(ratings == null) return 0; int people = ratings.length; int[] candys = new int[ratings.length]; candys[0] =1; for(int i=1;i<people;i++){ candys[i]=1; if(ratings[i]>ratings[i-1]){ candys[i]=candys[i-1]+1; } else { candys[i] = 1; } } for(int j= people -1; j > 0;j--){ if(ratings[j] < ratings[j-1] && candys[j] >= candys[j-1]){ candys[j-1] = candys[j] +1; } } int sum = 0; for(int a : candys) sum += a; return sum; }
115c4e18-f809-4f5e-8793-6a36635d8a35
6
private void jTextField7FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField7FocusLost // TODO add your handling code here: if ((evt.getOppositeComponent()!=jTextField3) && (evt.getOppositeComponent()!=campoFecha1) && (evt.getOppositeComponent()!=campoFecha2)){ if(!jTextField7.getText().equals("")){ Validaciones v = new Validaciones(); if (v.isFloat(jTextField7.getText())){ if (Float.parseFloat(jTextField7.getText())>=0){ mensajeError(" "); jTextField8.setText(""); jTextField8.setEnabled(false); jTextField8.nextFocus(); } else{ mensajeError("El saldo al Debe es negativo."); jTextField7.requestFocus(); jTextField7.selectAll(); } } else{ mensajeError("El saldo al Debe no es un valor numérico."); jTextField7.requestFocus(); jTextField7.selectAll(); } } else{ mensajeError(" "); jTextField8.setEnabled(true); jTextField8.requestFocus(); } } }//GEN-LAST:event_jTextField7FocusLost
55773ebe-034f-4393-88bc-ac158a038e34
9
private static void renderMethods(Class cls) { Method[] methods = cls.getMethods(); Method m; StringAppender appender = new StringAppender(); int mf; for (int i = 0; i < methods.length; i++) { appender.append(TextUtil.paint(' ', PADDING + 2)); if (((mf = (m = methods[i]).getModifiers()) & Modifier.PUBLIC) != 0) appender.append("public"); else if ((mf & Modifier.PRIVATE) != 0) appender.append("private"); else if ((mf & Modifier.PROTECTED) != 0) appender.append("protected"); appender.append(' ').append(m.getReturnType().getName()).append(' ').append(m.getName()).append("("); Class[] parmTypes = m.getParameterTypes(); for (int y = 0; y < parmTypes.length; y++) { if (parmTypes[y].isArray()) { appender.append(parmTypes[y].getComponentType().getName() + "[]"); } else { appender.append(parmTypes[y].getName()); } if ((y + 1) < parmTypes.length) appender.append(", "); } appender.append(")"); if (m.getDeclaringClass() != cls) { appender.append(" [inherited from: ").append(m.getDeclaringClass().getName()).append("]"); } if ((i + 1) < methods.length) appender.append('\n'); } System.out.println(appender.toString()); }
11e923a8-65b6-47da-a36d-82801cadd9ff
4
private Vector<DashboardIcon> getCostensValues(Player player) { // object variable costs DashboardIcon variableCosts = new DashboardIcon(); variableCosts.setTitle("variable costs"); variableCosts.setIcon("align-left"); variableCosts.setColor("turquoise"); try { variableCosts.setValue(Double.toString(player.getData() .lastElement().getVarCosts())); } catch (Exception e) { } // object fix costs DashboardIcon cumulativeCosts = new DashboardIcon(); cumulativeCosts.setTitle("fix costs"); cumulativeCosts.setIcon("sort-alpha-asc"); cumulativeCosts.setColor("red"); try { cumulativeCosts.setValue(Double.toString(player.getData() .lastElement().getFixCosts())); } catch (Exception e) { } // object price per Airplane DashboardIcon costsPerPlane = new DashboardIcon(); costsPerPlane.setTitle("price per Airplane"); costsPerPlane.setIcon("plane"); costsPerPlane.setColor("gray"); try { costsPerPlane.setValue(Double.toString(player.getData() .lastElement().getPricePerAirplane())); } catch (Exception e) { } // object overhead costs DashboardIcon overheadCosts = new DashboardIcon(); overheadCosts.setTitle("overhead costs"); overheadCosts.setIcon("align-justify"); overheadCosts.setColor("purple"); try { overheadCosts.setValue(Double.toString(player.getData() .lastElement().getCosts())); } catch (Exception e) { } Vector<DashboardIcon> dashboard = new Vector<DashboardIcon>(); dashboard.add(variableCosts); dashboard.add(cumulativeCosts); dashboard.add(costsPerPlane); dashboard.add(overheadCosts); return dashboard; }
388d22f3-11b0-4e9a-99f9-4afb5568eec6
9
public GameState update(KeyboardInput keyboard) { GameState nextState = GameState.PLAYING; if (keyboard.keyPressed(KeyEvent.VK_TAB)) { nextState = GameState.MENU; } else { Direction dir = keyboard.getArrowKeyDirection(); if (keyboard.keyIsDown(KeyEvent.VK_A) && timeUntilNextBullet <= 0) { shootBullet(dir); } for (Sprite sprite : sprites) { sprite.update(keyboard, sprites, tilemap); } List<Sprite> newSpriteList = new ArrayList<Sprite>(); for (Sprite sprite : sprites) { if (!sprite.isDestroyed()) { newSpriteList.add(sprite); } } if (playerChar.isDestroyed()) { nextState = GameState.GAME_OVER; } sprites = newSpriteList; if (dir != Direction.NONE) { lastPlayerDir = dir; } if (timeUntilNextBullet > 0) { timeUntilNextBullet--; } } return nextState; }
4f53e197-7b46-4c6a-9bf5-3f65063312e0
3
@SuppressWarnings("unchecked") public String loadMatches() { PreparedStatement st = null; ResultSet rs = null; JSONArray json = new JSONArray(); try { conn = dbconn.getConnection(); st = conn.prepareStatement("SELECT match_number FROM match_record_2013 where event_id = ? group by match_number"); st.setInt(1, this.getSelectedEvent()); rs = st.executeQuery(); while (rs.next()) { JSONObject o = new JSONObject(); o.put("id", rs.getInt("match_number")); json.add(o); } } catch (SQLException e) { e.printStackTrace(); } finally { try{ conn.close(); st.close(); rs.close(); }catch (SQLException e) { System.out.println("Error closing query"); } } return json.toString(); }
b2ffff32-5e32-493b-adf1-8c8d2296a914
7
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Product)) return false; Product product = (Product) o; if (id != product.id) return false; if (catalog != null ? !catalog.equals(product.catalog) : product.catalog != null) return false; if (description != null ? !description.equals(product.description) : product.description != null) return false; return true; }
af0ebd67-6389-4718-8f4e-9d6887852efd
3
public Markers createGenomicRegions() { Markers markers = new Markers(); // Add up-down stream intervals for (Marker upDownStream : genome.getGenes().createUpDownStream(upDownStreamLength)) markers.add(upDownStream); // Add splice site intervals for (Marker spliceSite : genome.getGenes().createSpliceSites(spliceSiteSize, spliceRegionExonSize, spliceRegionIntronMin, spliceRegionIntronMax)) markers.add(spliceSite); // Intergenic markers for (Intergenic intergenic : genome.getGenes().createIntergenic()) markers.add(intergenic); return markers; }
0989ff89-4daa-4f8b-b479-1951227ef693
4
public void loadCards() throws BadConfigFormatException { try { // open the cards file, which has 6 person, 6 weapon, then 9 room cards in that order FileReader reader = new FileReader("cards.txt"); Scanner in = new Scanner(reader); // stored to know card type int lineNumber = 0; Card card; // loop to read each line while(in.hasNextLine()) { String line = in.nextLine(); lineNumber++; if (lineNumber < 7) { card = new Card(line,Card.CardType.PERSON); } else if (lineNumber < 13) { card = new Card(line,Card.CardType.WEAPON); } else { card = new Card(line,Card.CardType.ROOM); } cards.add(card); } } catch (FileNotFoundException e) { throw new BadConfigFormatException(e.getMessage()); } }
71b15397-03b8-42c3-8d63-f9e80cefa01c
7
public Template waitForMatch(Template tpl, int timeout) { String queryString = ""; int i = 0; for (i = 0; i < 9; i++) { Integer min; Integer max; try { min = (Integer) PropertyUtils.getSimpleProperty(tpl, "property" + i + "_min"); max = (Integer) PropertyUtils.getSimpleProperty(tpl, "property" + i + "_max"); if (min != null && max != null) { if (!queryString.isEmpty()) { queryString += " AND "; } queryString += " property" + i + "_current BETWEEN " + (min-1) + " AND " + (max+1); } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } queryString += " AND price <= " + tpl.getPrice_max(); //System.out.println("customer query: " + queryString); return space.read(new SQLQuery<Template>(Template.class, queryString), timeout); }
2816d670-94ad-4b17-82e3-d6e6140121e0
0
@Basic @Column(name = "CSA_ID_SOLICITUD") public int getIdSolicitud() { return idSolicitud; }
16e38893-2f5d-400f-851e-7d5bb4e2e1cd
0
@Test public void testListHdfs() throws IOException { System.setProperty("HADOOP_USER_NAME", "hduser"); Injector injector = Guice.createInjector(new Context()); HDFS hdfs = injector.getInstance(HDFS.class); hdfs.init(); hdfs.listRoot(); }
cb8455f1-14d3-4525-b857-09d6dda3cea7
2
public boolean matchesOperator(String text) { int operatorCount = this.operatorList.size(); for(int i = 0;i<operatorCount;i++) { String currentOperator = this.operatorList.get(i).getLiteral(); boolean isMatchingExpression = text.equals(currentOperator); if (isMatchingExpression) { return true; } } return false; }
5d3f0a92-bab4-41ec-a4c0-14f75a961df7
5
public void dump() { updateKnown(); File imgdir = new File(Constants.getCacheDirectory() + "rsimg" + System.getProperty("file.separator")); if (!imgdir.exists()) { imgdir.mkdir(); } int count = imageArchive.countImages(); int total = count; try { for (int index = 0; index < count; index++) { File directory = new File(Constants.getCacheDirectory() + "rsimg" + System.getProperty("file.separator") + getArchiveList()[index]); if (!directory.exists()) { directory.mkdir(); } for (int index2 = 0; index2 < imageArchive.getImage(index).getImageBeanCount(); index2++) { BufferedImage bi = imageArchive.getImage(index).getImage(index2); ImageIO.write(bi, "png", new File(directory + System.getProperty("file.separator") + index2 + ".png")); total++; } } log("Dumped " + total + " indices."); } catch (IOException e) { e.printStackTrace(); } }
9d1a5dc1-5981-4cb3-9647-b353cc3e7b45
1
public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals(Constantes.CLOSE)) { this.setVisible(false); } }