method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
68ad2292-9e7c-4aad-b8ac-3073d8e0b9d3
1
public static void main(String[] args) { //Liskov sub ProgrammingCourse[] courseList = { new AdvancedJavaCourse("Advanced Java","COURSE_NUMBER"), new IntroJavaCourse("Introduction to Java","COURSE_NUMBER"), new IntroToProgrammingCourse("Introduction to Programming","COURSE_NUMBER")}; for(ProgrammingCourse c : courseList) { System.out.println(c.getCourseName()); } }
503c12d8-8701-47bb-95cd-402186c6084b
8
private void expand1(byte[] src, byte[] dst) { for(int i=1,n=dst.length ; i<n ; i+=8) { int val = src[1 + (i >> 3)] & 255; switch(n-i) { default: dst[i+7] = (byte)((val ) & 1); case 7: dst[i+6] = (byte)((val >> 1) & 1); case 6: dst[i+5] = (byte)((val >> 2) & 1); case 5: dst[i+4] = (byte)((val >> 3) & 1); case 4: dst[i+3] = (byte)((val >> 4) & 1); case 3: dst[i+2] = (byte)((val >> 5) & 1); case 2: dst[i+1] = (byte)((val >> 6) & 1); case 1: dst[i ] = (byte)((val >> 7) ); } } }
18e1fa1a-f322-4776-949e-3a50ec86ec0a
4
private double doSingleSwap(Deque<Pair<Vertex>> swaps) { Pair<Vertex> maxPair = null; double maxGain = Double.NEGATIVE_INFINITY; for (Vertex v_a : unswappedA) { for (Vertex v_b : unswappedB) { Edge e = graph.findEdge(v_a, v_b); double edge_cost = (e != null) ? e.weight : 0; // Calculate the gain in cost if these vertices were swapped // subtract 2*edge_cost because this edge will still be an external edge // after swapping double gain = getVertexCost(v_a) + getVertexCost(v_b) - 2 * edge_cost; if (gain > maxGain) { maxPair = new Pair<Vertex>(v_a, v_b); maxGain = gain; } } } swapVertices(A, maxPair.first, B, maxPair.second); swaps.push(maxPair); unswappedA.remove(maxPair.first); unswappedB.remove(maxPair.second); return getCutCost(); }
84831517-69d3-49ba-8623-376955974e17
4
public static void secondinit() throws SlickException{ if(dogepossible==true) chicken1= new Image("resources/images/doge.png"); else if (dogepossible==false) chicken1= new Image("resources/images/chickun1.png"); if(cagepossible==true) chicken2= new Image("resources/images/cage.png"); else if (cagepossible==false) chicken2= new Image("resources/images/chickun2.png"); }
98ae06c0-89b0-489e-b61a-3b17dacd2eaf
8
public Set<Map.Entry<Character,Integer>> entrySet() { return new AbstractSet<Map.Entry<Character,Integer>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TCharIntMapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if (o instanceof Map.Entry) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return TCharIntMapDecorator.this.containsKey(k) && TCharIntMapDecorator.this.get(k).equals(v); } else { return false; } } public Iterator<Map.Entry<Character,Integer>> iterator() { return new Iterator<Map.Entry<Character,Integer>>() { private final TCharIntIterator it = _map.iterator(); public Map.Entry<Character,Integer> next() { it.advance(); char ik = it.key(); final Character key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik ); int iv = it.value(); final Integer v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv ); return new Map.Entry<Character,Integer>() { private Integer val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals(key) && ( ( Map.Entry ) o ).getValue().equals(val); } public Character getKey() { return key; } public Integer getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public Integer setValue( Integer value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<Character,Integer> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked Character key = ( ( Map.Entry<Character,Integer> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection<? extends Map.Entry<Character, Integer>> c ) { throw new UnsupportedOperationException(); } public void clear() { TCharIntMapDecorator.this.clear(); } }; }
71b0fdbd-4625-4bfe-8148-cd04af9fe851
4
@Override public void actionPerformed(ActionEvent e) { if(e.getSource() == widokOpisTworcow.btn_WrocDoWyboruKategorii) powrotDoOknaGlownego(); if(e.getSource() == widokOpisTworcow.mnI_Wyjscie) wyjscie(); if(e.getSource() == widokOpisTworcow.mnI_InstrukcjaObslugi) { } if(e.getSource() == widokOpisTworcow.mnI_UstawieniaLokalne) { widokOpisTworcow.widokGlowny.widokUstawien.widokUstawienZdarzenia.setOknoMacierzyste("OknoOpisAplikacji"); pokazOknoUstawienLokalnych(); } }
9cc19b5d-feac-489f-8d48-8d093ecb2c26
0
public void addFileDownloadListener(FileDownloadListener listener){ listeners.add(listener); }
bbb93a6b-35a3-4476-b7c1-7f8fddfaa458
9
private void verifyTransfer(boolean srcdirect, boolean dstdirect) { String txt1 = "123"; String txt2 = "abcde"; String srctxt = txt1+txt2; byte[] srcdata = srctxt.getBytes(); org.junit.Assert.assertEquals(srctxt.length(), srcdata.length); //sanity check java.nio.ByteBuffer srcbuf = NIOBuffers.create(srcdata.length, srcdirect); java.nio.ByteBuffer dstbuf = NIOBuffers.create(srcbuf.capacity(), dstdirect); org.junit.Assert.assertEquals(0, srcbuf.position()); org.junit.Assert.assertEquals(srcdata.length, srcbuf.capacity()); org.junit.Assert.assertEquals(srcbuf.limit(), srcbuf.capacity()); srcbuf.put(srcdata); org.junit.Assert.assertEquals(srcdata.length, srcbuf.position()); org.junit.Assert.assertEquals(srcdata.length, srcbuf.capacity()); org.junit.Assert.assertEquals(srcbuf.limit(), srcbuf.capacity()); srcbuf.flip(); org.junit.Assert.assertEquals(0, srcbuf.position()); org.junit.Assert.assertEquals(srcbuf.limit(), srcbuf.capacity()); srcbuf.position(txt1.length()); org.junit.Assert.assertEquals(txt1.length(), srcbuf.position()); org.junit.Assert.assertEquals(srcbuf.limit(), srcbuf.capacity()); dstbuf.put((byte)'x'); dstbuf.mark(); dstbuf.put((byte)'x'); dstbuf.reset(); int nbytes = NIOBuffers.transfer(srcbuf, dstbuf, null); if (srcdirect && dstdirect) { org.junit.Assert.assertEquals(-txt2.length(), nbytes); nbytes = NIOBuffers.transfer(srcbuf, dstbuf, new byte[-nbytes]); } org.junit.Assert.assertEquals(txt2.length(), nbytes); org.junit.Assert.assertEquals(txt1.length()+nbytes, srcbuf.position()); org.junit.Assert.assertEquals(srcbuf.limit(), srcbuf.capacity()); org.junit.Assert.assertEquals(nbytes+1, dstbuf.position()); org.junit.Assert.assertEquals(dstbuf.limit(), dstbuf.capacity()); dstbuf.flip(); org.junit.Assert.assertEquals((byte)'x', dstbuf.get()); for (int idx = 0; idx != txt2.length(); idx++) { org.junit.Assert.assertEquals((byte)txt2.charAt(idx), dstbuf.get()); } if (srcdirect && dstdirect) { // do an additional test of the no-transfer-buf method, with buffers that normally need a transfer-buf srcbuf.clear(); srcbuf.put(srcdata); srcbuf.flip(); srcbuf.position(txt1.length()); dstbuf.clear(); dstbuf.put((byte)'x'); dstbuf.mark(); dstbuf.put((byte)'x'); dstbuf.reset(); nbytes = NIOBuffers.transfer(srcbuf, dstbuf); org.junit.Assert.assertEquals(txt2.length(), nbytes); org.junit.Assert.assertEquals(txt1.length()+nbytes, srcbuf.position()); org.junit.Assert.assertEquals(srcbuf.limit(), srcbuf.capacity()); org.junit.Assert.assertEquals(nbytes+1, dstbuf.position()); org.junit.Assert.assertEquals(dstbuf.limit(), dstbuf.capacity()); dstbuf.flip(); org.junit.Assert.assertEquals((byte)'x', dstbuf.get()); for (int idx = 0; idx != txt2.length(); idx++) { org.junit.Assert.assertEquals((byte)txt2.charAt(idx), dstbuf.get()); } } else if (!srcdirect && !dstdirect) { // do an additional test of the no-transfer-buf method, with buffers that don't need transfer-buf srcbuf.clear(); srcbuf.put(srcdata); srcbuf.flip(); srcbuf.position(txt1.length()); dstbuf.clear(); int dstlmt = txt2.length() - 1; dstbuf.limit(dstlmt); nbytes = NIOBuffers.transfer(srcbuf, dstbuf); org.junit.Assert.assertEquals(dstlmt, nbytes); org.junit.Assert.assertEquals(txt1.length()+nbytes, srcbuf.position()); org.junit.Assert.assertEquals(srcbuf.limit(), srcbuf.capacity()); org.junit.Assert.assertEquals(nbytes, dstbuf.position()); org.junit.Assert.assertEquals(dstlmt, dstbuf.limit()); dstbuf.flip(); for (int idx = 0; idx != txt2.length()-1; idx++) { org.junit.Assert.assertEquals((byte)txt2.charAt(idx), dstbuf.get()); } } }
fd492679-4b92-4898-879c-b0044b5093e0
4
public void renderModel(TextureManager var1, float var2, float var3, float var4, float var5, float var6, float var7) { super.renderModel(var1, var2, var3, var4, var5, var6, var7); Model var9 = modelCache.getModel(this.modelName); GL11.glEnable(3008); if(this.allowAlpha) { GL11.glEnable(2884); } if(this.hasHair) { GL11.glDisable(2884); HumanoidModel var10 = null; (var10 = (HumanoidModel)var9).headwear.yaw = var10.head.yaw; var10.headwear.pitch = var10.head.pitch; var10.headwear.render(var7); GL11.glEnable(2884); } if(this.armor || this.helmet) { GL11.glBindTexture(3553, var1.load("/armor/plate.png")); GL11.glDisable(2884); HumanoidModel var8; (var8 = (HumanoidModel)modelCache.getModel("humanoid.armor")).head.render = this.helmet; var8.body.render = this.armor; var8.rightArm.render = this.armor; var8.leftArm.render = this.armor; var8.rightLeg.render = false; var8.leftLeg.render = false; HumanoidModel var11 = (HumanoidModel)var9; var8.head.yaw = var11.head.yaw; var8.head.pitch = var11.head.pitch; var8.rightArm.pitch = var11.rightArm.pitch; var8.rightArm.roll = var11.rightArm.roll; var8.leftArm.pitch = var11.leftArm.pitch; var8.leftArm.roll = var11.leftArm.roll; var8.rightLeg.pitch = var11.rightLeg.pitch; var8.leftLeg.pitch = var11.leftLeg.pitch; var8.head.render(var7); var8.body.render(var7); var8.rightArm.render(var7); var8.leftArm.render(var7); var8.rightLeg.render(var7); var8.leftLeg.render(var7); GL11.glEnable(2884); } GL11.glDisable(3008); }
9db88d28-2bf9-42c9-bf49-b74971c7bc62
7
public void translateSelectedAtomsXYBy(Matrix3f transform, BitSet bs, float dx, float dy) { if (translationMatrix == null) translationMatrix = new Matrix4f(); if (tempMatrix1 == null) tempMatrix1 = new Matrix3f(); if (tempMatrix4f == null) tempMatrix4f = new Matrix4f(); if (tempPoint3f == null) tempPoint3f = new Point3f(); if (tempVector3f == null) tempVector3f = new Vector3f(); // *watch* the order of matrix multiplications: first transform the atomic coordinates into the current // view space, and then apply translation, and then transform back to the model space. tempMatrix4f.setIdentity(); tempMatrix1.invert(transform); tempMatrix4f.setRotation(tempMatrix1); translationMatrix.set(tempMatrix4f); tempMatrix4f.setIdentity(); tempVector3f.set(dx * 0.05f, -dy * 0.05f, 0); tempMatrix4f.setTranslation(tempVector3f); translationMatrix.mul(tempMatrix4f); tempMatrix4f.setRotation(transform); tempVector3f.set(0, 0, 0); tempMatrix4f.setTranslation(tempVector3f); translationMatrix.mul(tempMatrix4f); for (int i = 0; i < iAtom; i++) { if (bs.get(i)) { tempPoint3f.x = atom[i].rx; tempPoint3f.y = atom[i].ry; tempPoint3f.z = atom[i].rz; translationMatrix.transform(tempPoint3f); atom[i].setLocation(tempPoint3f); } } }
f32d1399-272a-4e13-9578-3e7a0520f0d3
1
private String removeNamespace(String string){ if (string.contains(":")){ return string.substring(string.indexOf(":")+1); }else{ return string; } }
faac6139-8886-470c-b537-74084460756c
0
@Override public String toString() { return "fleming.entity.Perfil[ idPerfil=" + idPerfil + " ]"; }
6872833f-8561-4a51-829f-943084c6df37
3
@Override public void run() { long lastTime = System.nanoTime(); start(); long now = System.nanoTime(); long timer = System.currentTimeMillis(); double delta = 0; int frames = 0; int updates = 0; System.out.println("Initialized in " + ((now - lastTime) / 1000000000.0) + " seconds"); while(!Display.isCloseRequested()) { now = System.nanoTime(); delta += (now - lastTime) / NANOSECS; lastTime = now; while(delta >= 1) { update(updates); updates++; delta--; } render(); frames++; if(System.currentTimeMillis() - timer > 1000) { timer += 1000; Display.setTitle("SplitMan | FPS: " + frames + " | UPS: " + updates); frames = 0; updates = 0; } Display.update(); Display.sync(120); } stop(); }
afd8a25f-1e7f-4983-ac98-60d708730a59
8
public boolean bodyCall(Node[] args, int length, RuleContext context) { checkArgs(length, context); BindingEnvironment env = context.getEnv(); Node n1 = getArg(0, args, context); Node n2 = getArg(1, args, context); if (n1.isLiteral() && n2.isLiteral()) { Object v1 = n1.getLiteralValue(); Object v2 = n2.getLiteralValue(); Node quo = null; if (NumberUtil.isNumber(v1) && NumberUtil.isNumber(v2)) { if (v1 instanceof Float || v1 instanceof Double || v2 instanceof Float || v2 instanceof Double) { double dv1 = Double.parseDouble(v1.toString()); double dv2 = Double.parseDouble(v2.toString()); quo = Util.makeDoubleNode(dv1 / dv2); } else { long lv1 = Long.parseLong(v1.toString()); long lv2 = Long.parseLong(v2.toString()); quo = Util.makeLongNode(lv1 / lv2); } return env.bind(args[2], quo); } } // Doesn't (yet) handle partially bound cases return false; }
ae4d78d8-e3c3-49fa-b90e-09c93b7be9ef
3
public boolean isScopeOf(Object obj, int scopeType) { if (scopeType == METHODSCOPE && obj instanceof ClassInfo) { ClassAnalyzer ana = getClassAnalyzer((ClassInfo) obj); if (ana != null) return ana.getParent() == this; } return false; }
6b4ae6b0-18e8-44de-b1e0-bc810a5a695b
6
public static HashMap<String, HashMap<String, Integer>> getMap(String filePath) throws Exception { HashMap<String, HashMap<String, Integer>> map = new HashMap<String, HashMap<String,Integer>>(); BufferedReader reader = filePath.toLowerCase().endsWith("gz") ? new BufferedReader(new InputStreamReader( new GZIPInputStream( new FileInputStream( filePath)))) : new BufferedReader(new FileReader(new File(filePath ))); String nextLine = reader.readLine(); int numDone =0; while(nextLine != null) { StringTokenizer sToken = new StringTokenizer(nextLine, "\t"); String sample = sToken.nextToken().replace(".fastatoRDP.txt.gz", ""); String taxa= sToken.nextToken(); int count = Integer.parseInt(sToken.nextToken()); if( sToken.hasMoreTokens()) throw new Exception("No"); HashMap<String, Integer> innerMap = map.get(sample); if( innerMap == null) { innerMap = new HashMap<String, Integer>(); map.put(sample, innerMap); } if( innerMap.containsKey(taxa)) throw new Exception("parsing error " + taxa); innerMap.put(taxa, count); nextLine = reader.readLine(); numDone++; if( numDone % 1000000 == 0 ) System.out.println(numDone); } return map; }
dee2f264-a5ce-4385-a61c-596b97159dcb
8
@Override public String returnXMLBlock(String Blob, String Tag) { int foundb=Blob.indexOf("<"+Tag+">"); if(foundb<0) foundb=Blob.indexOf("<"+Tag+" "); if(foundb<0) foundb=Blob.indexOf("<"+Tag+"/"); if(foundb<0) return ""; int founde=Blob.indexOf("/"+Tag+">",foundb)-1; if(founde<0) founde=Blob.indexOf("/"+Tag+" ",foundb)-1; if(founde<0) { founde=Blob.indexOf('>',foundb); if((founde>0)&&(Blob.charAt(founde-1)!='/')) founde=-1; } if(founde<0) return ""; Blob=Blob.substring(foundb,founde).trim(); return Blob; }
3fd875a4-7319-45d3-bc30-6d431b075ca6
5
public int maxDepth(TreeNode root) { if (root == null){ return 0; } if (root.left == null && root.right == null){ return 1; } else if (root.left == null){ return maxDepth(root.right)+1; } else if (root.right == null){ return maxDepth(root.left)+1; } else { return Math.max(maxDepth(root.left),maxDepth(root.right))+1; } }
1594077e-a3e3-42c5-9b85-3d0c96bf26aa
2
public boolean checkShapeDate(long fechaDesde, long fechaHasta){ return (fechaAlta >= fechaDesde && fechaAlta < fechaHasta && fechaBaja >= fechaHasta); }
1252d0ad-6da0-4128-b20d-fc6a65a1e3be
2
private boolean containsElement(List<ElementInfo> elements, ElementInfo element) { for(ElementInfo e : elements) if (e.equals(element)) return true; return false; }
6fcbe46a-08bf-4efe-81ed-89a9451f788d
0
public void addPanelToLayer(Panel pi) { this.ditems.add(pi); }
9a4f76eb-5aaf-46a1-95a5-c55d6cb7f851
9
private void imprimirElementorSin(ArrayList<Nodo> tem,DefaultMutableTreeNode padre){ Iterator nex=tem.iterator(); Nodo a; int con=0; try{ while(nex.hasNext()){ String tabla = ""; a=(Nodo)nex.next(); DefaultMutableTreeNode hijo; if(a.getTipoDato().equals("int")) { hijo= new DefaultMutableTreeNode(a.getDato()+", Tipo = "+a.getTipoDato()+", Valor = "+a.getValorNumInt()); }else if(a.getTipoDato().equals("float")) { hijo= new DefaultMutableTreeNode(a.getDato()+", Tipo = "+a.getTipoDato()+", Valor = "+a.getValorNumFloat()); }else if(a.getTipoDato().equals("")) { hijo= new DefaultMutableTreeNode(a.getDato()+", Tipo = Indefinido"); }else if(a.getTipoDato().equals("bool")) { hijo= new DefaultMutableTreeNode(a.getDato()+", Tipo = "+a.getTipoDato()+ ", Valor = "+a.getComando()); }else{ hijo= new DefaultMutableTreeNode(a.getDato()+", Tipo = "+a.getTipoDato()+ ", Valor = ("+a.getValorNumInt()+"-"+a.getValorNumFloat()+")"); } if(a.getTipoDato().equals("int")){ if(!a.getDato().equals("int")) { tabla = "Dato = " + a.getDato() + " Tipo de dato = " +a.getTipoDato()+ " Valor = " + a.getValorNumInt() + " Localidad: " + localidad++; } } else if(a.getTipoDato().equals("real")){ tabla = "Dato = " + a.getDato() + " Tipo de dato = " + a.getTipoDato() + " Valor = " + a.getValorNumFloat() + " Localidad: " + localidad++; } modelSem.insertNodeInto(hijo, padre, con); con++; this.imprimirElementorSin(a.getNodo(), hijo); } } catch(NullPointerException as){} }
6bbe8121-fd0a-47b7-8ef5-a9df9dbc9aee
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Classroom other = (Classroom) obj; if (this.number != other.number) { return false; } return true; }
ac849d6a-71c5-4d02-ab9e-8aae9cc94a11
9
@Override public void draw(Graphics g) { int width = getWidth(); int height = getHeight(); if (width == -1 || height == -1) return; g.setClip(getRealX(), getRealY(), width, height); if (this.hasBackground()) g.setColor(getBackground()); else g.setColor(Color.darkGray); g.fillRect(getRealX(), getRealY(), width, height); if (this.hasBorder()) g.setColor(getBorder().getColor()); else g.setColor(new Color(150,150,150)); g.drawRect(getRealX(), getRealY(), width-1, height-1); if (hasText()) { g.setColor(getTextColor()); int x = getRealX() , y = getRealY(); if (isTextCenteredX()) { x -= g.getFont().getWidth(getDisplayText())/2; if (hasWidth()) x += getWidth()/2; } if (isTextCenteredY()) { y -= g.getFont().getHeight(getDisplayText())/2; if (hasHeight()) y += getHeight()/2; } g.drawString(getDisplayText(), x, y); } g.clearClip(); }
19d46e7b-bdf3-44ad-a5c4-3977b937f74e
8
private TreeNode checkChildrenForKeyWords(TreeNode currentNode, String currentWord) { List<TreeNode> children = currentNode.getChildren(); for (TreeNode child : children) { if (child.isTempVisited()) continue; child.setTempVisited(true); if (child.isAccessible()) { List<String> keyWords = child.getKeywords(); for (String keyWord : keyWords) if (keyWord.equals(currentWord)) { currentNode = child; currentNode.setVisited(true); foundDialogue = true; } } } // this checks the currentNode for its own keywords, which is a way of // checking the root for keywords, since it is the child of nothing if (!foundDialogue) { List<String> keyWords = currentNode.getKeywords(); for (String keyWord : keyWords) { if (keyWord.equals(currentWord)) { foundDialogue = true; } } } return currentNode; }
fc589009-3e36-49f1-afaa-7e9d5f7ae712
9
public boolean pickAndExecuteAnAction() { try { //synchronized(Customers){ for(int i =0; i < Customers.size(); i++){ ////print("" + Customers.get(i).s ); if(Customers.get(i).s == CustomerState.waiting){ seatCustomer(Customers.get(i)); return true; } } //synchronized(Customers){ for(int i =0; i < Customers.size(); i++){ if(Customers.get(i).s == CustomerState.readyToOrder){ takeOrder(Customers.get(i)); return true; } } //} //synchronized(Customers){ for(int i =0; i < Customers.size(); i++){ if(Customers.get(i).s == CustomerState.customersFoodReady){ pickUpFood(Customers.get(i)); return true; } } //} //synchronized(Customers){ for(int i =0; i < Customers.size(); i++){ if(Customers.get(i).s == CustomerState.eating){ GetBill(Customers.get(i)); return true; } } //} waiterGui.GoToIdleSpot(); return false; //we have tried all our rules and found //nothing to do. So return false to main loop of abstract agent //and wait. } catch (ConcurrentModificationException e) { return false; } }
ea791e35-8236-42fc-b6d3-7fc98ab3d7d1
5
public void setOpMode(int mode){ opmode = mode; boolean[] es = new boolean[]{false, true, false, false, true, true}; if(es[mode] == false){pause();} switch(aamode){ case 1: pete.setEnabled(es[mode]); break; case 2: for(int y = 0; y < gridy; y++){ for(int x = 0; x < gridx; x++){ grid[x][y].setEnabled(es[mode]);}} break; } }
16e26741-5c76-428a-b39b-fff432b070ae
7
private void expTypeChanged() { if (m_Exp == null) return; // update parameter ui if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_CROSSVALIDATION_TEXT) { m_ExperimentParameterLabel.setText("Number of folds:"); m_ExperimentParameterTField.setText("" + m_numFolds); } else { m_ExperimentParameterLabel.setText("Train percentage:"); m_ExperimentParameterTField.setText("" + m_trainPercent); } // update iteration ui if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_FIXEDSPLIT_TEXT) { m_NumberOfRepetitionsTField.setEnabled(false); m_NumberOfRepetitionsTField.setText("1"); m_Exp.setRunLower(1); m_Exp.setRunUpper(1); } else { m_NumberOfRepetitionsTField.setText("" + m_numRepetitions); m_NumberOfRepetitionsTField.setEnabled(true); m_Exp.setRunLower(1); m_Exp.setRunUpper(m_numRepetitions); } SplitEvaluator se = null; Classifier sec = null; if (m_ExpClassificationRBut.isSelected()) { se = new ClassifierSplitEvaluator(); sec = ((ClassifierSplitEvaluator)se).getClassifier(); } else { se = new RegressionSplitEvaluator(); sec = ((RegressionSplitEvaluator)se).getClassifier(); } // build new ResultProducer if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_CROSSVALIDATION_TEXT) { CrossValidationResultProducer cvrp = new CrossValidationResultProducer(); cvrp.setNumFolds(m_numFolds); cvrp.setSplitEvaluator(se); PropertyNode[] propertyPath = new PropertyNode[2]; try { propertyPath[0] = new PropertyNode(se, new PropertyDescriptor("splitEvaluator", CrossValidationResultProducer.class), CrossValidationResultProducer.class); propertyPath[1] = new PropertyNode(sec, new PropertyDescriptor("classifier", se.getClass()), se.getClass()); } catch (IntrospectionException e) { e.printStackTrace(); } m_Exp.setResultProducer(cvrp); m_Exp.setPropertyPath(propertyPath); } else { RandomSplitResultProducer rsrp = new RandomSplitResultProducer(); rsrp.setRandomizeData(m_ExperimentTypeCBox.getSelectedItem() == TYPE_RANDOMSPLIT_TEXT); rsrp.setTrainPercent(m_trainPercent); rsrp.setSplitEvaluator(se); PropertyNode[] propertyPath = new PropertyNode[2]; try { propertyPath[0] = new PropertyNode(se, new PropertyDescriptor("splitEvaluator", RandomSplitResultProducer.class), RandomSplitResultProducer.class); propertyPath[1] = new PropertyNode(sec, new PropertyDescriptor("classifier", se.getClass()), se.getClass()); } catch (IntrospectionException e) { e.printStackTrace(); } m_Exp.setResultProducer(rsrp); m_Exp.setPropertyPath(propertyPath); } m_Exp.setUsePropertyIterator(true); m_Support.firePropertyChange("", null, null); }
41e79f00-48f4-4eb1-98fb-bc64529da7bc
5
private void jpeg2dicom(File archivoJPEG, File archivoDICOM) { try { BufferedImage jpegImage = ImageIO.read(archivoJPEG); if(jpegImage == null) { System.err.println("No se pudo crear imagen de archivo JPEG"); } //atributos de imagen int colorComponents = jpegImage.getColorModel().getNumColorComponents(); int bitsPerPixel = jpegImage.getColorModel().getPixelSize(); int bitsAllocated = (bitsPerPixel / colorComponents); int samplesPerPixel = colorComponents; //crea un nuevo objeto dicom DicomObject dicom = new BasicDicomObject(); dicom.putString(Tag.SpecificCharacterSet, VR.CS, "ISO_IR 100"); dicom.putString(Tag.PhotometricInterpretation, VR.CS, samplesPerPixel == 3 ? "YBR_FULL_422" : "MONOCHROME2"); dicom.putInt(Tag.SamplesPerPixel, VR.US, samplesPerPixel); //valores del header obligatorios dicom.putInt(Tag.Rows, VR.US, jpegImage.getHeight()); dicom.putInt(Tag.Columns, VR.US, jpegImage.getWidth()); dicom.putInt(Tag.BitsAllocated, VR.US, bitsAllocated); dicom.putInt(Tag.BitsStored, VR.US, bitsAllocated); dicom.putInt(Tag.HighBit, VR.US, bitsAllocated-1); dicom.putInt(Tag.PixelRepresentation, VR.US, 0); dicom.putDate(Tag.InstanceCreationDate, VR.DA, new Date()); dicom.putDate(Tag.InstanceCreationTime, VR.TM, new Date()); //cada dicom debe tener un UID dicom.putString(Tag.StudyInstanceUID, VR.UI, UIDUtils.createUID()); dicom.putString(Tag.SeriesInstanceUID, VR.UI, UIDUtils.createUID()); dicom.putString(Tag.SOPInstanceUID, VR.UI, UIDUtils.createUID()); //metafile information jpeg encapsulado en el dicom dicom.initFileMetaInformation(UID.JPEGBaseline1); //terminada la definicion de headers abre un outputstream al archivo dicom FileOutputStream fos = new FileOutputStream(archivoDICOM); BufferedOutputStream bos = new BufferedOutputStream(fos); DicomOutputStream dos = new DicomOutputStream(bos); dos.writeDicomFile(dicom); //configura los headers para la escritura de la imagen JPEG en el dicom dos.writeHeader(Tag.PixelData, VR.OB, -1); dos.writeHeader(Tag.Item, null, 0); /* According to Gunter from dcm4che team we have to take care that the pixel data fragment length containing the JPEG stream has an even length. */ int jpgLen = (int) archivoJPEG.length(); dos.writeHeader(Tag.Item, null, (jpgLen+1)&~1); FileInputStream fis = new FileInputStream(archivoJPEG); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis); //escribe los datos del JPEG en el DICOM byte[] buffer = new byte[65536]; int b; while ((b = dis.read(buffer)) > 0) { dos.write(buffer, 0, b); } /* According to Gunter from dcm4che team we have to take care that the pixel data fragment length containing the JPEG stream has an even length. So if needed the line below pads JPEG stream with odd length with 0 byte. */ if ((jpgLen&1) != 0) dos.write(0); dos.writeHeader(Tag.SequenceDelimitationItem, null, 0); dos.close(); } catch (IOException ex) { System.err.println("Error al crar buffer en archivo JPEG"); } }
b3e6594b-62a2-45ab-98c3-c253d0c8868c
0
public boolean isStart() { return type == START; }
ef29528e-290f-476b-a283-21c40d728b38
4
@Override public float[] getData() { if (ptr != 0) { return null; } else { if (isConstant()) { if (length > getMaxSizeOf32bitArray()) return null; float[] out = new float[(int) length]; for (int i = 0; i < length; i++) { out[i] = data[0]; } return out; } else { return data; } } }
ab6f126f-3889-41e2-ba6f-dfd9795eae2d
9
@Override public QueryResults<String> parseObjectIdentifiers(AtmosResponse response) { Collection<String> identifiers = new LinkedList<String>(); HttpEntity body = response.getEntity(); if (body != null) { try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document xml = documentBuilder.parse(body.getContent()); NodeList objects = xml.getElementsByTagName("Object"); for (int i = 0; i < objects.getLength(); i++) { Node objectNode = objects.item(i); NodeList objectNodeChildren = objectNode.getChildNodes(); for (int j = 0; j < objectNodeChildren.getLength(); j++) { Node objectNodeChild = objectNodeChildren.item(j); if (isNamedElement(objectNodeChild, "ObjectID")) { identifiers.add(objectNodeChild.getFirstChild().getNodeValue()); break; } } } } catch (ParserConfigurationException e) { throw new AtmosStorageException(e.getMessage(), e); } catch (IllegalStateException e) { throw new AtmosStorageException(e.getMessage(), e); } catch (SAXException e) { throw new AtmosStorageException(e.getMessage(), e); } catch (IOException e) { throw new AtmosStorageException(e.getMessage(), e); } } identifiers = (identifiers.size() > 0) ? identifiers : null; return new QueryResults<String>(identifiers, response.getContinuationToken()); }
8f1b37ee-f747-4b76-a1d1-1253dc41a9d8
4
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: try { String arquivo = null; jSalvar_Backup.setVisible(true); int result = jSalvar_Backup.showSaveDialog(null); if(result == JFileChooser.APPROVE_OPTION){ arquivo = jSalvar_Backup.getSelectedFile().toString().concat(".sql"); File file = new File(arquivo); if(file.exists()){ Object[] options = { "Sim", "Não" }; int opcao = JOptionPane.showOptionDialog(null,"Um arquivo com este nome já existe. Deseja alterar o arquivo?", "Atenção!!!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,options, options[0]); if (opcao == JOptionPane.YES_OPTION) { Runtime bck = Runtime.getRuntime(); bck.exec("C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump.exe -v -v -v --host=localhost --user=root " + "--password=123456 --port=3306 --protocol=tcp --force --allow-keywords " + "--compress --add-drop-table --default-character-set=latin1 --hex-blob " + "--result-file="+arquivo+" --databases compuponto"); JOptionPane.showMessageDialog(null, "Backup realizado com sucesso.", "", 1); }else{ JB_BackupActionPerformed(evt); } }else{ Runtime bck = Runtime.getRuntime(); bck.exec("C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump.exe -v -v -v --host=localhost --user=root " + "--password=123456 --port=3306 --protocol=tcp --force --allow-keywords " + "--compress --add-drop-table --default-character-set=latin1 --hex-blob " + "--result-file="+arquivo+" --databases compuponto"); JOptionPane.showMessageDialog(null, "Backup realizado com sucesso.", "", 1); } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, "Erro!", 2); } }//GEN-LAST:event_jButton1ActionPerformed
073ec7f3-ef1b-4fd2-ba7c-e8dcdcb64a4c
9
public void init(int i, int j, PersonnageType v) { if(i<0 && j <0) throw new PreConditionError("i>=0 && j>=0"); super.init(i, j, v); if(!(super.getType()==v)) throw new PostConditionError("getType(init(i,j,v)) == v"); if(!(super.getForceVitale() == 3)) throw new PostConditionError("getForceVitale(init(i,j,v)) == 3"); if(!(super.getX() == i)) throw new PostConditionError("getX(init(i,j,v)) == i"); if(!(super.getY() == j)) throw new PostConditionError("getX(init(i,j,v)) == j"); if(!(super.getSante() == Sante.VIVANT)) throw new PostConditionError("getSante(init(i,j,v)) == Sante::VIVANT"); if(!(super.getCompteurFireSuit() == 0)) throw new PostConditionError("getCompteurFireSuit(init(i,j,v)) == 0"); if(!(super.getNbBombes() == 1)) throw new PostConditionError("getNbBombes(init(i,j,v)) == 1"); }
f528e077-9d56-4505-9279-47b2ff99a99a
2
private boolean isValidUrl(String urlString) { boolean isUrl = false; try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); conn.connect(); isUrl = true; } catch (MalformedURLException e) { // the URL is not in a valid form } catch (IOException e) { // the connection couldn't be established } return isUrl; }
87390e6b-7a56-48d6-a0b9-71a550bf5102
3
private static int sign(int [] a){ int x=0; int len = a.length; for(int k=1; k<len; k++) if (a[k]> k ) x+=a[k]-k; x%=2; if (x==1) return -1; else return 1; }
ee41abb7-b263-48cf-9049-01a4f3ae7472
8
public boolean gameEnded() { int seeds = 0; //Player 1 - South for (int i = START_S; i <= END_S; i++) { seeds += board[i]; } if (seeds == 0) { //Gather opponents seeds (if any) //Rule 6 for (int i = START_N; i <= END_N; i++) { if (board[i] > 0) { board[HOUSE_N] += board[i]; board[i] = 0; } } return true; } //Player 2 - North seeds = 0; for (int i = START_N; i <= END_N; i++) { seeds += board[i]; } if (seeds == 0) { //Gather opponents seeds (if any) //Rule 6 for (int i = START_S; i <= END_S; i++) { if (board[i] > 0) { board[HOUSE_S] += board[i]; board[i] = 0; } } return true; } return false; }
840a797a-9217-4ab6-b5de-596df0b9b349
6
public void adjacencyListConnections(GraphNode<T> a, GraphNode<T> b, int direction,int weight) {//creates connection between two nodes forming the adjacency list.(lists inside lists) if (existNode(a) && existNode(b)) {//if a and b exists in the list of graph nodes. if (direction == 0 || direction == 1) {// direction param: 1 if it is directed(directed from a to b). if (direction == 0) { //0 if it has links to both sides.(a to b, b to a) //creates bidirectional link //to first direction. GraphNode gr_node = (GraphNode) graph_nodes.get(searchNodePosition(a)); List<GraphNode> grphn = gr_node.getNode_graphs(); grphn.append(b); gr_node.setNode_graphs(grphn);//adds the node to the adjacency list ((GraphNode) (gr_node)).addLink(b, weight);//makes the link between nodes this.num_aristas += 1; //to the other direction. GraphNode gr_node2 = (GraphNode) graph_nodes.get(searchNodePosition(b)); List<GraphNode> grphn2 = gr_node2.getNode_graphs(); grphn2.append(a); gr_node2.setNode_graphs(grphn2);//adds the node to the adjacency list ((GraphNode) (gr_node2)).addLink(a, weight);//makes the link between nodes this.num_aristas += 1; } else if (direction == 1) {//creates one direction link //to first direction. GraphNode gr_node = (GraphNode) graph_nodes.get(searchNodePosition(a)); gr_node.getNode_graphs().append(b); gr_node.setNode_graphs(gr_node.getNode_graphs()); ((GraphNode) (gr_node)).addLink(b, weight); this.num_aristas += 1; } } } else { System.out.println("graphnode a or graphnode b are not in the list"); } }
5619738b-8dfc-4b35-bc95-f83b449bde44
2
public static PlayOutside getSingleton(){ // needed because once there is singleton available no need to acquire // monitor again & again as it is costly if(singleton==null) { synchronized(PlayOutside.class){ // this is needed if two threads are waiting at the monitor at the // time when singleton was getting instantiated if(singleton==null) singleton = new PlayOutside(); } } return singleton; }
805bebf4-ed5d-404f-9b4f-c0dbdc4611d6
1
@Test public void worksWithSeveralFieldFilters2() { citations.add(c1); citations.add(c2); citations.add(cnull); filter.addFieldFilter("publisher", "Otava"); filter.addFieldFilter("year", "2012"); List<Citation> filtered = filter.getFilteredList(); List<Citation> expected = new LinkedList<Citation>(); expected.add(c1); expected.add(c2); assertTrue(filtered.containsAll(expected) && filtered.size() == 2); }
a48bca5c-4a3a-40f7-a6a9-a06c48aa1964
0
public void setIdAlmacen(int idAlmacen) { this.idAlmacen = idAlmacen; }
5d619ad2-e2c3-452e-b8f7-3ce198ce68ef
2
public void printSources(){ if (sources == null) { System.err.println("Sources not calculated yet"); return; } System.out.println("Sources:"); for (AndroidMethod am : sources) { System.out.println(am.toString()); } System.out.println("End of Sources"); }
d974ed6f-19ce-4bf8-9d34-e2b023de4903
0
@Override public void documentRemoved(DocumentRepositoryEvent e) {}
9767a3e8-3608-437f-b4b5-38bb25623f80
4
static Direction getDir(String s) { if(s.equalsIgnoreCase("r")) return RIGHT; if(s.equalsIgnoreCase("d")) return DOWN; if(s.equalsIgnoreCase("l")) return LEFT; if(s.equalsIgnoreCase("u")) return UP; return null; }
d07ed1e1-0a9b-4d8f-a5a3-cfe96f7ac216
0
public boolean isFrozen() { return frozen; }
0cda3161-9ed5-424b-aaab-16090ee38a09
2
public boolean checkNaive(List<Integer> list) { for (int idx = 0; idx < list.size(); ++idx) if (idx != list.get(idx)) { System.out.print("[FAILED] "); printList(list); return false; } System.out.print("[PASSED] "); printList(list); return true; }
da6e4aec-a60b-42be-b5b9-259d7b14854d
9
public void run() { while(isRunning()) { if(isEnabled()) { while(Keyboard.next()) { switch(Keyboard.getEventKey()) { case Keyboard.KEY_W: setUp(Keyboard.getEventKeyState()); break; case Keyboard.KEY_A: setLeft(Keyboard.getEventKeyState()); break; case Keyboard.KEY_S: setDown(Keyboard.getEventKeyState()); break; case Keyboard.KEY_D: setRight(Keyboard.getEventKeyState()); break; case Keyboard.KEY_SPACE: setAttack(Keyboard.getEventKeyState()); break; default: break; } setTime(); } } try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } //Slight Speed Limiter } }
ed2a85b1-dd8b-484c-9c2d-b5c671e00686
2
public ProfileResponse updateCard(String profileId, Card card) throws BeanstreamApiException { ProfilesUtils.validateProfileId(profileId); Gateway.assertNotNull(card, "card is is null"); String cardId = card.getId(); Gateway.assertNotEmpty(cardId, "card Id is empty"); String url = BeanstreamUrls.getProfileCardUrl(config.getPlatform(), config.getVersion(), profileId, cardId); if (card.getNumber().contains("X") || card.getNumber().contains("x")) card.setNumber(null); card.setType(null); card.setFunction(null); CardWrapper cw = new CardWrapper(card); // send the card json without id JsonElement _card = gson.toJsonTree(cw, CardWrapper.class); String response = connector.ProcessTransaction(HttpMethod.put, url, _card); return gson.fromJson(response, ProfileResponse.class); }
20134692-2a4f-42c8-8eb0-0878b539bc31
5
private void gameLoop() { long beforeTime, afterTime, timeSpent, sleepTime, overTime; overTime = 0; long totalOverTime = 0; gameStart = System.nanoTime(); beforeTime = gameStart; while (sc.isRunning()) { sc.update(); sc.paint(); afterTime = System.nanoTime(); timeSpent = afterTime - beforeTime; sleepTime = FRAME_PERIOD - timeSpent - overTime; if (sleepTime < 0) { // Updating took longer than the frame period totalOverTime -= sleepTime; overTime = 0; } else { try { Thread.sleep(sleepTime/1000000); // ns --> ms } catch (InterruptedException e) { e.printStackTrace(); } overTime = System.nanoTime() - afterTime - sleepTime; } beforeTime = System.nanoTime(); // Update the game without rendering if speed-up is required to fulfill fps-request skips = 0; while (totalOverTime > FRAME_PERIOD && skips < MAX_NUMBER_OF_SKIPS) { sc.update(); totalOverTime -= FRAME_PERIOD; skips++; } updateStats(); } System.out.println("Average FPS: "+averageFPS); }
01d7ddb3-f5b7-4a84-84b1-2a3a2c8d7767
6
public int ReloadHeidelTimeDocs(int year) { File folder = new File(Configuration.HeidelCollectionRoot + "19" + year); File[] listOfFiles = folder.listFiles(); if (listOfFiles == null) { System.out.printf("ANNO 19%d assente\n", year); return 0; } int countFiles = 0; double perc = 0; for (File file : listOfFiles) { if (file.isFile()) { perc = 100 * (double)(countFiles + 1) / (double)listOfFiles.length; System.out.printf("ANNO 19%d %d/%d %.1f%%\r", year, (countFiles + 1), listOfFiles.length, perc); try { String path = file.getPath(); String str = readFile(path, Charset.defaultCharset()); String docId = path.substring(path.lastIndexOf("/") + 1, path.indexOf("_")); String dataCreazione = path.substring(path.indexOf("_") + 1); //System.out.println("\t" + docId + "\t" + dataCreazione); if (str.length() > 0) { Document d = new Document(); d.Id = docId; try { d.DataCreazione = new SimpleDateFormat("yyyy-MM-dd").parse(dataCreazione); } catch(ParseException ex) { } d.TestoTime = str; d.HeidelTerms = new ArrayList<HeidelTerm>(); d.HeidelTerms = GetHeidelTimeTerms(str); documents.add(d); countFiles++; } } catch(IOException ex) { } } } System.out.println(); return countFiles; }
af4ef3cb-d4b8-465c-8509-cfcc05d9789a
5
public double[][] getOpacites() { double[][] opacites = new double[grid.length][grid[0].length]; boolean[][] nextGrid = this.nextGeneration(); for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (nextGrid[i][j] != grid[i][j]) { // Proportionnel à l'endroit où on est rendu dans l'entre génération if (grid[i][j]) { // Si on passe de Vivant vers Mort opacites[i][j] = (Math.floor(generation) + 1 - generation); } else { // Si on passe de Mort à Vivant opacites[i][j] = 1 - (Math.floor(generation) + 1 - generation); } } else { // Sinon, l'opacité ne change pas entre les générations. // Elle est donc forcément soit 100%, soit 0% opacites[i][j] = grid[i][j] ? 1 : 0; } } } return opacites; }
52e1e1c4-a253-4093-9879-33e72644000c
0
public void setClassFieldString(String classFieldString) { this.classFieldString = classFieldString; }
a58bfae3-5b2d-4afb-ab59-089df8bfcd12
8
private void createKBestList() throws MaltChainedException { final Class<?> kBestListClass = history.getKBestListClass(); if (kBestListClass == null) { return; } final Class<?>[] argTypes = { java.lang.Integer.class, org.maltparserx.parser.history.action.SingleDecision.class }; final Object[] arguments = new Object[2]; arguments[0] = history.getKBestSize(); arguments[1] = this; try { final Constructor<?> constructor = kBestListClass.getConstructor(argTypes); kBestList = (KBestList)constructor.newInstance(arguments); } catch (NoSuchMethodException e) { throw new HistoryException("The kBestlist '"+kBestListClass.getName()+"' cannot be initialized. ", e); } catch (InstantiationException e) { throw new HistoryException("The kBestlist '"+kBestListClass.getName()+"' cannot be initialized. ", e); } catch (IllegalAccessException e) { throw new HistoryException("The kBestlist '"+kBestListClass.getName()+"' cannot be initialized. ", e); } catch (InvocationTargetException e) { throw new HistoryException("The kBestlist '"+kBestListClass.getName()+"' cannot be initialized. ", e); } }
11d12a72-9c71-49a8-9504-be2ac337baf5
9
public ArrayList<ParseResult> doIt(String x) { String s = new String("OK"); try { Path path = Paths.get(x); ArrayList<ParseResult> parseResults = new ArrayList<>(); // Read lines from file List<String> lines = Files.readAllLines(path); // Iterate all lines for (int i = 0; i < lines.size(); i++) { String value1 = ""; String value2 = ""; String value3 = ""; // Get line String line = lines.get(i); // Split line String[] split = line.split("|"); // Loop for (int iz = 0; iz < split.length; iz++) { if (split[iz].equals("value1")) { if (doItCount < 100) { value1 = split[iz]; } } else if (split[iz].equals("value2")) { System.out.print("Value 2 " + split[iz]); if (value1.length() > 5) value2 = split[iz]; else value2 = split[iz] + " details"; } else if (split[iz].equals("hello")) { value3 = split[iz] + " 3 "; doItCount++; } } parseResults.add(new ParseResult(value1, value2, value3, "", "")); } } catch (Exception e) { if (e.getClass().getName().equals(IOException.class.getName())) { s = "INPUT_EXCEPTION"; } else { s = "EXCEPTION"; } } System.out.println("Processing result status was" + s); return null; }
10a1bc72-75e1-4d30-8671-5a5f8265b98c
5
public List<Branch> getActiveBranches(){ List<Branch> list = new ArrayList<>(); Connection con = null; Statement stmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnection(dbCon.getDATABASE_URL(), dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD()); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select brh_id, brh_name, brh_address, brh_email, brh_phone, brh_fax, brh_mobile, brh_isactive, brh_activesince, brh_deactivatedsince,city_id " + "From branch where brh_isactive=TRUE order by brh_name"); while (rs.next()) { Branch brh = new Branch(); brh.setId(rs.getInt(1)); brh.setName(rs.getString(2)); brh.setAddress(rs.getString(3)); brh.setEmail(rs.getString(4)); brh.setPhone(rs.getString(5)); brh.setFax(rs.getString(6)); brh.setMobile(rs.getString(7)); brh.setIsActive(rs.getBoolean(8)); brh.setActiveSince(rs.getDate(9)); brh.setDeactivatedSince(rs.getDate(10)); brh.setCity(rs.getInt(11)); list.add(brh); } } catch (SQLException | ClassNotFoundException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } } return list; }
25c6a402-d717-44da-9cbd-f9dd78e34889
5
public TableModel(ResultWrapper rw) { myRes = rw.getResultSet(); wrapper = rw; try { if(myRes != null)// dml commands { int cols = myRes.getMetaData().getColumnCount(); colSizes = new int[cols + 1]; String tableName = null; for (int i = 1; i <= cols; i++) { String currTn = myRes.getMetaData().getTableName(i); if (tableName != null && !tableName.equals(currTn)) { moreThanOneTable = true; break; } tableName = currTn; } } } catch (SQLException ex) { } }
5527ae88-be2b-4ac3-bfc7-c9ee595ae43b
5
public int[][] csvInt( String filePath, int tableWidth, int tableLength ) { int[][] table = null; BufferedReader ingester = null; try { String line; table = new int[ tableWidth ][ tableLength ]; ingester = new BufferedReader( new FileReader( filePath ) ); while ( (line = ingester.readLine() ) != null ) { int j = 0; int stringIndex = 0; for( int i=0; i<line.length(); i++ ) { table[i][j] = Integer.parseInt( line.substring( stringIndex , line.indexOf( ',', stringIndex++ ) ) ); } j++; } } catch (FileNotFoundException e) { System.out.println( "\n\nERROR: Invalid File Path.\n" ); } catch (IOException e) { System.out.println( "\n\nERROR: Unable To Read Line.\n" ); }; try { ingester.close(); } catch (IOException e) { System.out.println( "\n\nERROR: BufferedReader is invalid.\n" ); }; return table; }
ad996d6f-6af1-42cf-8a1a-43215f6d4536
2
public iProperty(String fileName) { this.fileName = fileName; File file = new File(fileName); if (file.exists()) { try { load(); } catch (IOException ex) { log.severe("[PropertiesFile] Unable to load " + fileName + "!"); } } else { save(); } }
5965bae4-b36c-4fac-8821-0eb5afe287c6
2
public float getFloat(String key) { try { if(hasKey(key)) return ((NBTNumber<Float>) get(key)).getValue(); return 0; } catch (ClassCastException e) { return 0; } }
6691f044-b966-4349-8b88-0f65c1024903
8
* @param adj_data The data value of the adjacent block */ private STAIR_RENDER shouldRenderStairFront(short adj_id, byte adj_data) { if (adj_id < 0 || blockArray[adj_id] == null) { return STAIR_RENDER.YES; } if (blockArray[adj_id].isSolid()) { return STAIR_RENDER.NO; } else { switch (blockArray[adj_id].getType()) { case HALFHEIGHT: if ((adj_data & 0x8) == 0x8) { return STAIR_RENDER.YES; } else { return STAIR_RENDER.NO; } case SEMISOLID: case WATER: case GLASS: return STAIR_RENDER.OFFSET; default: return STAIR_RENDER.YES; } } }
5018cd57-3735-4b30-b045-cecbf359badf
5
@Override public void messageArrived(MqttTopic topic, MqttMessage message) { String[] topics = topic.getName().split("/"); String subtopic = topics[topics.length-1]; Housemate person = null; WCMessage msg = null; for(Housemate hm : Housemate.values()) { if (hm.getName().equals(subtopic)) { person = hm; } } if(person == null) return; try { msg = WCMessage.parseString(new String(message.getPayload())); Location l = Location.parseLocaction(msg.getLocation()); String date = msg.getDate(); updateHousemate(person, l, date); } catch (MqttException e) { e.printStackTrace(); } catch (ParseException e) { System.out.println(e.getMessage()); } drawClock(); }
bfe212cb-1525-49b1-aefe-d83703d8c7fe
9
protected void spaceMultipleTrees(StandardTreeNode root) { // Found the appropriate boundary of this tree, allowing for // orientation Point2D pos = graph.getLocation(root.cell); double rootX = 0; double rootY = 0; if (pos != null) { rootX = graph.getLocation(root.cell).getX(); rootY = graph.getLocation(root.cell).getY(); } if (orientation == SwingConstants.NORTH) { int leftMostX = root.getLeftWidth(); double leftMostTreeX = rootX - leftMostX; if (leftMostTreeX < treeBoundary + treeDistance) { rootX = treeBoundary + treeDistance + leftMostX; graph.setLocation(root.cell, rootX, rootY); } // Calculate right-most boundary of this tree for next calculation int rightMostX = root.getRightWidth(); treeBoundary = rootX + rightMostX; } if (orientation == SwingConstants.SOUTH) { int rightMostX = root.getRightWidth(); double rightMostTreeX = rootX - rightMostX; if (rightMostTreeX < treeBoundary + treeDistance) { rootX = treeBoundary + treeDistance + rightMostX; graph.setLocation(root.cell, rootX, rootY); } // Calculate left-most boundary of this tree for next calculation int leftMostX = root.getLeftWidth(); treeBoundary = rootX + leftMostX; } if (orientation == SwingConstants.WEST) { int topMostY = root.getLeftWidth(); double topMostTreeY = rootY - topMostY; if (topMostTreeY < treeBoundary + treeDistance) { rootY = treeBoundary + treeDistance + topMostY; graph.setLocation(root.cell, rootX, rootY); } // Calculate left-most boundary of this tree for next calculation int bottomMostY = root.getRightWidth(); treeBoundary = rootY + bottomMostY; } if (orientation == SwingConstants.EAST) { int topMostY = root.getRightWidth(); double topMostTreeY = rootY - topMostY; if (topMostTreeY < treeBoundary + treeDistance) { rootY = treeBoundary + treeDistance + topMostY; graph.setLocation(root.cell, rootX, rootY); } // Calculate right-most boundary of this tree for next calculation int bottomMostY = root.getLeftWidth(); treeBoundary = rootY + bottomMostY + getRightMostX(root).height; } }
9aef1e9b-b60f-4cf2-b420-08165cd59523
2
public Anim(byte[] buf) { id = Utils.int16d(buf, 0); d = Utils.uint16d(buf, 2); ids = new int[Utils.uint16d(buf, 4)]; if (buf.length - 6 != ids.length * 2) throw (new LoadException("Invalid anim descriptor in " + name, Resource.this)); for (int i = 0; i < ids.length; i++) ids[i] = Utils.int16d(buf, 6 + (i * 2)); }
f1db884d-1e71-4a27-b072-c42da8db9fcc
5
@Override public Property deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject o = jsonElement.getAsJsonObject(); String name = o.get("name").getAsString(); int displayMode = o.get("displayMode").getAsInt(); JsonArray values = o.getAsJsonArray("values"); if (values.size() == 1) { JsonArray base = values.get(0).getAsJsonArray(); String val = base.get(0).getAsString(); int augmentColour = base.get(1).getAsInt(); if (val.contains("-")) { // Min/Max int minValue = Integer.valueOf(val.split("-")[0]); int maxValue = Integer.valueOf(val.split("-")[1]); return new MinMaxProperty(name, displayMode, AugmentColour.forId(augmentColour), minValue, maxValue); } else if (val.contains("/")) { // Stack Size int minValue = Integer.valueOf(val.split("/")[0]); int maxValue = Integer.valueOf(val.split("/")[1]); return new MinMaxProperty(name, displayMode, AugmentColour.forId(augmentColour), minValue, maxValue); } else if (val.contains("%")) { // Percentage int value = Integer.valueOf(base.get(0).getAsString().replaceAll("[^\\d]", "")); return new PercentageProperty(name, displayMode, AugmentColour.forId(augmentColour), value); } else if (val.contains(".")) { // Fraction double value = Double.parseDouble(base.get(0).getAsString().replaceAll("[^\\d.]", "")); return new DecProperty(name, displayMode, AugmentColour.forId(augmentColour), value); } else { // Flat int value = Integer.parseInt(base.get(0).getAsString().replaceAll("[^\\d]", "")); return new IntProperty(name, displayMode, AugmentColour.forId(augmentColour), value); } } else { return new Property(name, displayMode, AugmentColour.WHITE); } }
1f0c28d0-0029-4331-ad0c-8dd9a69c6269
4
@Override public void mouseReleased(MouseEvent e) { if (enteredOC != null) { this.setSelectedOC(enteredOC, enteredOC.getParent()); enteredOC = null; } else if (e.isPopupTrigger()) { for (Component ele : elements) { if (ele.contains(e.getPoint())) { setSelected(ele); ele.showMenu(e.getX(), e.getY()); changed(); break; } } } }
1b06db66-d132-49bd-b9ba-8fa2d40f2dc1
4
private static void listFile(File f) throws InterruptedException { if (f == null) { throw new IllegalArgumentException(); } if (f.isFile()) { System.out.println(f); return; } File[] allFiles = f.listFiles(); if (Thread.interrupted()) { throw new InterruptedException("文件扫描任务被中断"); } for (File file : allFiles) { //还可以将中断检测放到这里 listFile(file); } }
e08abbe4-0c57-4346-96c6-ed5411be427e
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Source other = (Source) obj; if (sourceName == null) { if (other.sourceName != null) return false; } else if (!sourceName.equals(other.sourceName)) return false; return true; }
2d0aaa16-4418-4704-89c6-3578a7e91a78
6
protected static char[] encodeBlock(byte[] raw, int offset) { int block = 0; // how much space left in input byte array int slack = raw.length - offset - 1; // if there are fewer than 3 bytes in this block, calculate end int end = (slack >= 2) ? 2 : slack; // convert signed quantities into unsigned for (int i = 0; i <= end; i++) { byte b = raw[offset + i]; int neuter = (b < 0) ? b + 256 : b; block += neuter << (8 * (2 - i)); } // extract the base64 digets, which are six bit quantities. char[] base64 = new char[4]; for (int i = 0; i < 4; i++) { int sixbit = (block >>> (6 * (3 - i))) & 0x3f; base64[i] = getChar(sixbit); } // pad return block if needed if (slack < 1) base64[2] = '='; if (slack < 2) base64[3] = '='; // always returns an array of 4 characters return base64; }
58620922-e5c6-4dc6-9418-71f1c999ec1c
3
private boolean areDirectlyConnected(State s1, State s2, Automaton automaton) { if (s1 == s2) return false; if (automaton.getTransitionsFromStateToState(s1, s2).length == 0 && automaton.getTransitionsFromStateToState(s2, s1).length == 0) return false; return true; }
cbe0f14d-d71e-401a-95b3-6d525a592406
2
public Lista<Rama_Hoja> getSalidas(){ Lista<Rama_Hoja> resp = null; for (Nodo<Rama_Hoja> i = arrayIO.getHead(); i != null; i=i.getSiguiente()){ if(i.getIndex().split("_")[2]=="O") resp.insertar(i.getDato()); } return resp; }
f7f268f7-5e29-49b1-b90a-132eeb9ab2d4
6
public static void cardclick(int button) { // in case of button gets clicked again if ((newhand[button] != handcopy[button]) && newhand[button] >= 1) { newhand[button]--; } // in case new button gets clicked else if ((newhand[button] == handcopy[button]) && newhand[button] >= 1) { System.arraycopy(handcopy,0,newhand,0,13); newhand[button]--; } // in case of button gets clicked with 0 cards else if((newhand[button] == handcopy[button]) && newhand[button] == 0){ System.arraycopy(handcopy,0,newhand,0,13); } // change display array display[0] = button; display[1] = handcopy[button] - newhand[button]; }
2c6bc3f9-a1a8-459f-8466-13bd1c30b48b
9
private int checkHtml(final StringBuilder out, final String in, int start) { final StringBuilder temp = new StringBuilder(); int pos; // Check for auto links temp.setLength(0); pos = Utils.readUntil(temp, in, start + 1, ':', ' ', '>', '\n'); if(pos != -1 && in.charAt(pos) == ':' && HTML.isLinkPrefix(temp.toString())) { pos = Utils.readUntil(temp, in, pos, '>'); if(pos != -1) { final String link = temp.toString(); this.config.decorator.openLink(out); out.append(" href=\""); Utils.appendValue(out, link, 0, link.length()); out.append("\">"); Utils.appendValue(out, link, 0, link.length()); out.append("</a>"); return pos; } } // Check for mailto or adress auto link temp.setLength(0); pos = Utils.readUntil(temp, in, start + 1, '@', ' ', '>', '\n'); if(pos != -1 && in.charAt(pos) == '@') { pos = Utils.readUntil(temp, in, pos, '>'); if(pos != -1) { final String link = temp.toString(); this.config.decorator.openLink(out); out.append(" href=\""); //address auto links if(link.startsWith("@")) { String slink = link.substring(1); String url = "https://maps.google.com/maps?q="+slink.replace(' ', '+'); out.append(url); out.append("\">"); out.append(slink); } //mailto auto links else { Utils.appendMailto(out, "mailto:", 0, 7); Utils.appendMailto(out, link, 0, link.length()); out.append("\">"); Utils.appendMailto(out, link, 0, link.length()); } out.append("</a>"); return pos; } } // Check for inline html if(start + 2 < in.length()) { temp.setLength(0); return Utils.readXML(out, in, start, this.config.safeMode); } return -1; }
1584d340-6c84-478d-9b3e-d5e6b9287e2f
7
public static boolean couldBeDouble(final String v) { if(null==v) { return false; } final int len = v.length(); if(len<=0) { return true; } if(len>40) { return false; } if(BurstMap.missingDoubleValue(v)) { return true; } if(v.equalsIgnoreCase(BurstMap.doublePosInfString)||v.equalsIgnoreCase(BurstMap.doubleNegInfString)) { return true; } try { Double.parseDouble(v); return true; } catch (NumberFormatException ex) { } return false; }
feef70e4-8bea-43f3-9e45-3b8b64aa6c80
1
public void addMany(int... elements) { if (manyItems + elements.length > data.length) { // Ensure twice as much space as we need. ensureCapacity((manyItems + elements.length)*2); } System.arraycopy(elements, 0, data, manyItems, elements.length); manyItems += elements.length; }
a5c5ae2e-aa51-4462-833a-c41cf33e0b35
7
public final DirkExpParser.additiveExpr_return additiveExpr() throws RecognitionException { DirkExpParser.additiveExpr_return retval = new DirkExpParser.additiveExpr_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token set15=null; DirkExpParser.multiplyExpr_return multiplyExpr14 = null; DirkExpParser.multiplyExpr_return multiplyExpr16 = null; CommonTree set15_tree=null; try { // F:\\antlr\\BoncExp.g:39:5: ( multiplyExpr ( ( PLUS | MINUS ) multiplyExpr )* ) // F:\\antlr\\BoncExp.g:39:9: multiplyExpr ( ( PLUS | MINUS ) multiplyExpr )* { root_0 = (CommonTree)adaptor.nil(); pushFollow(FOLLOW_multiplyExpr_in_additiveExpr302); multiplyExpr14=multiplyExpr(); state._fsp--; adaptor.addChild(root_0, multiplyExpr14.getTree()); // F:\\antlr\\BoncExp.g:39:22: ( ( PLUS | MINUS ) multiplyExpr )* loop5: do { int alt5=2; int LA5_0 = input.LA(1); if ( ((LA5_0>=PLUS && LA5_0<=MINUS)) ) { alt5=1; } switch (alt5) { case 1 : // F:\\antlr\\BoncExp.g:39:23: ( PLUS | MINUS ) multiplyExpr { set15=(Token)input.LT(1); set15=(Token)input.LT(1); if ( (input.LA(1)>=PLUS && input.LA(1)<=MINUS) ) { input.consume(); root_0 = (CommonTree)adaptor.becomeRoot((CommonTree)adaptor.create(set15), root_0); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } pushFollow(FOLLOW_multiplyExpr_in_additiveExpr312); multiplyExpr16=multiplyExpr(); state._fsp--; adaptor.addChild(root_0, multiplyExpr16.getTree()); } break; default : break loop5; } } while (true); } 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 { } return retval; }
19acb5b4-a3e4-48e4-b25d-11c5ffe604ce
1
private boolean Ingreso(float importe) { if (importe < 0 ) { return false; } saldo += importe; return true; }
d1d29a0c-ef13-4b84-99db-cb82149176f9
6
public void run(){ // If we have a list of replies from a previous repetition // calculate suspected processes if (started) { for(int i = 0; i <= p.getNo(); i++) { if (i != 0 && i != p.pid) { if (!successfulReplies[i-1] && !suspectedProcesses[i-1]) { Utils.out(p.pid,"Process " + i + " is now suspected"); suspectedProcesses[i-1] = true; isSuspected(i); } //clear the slot for next time successfulReplies[i-1] = false; } } } lastHeartbeat = System.currentTimeMillis(); //Utils.out(p.pid,""+lastHeartbeat); p.broadcast(Utils.HEARTBEAT,"" + lastHeartbeat); started = true; }
93e14f6e-7527-4971-89e7-bf9663329e6e
4
public void closeConnection() { //4: Closing connection try { if (in != null) { in.close(); } if (out != null) { out.close(); } if (providerSocket != null) { providerSocket.close(); } } catch (IOException ioException) { ioException.printStackTrace(); } }
1c0fbca6-02d2-4419-b167-cd9dbbd514be
6
public static void waitForElement(UIObject obj) throws Exception{ wait=new WebDriverWait(driver, 320); //wait.until(ExpectedConditions.visibilityOf(element)); log.info("waiting for element " +obj); try{ if(obj.getIdentifier().equalsIgnoreCase("Byid")){ wait.until(ExpectedConditions.presenceOfElementLocated(By.id(obj.getId()))); } else if(obj.getIdentifier().equalsIgnoreCase("Byname")){ wait.until(ExpectedConditions.presenceOfElementLocated(By.name(obj.getName()))); } else if(obj.getIdentifier().equalsIgnoreCase("Byxpath")){ wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(obj.getXpath()))); } else if(obj.getIdentifier().equalsIgnoreCase("BycssSelector")){ wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(obj.getCssselector()))); } else if(obj.getIdentifier().equalsIgnoreCase("Byclassname")){ wait.until(ExpectedConditions.presenceOfElementLocated(By.className(obj.getClassname()))); } }catch(Exception e){ String str=e.getMessage(); log.info(str); throw new Exception(str); } }
caa45acc-5641-4bce-b106-d16f6f0bd925
5
public boolean estBloquee(Piece p) { Piece sauv = p; Piece monRoi = null; boolean isBloquee = false; // Recherche de mon roi dans l'echiquier for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (this.tableau[i][j].getCouleur() == p.getCouleur() && this.tableau[i][j].getClass().getName() == "pieces.Roi") { monRoi = this.tableau[i][j]; } } } // On supprime ma piece pour tester supprimerPiece(p.getPosition()); if (estEchec(monRoi)) /* Roi de la meme couleur que la piece */ { isBloquee = true; } ajouterPiece(sauv); return isBloquee; }
cb86dc71-d3a0-4db8-a859-53c7c8320bdd
1
private static boolean isNullOrEmpty(String str) { return str == null || str.length() < 1; }
c7e4a454-f037-4065-98bf-9f4a6fa0bbc9
6
public boolean equals( Object other ) { if ( _set.equals( other ) ) { return true; // comparing two trove sets } else if ( other instanceof Set ) { Set that = ( Set ) other; if ( that.size() != _set.size() ) { return false; // different sizes, no need to compare } else { // now we have to do it the hard way Iterator it = that.iterator(); for ( int i = that.size(); i-- > 0; ) { Object val = it.next(); if ( val instanceof Double ) { double v = ( ( Double ) val ).doubleValue(); if ( _set.contains( v ) ) { // match, ok to continue } else { return false; // no match: we're done } } else { return false; // different type in other set } } return true; // all entries match } } else { return false; } }
56bf9a04-7e9c-4cbd-b9a1-9d39da814035
3
private boolean readCharToken(char ch, List<Token> parts) { switch (ch) { case '(': parts.add(CharToken.OPEN); return true; case ')': parts.add(CharToken.CLOSE); return true; case ',': parts.add(CharToken.SEPARATOR); return true; default: return false; } }
37caa0c5-0baa-4d34-b97e-de3d42b40a92
0
public String toString() { return xCoordinate+", "+yCoordinate; }
f859e61b-8c28-4e50-8e46-bdf759940b65
8
public int crearOpcion(Opcion op) { String consulta; try { if (con.isClosed()) { con = bd.conexion(); } Object ob = null; if (op.getdespuesDeOpcion().getCodigo() != 0) { ob = op.getdespuesDeOpcion().getCodigo(); } String des = op.getDescripcionOpcion().replace("\\", "\\\\"); consulta = "INSERT INTO Opcion VALUES(" + op.getCodigo() + ",'" + op.getUrl() + "','" + op.getOrden() + "'," + ob + ",'" + op.getPregunta().getCodigo() + "','" + des + "')"; Statement sta = con.createStatement(); int rs = sta.executeUpdate(consulta); //con.close(); if (rs == 1 || rs == 4 || rs == 4) { return 1; } else { return 0; } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Problemas creando la opcion!. Error: " + ex); } finally { if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } return 0; }
79d1beaf-9263-4ceb-ac50-8c6e0b3706a3
7
protected void setGrid() { String line; int count = 0; // update geometry this.updateDataSize(); grid = new DataGridCel[numberOfRows][numberOfCols + 1]; LineScanner scan = new LineScanner(dataBuffer.toString()); for (int r = 0; r < numberOfRows; r++) { if (scan.hasNext()) { line = scan.nextLine(); } else { line = new String(); } for (int c = 0; c < numberOfCols; c++) { if (c < line.length()) { grid[r][c] = new DataGridCel(line.charAt(c), count); count++; } else { if (r == (numberOfRows - 1) && c > 0 && c == line.length()) { grid[r][c] = new DataGridCel(count); } else { grid[r][c] = new DataGridCel(-1); } } } } }
f18da740-46f9-448c-8ef9-41c211d65117
0
public String getExtraData() { return this.extraData; }
56d5d08d-20b9-4367-a7e8-506ca5a5a016
5
public static int switchlt(int x) { int j = 1; switch(x) { case 1: j++;break; case 2: j++; case 3: j++; case 4: j++; case 5: j++; default: j++; } System.out.println("j = " + j); return j + x; }
8734e59b-1761-4b5d-af4a-99c0c703ad74
5
public static int d(int l1, int l2, int type) { switch (type) { case 01 : return ( match(l1, l2) + penalty01 ); case 10 : return ( match(l1, l2) + penalty01 ); case 11 : return ( match(l1, l2) ); case 12 : return ( match(l1, l2) + penalty21 ); case 21 : return ( match(l1, l2) + penalty21 ); default : return ( match(l1, l2) + penalty22 ); // catches the 2-2 case } }
8d845a8a-5972-4c14-8509-5f7e4db8bbe0
4
private int[][] pasaArregloAMatrizUp(int[] c0, int[] c1, int[] c2, int[] c3) { int[][] res = new int[4][4]; for (int k = 0; k < 4; k++) res[k][0] = c0[k]; for (int k = 0; k < 4; k++) res[k][1] = c1[k]; for (int k = 0; k < 4; k++) res[k][2] = c2[k]; for (int k = 0; k < 4; k++) res[k][3] = c3[k]; return res; }
b80e52d8-15ab-42c0-841e-a7fd975b5cb5
6
@Override public Boolean[] convertFromString(Class<? extends Boolean[]> cls, String str) { if (str.length() == 0) { return EMPTY; } Boolean[] array = new Boolean[str.length()]; for (int i = 0; i < array.length; i++) { char ch = str.charAt(i); if (ch == 'T') { array[i] = Boolean.TRUE; } else if (ch == 'F') { array[i] = Boolean.FALSE; } else if (ch == '-') { array[i] = null; } else { throw new IllegalArgumentException("Invalid Boolean[] string, must consist only of 'T', 'F' and '-'"); } } return array; }
225675be-f4a7-44ff-9724-f67709af82e3
9
@Override public void visitDocComment(JsDocComment comment) { boolean asSingleLine = comment.getTags().size() == 1; if (!asSingleLine) { newlineOpt(); } p.print("/**"); if (asSingleLine) { space(); } else { p.newline(); } boolean notFirst = false; for (Map.Entry<String, Object> entry : comment.getTags().entrySet()) { if (notFirst) { p.newline(); p.print(' '); p.print('*'); } else { notFirst = true; } p.print('@'); p.print(entry.getKey()); Object value = entry.getValue(); if (value != null) { space(); if (value instanceof CharSequence) { p.print((CharSequence) value); } else { accept((JsExpression) value); } } if (!asSingleLine) { p.newline(); } } if (asSingleLine) { space(); } else { newlineOpt(); } p.print('*'); p.print('/'); if (asSingleLine) { spaceOpt(); } }
6b380317-64b0-495d-93c5-bd602b422c5d
3
private JSONWriter end(char mode, char c) throws JSONException { if (this.mode != mode) { throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } this.pop(mode); try { this.writer.write(c); } catch (IOException e) { throw new JSONException(e); } this.comma = true; return this; }
6e172b3d-1356-4c7f-9db6-4a79b1c62163
0
public void setValue(T value) { this.value = value; }
c119217d-1e1d-410c-bc4e-6f67d57ecf8b
9
@Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if ("relation".equals(qName)) { cr.setRelationId(Integer.parseInt(attrs.getValue("id"))); } if ("member".equals(qName) && "relation".equals(eleStack.peek())) { if (clcMainWays.containsKey(Integer.parseInt(attrs.getValue("ref")))) { cr.addMember(new CustomRelationMember(attrs.getValue("type"), Integer.parseInt(attrs.getValue("ref")), attrs .getValue("role"))); if (attrs.getValue("role").equals("outer")) { CustomWay cw = clcMainWays.get(Integer.parseInt(attrs.getValue("ref"))); Iterator<Map.Entry<String, String>> it = cw.getTags().entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next(); cr.addTag(pairs.getKey(), pairs.getValue()); } cr.addTag("type", "multipolygon"); } isRelationMember = true; } } else if ("tag".equals(qName) && "relation".equals(eleStack.peek())) { if (!"fixme".equals(attrs.getValue("k"))) { cr.addTag(attrs.getValue("k"), attrs.getValue("v")); } } eleStack.push(qName); }
420344ec-6b54-4d84-9fdd-211aa194d299
3
@SuppressWarnings("unchecked") public static Map<String, Object> parseMapFirstObject(List<String> strings) { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = null; Map<String, Object> result = null; try { jp = factory.createParser(strings.get(0)); result = jp.readValueAs(HashMap.class); } catch (JsonParseException e) { _logger.error("JsonParseException: " + e.getMessage()); } catch (JsonProcessingException e) { _logger.error("JsonProcessingException: " + e.getMessage()); } catch (IOException e) { _logger.error("IOException: " + e.getMessage()); } return result; }
3add0af8-f16b-47c9-9ed7-ae7c44970335
0
public void setBossSpawnLocation(Location bossspawn) { this.bossspawn = bossspawn; }
c38c46b5-e5da-4c70-b234-353497f6f4d9
9
public void execute() throws MojoExecutionException, MojoFailureException { File scriptFile = null; File scriptMetaFile = null; UnityMenuCommands menuCommands = new UnityMenuCommands(new ProcessRunner(getLog()), unity, project.getBasedir().getAbsolutePath()); try { InputStream scriptStream = this.getClass().getClassLoader().getResourceAsStream("IOSBuildScript.cs"); scriptFile = new File(project.getBasedir().getAbsolutePath() + "/Assets/Editor/IOSBuildScript.cs"); scriptMetaFile = new File(project.getBasedir().getAbsolutePath() + "/Assets/Editor/IOSBuildScript.cs.meta"); FileUtils.copyInputStreamToFile(scriptStream, scriptFile); scriptStream.close(); ProcessRunner processRunner = new ProcessRunner(getLog()); menuCommands.syncMonoDevelopProject(); List<String> commandList = new ArrayList<String>(); commandList.add(unity); commandList.add("-projectPath"); commandList.add(project.getBasedir().getAbsolutePath()); commandList.add("-executeMethod"); commandList.add("ca.mestevens.unity.IOSBuildScript.GenerateXcodeProject"); if (scenes != null && !scenes.isEmpty()) { String scenesString = "-Dscenes="; for(String scene : scenes) { scenesString += scene + ","; } scenesString = scenesString.substring(0, scenesString.length() - 1); commandList.add(scenesString); } commandList.add("-DiosProjectTargetDirectory=" + xcodeTarget + "/" + unityProjectName + "-ios"); commandList.add("-batchmode"); commandList.add("-quit"); commandList.add("-logFile"); File targetDirectory = new File(xcodeTarget); if (!targetDirectory.exists()) { FileUtils.forceMkdir(targetDirectory); } processRunner.killProcessWithName("Unity"); int returnValue = processRunner.runProcess(null, commandList.toArray(new String[commandList.size()])); processRunner.checkReturnValue(returnValue); InputStream pomStream = this.getClass().getClassLoader().getResourceAsStream("pom-template-xcode.xml"); String pomString = IOUtils.toString(pomStream); File pomFile = new File(project.getBasedir().getAbsolutePath() + "/target/" + unityProjectName + "-ios/pom.xml"); String pomInfoString = "<groupId>" + project.getGroupId() + "</groupId>"; pomInfoString += "<artifactId>" + unityProjectName + "</artifactId>"; pomInfoString += "<version>" + project.getVersion() + "</version>"; pomInfoString += "<packaging>xcode-application</packaging>"; pomString = pomString.replace("<pomInfo></pomInfo>", pomInfoString); DependencyGatherer dependencyGatherer = new DependencyGatherer(getLog(), project, projectRepos, repoSystem, repoSession); String pomDependenciesString = dependencyGatherer.createXcodePomDependencySection(); pomString = pomString.replace("<pomDependencies></pomDependencies>", pomDependenciesString); String pomRepositoriesString = dependencyGatherer.createPomRepositoriesSection(); pomString = pomString.replace("<pomRepositories></pomRepositories>", pomRepositoriesString); FileUtils.writeStringToFile(pomFile, pomString); processRunner.runProcess(xcodeTarget + "/" + unityProjectName + "-ios", "mvn", "clean", "initialize", "-Dxcode.add.dependencies", "-Dxcode.project.path=" + xcodeTarget + "/Unity-iPhone.xcodeproj"); } catch (Exception ex) { throw new MojoFailureException(ex.getMessage()); } finally { if (scriptFile != null && scriptFile.exists()) { scriptFile.delete(); } if (scriptMetaFile != null && scriptMetaFile.exists()) { scriptMetaFile.delete(); } menuCommands.syncMonoDevelopProject(); } }
4753dfdb-e742-4c01-913b-5e8fcfa9463e
4
static void loadTickerSet(String fileName,ArrayList<String> tickers) { Scanner inFile = null; try { inFile = new Scanner(new File(fileName)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (inFile == null) { System.out.println("invalid file no symbols loaded"); return; } boolean firstLine = true; while (inFile.hasNextLine()) { String ticker = inFile.nextLine(); if (firstLine) { firstLine = false; continue; } String[] getTicker = ticker.split(","); tickers.add(getTicker[0].replaceAll("\"", "")); } }
c846a4a4-5c0d-43f8-baf4-eb6dfcd746e4
9
final private void handleOperator( Operator o ) { int precedence = o.getPrecedence(); int prevPrecedence = -1; if ( this.m_operatorsStack.size() > 0 ) { Token prev = this.m_operatorsStack.peek(); if ( prev instanceof Operator ) { prevPrecedence = ( (Operator) prev ).getPrecedence(); while( prev instanceof Operator && ( (precedence<prevPrecedence) || (o.isLeftAssociative() && precedence <= prevPrecedence ) ) ) { if ( this.m_operatorsStack.size() == 0 ) { break; } addToOutput( this.m_operatorsStack.pop() ); if ( this.m_operatorsStack.size() == 0 ) { break; } prev = this.m_operatorsStack.peek(); if ( prev instanceof Operator ) { prevPrecedence = ( ( Operator ) prev ).getPrecedence(); } } } } this.m_operatorsStack.push( o ); }