text
stringlengths
14
410k
label
int32
0
9
public static Integer idFromUrl(String url) { Pattern idPattern = Pattern.compile("http://myanimelist.net/(\\w+)/(\\d+)/?.*"); Matcher matcher = idPattern.matcher(url); if (matcher.find()) { return Integer.valueOf(matcher.group(2)); } return 0; }
1
public boolean more() throws JSONException { char nextChar = next(); if (nextChar == 0) { return false; } back(); return true; }
1
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double) o).isInfinite() || ((Double) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float) o).isInfinite() || ((Float) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
protected final void handleUpdate(Result result) { this.result = result; if (result == Result.UPDATE_AVAILABLE) { this.registerNewNotifier(); } else { result.handleUpdate(this.plugin.getLogger()); } }
1
public void setOptions(String[] options) throws Exception { String optionString; optionString = Utils.getOption('X', options); if (optionString.length() != 0) { setAttsToEliminatePerIteration(Integer.parseInt(optionString)); } optionString = Utils.getOption('Y', options); if (optionString.length() != 0) { setPercentToEliminatePerIteration(Integer.parseInt(optionString)); } optionString = Utils.getOption('Z', options); if (optionString.length() != 0) { setPercentThreshold(Integer.parseInt(optionString)); } optionString = Utils.getOption('P', options); if (optionString.length() != 0) { setEpsilonParameter((new Double(optionString)).doubleValue()); } optionString = Utils.getOption('T', options); if (optionString.length() != 0) { setToleranceParameter((new Double(optionString)).doubleValue()); } optionString = Utils.getOption('C', options); if (optionString.length() != 0) { setComplexityParameter((new Double(optionString)).doubleValue()); } optionString = Utils.getOption('N', options); if (optionString.length() != 0) { setFilterType(new SelectedTag(Integer.parseInt(optionString), SMO.TAGS_FILTER)); } else { setFilterType(new SelectedTag(SMO.FILTER_NORMALIZE, SMO.TAGS_FILTER)); } Utils.checkForRemainingOptions(options); }
7
public static void delete(String filename) { try { File file = new File(filename); if (file.exists()) { if (file.delete()) { System.out.println(filename + " is deleted!"); } else { System.out.println("Delete operation is failed. " + filename + " cannot be deleted"); } } } catch (Exception e) { e.printStackTrace(); } }
3
private BuilderPattern(Builder builder) { this.title = builder.title; this.auther = builder.auther; this.location = builder.location; this.published = builder.published; this.pageno = builder.pageno; }
0
public static void writeBlocking( WebSocketImpl ws, ByteChannel channel ) throws InterruptedException , IOException { assert ( channel instanceof AbstractSelectableChannel == true ? ( (AbstractSelectableChannel) channel ).isBlocking() : true ); assert ( channel instanceof WrappedByteChannel == true ? ( (WrappedByteChannel) channel ).isBlocking() : true ); ByteBuffer buf = ws.outQueue.take(); while ( buf.hasRemaining() ) channel.write( buf ); }
3
public int updateVariableData(byte[] newData, int offset) { int vertexCount = getVertexCount(); vertexIndexArray = new int[vertexCount]; for (int index = 0; index < vertexIndexArray.length; ++index) { ByteConversions.setUnsignedShortInByteArrayAtPosition(vertexIndexArray[index], newData, offset); offset += 2; } xDisplacementArray = new short[vertexCount]; for (int index = 0; index < xDisplacementArray.length; ++index) { ByteConversions.setShortInByteArrayAtPosition(xDisplacementArray[index], newData, offset); offset += 2; } yDisplacementArray = new short[vertexCount]; for (int index = 0; index < yDisplacementArray.length; ++index) { ByteConversions.setShortInByteArrayAtPosition(yDisplacementArray[index], newData, offset); offset += 2; } zDisplacementArray = new short[vertexCount]; for (int index = 0; index < zDisplacementArray.length; ++index) { ByteConversions.setShortInByteArrayAtPosition(zDisplacementArray[index], newData, offset); offset += 2; } uTextureArray = new short[vertexCount]; for (int index = 0; index < uTextureArray.length; ++index) { ByteConversions.setShortInByteArrayAtPosition(uTextureArray[index], newData, offset); offset += 2; } vTextureArray = new short[vertexCount]; for (int index = 0; index < vTextureArray.length; ++index) { ByteConversions.setShortInByteArrayAtPosition(vTextureArray[index], newData, offset); offset += 2; } return offset; }
6
* @return the XML datetime string corresponding to the given CycL date * @deprecated use DateConverter. */ static public String xmlDatetimeString(final CycList date) throws IOException, CycApiException { try { final CycNaut dateNaut = (CycNaut) CycNaut.convertIfPromising(date); final Date javadate = DateConverter.parseCycDate(dateNaut, TimeZone.getDefault(), false); int cycDatePrecision = DateConverter.getCycDatePrecision(dateNaut); if (cycDatePrecision > DateConverter.DAY_GRANULARITY) { return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(javadate); } else { return new SimpleDateFormat("yyyy-MM-dd").format(javadate); } } catch (Exception e) { return null; } }
2
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Defi)) { return false; } Defi other = (Defi) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
public boolean DownloadFile(String httpUrl,String saveFile){ int bytesum = 0; int byteread = 0; URL url = null; try { url = new URL(httpUrl); } catch (MalformedURLException e1) { System.out.println("URL format error"); // e1.printStackTrace(); return false; } try { URLConnection conn = url.openConnection(); InputStream inStream = conn.getInputStream(); FileOutputStream fs = new FileOutputStream(saveFile); byte[] buffer = new byte[1204]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } fs.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } }
4
public static void createDefprintUnit(Stella_Class renamed_Class) { if (!(KeyValueList.dynamicSlotValue(renamed_Class.dynamicSlots, Stella.SYM_STELLA_PRINT_FORM, null) == null)) { Cons.walkAuxiliaryTree(Cons.list$(Cons.cons(Stella.SYM_STELLA_DEFMETHOD, Cons.cons(Stella.SYM_STELLA_PRINT_OBJECT, Cons.cons(Cons.list$(Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_SELF, Cons.cons(renamed_Class.classType, Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_STREAM, Cons.cons(Stella.SYM_STELLA_NATIVE_OUTPUT_STREAM, Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(Stella.KWD_PUBLICp, Cons.cons(Stella.SYM_STELLA_TRUE, Cons.cons(Stella_Object.copyConsTree(KeyValueList.dynamicSlotValue(renamed_Class.dynamicSlots, Stella.SYM_STELLA_PRINT_FORM, null)), Cons.cons(Stella.NIL, Stella.NIL))))))))); { boolean testValue000 = false; testValue000 = ((Keyword)(Stella.$TRANSLATOROUTPUTLANGUAGE$.get())) == Stella.KWD_CPP; if (testValue000) { { boolean foundP000 = false; { Stella_Class renamed_Super = null; Cons iter000 = renamed_Class.classAllSuperClasses; loop000 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { renamed_Super = ((Stella_Class)(iter000.value)); if (KeyValueList.dynamicSlotValue(renamed_Super.dynamicSlots, Stella.SYM_STELLA_PRINT_FORM, null) != null) { foundP000 = true; break loop000; } } } testValue000 = foundP000; } testValue000 = !testValue000; } if (testValue000) { Symbol.pushVariableBinding(Stella.SYM_STELLA_SELF, renamed_Class.classType); Symbol.pushVariableBinding(Stella.SYM_STELLA_STREAM, Stella.SGT_STELLA_NATIVE_OUTPUT_STREAM); { TranslationUnit self000 = TranslationUnit.newTranslationUnit(); self000.theObject = renamed_Class; self000.category = Stella.SYM_STELLA_PRINT_METHOD; self000.tuHomeModule = ((Module)(Stella.$MODULE$.get())); self000.codeRegister = Stella_Object.walkATree(Cons.list$(Cons.cons(Stella.SYM_STELLA_IF, Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_NULLp, Cons.cons(Stella.SYM_STELLA_SELF, Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_PRINT_NATIVE_STREAM, Cons.cons(Stella.SYM_STELLA_STREAM, Cons.cons(StringWrapper.wrapString("!NULL!"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_PRINT_OBJECT, Cons.cons(Stella.SYM_STELLA_SELF, Cons.cons(Stella.SYM_STELLA_STREAM, Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Stella.NIL, Stella.NIL)))))), new Object[1]); self000.auxiliaryP = true; ((List)(Stella.$TRANSLATIONUNITS$.get())).push(self000); } Stella.popVariableBinding(); Stella.popVariableBinding(); } } { boolean testValue001 = false; testValue001 = ((Keyword)(Stella.$TRANSLATOROUTPUTLANGUAGE$.get())) == Stella.KWD_JAVA; if (testValue001) { { boolean foundP001 = false; { Stella_Class renamed_Super = null; Cons iter001 = renamed_Class.classAllSuperClasses; loop001 : for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) { renamed_Super = ((Stella_Class)(iter001.value)); if (KeyValueList.dynamicSlotValue(renamed_Super.dynamicSlots, Stella.SYM_STELLA_PRINT_FORM, null) != null) { foundP001 = true; break loop001; } } } testValue001 = foundP001; } testValue001 = !testValue001; } if (testValue001) { { Object old$Methodbeingwalked$000 = Stella.$METHODBEINGWALKED$.get(); try { Native.setSpecial(Stella.$METHODBEINGWALKED$, MethodSlot.newMethodSlot()); ((MethodSlot)(Stella.$METHODBEINGWALKED$.get())).methodReturnTypeSpecifiers = List.list(Cons.cons(Stella.SGT_STELLA_STRING, Stella.NIL)); Symbol.pushVariableBinding(Stella.SYM_STELLA_SELF, renamed_Class.classType); { TranslationUnit self002 = TranslationUnit.newTranslationUnit(); self002.theObject = renamed_Class; self002.category = Stella.SYM_STELLA_PRINT_METHOD; self002.tuHomeModule = ((Module)(Stella.$MODULE$.get())); self002.codeRegister = Stella_Object.walkATree(Cons.list$(Cons.cons(Stella.SYM_STELLA_IF, Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_NULLp, Cons.cons(Stella.SYM_STELLA_SELF, Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_RETURN, Cons.cons(StringWrapper.wrapString("!NULL!"), Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_RETURN, Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_VERBATIM, Cons.cons(Stella.KWD_JAVA, Cons.cons(StringWrapper.wrapString("#$(STELLAROOT).javalib.Native.stringify_via_print(self)"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(Stella.NIL, Stella.NIL)))))), new Object[1]); self002.auxiliaryP = true; ((List)(Stella.$TRANSLATIONUNITS$.get())).push(self002); } Stella.popVariableBinding(); } finally { Stella.$METHODBEINGWALKED$.set(old$Methodbeingwalked$000); } } } } } }
9
@Override protected String doPostWork(Params params) { String action = params.getValue("action"); if(action == null) { return WebUtil.error("unknown action!"); } if("list".equals(action)) { Templates templates = Global.getInstance().getTemplates(); return templates.listTemplatesJSON(); } String name = params.getValue("name"); if(name == null) { return WebUtil.error("unknown file name!"); } Template template = Global.getInstance().getTemplate(name); if(template == null) { return WebUtil.error("can not find template:" + name + "!"); } if("content".equals(action)) { params.setContentType("application/xml"); return template.fetchXMLContent(); } else if("delete".equals(action)) {//delete tree node String nodeName = params.getValue("node"); return template.deleteNode(nodeName); } else if("add".equals(action)) {//add tree node String nodeName = params.getValue("node"); return template.addNode(nodeName); } else if("rename".equals(action)) {//rename tree node name String nodeName = params.getValue("node"); return template.renameNode(nodeName); } else if("move".equals(action)) {//move tree node name String nodeName = params.getValue("node"); return template.moveNode(nodeName); } return null; }
9
void split(String filename, long cSize, File sf) throws FileNotFoundException, IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(sf)); // get the file length long fileSize = sf.length(); // loop for each full chunk int subfile; for (subfile = 1; subfile < fileSize / cSize; subfile++) { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename + "." + subfile)); for (int currentByte = 0; currentByte < cSize; currentByte++) { out.write(in.read()); } out.close(); } // loop for the last chunk (which may be smaller than the chunk size) if (fileSize != cSize * (subfile - 1)) { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename + "." + subfile)); int b; while ((b = in.read()) != -1) out.write(b); out.close(); } in.close(); }
4
public int readBit() throws IOException { int retVal; // 当前mBytePos指向字节已经读完 if(mBitPos == 8){ if (isEnd && mBytePos == mEndBytePos){ // 到达数据流的末端 throw new EOFException(); } // 缓冲区的数据完全读取完了 if(mBytePos == mByteBuf.length-1){ // 载入下一段数据到缓冲区中 int byteRead = mIs.read(mByteBuf); if (byteRead != mByteBuf.length){ if (byteRead == -1){ throw new EOFException(); } mEndBytePos = byteRead-1; isEnd = true; } mBitPos = mBytePos = 0; }else{ // 指向缓冲区中下一字节 ++mBytePos; mBitPos = 0; } // 得到一位 return readBit(); }else{ retVal = mByteBuf[mBytePos] >>> (7-mBitPos); ++mBitPos; return retVal & 0x1; } }
6
@Override public void action() { if(agente.getPasso() == 3){ if(agente.getQuantidadeDeAgentesVendedores() > 0){ System.out.println("Passo 3 AI"); ACLMessage mensagem = new ACLMessage(ACLMessage.CFP); mensagem.setProtocol(FIPANames.InteractionProtocol.FIPA_CONTRACT_NET); mensagem.setReplyByDate(new Date(System.currentTimeMillis() + 10000)); try { mensagem.setContentObject(agente.getListaDeCupons()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Iterator it = agente.getAgentesVendedores(); while(it.hasNext()){ AID tmp = (AID) it.next(); System.out.println("Vou enviar mensagem ao: " + tmp.getLocalName()); mensagem.addReceiver( tmp); } agente.send(mensagem); // Envia CFP para todos os agentes que fazem aquele servico done = true; } } }
4
public String toString(){ String result = ""; for(int i=0; i<=height+1; i++){ for(int j=0; j<=width+1; j++){ if (area[i][j]){ result+=1 ; }else{ result+=0; } } result+='\n'; } return result; }
3
private double testDoublyLinkedListDeletions(int inserts) { System.out.println("Testing DoublyLinkedList with " + inserts + " deletions"); long[] times = new long[20]; long startTime; long endTime; for (int i = 0; i < 20; i++) { doublyLinkedList = new DoublyLinkedList(); for (int j = 0; j < inserts; j++) { doublyLinkedList.insert(null); } startTime = System.currentTimeMillis(); for (int j = 0; j < inserts; j++) { doublyLinkedList.delete(); } endTime = System.currentTimeMillis(); times[i] = endTime - startTime; } double returnValue = 0; for (int i = 0; i < times.length; i++) { returnValue += times[i]; } return returnValue / 20.0; }
4
public void create(Software software) throws PreexistingEntityException, RollbackFailureException, Exception { if (software.getComputadoraCollection() == null) { software.setComputadoraCollection(new ArrayList<Computadora>()); } EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Collection<Computadora> attachedComputadoraCollection = new ArrayList<Computadora>(); for (Computadora computadoraCollectionComputadoraToAttach : software.getComputadoraCollection()) { computadoraCollectionComputadoraToAttach = em.getReference(computadoraCollectionComputadoraToAttach.getClass(), computadoraCollectionComputadoraToAttach.getIdComputadora()); attachedComputadoraCollection.add(computadoraCollectionComputadoraToAttach); } software.setComputadoraCollection(attachedComputadoraCollection); em.persist(software); for (Computadora computadoraCollectionComputadora : software.getComputadoraCollection()) { computadoraCollectionComputadora.getSoftwareCollection().add(software); computadoraCollectionComputadora = em.merge(computadoraCollectionComputadora); } em.getTransaction().commit(); } catch (Exception ex) { try { em.getTransaction().rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } if (findSoftware(software.getIdSoftware()) != null) { throw new PreexistingEntityException("Software " + software + " already exists.", ex); } throw ex; } finally { if (em != null) { em.close(); } } }
7
public List<Archivio> archiviCreatiIl(String data) { List<Archivio> lista = new ArrayList<>(); if (super.getDataCreazione().equals(data)) lista.addAll(this.elementi); for(Archivio elemento: this.elementi){ if (elemento.getClass() == Cartella.class && elemento.getDataCreazione().equals(data)){ lista.add(elemento); } } return lista; }
4
public boolean globtype(char k, KeyEvent ev) { if ((k == 27) && (this.menu_current_parent_resource != null)) { this.menu_current_parent_resource = null; menu_current_layer_elements_offset = 0; updlayout(); return (true); } else if ((k == 'N') && (layout[gsz.x - 2][gsz.y - 1] == menu_next_tab)) { use(menu_next_tab); return (true); } Resource r = hotmap.get(Character.toUpperCase(k)); if (r != null) { use(r); return (true); } return (false); }
5
@Test public void testLpaLimits() { Metabolism m = new Metabolism(); try { m.setLpa(0.); } catch(IncoherentLpaException e) { fail("An IncoherentLpaException has been thrown."); } try { m.setLpa(-1.); fail("An IncoherentLpaException should have been thrown."); } catch(IncoherentLpaException e) {} try { m.setLpa(3.1); fail("An IncoherentLpaException should have been thrown."); } catch(IncoherentLpaException e) {} try { m.setLpa(1.); } catch(IncoherentLpaException e) { fail("An IncoherentLpaException has been thrown."); } }
4
public void processEvent(Event event) { // the last directory response if (event.getType() == Event.COMPLETION_EVENT) { return; } if (event.getType() != Event.OMM_ITEM_EVENT) { System.out.println(_instanceName + " Received an unsupported Event type"); return; } OMMItemEvent itemEvent = (OMMItemEvent)event; OMMMsg msg = itemEvent.getMsg(); if (msg.getDataType() != OMMTypes.MAP) { System.out.println(_instanceName + " Expected MAP"); return; } OMMMap map = (OMMMap)msg.getPayload(); for (Iterator<?> iter = map.iterator(); iter.hasNext();) { OMMMapEntry mapEntry = (OMMMapEntry)iter.next(); byte action = mapEntry.getAction(); // each mapEntry will be a separate service String serviceName = mapEntry.getKey().toString(); if (action == OMMMapEntry.Action.DELETE) { System.out.println(_instanceName + " Received DELETE for " + serviceName); OMMState closeStatus = _parent._pool.acquireState(); closeStatus.setStreamState(OMMState.Stream.CLOSED); closeStatus.setDataState(OMMState.Data.NO_CHANGE); closeStatus.setCode(OMMState.Code.NONE); closeStatus.setText("Service has been closed."); _itemGroupManager.applyStatus(serviceName, closeStatus); } else { if (mapEntry.getDataType() != OMMTypes.FILTER_LIST) { System.out.println(_instanceName + " Expected FILTER_LIST"); continue; } decodeMapEntry(serviceName, mapEntry); } } }
7
@Override public Complex getPixel(Complex pixel) { /* LEFT */ if(parser[0].foundC()) { parser[0].setCvalue(pixel); } /* RIGHT */ if(parser[1].foundC()) { parser[1].setCvalue(pixel); } int result = expr[0].getValue().compare(expr[1].getValue()); if(result == -1) { // left > right if(parser2[0].foundC()) { parser2[0].setCvalue(pixel); } return expr2[0].getValue(); } else if(result == 1) { // right > left if(parser2[1].foundC()) { parser2[1].setCvalue(pixel); } return expr2[1].getValue(); } else if (result == 0) { //left == right if(parser2[2].foundC()) { parser2[2].setCvalue(pixel); } return expr2[2].getValue(); } return pixel; }
8
private Boolean fieldCheck(){ Boolean fields_pass_check; // If any of the conditions are true, popup a menu if ( course_name_field.getText().equalsIgnoreCase("") // course name empty || course_id_field.getText().equalsIgnoreCase("") //Course id empty || instructor_field.getText().equalsIgnoreCase("") // instructor id empty || ta_list.getText().equalsIgnoreCase("") //ta field empty || course_start_formatfield.getText().equalsIgnoreCase("") //start field empty || course_end_formatfield.getText().equalsIgnoreCase("") //end field empty || stud_list_file_location_field.getText().equalsIgnoreCase("") // file location field empty ){ JOptionPane.showMessageDialog(this, "One of your fields is not filled in, please check all your fields and resubmit!"); fields_pass_check = false; } else fields_pass_check = true; return fields_pass_check; }
7
public static boolean fuzzyEquals (double a, double b) { // value based on this table: // http://en.wikipedia.org/wiki/Machine_epsilon#Values_for_standard_hardware_floating_point_arithmetics final double EPSILON = 5.96e-08; if (Double.isNaN(a) && Double.isNaN(b) || Double.isInfinite(a) && Double.isInfinite(b)) { return true; } else { return Math.abs(a / b - 1) < EPSILON; } }
4
public static void print(UndirectedGraphNode node) { if (null == node) return; List<UndirectedGraphNode> nodes = new ArrayList<UndirectedGraphNode>(); int index = 0; if (null != node)nodes.add(node); while (index != nodes.size()) { UndirectedGraphNode n = nodes.get(index); System.out.print(n.label + "("); for (UndirectedGraphNode neighbor : n.neighbors) { if (!(nodes.contains(neighbor))) { nodes.add(neighbor); } System.out.print(neighbor.label + ","); } System.out.println(")"); index = index + 1; } }
5
private boolean isOperator(String ch){ String operators = "*/%+-"; if (operators.indexOf(ch) != -1) return true; else return false; }
1
public boolean hasPrevious() { if(previousShort != null)//Already found. This is prevention for possible inappropriate call. return true; while(strings.hasNext()){ previousShort = strings.previous(); index--; if(previousShort.length() <= maxLen) previousIndex = index; return true; } previousShort = null;//Not found. return false; }
3
@Override public void openIF(boolean safeMode) throws RoombaIFException { serialPort = new SerialPort(portName); if (isOpened) { throw new RoombaIFException(RoombaIFException.TYPE_ALREADY_OPEN); } try { serialPort.openPort(); serialPort.setParams(BAUDRATE, DATABITS, STOPBITS, PARITY); int mask = SerialPort.MASK_RXCHAR; serialPort.setEventsMask(mask); serialPort.addEventListener(new SerialPortReader()); serialPort.writeByte(START_COMMAND); //passive mode try { Thread.sleep(100); } catch (InterruptedException ex) { //Don't do anything. Nothing sends this thread an interrupt. } if (safeMode) { serialPort.writeByte(SAFE_COMMAND); //safe mode } else { serialPort.writeByte(FULL_COMMAND); //full mode } try { Thread.sleep(100); } catch (InterruptedException ex) { //Don't do anything. Nothing sends this thred an interrupt. } byte[] c = new byte[sensorPacketsRequested.length + 2]; c[0] = STREAM_COMMAND; c[1] = (byte) sensorPacketsRequested.length; for (int i = 0; i < sensorPacketsRequested.length; i++) { c[i + 2] = sensorPacketsRequested[i].id(); } serialPort.writeBytes(c); } catch (SerialPortException ex) { try { if (serialPort.isOpened()) { serialPort.closePort(); } } catch (SerialPortException ex2) { //Don't do anything. We are already going to throw an exception. } throw new RoombaIFException(RoombaIFException.TYPE_SERIAL + ": " + ex.getMessage()); } watchdogTimer = new Thread(new WatchdogTimer()); watchdogTimer.start(); isOpened = true; }
8
public static Cons cppTranslateMethodCall(Cons tree, boolean referencedP) { { Symbol methodname = ((Symbol)(tree.rest.value)); Surrogate owner = ((Surrogate)(tree.value)); Cons arguments = tree.rest.rest; if ((methodname == Stella.SYM_STELLA_DEFINEDp) || (methodname == Stella.SYM_STELLA_NULLp)) { return (Surrogate.cppTranslateDefinedPMethodCall(owner, arguments.value, methodname == Stella.SYM_STELLA_NULLp)); } else if ((methodname == Stella.SYM_STELLA_NTH) || (methodname == Stella.SYM_STELLA_NTH_SETTER)) { return (Symbol.cppTranslateNthMethodCall(methodname, owner, arguments)); } else if ((methodname == Stella.SYM_STELLA_AREF) || (methodname == Stella.SYM_STELLA_AREF_SETTER)) { return (Symbol.cppTranslateArefMethodCall(methodname, owner, arguments)); } else { if ((owner == Stella.SGT_STELLA_ARGUMENT_LIST) || (owner == Stella.SGT_STELLA_ARGUMENT_LIST_ITERATOR)) { return (Symbol.cppTranslateArgumentListTree(methodname, owner, arguments.value)); } } return (Symbol.cppTranslateNormalMethodCall(methodname, owner, arguments, referencedP)); } }
8
public boolean isSolved() { boolean solved = true; for (int x=0; x < size*size && solved; x++) { for (int y=0; y < size*size && solved; y++) { solved = (!sudokuGrid[x][y].equals(new String("*"))); } } return solved; }
4
private Expression equal( List<Expression> args, String caller ) { if ( args.size() != 2 ) { System.err.println("= expected 2 arguments and got " + args.size() ); System.exit(1); } DeferredSubst df = DeferredSubst.getInstance(); // if the values are the same if ( args.get(0).show( df, caller ).compareTo( args.get(1).show(df, caller)) == 0 ) { return new Value("#t"); } // values weren't the same return new Value("#f"); }
2
public int setCurrency(int amount) { ownCurrency = amount; int overflow = ownCurrency - 3904; int large = (int)Math.floor(ownCurrency / largeCurrency); if (large > 0) inventory.setItem(2, new ItemStack(largeCurrencyItem.getType(), large)); else { inventory.clear(2); } int medium = (int)Math.floor((ownCurrency - largeCurrency * large) / mediumCurrency); if (medium > 0) inventory.setItem(1, new ItemStack(mediumCurrencyItem.getType(), medium)); else { inventory.clear(1); } int small = (int)Math.floor(ownCurrency - largeCurrency * large - mediumCurrency * medium) / smallCurrency; if (small > 0) inventory.setItem(0, new ItemStack(smallCurrencyItem.getType(), small)); else { inventory.clear(0); } return overflow; }
3
public void saveToFile(File file) { String suffix = file.getAbsolutePath().substring( file.getAbsolutePath().lastIndexOf(".")+1); boolean saved = false; if (suffix.equalsIgnoreCase("fasta") || suffix.equalsIgnoreCase("fas") ) { FastaParser parser = new FastaParser(sunfishParent); parser.writeData(file, currentSG); setHasUnsavedChanges(false); saved = true; } if (suffix.equalsIgnoreCase("phy") || suffix.equalsIgnoreCase("ph") || suffix.equalsIgnoreCase("phylip")) { PhyParser parser = new PhyParser(sunfishParent); parser.writeData(file, currentSG); setHasUnsavedChanges(false); saved = true; } // if (suffix.equalsIgnoreCase("nex") || suffix.equalsIgnoreCase("nexus")) { // NexusParser parser = new NexusParser(sunfishParent); // parser.writeData(file, currentSG); // setHasUnsavedChanges(false); // saved = true; // } if (suffix.equalsIgnoreCase("im") || suffix.equalsIgnoreCase("ima")) { IMAParser parser = new IMAParser(sunfishParent); parser.writeData(file, currentSG); setHasUnsavedChanges(false); saved = true; } if (saved) { sunfishParent.getLogger().info("Saved SG file to : " + file.getAbsolutePath()); sourceFile = file; SunFishFrame.getSunFishFrame().getDisplayPane().setTitleForDisplay(this, file.getName()); SunFishFrame.getSunFishFrame().setInfoLabelText("Saved file " + file.getName()); } else sunfishParent.getLogger().warning("Error, did not save SG file to : " + file.getAbsolutePath()); }
8
private static void handleError(String message, Throwable e) { MessageDialog.getInstance().showError(message); LOGGER.error(message, e); }
0
private void preencherCampos() { ArrayList<String> telefones; ArrayList<Premiacao> premiacoes; jTextFieldAltura.setText(Double.toString(piloto.getAltura())); jTextFieldBairro.setText(piloto.getEndereco().getBairro()); jTextFieldCategoriaPeso.setText(Double.toString(piloto.getPeso())); jTextFieldCep.setText(piloto.getEndereco().getCep()); jTextFieldCidade.setText(piloto.getEndereco().getCidade()); jTextFieldComplemento.setText(piloto.getEndereco().getComplemento()); jTextFieldCpf.setText(piloto.getCpf()); if (piloto.getDataNascimento() == null) { jTextFieldDataNascimento.setText(null); } else { jTextFieldDataNascimento.setText(dateFormat.format(piloto.getDataNascimento())); } //jTextFieldEnvergadura.setText(Double.toString(piloto.getEnvergadura())); jComboBoxEstado.setSelectedItem(piloto.getEndereco().getEstado()); jTextFieldLogradouro.setText(piloto.getEndereco().getLogradouro()); jTextFieldNome.setText(piloto.getNome()); jTextFieldNomeMae.setText(piloto.getNomeMae()); jTextFieldNomePai.setText(piloto.getNomePai()); jTextFieldNumero.setText(piloto.getEndereco().getNumero().toString()); jTextFieldPais.setText(piloto.getEndereco().getPais()); jTextFieldPeso.setText(Double.toString(piloto.getPeso())); jTextFieldRg.setText(piloto.getRg()); //jTextFieldTotalDerrotas.setText(Integer.toString(piloto.getTotalDerrotas())); //jTextFieldTotalDesistencias.setText(Integer.toString(piloto.getTotalDesistencias())); //jTextFieldTotalEmpates.setText(Integer.toString(piloto.getTotalEmpates())); //jTextFieldTotalLutas.setText(Integer.toString(piloto.getTotalLutas())); //jTextFieldTotalNocaute.setText(Integer.toString(piloto.getTotalVitoriasNocaute())); //jTextFieldTotalVitorias.setText(Integer.toString(piloto.getTotalVitorias())); telefonesListModel.clear(); telefones = piloto.getTelefones(); for (String t : telefones) { telefonesListModel.addElement(t); } premiacaoListModel.clear(); premiacoes = piloto.getPremiacoes(); for (Premiacao p : premiacoes) { premiacaoListModel.addElement(p); } switch (piloto.getSexo()) { case SEXO_MASCULINO_VALOR: jComboBoxSexo.setSelectedIndex(SEXO_MASCULINO_INDICE); break; case SEXO_FEMININO_VALOR: jComboBoxSexo.setSelectedIndex(SEXO_FEMININO_INDICE); break; } switch (piloto.getCategoria()) { case CATEGORIA_AMADOR_VALOR: jComboBoxCategoria.setSelectedIndex(CATEGORIA_AMADOR_INDICE); break; case CATEGORIA_PROFISSIONAL_VALOR: jComboBoxCategoria.setSelectedIndex(CATEGORIA_PROFISSIONAL_INDICE); break; } this.atualizarCategoriaPeso(); }
7
static boolean player1Move(int x, int y) { if (getGame().m_board.anyValid(m_player1Colour)) { if (getGame().move(x, y, m_player1Colour)) { if (m_p1colour == Piece.OthelloPieceColour.WHITE) { m_gridButtons[x][y].setIcon(m_whitePiece); } else { m_gridButtons[x][y].setIcon(m_blackPiece); } OthelloPiece piecesToSwap[][] = getGame().m_board.setPieces(); player1DoSwapPieces(piecesToSwap); getGame().setPlayer1Score(1); getGame().m_board.clearPieces(); System.out.print("player 1 score: " + getGame().getPlayer1Score()); System.out.println(" player 2 score: " + getGame().getPlayer2Score()); return true;// made a valid move } return false;// invalid move } return true; // no possible move }
3
public void run() { while(true) { try{ long t = System.currentTimeMillis(); //check if products are still up to date and put the new ppc id in ppc otherwise if(!vn.validateProducts(init.getPPC())) { barPanel.initBarProducts(); System.out.println("Er is een product geupdate"); } //Set the last update date to now dBUpdate.runUpdate(String.format("UPDATE clients SET last_client_update = NOW() WHERE client_id = %d",init.getCurClient().getID())); dBUpdate.commit(); System.out.println("Tijd nodig: " + Long.toString(System.currentTimeMillis()-t)); Thread.sleep(500); } catch(InterruptedException e){ e.printStackTrace(); } } }
3
public void received(Connection c, Object o) { if(o instanceof Packet) { Packet p = ((Packet)o); p.decompressData(); // BlockyMain.console("Received packet "+p.name); if(p.name.equals("Ping+infos response")) { try { long ping = System.currentTimeMillis()-this.pingSentAt; ByteArrayInputStream input = new ByteArrayInputStream(p.data); DataInputStream in = new DataInputStream(input); int nbrPlayers = in.readInt(); int maxPlayers = in.readInt(); String serverName = in.readUTF(); long serverWorldTime = in.readLong(); in.close(); input.close(); System.out.println("Ping request on server: "+serverName); System.out.println("==================================="); System.out.println("Number of connected players: "+nbrPlayers); System.out.println("Max players: "+maxPlayers); System.out.println("Ping: "+ping); System.out.println("WorldTime: "+serverWorldTime); System.out.println("==================================="); if(pingRequest) c.close(); pingSentAt = System.currentTimeMillis(); } catch(Exception e) { e.printStackTrace(); } } else { if(p.name.equals("AuthPacket")) { NetworkCommons.sendPacketTo(createAuthPacket(pingRequest ? ConnectionType.INFOS : ConnectionType.GAME), false, c); seemsConnected = true; } else { packetHandler.handlePacket(p, c); } } } }
6
@Test public void testSignedIntegerCompare() throws Exception { int[] testNumbers = { Integer.MIN_VALUE, -1000, 0, 1000, Integer.MAX_VALUE}; for (int n1 : testNumbers) { byte[] n1Bytes = toSortableBytes(n1); for (int n2 : testNumbers) { byte[] n2Bytes = toSortableBytes(n2); int cmp = Bytes.compareTo(n1Bytes, n2Bytes); if (cmp == 0) { if (n1 != n2) { System.out.println(n1 + " = " + n2); assertTrue(n1 == n2); } } else if (cmp < 0) { if (!(n1 < n2)) { System.out.println(n1 + " < " + n2); assertTrue(n1 < n2); } } else if (cmp > 0) { if (!(n1 > n2)) { System.out.println(n1 + " > " + n2); assertTrue(n1 > n2); } } } } }
8
public static Ime_Velicina_Adresa OBRADI_izravni_deklarator(int trenutacnaLabela){ String linija = mParser.ParsirajNovuLiniju(); // ucitaj IDN UniformniZnak uz_idn = UniformniZnak.SigurnoStvaranje(linija); linija = mParser.DohvatiProviriVrijednost(); UniformniZnak uz_1 = UniformniZnak.SigurnoStvaranje(linija); if (uz_1.mNaziv.equals("L_UGL_ZAGRADA")){ // <<<< deklariranje nizova >>>> linija = mParser.ParsirajNovuLiniju(); // ucitaj L_UGL_ZAGRADA linija = mParser.ParsirajNovuLiniju(); // ucitaj BROJ UniformniZnak uz_broj = UniformniZnak.SigurnoStvaranje(linija); int broj = Integer.parseInt(uz_broj.mLeksickaJedinka); linija = mParser.ParsirajNovuLiniju(); // ucitaj D_UGL_ZAGRADA // neznamo dali ce biti pridruzena vrijednost pri deklaraciji pa inicijaliziramo cijelo polje na nulu if (NaredbenaStrukturaPrograma.mStog == null){ // u globalnom smo djelokrugu for (int i = 0; i < broj; ++i){ mIspisivac.DodajGlobalnuVarijablu("TEMP_" + (trenutacnaLabela + i), "DW %D 0"); } mIspisivac.DodajPreMainKod("MOVE TEMP_" + (trenutacnaLabela + broj - 1) + ", R0", "inicijalizacija polja: spremanje adrese pocetnog clana"); mIspisivac.DodajPreMainKod("PUSH R0"); Ime_Velicina_Adresa vrati = new Ime_Velicina_Adresa(); vrati.mIme = uz_idn.mLeksickaJedinka; vrati.mAdresa = true; vrati.mVelicina = 4; NaredbenaStrukturaPrograma.mGlobalniDjelokrug.add(vrati); return vrati; }else{ // u lokalnom smo djelokrugu mIspisivac.DodajKod("MOVE %D 0, R0", "inicijaliziraj polje na nulu"); for (int i = 0; i < broj; ++i){ mIspisivac.DodajKod("PUSH R0"); Ime_Velicina_Adresa novi = new Ime_Velicina_Adresa(); novi.mIme = null; novi.mAdresa = false; novi.mVelicina = 4; NaredbenaStrukturaPrograma.mStog.add(novi); } mIspisivac.DodajKod("PUSH R7", "inicijalizacija polja: dohvati adr zadnjeg clana na vrhu stoga (korak 1)"); mIspisivac.DodajKod("POP R0", "inicijalizacija polja: dohvati adr zadnjeg clana na vrhu stoga (korak 2)"); mIspisivac.DodajKod("ADD R0, 4, R0", "inicijalizacija polja: dohvati adr zadnjeg clana na vrhu stoga (korak 3)"); mIspisivac.DodajKod("ADD R0, " + 4*broj + ", R0", "inicijalizacija polja: dohvati adr prvog clana"); mIspisivac.DodajKod("PUSH R0", "inicijalizacija polja: stavi je na stog"); Ime_Velicina_Adresa vrati = new Ime_Velicina_Adresa(); vrati.mIme = uz_idn.mLeksickaJedinka; vrati.mAdresa = true; vrati.mVelicina = 4; NaredbenaStrukturaPrograma.mStog.add(vrati); return vrati; } } else if (uz_1.mNaziv.equals("L_ZAGRADA")){ // <<<<< deklaracije funkcija >>>>> linija = mParser.ParsirajNovuLiniju(); // ucitaj L_ZAGRADA linija = mParser.ParsirajNovuLiniju(); if (linija.equals("<lista_parametara>")){ // -------- funkcija sa parametrima -------- OBRADI_lista_parametara(); linija = mParser.ParsirajNovuLiniju(); // ucitaj D_ZAGRADA } else{ // --------- funkcija bez parametara ---------- linija = mParser.ParsirajNovuLiniju(); // ucitaj D_ZAGRADA } if (NaredbenaStrukturaPrograma.mStog == null){ // u globalnom smo djelokrugu mIspisivac.DodajPreMainKod("MOVE F_" + uz_idn.mLeksickaJedinka.toUpperCase() + ", R0", "deklaracija funkcije " + uz_idn.mLeksickaJedinka); mIspisivac.DodajPreMainKod("PUSH R0"); Ime_Velicina_Adresa novi = new Ime_Velicina_Adresa(); novi.mIme = uz_idn.mLeksickaJedinka; novi.mAdresa = true; novi.mVelicina = 4; NaredbenaStrukturaPrograma.mGlobalniDjelokrug.add(novi); return novi; }else{ // u lokalnom smo djelokrugu mIspisivac.DodajKod("MOVE F_" + uz_idn.mLeksickaJedinka.toUpperCase() + ", R0", "deklaracija funkcije " + uz_idn.mLeksickaJedinka); mIspisivac.DodajKod("PUSH R0"); Ime_Velicina_Adresa novi = new Ime_Velicina_Adresa(); novi.mIme = uz_idn.mLeksickaJedinka; novi.mAdresa = true; novi.mVelicina = 4; NaredbenaStrukturaPrograma.mStog.add(novi); return novi; } } else{ // <<<<<generiranje varijabli cjelobrojnog tipa>>>>> if (NaredbenaStrukturaPrograma.mStog != null){ // jesmo li u globalnom djelokrugu ili u funkciji mIspisivac.DodajKod("MOVE %D 0, R0", "izravni deklarator cijelobrojne varijable: postavi na nulu"); mIspisivac.DodajKod("PUSH R0"); Ime_Velicina_Adresa vrati = new Ime_Velicina_Adresa(); vrati.mIme = uz_idn.mLeksickaJedinka; vrati.mAdresa = false; vrati.mVelicina = 4; NaredbenaStrukturaPrograma.mStog.add(vrati); return vrati; }else{ mIspisivac.DodajPreMainKod("MOVE %D 0, R0", "izravni deklarator cijelobrojne varijable: postavi na nulu"); mIspisivac.DodajPreMainKod("PUSH R0"); Ime_Velicina_Adresa vrati = new Ime_Velicina_Adresa(); vrati.mIme = uz_idn.mLeksickaJedinka; vrati.mAdresa = false; vrati.mVelicina = 4; NaredbenaStrukturaPrograma.mGlobalniDjelokrug.add(vrati); return vrati; } } }
8
protected void consumeMethodHeader() { // MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims ThrowsClauseopt // AnnotationMethodHeader ::= AnnotationMethodHeaderName FormalParameterListopt MethodHeaderRightParen MethodHeaderExtendedDims AnnotationMethodHeaderDefaultValueopt // RecoveryMethodHeader ::= RecoveryMethodHeaderName FormalParameterListopt MethodHeaderRightParen MethodHeaderExtendedDims AnnotationMethodHeaderDefaultValueopt // RecoveryMethodHeader ::= RecoveryMethodHeaderName FormalParameterListopt MethodHeaderRightParen MethodHeaderExtendedDims MethodHeaderThrowsClause // retrieve end position of method declarator AbstractMethodDeclaration method = (AbstractMethodDeclaration)this.astStack[this.astPtr]; if (this.currentToken == TokenNameLBRACE){ method.bodyStart = this.scanner.currentPosition; } else if (currentToken != TokenNameSEMICOLON) { // insert semicolon currentToken = TokenNameSEMICOLON; scanner.pushBack(); } // recovery if (this.currentElement != null){ // if(method.isAnnotationMethod()) { // method.modifiers |= AccSemicolonBody; // method.declarationSourceEnd = this.scanner.currentPosition-1; // method.bodyEnd = this.scanner.currentPosition-1; // this.currentElement = this.currentElement.parent; // } else if (this.currentToken == TokenNameSEMICOLON /*&& !method.isAnnotationMethod()*/){ method.modifiers |= ExtraCompilerModifiers.AccSemicolonBody; method.declarationSourceEnd = this.scanner.currentPosition-1; method.bodyEnd = this.scanner.currentPosition-1; // if (this.currentElement.parseTree() == method && this.currentElement.parent != null) { // this.currentElement = this.currentElement.parent; // } } else if(this.currentToken == TokenNameLBRACE) { if (this.currentElement instanceof RecoveredMethod && ((RecoveredMethod)this.currentElement).methodDeclaration != method) { this.ignoreNextOpeningBrace = true; this.currentElement.bracketBalance++; } } this.restartRecovery = true; // used to avoid branching back into the regular automaton } }
7
public void setUserData(String userData) { this.userData = userData; }
0
public void testStringSort() throws IOException, ParseException { r = newRandom(); ScoreDoc[] result = null; IndexSearcher searcher = getFullStrings(); sort.setSort( new SortField("string", SortField.STRING), new SortField("string2", SortField.STRING, true), SortField.FIELD_DOC ); result = searcher.search(new MatchAllDocsQuery(), null, 500, sort).scoreDocs; StringBuilder buff = new StringBuilder(); int n = result.length; String last = null; String lastSub = null; int lastDocId = 0; boolean fail = false; for (int x = 0; x < n; ++x) { Document doc2 = searcher.doc(result[x].doc); String[] v = doc2.getValues("tracer"); String[] v2 = doc2.getValues("tracer2"); for (int j = 0; j < v.length; ++j) { if (last != null) { int cmp = v[j].compareTo(last); if (!(cmp >= 0)) { // ensure first field is in order fail = true; System.out.println("fail:" + v[j] + " < " + last); } if (cmp == 0) { // ensure second field is in reverse order cmp = v2[j].compareTo(lastSub); if (cmp > 0) { fail = true; System.out.println("rev field fail:" + v2[j] + " > " + lastSub); } else if(cmp == 0) { // ensure docid is in order if (result[x].doc < lastDocId) { fail = true; System.out.println("doc fail:" + result[x].doc + " > " + lastDocId); } } } } last = v[j]; lastSub = v2[j]; lastDocId = result[x].doc; buff.append(v[j] + "(" + v2[j] + ")(" + result[x].doc+") "); } } if(fail) { System.out.println("topn field1(field2)(docID):" + buff); } assertFalse("Found sort results out of order", fail); }
9
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String action = (String)req.getParameter("action"); if (action == null) action = ""; ProductViewHelper productViewHelper; String url = "/ProductView.jsp"; switch (action) { case ViewHelperFactory.GAMES: productViewHelper = ViewHelperFactory.getInstance() .getProductViewHelper(ViewHelperFactory.GAMES, req); req.setAttribute("productViewHelper", productViewHelper); req.setAttribute("productViewType", ViewHelperFactory.GAMES); break; case ViewHelperFactory.TOYS: productViewHelper = ViewHelperFactory.getInstance() .getProductViewHelper(ViewHelperFactory.TOYS, req); req.setAttribute("productViewHelper", productViewHelper); req.setAttribute("productViewType", ViewHelperFactory.TOYS); break; case ViewHelperFactory.SEARCH: productViewHelper = ViewHelperFactory.getInstance() .getProductViewHelper(ViewHelperFactory.SEARCH, req); if (productViewHelper.getProducts().size() == 0) { req.setAttribute("msg", "sorry, no results found for \"" + productViewHelper.getKeyword() + "\""); req.setAttribute("link", "back to " + "<a href=\"/GAMER/shop?action=home\">shopping</a>"); url = "/UserMsg.jsp"; } else { req.setAttribute("productViewHelper", productViewHelper); req.setAttribute("productViewType", ViewHelperFactory.SEARCH); } break; default: productViewHelper = ViewHelperFactory.getInstance() .getProductViewHelper(ViewHelperFactory.HOME, req); req.setAttribute("productViewHelper", productViewHelper); req.setAttribute("productViewType", ViewHelperFactory.HOME); break; } getServletContext().getRequestDispatcher(url).forward(req, res); }
5
public void insertVisitingHours(VisingHoursBean bean){ ResultSet rs=null; Connection con=null; PreparedStatement ps=null; try{ String sql="INSERT INTO OFFICE_HOURS(p_id, weekday, timings) VALUES (?,?)"; con=ConnectionPool.getConnectionFromPool();; ps=con.prepareStatement(sql); ps.setInt(1, bean.getProfessorId()); ps.setString(2, bean.getDay()); ps.setString(3,bean.getTime()); ps.execute(); } catch(Exception ex) { ex.printStackTrace(); } finally{ if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!=null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(con!=null) { try { ConnectionPool.addConnectionBackToPool(con);; } catch (Exception e) { e.printStackTrace(); } } } }
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IdCount idCount = (IdCount) o; if (id != idCount.id) return false; return true; }
4
final public void AndExpression() throws ParseException { EqualExpression(); label_2: while (true) { switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case AND: break; default: jj_la1[2] = jj_gen; break label_2; } ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { jj_consume_token(AND); EqualExpression(); jjtree.closeNodeScope(jjtn001, 2); jjtc001 = false; jjtn001.setFunction(tokenImage[AND], new Logical(0)); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { throw (RuntimeException) jjte001; } if (jjte001 instanceof ParseException) { throw (ParseException) jjte001; } throw (Error) jjte001; } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, 2); } } } }
8
public MapEntry acquire(int length) throws IOException { // length check int fIndex = mapLengthToFreeEntryArrayIndex(length); if (fIndex < 0 || fIndex >= FREE_ENTRY_ARRAY_SIZE) throw new IllegalArgumentException(length + " <= 0 or > max allowed data slot length " + MAX_DATA_SLOT_LENGTH); // metrics this.totalRealUsedSlotSize.addAndGet(length); this.totalAcquireCounter.incrementAndGet(); // find exact match MapEntry freeEntry = findFreeEntryByLength(fIndex, length); if (freeEntry != null) { this.totalExactMatchReuseCounter.incrementAndGet(); freeEntry.MarkInUse(); freeEntry.putCreatedTime(System.currentTimeMillis()); return freeEntry; } // find within length + 1 -> 2 * len (so we will waste at most half free space) if (fIndex < FREE_ENTRY_ARRAY_SIZE - 1) { int fromIndex = fIndex + 1; int dIndex = fIndex == 0 ? 1 : fIndex * 2; int toIndex = dIndex < FREE_ENTRY_ARRAY_SIZE - 1 ? dIndex : FREE_ENTRY_ARRAY_SIZE - 1; SortedSet<Integer> freeEntryIndexCandidates = freeEntryIndexSet.subSet(fromIndex, true, toIndex, true); for(int freeIndex : freeEntryIndexCandidates) { freeEntry = findFreeEntryByLength(freeIndex, length); if (freeEntry != null) { this.totalApproximateMatchReuseCounter.incrementAndGet(); freeEntry.MarkInUse(); freeEntry.putCreatedTime(System.currentTimeMillis()); return freeEntry; } } } // acquire new entry freeEntry = this.acquireNew(length); freeEntry.MarkInUse(); freeEntry.putCreatedTime(System.currentTimeMillis()); return freeEntry; }
8
public void process() { List<CycleEventContainer> eventsCopy = new ArrayList<CycleEventContainer>(events); List<CycleEventContainer> remove = new ArrayList<CycleEventContainer>(); for (CycleEventContainer c : eventsCopy) { if (c != null) { if (c.needsExecution()) c.execute(); if (!c.isRunning()) { remove.add(c); } } } for (CycleEventContainer c : remove) { events.remove(c); } }
5
public static AbstractTableModel getBoundProperties(final CSProperties p, String boundName) throws ParseException { final int rows = DataIO.getInt(p, boundName); final List<String> arr = keysByMeta(p, "bound", boundName); return new AbstractTableModel() { @Override public int getRowCount() { return rows; } @Override public int getColumnCount() { return arr.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { String colname = arr.get(columnIndex); String[] d = Conversions.convert(p.get(colname), String[].class); return d[rowIndex].trim(); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { String colname = arr.get(columnIndex); String[] d = Conversions.convert(p.get(colname), String[].class); d[rowIndex] = aValue.toString().trim(); String s = toArrayString(d); p.put(colname, s); } @Override public String getColumnName(int column) { return arr.get(column); } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } }; }
1
public JSONObject optJSONObject(int index) { Object o = this.opt(index); return o instanceof JSONObject ? (JSONObject) o : null; }
1
private static Tree setParents(Tree a, int[] L) { for(int i=0;i<L.length;i++){ if(L[i]==0){ a.addLeaf(i+1); } } for(int i=0;i<L.length;i++){ if(L[i]!=0){ a.addLeaf(L[i],i+1); } } return a; }
4
final private boolean jj_3R_189() { Token xsp; xsp = jj_scanpos; if (jj_scan_token(85)) { jj_scanpos = xsp; if (jj_scan_token(86)) { jj_scanpos = xsp; if (jj_scan_token(83)) { jj_scanpos = xsp; if (jj_scan_token(84)) { jj_scanpos = xsp; if (jj_scan_token(92)) { jj_scanpos = xsp; if (jj_scan_token(93)) { jj_scanpos = xsp; if (jj_scan_token(94)) { jj_scanpos = xsp; if (jj_scan_token(95)) return true; } } } } } } } if (jj_3R_176()) return true; return false; }
9
public static boolean isAlpha(int c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }
3
public static void main(String[] args) { Inner1 inner = new Inner1(); inner.dosomething(); }
0
@Override public void propertyChange(PropertyChangeEvent evt) { CompoundPainter<?> painter = ref.get(); if (painter == null) { AbstractPainter<?> src = (AbstractPainter<?>) evt.getSource(); src.removePropertyChangeListener(this); } else { String property = evt.getPropertyName(); if ("dirty".equals(property) && evt.getNewValue() == Boolean.FALSE) { return; } painter.setDirty(true); } }
6
@SuppressWarnings("unchecked") public static <T> ImmutableList<T> of( final ImmutableList<? extends T> left, final ImmutableList<? extends T> right) { if (right.isEmpty()) { return (ImmutableList<T>) left; } if (left.isEmpty()) { return (ImmutableList<T>) right; } return new ImmutableJoinList<>(left, right); }
4
public void doVictimsOfCrime(Area A, LegalBehavior B, Law theLaw, MOB mob, boolean allowedToModify) throws IOException { if(mob.session()==null) return; mob.tell(getFromTOC("P3"+(theLaw.hasModifiableLaws()?"MOD":""))); mob.tell(L("Protected victims: @x1",CMLib.masking().maskDesc(theLaw.getInternalStr("PROTECTED")))); if((theLaw.hasModifiableLaws())&&(allowedToModify)) { String s="?"; while(s.trim().equals("?")) { s=mob.session().prompt(L("Enter a new mask, ? for help, or RETURN=[@x1]\n\r: ",theLaw.getInternalStr("PROTECTED")),theLaw.getInternalStr("PROTECTED")); if(s.trim().equals("?")) mob.tell(CMLib.masking().maskHelp("\n\r","protects")); else if(!s.equals(theLaw.getInternalStr("PROTECTED"))) { changeTheLaw(A,B,mob,theLaw,"PROTECTED",s); mob.tell(L("Changed.")); } } } }
7
private byte[] handleHandshake(NfcMessage inputMessage) { // no sequence number in handshake if (inputMessage.isSelectAidApdu()) { /* * The size of the returned message is specified in NfcTransceiver * and is currently set to 2. */ if (Config.DEBUG) Log.d(TAG, "AID selected"); return new NfcMessage(Type.AID).response().bytes(); } else if (inputMessage.type() == Type.USER_ID) { if (inputMessage.version() > NfcMessage.getSupportedVersion()) { if (Config.DEBUG) Log.d(TAG, "excepted NfcMessage version "+NfcMessage.getSupportedVersion()+" but was "+inputMessage.version()); eventHandler.handleMessage(NfcEvent.FATAL_ERROR, NfcInitiator.INCOMPATIBLE_VERSIONS); return new NfcMessage(Type.ERROR).payload(NfcInitiator.INCOMPATIBLE_VERSIONS.getBytes()).bytes(); } // now we have the user id, get it long newUserId = Utils.byteArrayToLong(inputMessage.payload(), 0); int maxFragLen = Utils.byteArrayToInt(inputMessage.payload(), 8); messageSplitter.maxTransceiveLength(maxFragLen); if (inputMessage.isResume() && newUserId == userIdReceived) { if (Config.DEBUG) Log.d(TAG, "resume"); return new NfcMessage(Type.DEFAULT).resume().bytes(); } else { if (Config.DEBUG) Log.d(TAG, "new session (no resume)"); userIdReceived = newUserId; lastMessageSent = null; lastMessageReceived = null; eventHandler.handleMessage(NfcEvent.INITIALIZED, Long.valueOf(userIdReceived)); resetStates(); return new NfcMessage(Type.USER_ID).bytes(); } } return null; }
9
public void paintColorsMode(Graphics g, int x, int y) { Point p = new Point(x, y); String rbs =request.buttonGroup.getSelection().getActionCommand(); //radio button selected colorBiddableLand(g); Grid grid = request.operator.getGrid(); grid.goToSurface(); if (rbs.equals("B")){ //If the bid radio box is selected selectCell(g, new Color(210,210,210), p); doBid(p); } else if(rbs.equals("D")){ //if the drill radio box is selected colorDrillableLand(g); selectCell(g, Color.CYAN, p); doDrill(p); } else if(rbs.equals("S")){ //if the seismic line radio box is selected colorSeismicKnowledge(g); Point startP = new Point(0,0); Point endP = new Point(0,0); try { startP = new Point(request.getStartX(),request.getStartY()); endP = new Point(request.getEndX(),request.getEndY()); } catch (Exception e) { } //sMode is toggled with every mouse click in onMouseClick() //if sMode indicates setting the start value if (sMode==0){ startP = p; //display the starting x,y values in their textbox request.setStartX(startP.x); request.setStartY(startP.y); //clear the ending x,y values request.setendX(""); request.setendY(""); //instruct to select ending cell request.setseismicCostField("Click Second Cell."); //color the starting selection seismicColor(g, startP, startP); //if sMode indicates setting the end value }else{ endP = p; //display the x,y values in their textbox request.setendX(endP.x+""); request.setendY(endP.y+""); //get the cost and display it String cost = request.operator. getCostSeismic(startP.x, startP.y, endP.x, endP.y); request.setseismicCostField(cost); //color the selection seismicColor(g, startP, endP); /*if the selection is not valid, display a helpful message. */ if(cost.equals("Invalid Coordinates.")) { request.setseismicCostField("Problem with Request."); } } } }
6
public PrintableDialog() { setTitle("Print Preview"); printMode.setStyle(CharProps.getIntProperty("last.printmode.style", PrintMode.STYLE_CRAM)); printMode.setText(CharProps.getIntProperty("last.printmode.text", PrintMode.TEXT_CHARS)); Container thiss = this.getContentPane(); thiss.setLayout(new BorderLayout()); gridPanel = new GridPanel(printMode); Paper paper = new Paper(); double margin = CharProps.getDoubleProperty("paper.margins", gridPanel.getMargins()) * 72; String paperSize = CharProps.getProperty("paper.size"); // A bit of a hack. if ("A4".equalsIgnoreCase(paperSize)) { paper.setImageableArea(margin, margin, 558.1417322834645, 805.8897637795276); paper.setSize(595.275590551181, 841.8897637795276); } paper.setImageableArea(margin, margin, paper.getWidth() - 2 * margin, paper.getHeight() - 2 * margin); format = new PageFormat(); format.setPaper(paper); thiss.add(gridPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); printButton = new JButton("Print"); setupButton = new JButton("Page Setup"); closeButton = new JButton("Close"); printButton.setBackground(CharApp.COLOR_BUTTON); setupButton.setBackground(CharApp.COLOR_BUTTON); closeButton.setBackground(CharApp.COLOR_BUTTON); printButton.addActionListener(this); setupButton.addActionListener(this); closeButton.addActionListener(this); buttonPanel.add(printButton); buttonPanel.add(setupButton); buttonPanel.add(closeButton); buttonPanel.setBackground(CharApp.COLOR_BG); JPanel controlPanel = new JPanel(new GridLayout(3, 1)); controlPanel.setBackground(CharApp.COLOR_BG); style = new JComboBox(styles); text = new JComboBox(texts); style.setBackground(CharApp.COLOR_BUTTON); text.setBackground(CharApp.COLOR_BUTTON); guides = new JCheckBox("Guides"); guides.setBackground(CharApp.COLOR_BG); grid = new JCheckBox("Grid Style"); grid.setBackground(CharApp.COLOR_BG); randomize = new JCheckBox("Random"); randomize.setBackground(CharApp.COLOR_BG); fillPage = new JCheckBox("Fill page"); fillPage.setBackground(CharApp.COLOR_BG); lines = new JCheckBox("Lines"); lines.setBackground(CharApp.COLOR_BG); header = new JCheckBox("Header"); header.setBackground(CharApp.COLOR_BG); guides.setSelected("true".equals(CharProps.getProperty("draw.guides"))); grid.setSelected("true".equals(CharProps.getProperty("draw.gridstyle"))); grid.setEnabled(guides.isSelected()); randomize.setSelected(gridPanel.isRandomOrder()); fillPage.setSelected(gridPanel.isFillThePage()); lines.setSelected(true); header.setSelected(true); guides.addActionListener(this); grid.addActionListener(this); randomize.addActionListener(this); fillPage.addActionListener(this); lines.addActionListener(this); header.addActionListener(this); next = new JButton(">"); prev = new JButton("<"); next.setBackground(CharApp.COLOR_BUTTON); prev.setBackground(CharApp.COLOR_BUTTON); fontButton = new JButton("Fonts"); fontButton.setBackground(CharApp.COLOR_BUTTON); sizesButton = new JButton("Boxes"); sizesButton.setBackground(CharApp.COLOR_BUTTON); next.addActionListener(this); prev.addActionListener(this); fontButton.addActionListener(this); sizesButton.addActionListener(this); JPanel temp = new JPanel(); temp.setBackground(CharApp.COLOR_BG); temp.add(new JLabel("Style:")); temp.add(style); temp.add(guides); temp.add(grid); temp.add(randomize); temp.add(fillPage); controlPanel.add(temp); temp = new JPanel(); temp.setBackground(CharApp.COLOR_BG); temp.add(new JLabel("Text:")); temp.add(text); temp.add(fontButton); temp.add(sizesButton); temp.add(lines); temp.add(header); controlPanel.add(temp); controlPanel.add(buttonPanel); switch (printMode.getText()) { case PrintMode.TEXT_CHARS: text.setSelectedIndex(1); break; case PrintMode.TEXT_PINYIN: text.setSelectedIndex(2); break; case PrintMode.TEXT_ENGLISH: text.setSelectedIndex(3); break; case PrintMode.TEXT_ENGLISH_PINYIN: text.setSelectedIndex(4); break; default: text.setSelectedIndex(0); } switch (printMode.getStyle()) { case PrintMode.STYLE_CRAM: style.setSelectedIndex(1); break; case PrintMode.STYLE_ALTERNATING_LINES: style.setSelectedIndex(2); break; case PrintMode.STYLE_READING: style.setSelectedIndex(3); break; default: style.setSelectedIndex(0); } style.addActionListener(this); text.addActionListener(this); buttonPanel.setBorder(BorderFactory.createLineBorder(Color.blue)); controlPanel.setBorder(BorderFactory.createLineBorder(Color.blue)); buttonPanel.add(new JLabel("Page:")); buttonPanel.add(prev); buttonPanel.add(next); JScrollPane scroller = new JScrollPane(controlPanel); // thiss.add(controlPanel, BorderLayout.SOUTH); thiss.add(scroller, BorderLayout.SOUTH); this.setResizable(true); this.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { if (ratio < 0) { ratio = (double) getHeight() / (double) getWidth(); } setSize((int) ((double) getHeight() / ratio), getHeight()); } }); }
9
public static void main(String[] args) { long start = System.nanoTime(); int found = 0, sum = 0; for (int i = 19; found < 11; i += 2) { if (isPrime(i)) { if (isTruncatable(Integer.toString(i))) { found += 1; sum += i; } } } System.out.println(sum); System.out.println("Done in " + (double) (System.nanoTime() - start) / 1000000000 + " seconds."); }
3
private void setMenuItems(){ // file menu // help menu welcome = new JMenuItem("Welcome"); about = new JMenuItem("About this"); help.add(welcome); help.add(about); }
0
public void enter(Miner miner){ if (miner.getLocation() != Location.saloon) { miner.changeLocation(Location.saloon); System.out.println(miner.getName() + " Boy, ah sure is thusty! Walking to the saloon"); } }
1
public static final void login(final SeekableLittleEndianAccessor slea, final MapleClient c) { final String login = slea.readMapleAsciiString(); final String pwd = slea.readMapleAsciiString(); c.setAccountName(login); final boolean ipBan = c.hasBannedIP(); // final boolean macBan = false; // MSEA doesn't sent mac final boolean macBan = c.hasBannedMac(); int loginok = c.login(login, pwd, ipBan || macBan); final Calendar tempbannedTill = c.getTempBanCalendar(); if (loginok == 0 && (ipBan || macBan)) { loginok = 3; if (macBan) { // this is only an ipban o.O" - maybe we should refactor this a bit so it's more readable MapleCharacter.ban(c.getSession().getRemoteAddress().toString().split(":")[0], "Enforcing account ban, account " + login, false); } } if (loginok != 0) { if (!loginFailCount(c)) { c.getSession().write(LoginPacket.getLoginFailed(loginok)); } } else if (tempbannedTill.getTimeInMillis() != 0) { if (!loginFailCount(c)) { c.getSession().write(LoginPacket.getTempBan(KoreanDateUtil.getTempBanTimestamp(tempbannedTill.getTimeInMillis()), c.getBanReason())); } } else { c.loginAttempt = 0; LoginWorker.registerClient(c); } }
9
public void sendGuessMove(String guess){ check(isMyTurn() && currentMove == GUESS); int maxDigit = (Integer)state.get(MAXDIGIT); check(masterMindLogic.checkValidCode(guess, maxDigit)); this.sendGuessOperation(coderId, guesserId, guess, state); }
1
public static String shitWordN(String s,int n){ if(s!=null && n >= 0 && n <= s.length()){ char[] shit = s.toCharArray(); reverseChar(shit,0,n-1); reverseChar(shit,n,s.length()-1); reverseChar(shit,0,s.length()-1); return new String(shit); } return null; }
3
public Address getIndirizzo() { return address; }
0
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void main(String[] argx) { List<String> listWithDup = new ArrayList<String>(); listWithDup.add("1"); listWithDup.add("2"); listWithDup.add("3"); listWithDup.add("1"); List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(listWithDup)); System.out.println("list with dup:"+ listWithDup); System.out.println("list without dup:"+ listWithoutDup); System.out.println("========================="); List list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); list.add("1"); List list2 = new ArrayList(new HashSet(list)); System.out.println("list with dup:"+ list); System.out.println("list without dup:"+ list2); }
0
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, InterruptedException, ExecutionException { System.out.println("Running benchmark. Press any key to continue."); System.in.read(); Map<Class<?>, Map<String, String>> keyLookupClasses = new LinkedHashMap<Class<?>, Map<String, String>>(); //Map<String, String> hashMapKeyValueConfiguration = new HashMap<String, String>(); //keyLookupClasses.put(HashMapKeyValueLookup.class, // hashMapKeyValueConfiguration); Map<String, String> concurrentHashMapKeyValueConfiguration = new HashMap<String, String>(); keyLookupClasses.put(ConcurrentHashMapKeyValueLookup.class, concurrentHashMapKeyValueConfiguration); Map<String, String> memcachedKeyValueConfiguration = new HashMap<String, String>(); keyLookupClasses.put(MemcachedKeyValueLookup.class, memcachedKeyValueConfiguration); Map<String, String> mySQLKeyValueLookupConfiguration = new HashMap<String, String>(); keyLookupClasses.put(MySQLKeyValueLookup.class, mySQLKeyValueLookupConfiguration); ExecutorService executor = Executors.newFixedThreadPool(16); for (Entry<Class<?>, Map<String, String>> clazzEntry : keyLookupClasses .entrySet()) { final KeyValueLookup keyValueLookup = (KeyValueLookup) clazzEntry .getKey().newInstance(); keyValueLookup.init(clazzEntry.getValue()); benchmark(keyValueLookup, executor); keyValueLookup.cleanup(); } executor.shutdown(); }
4
public AttributeInfo copy(ConstPool newCp, Map classnames) { if (methodIndex() == 0) return new EnclosingMethodAttribute(newCp, className()); else return new EnclosingMethodAttribute(newCp, className(), methodName(), methodDescriptor()); }
1
public static Subject findSubjectOfBestHj(Data myData, Subject[] givenSubjects){ int i = 0; Subject bestSubject = givenSubjects[i]; for(int j=i+1; j<givenSubjects.length; j++){ if (findBestSubjectSemester(bestSubject)==null){ bestSubject = givenSubjects[j]; i = j; } else break; } for(int k=i+1; k<givenSubjects.length; k++){ if (findBestSubjectSemester(givenSubjects[k])!=null){ if (findBestSubjectSemester(givenSubjects[k]).mark>findBestSubjectSemester(bestSubject).mark){ bestSubject = givenSubjects[k]; } } } return bestSubject; }
5
public void run() { while(active){ if(freeze){ try { this.freeze = false; Ob.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } sim = new Driver(); sim.Constants = this.Constants; sim.verbose = this.verbose; sim.init(); sim.run(); if(freeze){ try { this.freeze = false; Ob.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ticks = sim.ticks; try { hold.TaskHand(this); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
6
public void assignRoles() { calculateRatio(); for (Player player : players.getPlayers()) { if (getRandomDecision()) { assignAsMafia(player); } else { assignAsVillager(player); } } }
2
@Override public DefaultConnectionLabel toItem( ConnectionLabelData data, DefaultUmlDiagram diagram ) { AbstractConnection connection = (AbstractConnection)diagram.getItem( data.getConnection() ); if(connection == null){ throw new IllegalStateException( "cannot find connection of label" ); } DefaultConnectionLabel label = new DefaultConnectionLabel( diagram, data.getKey(), connection ); label.setText( data.getText() ); label.setConfiguration( new ConnectionLabelConfiguration( data.getConfigurationId() ) ); return label; }
1
public static void main(String[] args) { long[]arr = new long[]{1,3,4,1,2,5}; display(arr); InsertSort.sort(arr); display(arr); }
0
public static String producto(String archivo, String factorA, String factorB) { try { Workbook libro = Workbook.getWorkbook(new File("src/txts/" + archivo)); int altoTabla = libro.getSheet(0).getRows(); String[][] tabla = new String[libro.getSheet(0).getColumns()][altoTabla]; for (int i = 0; i < tabla.length; i++) for (int j = 0; j < altoTabla; j++) tabla[i][j] = libro.getSheet(0).getCell(i, j).getContents(); int x = 0, y = 0; for (int i = 0; i < tabla.length; i++) if (tabla[i][0].compareTo(factorA) == 0) x = i; for (int j = 0; j < altoTabla; j++) if (tabla[0][j].compareTo(factorB) == 0) y = j; return tabla[x][y]; } catch (BiffException | IOException ex) { return ""; } }
7
public static ClassLoader getDefaultClassLoader() { ClassLoader cl = null; try { cl = Thread.currentThread().getContextClassLoader(); } catch (Throwable ex) { // Cannot access thread context ClassLoader - falling back to system // class loader... } if (cl == null) { // No thread context class loader -> use class loader of this class. cl = SpringClassUtils.class.getClassLoader(); } return cl; }
2
@Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child if(this._condicao_ == oldChild) { setCondicao((PExpLogica) newChild); return; } for(ListIterator<PComando> i = this._comando_.listIterator(); i.hasNext();) { if(i.next() == oldChild) { if(newChild != null) { i.set((PComando) newChild); newChild.parent(this); oldChild.parent(null); return; } i.remove(); oldChild.parent(null); return; } } throw new RuntimeException("Not a child."); }
4
public String getStateName() { return stateName.get(); }
0
ArrayList<String> wordBreakDFS( String s, Set<String> dict ) { ArrayList<String> result = new ArrayList<String>(), tmpList; for( int i = 0; i < s.length(); i++ ) { String head = s.substring(0, i+1); String tail = s.substring(i+1); if( dict.contains(head) ) { if( tail.length() == 0 ) { result.add( head ); break; } if( cache.containsKey( tail ) ) { tmpList = cache.get( tail ); } else { tmpList = wordBreakDFS( tail, dict ); } for( String ss : tmpList ) { result.add( head + " " + ss ); } } } cache.put( s, result ); return result; }
5
public static void main(String args[]){ System.out.println("Digite o numero para verificar se é primo ou não:"); Scanner scan = new Scanner(System.in); int n = scan.nextInt(); boolean primo = true; for (int i = n-1; i > 1; i--) { if (n%i == 0) { primo = false; break; } } if (primo) { System.out.println("O numero " + n + " é primo"); } else { System.out.println("O numero " + n + " não é primo"); } }
3
public Image[] getCells(ImageRetriever paramImageRetriever, int paramInt1, int paramInt2) { Integer localInteger = new Integer(paramInt1); if (animationList == null) animationList = new Hashtable(); Object localObject = animationList.get(localInteger); Image[] arrayOfImage; if (localObject == null) { Vector localVector = new Vector(); for (int i = 0; i < (paramInt1 % 90 == 0 ? getAnimationFrames() : 1); i++) localVector.addElement(paramImageRetriever.getImage("com/templar/games/stormrunner/media/images/robot/chassis/" + getID() + "/walk" + i + "_" + paramInt1 + ".gif")); arrayOfImage = new Image[localVector.size()]; localVector.copyInto(arrayOfImage); animationList.put(localInteger, arrayOfImage); } else { arrayOfImage = (Image[])localObject; }return arrayOfImage; }
4
@Test public void ensureSalaryItemInBudgetContainsDifferentValueFormObjectTestTwo() { when(budgetFormData.getSalary()).thenReturn(new BigDecimal("2500")); try { budget.buildBudget(budgetFormData); } catch (Exception e) { e.printStackTrace(); } assertTrue(budget.getSalary().intValue() != 2500); }
1
public void render(Screen screen) { Vector2i pos = getPlayers().get(0).getPos().toVector2i(); int xOffset = pos.getX() - screen.w / 2; int yOffset = pos.getY() - screen.h / 2; screen.setOffset(xOffset, yOffset); int x0 = xOffset >> 4; int x1 = (xOffset + screen.w + 16) >> 4; int y0 = yOffset >> 4; int y1 = (yOffset + screen.h + 16) >> 4; for (int y = y0; y < y1; y++) { for (int x = x0; x < x1; x++) { getTile(x, y).render(screen); } } List<Entity> entities = getEntities(); List<Player> players = new ArrayList<Player>(); for (Entity e : entities) { if (!(e.tag.contains("player"))) e.render(screen); else players.add((Player) e); } for (OnlinePlayers op : onlinePlayers) { if (op != null) { op.render(screen); } } for (Player p : players) { p.render(screen); } }
7
public void mouseExited(MouseEvent event) { adapter.mouseExited(event); }
0
public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); HTTPTokener x = new HTTPTokener(string); String token; token = x.nextToken(); if (token.toUpperCase().startsWith("HTTP")) { // Response jo.put("HTTP-Version", token); jo.put("Status-Code", x.nextToken()); jo.put("Reason-Phrase", x.nextTo('\0')); x.next(); } else { // Request jo.put("Method", token); jo.put("Request-URI", x.nextToken()); jo.put("HTTP-Version", x.nextToken()); } // Fields while (x.more()) { String name = x.nextTo(':'); x.next(':'); jo.put(name, x.nextTo('\0')); x.next(); } return jo; }
2
public int getPoints() { return points; }
0
public static String convert(String s, int nRows) { String result = ""; if (nRows < 2 || s == null) { return s; } String[] strings = new String[nRows]; int current = 0; int dir = -1; for (int i = 0; i < s.length(); i++) { if (strings[current] == null) { strings[current] = ""; } strings[current] += s.charAt(i); if (current == 0 || current == nRows - 1) { dir *= -1; } current += dir; } for (int i = 0; i < nRows; i++) { if (strings[i] != null) { result += strings[i]; } } return result; }
8
public static int triangleBsum1(int x[][]) { int sum = 0; for (int i = 0; i < x.length; i++) { System.out.println(); for (int j = 0; j < x[i].length; j++) { if (i >= j) { System.out.print(x[i][j] + " "); sum = sum + x[i][j]; } } } System.out.println(); return sum; }
3
public boolean validateConnection(String direction) { switch (direction) { case "north": if (this.north[0].equals("X")) { return false; } else { return true; } case "east": if (this.east[0].equals("X")) { return false; } else { return true; } case "south": if (this.south[0].equals("X")) { return false; } else { return true; } case "west": if (this.west[0].equals("X")) { return false; } else { return true; } default: System.out.println("Valid options are: North, East, South, West!"); return false; } }
8
@Override public void render(GameContainer gc, Graphics g) throws SlickException { for (int x = 0; x < tiles.length; x++){ for (int y = 0; y < tiles[x].length; y++){ if (tiles[x][y] != null) tiles[x][y].render( x*tiles[x][y].getSprite().getWidth(), y*tiles[x][y].getSprite().getHeight() ); } } }
3
public void update(GameContainer gc, StateBasedGame sb, float delta) { if (cooldown <= 0) { cooldown = 0; onCooldown = false; } else if (onCooldown) { cooldown -= delta; } }
2
public void process(String dirname) { FileWriter fw = null; try { File dir = new File(dirname); fw = new FileWriter(output); BufferedWriter bw = new BufferedWriter(fw); File[] fa = dir.listFiles(new EndsWithFilter(extension)); for (File f : fa) { String name = f.getName(); System.out.print(name + "\t"); BufferedReader br = new BufferedReader(new FileReader(f)); String ln = br.readLine(); Iterator<Long> it = ids.iterator(); while(it.hasNext()){ if(ln.contains(Long.toString(it.next())+"=")){ System.out.print("writing...\t"); String fileName = f.getPath(); int end = fileName.lastIndexOf("."); String substring = fileName.substring(0,end); File trjfile = new File(substring + ".trj"); BufferedReader br2 = new BufferedReader(new FileReader(trjfile)); String ln2 = br2.readLine(); if(headerWrite){ bw.write(ln2 + "\n"); ln2 = br2.readLine(); headerWrite=false; } while(ln2!=null){ bw.write(ln2 + "\n"); ln2 = br2.readLine(); } br2.close(); break; // We're already writing the file so don't need to check for other items in list } } System.out.println(" done."); br.close(); } bw.flush(); bw.close(); } catch (IOException e) { System.out.println("Error accessing output file: " + output); e.printStackTrace(); } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("ERROR: " + output + " could not be closed properly."); e.printStackTrace(); } } } File ofile = new File(output); if(ofile.length()==0){ System.out.println("\nWARNING: " + output + " length is 0\n"); } }
9
private int addNewPlayers(List<Player> player, Message mg) { int numberOfPlayers = 0; while(numberOfPlayers == 0){ try{ numberOfPlayers = Integer.parseInt(getInput()); } catch (NumberFormatException e){ mg.displayMessage(3); } } /* * This code generates the new players by user input */ for (int count = 0; count < numberOfPlayers; count++ ){ if (count != 1138){ String fn = null; String an = null; Player newPlayer = new Player(); newPlayer.setPersonalID(count); newPlayer.setWallet(200); newPlayer.setDealer(false); mg.displayMessage(4, (count+1)); fn = getInput(); newPlayer.setFirstName(fn); if (!fn.equals("") && !fn.equals(null)){ newPlayer.setPlayerPreferredName(fn); } mg.displayMessage(6); an = getInput(); newPlayer.setPlayerAlias(an); if (!an.equals("") && !an.equals(null)){ newPlayer.setPlayerPreferredName(an); } player.add(newPlayer); } } return numberOfPlayers; }
8
World(int level) { walls = new ArrayList<Wall>(); walls.add(new Wall(0, 0, 600, 20)); walls.add(new Wall(0, 0, 20, 600)); walls.add(new Wall(0, 571, 600, 600)); walls.add(new Wall(571, 0, 600, 600)); switch(level) { case 1: initWorldLevelOne(); break; case 2: initWorldLevelTwo(); break; case 3: initWorldLevelThree(); break; } }
3
@Test public void testGetQuantidadeProduto() { try { Assert.assertEquals(10, facade.getQuantidadeProduto(1)); } catch (FacadeException e) { Assert.fail(e.getMessage()); } try { facade.getQuantidadeProduto(5); Assert.fail("era para lanÁa exceÁ„o"); } catch (FacadeException e) { // n„o È para lanÁa exceÁ„o por que o valor n„o È valido } try { Assert.assertEquals(5, facade.getQuantidadeProduto(2)); } catch (FacadeException e) { Assert.fail(e.getMessage()); } try { Assert.assertEquals(1, facade.getQuantidadeProduto(4)); } catch (FacadeException e) { Assert.fail(e.getMessage()); } }
4