text
stringlengths
14
410k
label
int32
0
9
public void noteOn(int note, int velocity) { //search through the voices to find one that's available and press it for (int i = 0; i < voices.length; i++) { if (!voices[i].isInUse()) { voices[i].press(note, velocity); break; } } }
2
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final Physical target=mob.location(); if(target==null) return false; if(target.fetchEffect(ID())!=null) { mob.tell(L("This place is already a blood hearth.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> @x1 to fill this place with blood.^?",prayForWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); setMiscText(mob.Name()); if((target instanceof Room) &&(CMLib.law().doesOwnThisProperty(mob,((Room)target)))) { final String landOwnerName=CMLib.law().getPropertyOwnerName((Room)target); if(CMLib.clans().getClan(landOwnerName)!=null) setMiscText(landOwnerName); target.addNonUninvokableEffect((Ability)this.copyOf()); CMLib.database().DBUpdateRoom((Room)target); } else beneficialAffect(mob,target,asLevel,0); } } else beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 to fill this place with blood, but <S-IS-ARE> not answered.",prayForWord(mob))); return success; }
9
protected void forwardAction(String className){ Point currentLocation = myFrame.getLocation(); myFrame.setVisible(false); try{ Class<?> clazz = Class.forName(className); Constructor<?> con = clazz.getConstructor(Point.class); con.newInstance(currentLocation); } catch(Exception e){ System.out.println(e); } }
3
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Ticket other = (Ticket) obj; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; return true; }
6
public void changeVolume(VolumeControlGUI vc,int newVolume) { if(vc != null) { for(int i=0; i<list.capacity(); i++) { //only change the volume, if this slider does not changed the volume if(list.get(i) != vc) { list.get(i).setVolume(newVolume); } //finally set it in the sound system mainGui.setVolume(newVolume); } } }
3
private void useData(String line) { int data[] = convertData(line); if(data[0] == 1 && !logedin) { login(data); } if(data[0] == 2) { //gets the best scores. List<MysqlPlayerScore> scores = getBestScore(data[1],true); //formats a message to send. String message = "/pBestS;"; if(scores == null) // the scores could be null and that should be checked! message += "0;"; else { message += scores.size()+";"; //adds the scores to the message for(int i = 0;i<scores.size();i++) message += scores.get(i).getScore()+";"; } //sends the one message with all the data. sendMessage(message); } if(data[0] == 3) { //gets the best scores. List<MysqlPlayerScore> scores = getBestScore(data[1],false); //formats a message to send. String message = "/gBestS;"; if(scores == null) // the scores could be null and that should be checked! message += "0;"; else { message += scores.size()+";"; //adds the scores to the message for(int i = 0;i<scores.size();i++) message += scores.get(i).getScore()+";"; } //sends the one message with all the data. sendMessage(message); } if(data[0] == 4) { addScore(data[1]); notifyScoreChange(); } /*if(data[0] == 5) cia veliau kai bus onlinas arba rank sistema globali. { //uzdeda nauja nika is line pasiemes ji savePlayerToMysql(); }*/ }
9
public void run(int pumpCount, int attendantCount, int duration){ makePumps(pumpCount); makeAttendants(attendantCount); for (int i=0;i<duration;i++){ carQueue(); while(freePump()&&l.hasNext()&&freeAttendant()){ tryToFill(); } nextFrame(); } }
4
public String getMask() { StringBuilder mask = new StringBuilder(); // Build Flag mask mask.append(isMemory() ? "1" : "0"); mask.append(isOverflow() ? "1" : "0"); mask.append(isNot() ? "1" : "0"); mask.append(isCarry() ? "1" : "0"); mask.append(isNegative() ? "1" : "0"); mask.append(isZero() ? "1" : "0"); return mask.toString(); }
6
public boolean valid(int tableIndex, int columnIndex, String value) { boolean result = true; boolean findColumn = false; boolean or = false; boolean nonFilter = true; if(tableIndex == 1){ System.out.println("This is Date"); } for (String filter : filters) { if(tableIndex == 1){ System.out.println("nonFilter:"+nonFilter); } // 尋找該欄位的篩選條件 if (filter.contains(SCHEMA[tableIndex][columnIndex])) { findColumn = true; nonFilter = false; if (filter.contains(BETWEEN)) { result &= validBetween(filter, value); } else if (filter.contains(OR)) { or |= validOr(filter, value); result &= or; } else { result &= validNormal(filter, value); } } } return or || (result && findColumn) || nonFilter; }
9
public static <GInput, GOutput> Pointer<GOutput> convertedPointer(final Converter<? super GInput, ? extends GOutput> converter, final Pointer<? extends GInput> pointer) throws NullPointerException { if (converter == null) throw new NullPointerException("converter = null"); if (pointer == null) throw new NullPointerException("pointer = null"); return new BasePointer<GOutput>() { @Override public GOutput data() { return converter.convert(pointer.data()); } @Override public String toString() { return Objects.toInvokeString("convertedPointer", converter, pointer); } }; }
5
public RegisterServiceType() { setTitle("Tipo de Servi\u00E7o"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 500, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(10, 11, 360, 240); contentPane.add(scrollPane); /* Creating a table to show the type of services informations. */ final DefaultTableModel tableModel = new DefaultTableModel(null, new String[] { "Serviço", "Valor" }); final JTable table = new JTable(tableModel); /* * Getting an instance of a service type to populate the table with the * its informations. */ try { ServiceTypeController serviceTypeController = ServiceTypeController .getInstance(); ServiceType serviceType = new ServiceType(); ResultSet serviceTypeResultSet = serviceTypeController .mostrarTipoServicoCadastrados(serviceType); while (serviceTypeResultSet.next()) { String[] serviceTypeData = new String[2]; serviceTypeData[0] = serviceTypeResultSet.getString("nome"); serviceTypeData[1] = serviceTypeResultSet.getString("preco"); tableModel.addRow(serviceTypeData); } } catch (SQLException e) { showErrorMessage(e.getMessage()); } scrollPane.setViewportView(table); /* * Add a mouse clicked event. When the Novo Button is clicked, it goes * to a new window, which is NewServiceType, and dispose this one that * is not needed. */ JButton btnNewServiceType = new JButton("Novo"); btnNewServiceType.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { dispose(); NewServiceType newNewServiceTypeWindow = new NewServiceType(); newNewServiceTypeWindow.setVisible(true); newNewServiceTypeWindow.setLocationRelativeTo(null); } }); btnNewServiceType.setBounds(380, 24, 94, 23); contentPane.add(btnNewServiceType); /* * Add a mouse clicked event. When the Alterar Button is clicked, it * goes to a new window, which is AlterServiceType, and dispose this one * that is not needed. A temporary value of the TipoServico model class * is set here to be used in the new window displayed. */ JButton btnUpdateServiceType = new JButton("Alterar"); btnUpdateServiceType.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { ServiceType.setTempNome(tableModel.getValueAt( table.getSelectedRow(), 0).toString()); AlterServiceType newAlterServiceTypeWindow = new AlterServiceType(); newAlterServiceTypeWindow.setVisible(true); newAlterServiceTypeWindow.setLocationRelativeTo(null); dispose(); } catch (ServiceException e1) { showErrorMessage(e1.getMessage()); } catch (ArrayIndexOutOfBoundsException e1) { showErrorMessage("Selecione um Tipo de Serviço"); } } }); btnUpdateServiceType.setBounds(380, 58, 94, 23); contentPane.add(btnUpdateServiceType); /* * Add a mouse clicked event. When the Remover Button is clicked, it * access the database and remove the type of service that is selected * in the table. */ JButton btnRemoveServiceType = new JButton("Remover"); btnRemoveServiceType.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { String serviceTypeName = (String) table.getValueAt( table.getSelectedRow(), 0); ServiceType serviceType = new ServiceType(); try { serviceType.setNomeTipoServico(serviceTypeName); } catch (ServiceException e1) { e1.printStackTrace(); } int confirmation = JOptionPane.showConfirmDialog(null, "Remover " + serviceTypeName + " da lista?"); if (confirmation == JOptionPane.YES_OPTION) { ServiceTypeController serviceTypeController = ServiceTypeController .getInstance(); try { serviceTypeController.excluir(serviceType); } catch (SQLException e1) { e1.printStackTrace(); } dispose(); RegisterServiceType newRegisterServiceTypeWindow = new RegisterServiceType(); newRegisterServiceTypeWindow.setVisible(true); newRegisterServiceTypeWindow.setLocationRelativeTo(null); } } }); btnRemoveServiceType.setBounds(380, 92, 94, 23); contentPane.add(btnRemoveServiceType); /* * Add a mouse clicked event. When the Voltar Button is clicked, it * returns the the previous window, which is Administrative. */ JButton btnReturn = new JButton("Voltar"); btnReturn.setBounds(380, 228, 94, 23); btnReturn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); Administrative newAdministrativeWindow = new Administrative(); newAdministrativeWindow.setVisible(true); newAdministrativeWindow.setLocationRelativeTo(null); } }); contentPane.add(btnReturn); }
7
public static int critRate(int uCrit, int eLuk) { return Math.min(uCrit - eLuk, 100); }
0
@Override public void onFTP( final String senderIP, final String senderName, final String fileName, final String fullpath, final int socketNo, final long fileLength) { // // Process this ftp request with a thread so that // further messages can be processed without waiting for // finishing of this ftp. // Thread ftpThread = new Thread() { @Override public void run() { String directory; String file; synchronized (FTPListenerImpl.this) { if (fSaveDialog == null) { fSaveDialog = new FileDialog(fParentFrame, "MessagingTool: " + StringDefs.SAVE_FILE_AS, FileDialog.SAVE); } fSaveDialog.setFile(fileName); ComponentUtil.overlapComponents(fSaveDialog, fParentFrame, 32, false); fSaveDialog.setVisible(true); fSaveDialog.dispose(); directory = fSaveDialog.getDirectory(); file = fSaveDialog.getFile(); if (directory == null || file == null) { return; } if (directory.length() == 0 || file.length() == 0) { return; } } File newlyCreatedFile = new File(directory, file); try (FileOutputStream os = new FileOutputStream(newlyCreatedFile);) { if (!FTP.getInstance().retrieve(senderIP, fullpath, file, os, socketNo, fileLength)) { newlyCreatedFile.delete(); } } catch (IOException e) { System.out.println(e); newlyCreatedFile.delete(); } } }; ftpThread.setDaemon(true); ftpThread.start(); }
7
public EvaluationResult evaluate(List inputs, EvaluationCtx context) { // Evaluate the arguments AttributeValue [] argValues = new AttributeValue[inputs.size()]; EvaluationResult result = evalArgs(inputs, context, argValues); if (result != null) return result; // Now that we have real values, perform the requested operation. AttributeValue attrResult = null; switch (getFunctionId()) { // *-one-and-only takes a single bag and returns a // single value of baseType case ID_BASE_ONE_AND_ONLY: { BagAttribute bag = (BagAttribute)(argValues[0]); if (bag.size() != 1) return makeProcessingError(getFunctionName() + " expects " + "a bag that contains a single " + "element, got a bag with " + bag.size() + " elements"); attrResult = (AttributeValue)(bag.iterator().next()); break; } // *-size takes a single bag and returns an integer case ID_BASE_BAG_SIZE: { BagAttribute bag = (BagAttribute)(argValues[0]); attrResult = new IntegerAttribute(bag.size()); break; } // *-bag takes any number of elements of baseType and // returns a bag containing those elements case ID_BASE_BAG: { List argsList = Arrays.asList(argValues); attrResult = new BagAttribute(getReturnType(), argsList); break; } } return new EvaluationResult(attrResult); }
5
public static void main(String[] args) { try { System.out.println("Starting..."); CycAccess cycAccess = new CycAccess("public1", 3600); InferenceParameters parameters = new DefaultInferenceParameters(cycAccess); parameters.put(new CycSymbol(":MAX-NUMBER"), new Integer(10)); parameters.put(new CycSymbol(":PROBABLY-APPROXIMATELY-DONE"), new Double(0.5)); parameters.put(new CycSymbol(":ABDUCTION-ALLOWED?"), Boolean.TRUE); parameters.put(new CycSymbol(":EQUALITY-REASONING-METHOD"), new CycSymbol(":CZER-EQUAL")); try { parameters.put(new CycSymbol(":MAX-NUMBER"), new CycSymbol(":BINDINGS")); System.out.println("Failed to catch exception."); } catch (Exception e) { } // ignore try { parameters.put(new CycSymbol(":PROBABLY-APPROXIMATELY-DONE"), new CycSymbol(":BINDINGS")); System.out.println("Failed to catch exception."); } catch (Exception e) { } // ignore try { parameters.put(new CycSymbol(":ABDUCTION-ALLOWED?"), new CycSymbol(":BINDINGS")); System.out.println("Failed to catch exception."); } catch (Exception e) { } // ignore try { parameters.put(new CycSymbol(":EQUALITY-REASONING-METHOD"), new Double(0.5)); System.out.println("Failed to catch exception."); } catch (Exception e) { } // ignore System.out.println("PARAMETERS: " + parameters.stringApiValue()); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("Exiting..."); System.exit(0); } }
5
public void run() { while (run == true) { try { udpSocket.receive(datagram); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Received!"); System.out.println(run); } }
2
@Override public LegendItem getLegendItem(int datasetIndex, int series) { CategoryPlot cp = getPlot(); if (cp == null) { return null; } if (isSeriesVisible(series) && isSeriesVisibleInLegend(series)) { CategoryDataset dataset = cp.getDataset(datasetIndex); String label = getLegendItemLabelGenerator().generateLabel( dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); Paint fillPaint = (this.useFillPaint ? getItemFillPaint(series, 0) : paint); boolean shapeOutlineVisible = this.drawOutlines; Paint outlinePaint = (this.useOutlinePaint ? getItemOutlinePaint(series, 0) : paint); Stroke outlineStroke = lookupSeriesOutlineStroke(series); LegendItem result = new LegendItem(label, description, toolTipText, urlText, true, shape, getItemShapeFilled(series, 0), fillPaint, shapeOutlineVisible, outlinePaint, outlineStroke, false, new Line2D.Double(-7.0, 0.0, 7.0, 0.0), getItemStroke(series, 0), getItemPaint(series, 0)); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getRowKey(series)); result.setSeriesIndex(series); return result; } return null; }
8
private Document _checkResponse(final String response) { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { // Get and parse into a document final DocumentBuilder db = dbf.newDocumentBuilder(); final Document doc = db.parse(new InputSource(new StringReader(response))); // Navigate to the status code and read it. final Element root = doc.getDocumentElement(); final NodeList nl = root.getElementsByTagName("RESPONSE"); String status = "ERROR"; if (nl != null && nl.getLength() > 0) { status = nl.item(0).getAttributes().getNamedItem("STATUS").getNodeValue(); } // Handle error codes accordingly if (status.equals("ERROR")) throw new GracenoteException("API response error."); if (status.equals("NO_MATCH")) throw new GracenoteException("No match response."); if (!status.equals("OK")) throw new GracenoteException("Non-OK API response."); return doc; } catch (final Exception e) { e.printStackTrace(); } return null; }
6
public void setLisState(int num){ if(num == 1){ currentState = LisState.LINE; }else if(num == 2){ currentState = LisState.DRAW; }else if(num == 3){ currentState = LisState.TRIANGLE; }else if(num == 4){ currentState = LisState.ERASE; }else if(num == 5){ currentState = LisState.CIRCLE; }else if(num == 6){ currentState = LisState.SQUARE; }else if(num == 7){ currentState = LisState.TEXT; }else if(num == 8){ currentState = LisState.MAGIC; }else{ currentState = LisState.NONE; } }
8
public void run() { try { boolean running = true; while (running) { try { String line = null; while ((line = _breader.readLine()) != null) { try { _bot.handleLine(line); } catch (Throwable t) { // Stick the whole stack trace into a String so we can output it nicely. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); StringTokenizer tokenizer = new StringTokenizer(sw.toString(), "\r\n"); synchronized (_bot) { _bot.log("### Your implementation of PircBot is faulty and you have"); _bot.log("### allowed an uncaught Exception or Error to propagate in your"); _bot.log("### code. It may be possible for PircBot to continue operating"); _bot.log("### normally. Here is the stack trace that was produced: -"); _bot.log("### "); while (tokenizer.hasMoreTokens()) { _bot.log("### " + tokenizer.nextToken()); } } } } if (line == null) { // The server must have disconnected us. running = false; } } catch (InterruptedIOException iioe) { // This will happen if we haven't received anything from the server for a while. // So we shall send it a ping to check that we are still connected. this.sendRawLine("PING " + (System.currentTimeMillis() / 1000)); // Now we go back to listening for stuff from the server... } } } catch (Exception e) { // Do nothing. } // If we reach this point, then we must have disconnected. try { _socket.close(); } catch (Exception e) { // Just assume the socket was already closed. } if (!_disposed) { _bot.log("*** Disconnected."); _isConnected = false; _bot.onDisconnect(); } }
9
public InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException { Enumeration en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface i = (NetworkInterface) en.nextElement(); for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) { InetAddress addr = (InetAddress) en2.nextElement(); if (!addr.isLoopbackAddress()) { if (addr instanceof Inet4Address) { if (preferIPv6) { continue; } return addr; } if (addr instanceof Inet6Address) { if (preferIpv4) { continue; } return addr; } } } } return null; }
7
public String getImgCodeManual(String url) throws IOException { url = url + RandomUtil.getJSRandomDecimals(); String imageCode = ""; String fileSuffix =".gif"; if(url.contains("CreateCode2")){ fileSuffix =".jpg"; } String fileName = Util.generateUUID() + fileSuffix; // 生成唯一的id String imgDir = "d:/haijia/img"; String comand = "ping " ; //都有的命令 if (OSUtil.getOSType() ==OSUtil.LINUX){ imgDir = SystemConfigurations.getSystemStringProperty("system.img.linux.dir", "/home/wjj/haijia/img"); comand = "eog " ; }else{ imgDir = SystemConfigurations.getSystemStringProperty("system.img.dir", "d:/haijia/img"); comand = "cmd /c start " ; } String storeAddress = imgDir + File.separator + fileName; ByteBuffer bytes = null; // 重试三次 int loop = 0; do { bytes = httpUtil4.getImage(url); loop++; } while (bytes == null && loop < 5); if (bytes != null) { IO.writeByteToFile(bytes, storeAddress); }else{ throw new IOException("download image error!"); } comand += storeAddress; //命令行 Process process = Runtime.getRuntime().exec(comand); int w = 0; try { w = process.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("请输入验证码..."); do { BufferedReader strin2 = new BufferedReader(new InputStreamReader( System.in)); imageCode = strin2.readLine().trim(); System.out.println("输入为:" + imageCode + ";输入错误按R/r,重新下载验证码按D/d,任意键OK"); String command = strin2.readLine().trim().toLowerCase(); if (command.equals("r")) { System.out.println("重新输入..."); continue; }else if(command.equals("d")){ System.out.println("重新下载验证码..."); return null; }else{ break; } } while (true); IO.deleteFile(storeAddress); return imageCode; }
9
public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if (!Task.PROP_DONE.equals(propertyName)) { return; // sca } Task<?, ?> task = (Task<?, ?>) e.getSource(); if (task.isDone()) { List<Task<?, ?>> oldTaskList, newTaskList; synchronized (tasks) { oldTaskList = copyTasksList(); tasks.remove(task); task.removePropertyChangeListener(taskPCL); newTaskList = copyTasksList(); } firePropertyChange(TASKS_PROPERTY, oldTaskList, newTaskList); Task.InputBlocker inputBlocker = task.getInputBlocker(); if (inputBlocker != null) { inputBlocker.unblock(); } } }
9
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(frmParalelo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(frmParalelo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(frmParalelo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(frmParalelo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmParalelo().setVisible(true); } }); }
6
public boolean summon(Familiar familiar) { if (!canSummon(familiar)) { return false; } // Close bank if (ctx.bank.opened()) { ctx.bank.close(); ctx.sleep(500); } final Item pouch = ctx.backpack.shuffle().poll(); if (ctx.hud.open(Hud.Window.BACKPACK)) { ctx.sleep(400); return pouch.valid() && ctx.backpack.scroll(pouch) && pouch.interact("Summon"); } return false; }
5
protected void naughtyCalculation(){ //Enable Naughty Lists Buttons if applicable if(labs.exists()){ ArrayList<Student> studs = new ArrayList<Student>(); for(Student s: output.getFlagged()){ if(s.getFlaggedForLabs()) studs.add(s); } flaggedLabs.setText("Flagged for Labs - " + studs.size()); if(!studs.isEmpty()) flaggedLabsButton.setEnabled(true); else flaggedLabsButton.setEnabled(false); } if(tuts.exists()){ ArrayList<Student> studs = new ArrayList<Student>(); for(Student s: output.getFlagged()){ if(s.getFlaggedForTuts()) studs.add(s); } flaggedTuts.setText("Flagged for Tuts - " + studs.size()); if(!studs.isEmpty()) flaggedTutsButton.setEnabled(true); else flaggedTutsButton.setEnabled(false); } frame.validate(); }
8
public static void main(String[] args) { final String SAT = "sat"; final String UNSAT = "unsat"; int n = 0; LocalSearchSAT lss = new LocalSearchSAT(); File satFolder = new File(SAT); boolean checkSAT = true; for (File file : satFolder.listFiles()) { ClauseSet clauseSet = Parser.get(file); System.out.println("File: " + file.getName()); if (clauseSet != null) { checkSAT = checkSAT && lss.localSearchSat(clauseSet); n++; } } File unsatFolder = new File(UNSAT); boolean checkUNSAT = false; for (File file : unsatFolder.listFiles()) { ClauseSet clauseSet = Parser.get(file); System.out.println("File: " + file.getName()); if (clauseSet != null) { checkUNSAT = checkUNSAT || lss.localSearchSat(clauseSet); n++; } } System.out.println("checked files: " + n); if (checkSAT) { System.out.println("SAT test successfull"); } else { System.out.println("SAT test error"); } if (checkUNSAT) { System.out.println("UNSAT test error"); } else { System.out.println("UNSAT test successfull"); } }
8
public String bestEpToString() { String string = ""; for (HardwareSetAlternative hardwareSetAlternative : hardwareSystem.getHardwareSetAlternatives()) { string += hardwareSetAlternative + " hosts "; for (DeployedComponent deployedComponent : deploymentEP.getDeployedComponents()) if (deployedComponent.getHardwareSet().equals(hardwareSetAlternative.getHardwareSet())) string += deployedComponent.getComponent().getName() + ", "; string = string.substring(0, string.length() - 2) + "\n"; } for (int i = 0; i < consumptionEnergyPoints.length; i++) { String res = "uncalculable\n"; if (consumptionEnergyPoints[i] > 0) res = consumptionEnergyPoints[i] + "EP\n"; string += "FR" + (i + 1) + " = " + res; } return string; }
5
protected double[] missingValueStrategyAggregateNodes(double[] instance, Attribute classAtt) throws Exception { if (classAtt.isNumeric()) { throw new Exception("[TreeNode] missing value strategy aggregate nodes, " + "but class is numeric!"); } double[] preds = null; TreeNode trueNode = null; boolean strategyInvoked = false; int nodeCount = 0; // look at the evaluation of the child predicates for (TreeNode c : m_childNodes) { if (c.getPredicate().evaluate(instance) == Predicate.Eval.TRUE) { // note the first child to evaluate to true if (trueNode == null) { trueNode = c; } nodeCount++; } else if (c.getPredicate().evaluate(instance) == Predicate.Eval.UNKNOWN) { strategyInvoked = true; nodeCount++; } } if (strategyInvoked) { double[] aggregatedCounts = freqCountsForAggNodesStrategy(instance, classAtt); // normalize Utils.normalize(aggregatedCounts); preds = aggregatedCounts; } else { if (trueNode != null) { preds = trueNode.score(instance, classAtt); } else { doNoTrueChild(classAtt, preds); } } return preds; }
7
public void setName(String name) { this.name = name; }
0
public void ViewCountAndCrowdSize(AbstractApi api ) { Search info = new Search(); info.Init(); String tag = api.MainTag; try { String qTable = tag + "questions_table"; String aTable = tag + "answers_table"; info.CreateTemporaryTable(tag, qTable); info.CreateTemporaryRelatedTable(tag, aTable, qTable); Connection conn = info.getConnection(); Statement s = conn.createStatement(); FileWriter fstream = new FileWriter("C:\\method_output.txt"); PrintWriter out = new PrintWriter(fstream); out.println("class,method,accepted,viewCountSum,scoreSum,answerCountSum,commentCountSum,favoriteCountSum,questions"); // WordDistributions wd = new WordDistributions(); for( PackageElem pack : api.Packages ) { System.out.println("Package: " + pack.Name); int counter = 0; for( ClassElem klass : pack.Classes ) { // if (wd.WordLength(klass.Name) == 1) { // continue; // } System.out.println("Class: " + klass.Name + " (" + ++counter + "/" + pack.Classes.size() + ")"); for (MethodElem methodElem : klass.Methods) { List<Integer> methodQuestionIds = info.GetIds(qTable, methodElem.Name); int acceptedAnswers = 0; int viewCounts = 0; int scores = 0; int answerCounts = 0; int commentCounts = 0; int favoriteCounts = 0; for( int id : methodQuestionIds ) { ResultSet question = s.executeQuery( "SELECT * FROM POSTS " + "WHERE Id = " + id ); while (question.next()) { if (question.getInt("AcceptedAnswerId") > 0) { acceptedAnswers++; } viewCounts += question.getInt("ViewCount"); scores += question.getInt("Score"); answerCounts += question.getInt("AnswerCount"); commentCounts += question.getInt("CommentCount"); favoriteCounts += question.getInt("FavoriteCount"); } } out.print(pack.Name + ":" + klass.Name + "," + methodElem.Name + ","); out.print(acceptedAnswers + ","); out.print(viewCounts + ","); out.print(scores + ","); out.print(answerCounts + ","); out.print(commentCounts + ","); out.print(favoriteCounts + ","); out.print(methodQuestionIds.size()); out.println(""); out.flush(); } } } out.close(); } catch (SQLException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } info.Close(); }
8
public void destruct() { if(mySock == null) return; // already shutdown try { misc.println("ClientHandler: Client "+playerName+" disconnected."); disconnected = true; if(in != null) in.close(); if(out != null) out.close(); mySock.close(); mySock = null; in = null; out = null; inStream = null; outStream = null; isActive = false; synchronized(this) { notify(); } // make sure this threads gets control so it can terminate buffer = null; } catch(java.io.IOException ioe) { ioe.printStackTrace(); } super.destruct(); }
4
private String lngTip() { String tt = shrtTip(); if (tt != null) { tt += "\nResource: " + GetResName(); } return tt; }
1
public boolean modifyBookCatalogue(int id, BookCatalogue bc){ if(id != 0){ String sql = "update book_catalogue set name=?, description=? where id=?"; try{ PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, bc.getName()); ps.setString(2, bc.getDescription()); ps.setInt(3, id); ps.executeUpdate(); return true; } catch(SQLException ex){ System.err.println(ex.getMessage()); return false; } } else{ System.err.println("Invalid ID - Not found"); return false; } }
2
public Filter or( Filter other ) { return new Or( this, other ); }
0
private void prepare() { if (prepared) { return; } if (elementConverter == null) { if (classLoader == null && elementClass != null) { classLoader = elementClass.getClassLoader(); } elementConverter = Converters.bestConverter(elementClass, classLoader); } if (compressElement) { elementConverter = new ZipCompressionConverter<E>(elementConverter); } if (memoryManager == null) { if (blockSize == null) { int serializedLength = elementConverter.serializedLength(); blockSize = serializedLength > 0 ? serializedLength : MemoryMappedFileManager.NO_BLOCK_SIZE; } memoryManager = new MemoryMappedFileManager(bufferSize, blockSize); } if (capacity == 0) { capacity = 8; } prepared = true; }
9
Bot(Datamodel datamodel, Link url) { if (Bot.linksFromUrl == -1) { Bot.linksFromUrl = Integer.parseInt(Config.getInstance().get( "LinksFromUrl")); } if (Bot.maxDoLinks == -1) { Bot.maxDoLinks = Integer.parseInt(Config.getInstance().get( "MaxDoLinks")); } if (Bot.maxTextSize == -1) { Bot.maxTextSize = Integer.parseInt(Config.getInstance().get( "MaxTextSize")); } this.url = url; if (Bot.datamodel == null) { Bot.datamodel = datamodel; } // Create a new thread this.t = new Thread(this, url.getUrl()); t.start(); // Start the thread }
4
public Expression negate() { if (getOperatorIndex() == LOG_AND_OP || getOperatorIndex() == LOG_OR_OP) { setOperatorIndex(getOperatorIndex() ^ 1); for (int i = 0; i < 2; i++) { subExpressions[i] = subExpressions[i].negate(); subExpressions[i].parent = this; } return this; } return super.negate(); }
3
@Override public TVC clone() { try { return (TVC) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException("fatal", e); } }
1
public Programmetajs() { }
0
protected static Ptg calcBin2Hex( Ptg[] operands ) { if( operands.length < 1 ) { return new PtgErr( PtgErr.ERROR_NULL ); } debugOperands( operands, "BIN2HEX" ); String bString = operands[0].getString().trim(); int places = 0; if( operands.length > 1 ) { places = operands[1].getIntVal(); } // 10 bits at most if( bString.length() > 10 ) { return new PtgErr( PtgErr.ERROR_NUM ); } // must det. manually if binary string is negative because parseInt does not // handle two's complement input!!! boolean bIsNegative = ((bString.length() == 10) && bString.substring( 0, 1 ).equalsIgnoreCase( "1" )); long dec; String hString; try { dec = Long.parseLong( bString, 2 ); if( bIsNegative ) { dec -= 1024; // 2^10 (= signed 11 bits) } hString = Long.toHexString( dec ).toUpperCase(); } catch( Exception e ) { return new PtgErr( PtgErr.ERROR_NUM ); } if( dec < 0 ) { // truncate to 10 digits automatically (should already be two's complement) hString = hString.substring( Math.max( hString.length() - 10, 0 ) ); } else if( places > 0 ) { if( hString.length() > places ) { return new PtgErr( PtgErr.ERROR_NUM ); } hString = ("0000000000" + hString); // maximum= 10 bits hString = hString.substring( hString.length() - places ); } PtgStr pstr = new PtgStr( hString ); log.debug( "Result from BIN2HEX= " + pstr.getString() ); return pstr; }
9
@DataProvider(name = "group_tests") public Iterator<Object[]> groupCommandsData() throws IOException { CSVReader csvReader = new CSVReader(new FileReader(TESTS_FILENAME)); List<Object[]> commandBlocks = new ArrayList<Object[]>(); CommandDataBuilder builder = new CommandDataBuilder(); // Reading tests List<String[]> data = csvReader.readAll(); List<CommandData> command = new ArrayList<CommandData>(); for (String[] testData : data) { if (testData.length <= 1) { if (command.size() > 0) { commandBlocks.add(new Object[]{command}); command = new ArrayList<CommandData>(); } } else { CommandData commandData = builder.build(testData); command.add(commandData); } } if (command.size() > 0) { commandBlocks.add(new Object[]{command}); } return commandBlocks.iterator(); }
4
public final V get(final K key) { this.querycount++; final HashCounter hc = new HashCounter(key); if (hc.minCounter == 0) return null; Entry<K,V> e = new Entry<K,V>(key); V r = null; if (!pruned) { Integer index = off[hc.mli].indexOf(e); if (index == -1) { this.fpcount++; return r; } r = off[hc.mli].get(index).getV(); } else { try { r = onl[hc.mli].get(onl[hc.mli].indexOf(e)).getV(); } catch (ArrayIndexOutOfBoundsException ax) { try { r = cam.get(e.getK()).getV(); } catch (NullPointerException nx) { this.fpcount++; } } } return r; }
5
@Override public boolean onCommand(final CommandSender sender, Command cmdObj, String label, final String[] args) { if(!(sender instanceof Player)) { return false; } else { if(!((Player)sender).hasPermission("kitpvp.setspawnpoint")) { sender.sendMessage(ChatColor.RED + "You do not have permission to execute this command!"); sender.sendMessage(ChatColor.YELLOW + "(kitpvp.setspawnpoint)"); return true; } if(args.length <= 0 || args.length > 1) { sender.sendMessage(ChatColor.YELLOW + "Usage: /pvpp [1-4]"); return true; } else { Integer point; try { point = Integer.parseInt(args[0]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + args[0] + " is not a valid number!"); return true; } switch(point) { case 1: Main.spawn1 = ((Player)sender).getLocation(); sender.sendMessage(ChatColor.GREEN + "Spawn 1 set!"); break; case 2: Main.spawn2 = ((Player)sender).getLocation(); sender.sendMessage(ChatColor.GREEN + "Spawn 2 set!"); break; case 3: Main.spawn3 = ((Player)sender).getLocation(); sender.sendMessage(ChatColor.GREEN + "Spawn 3 set!"); break; case 4: Main.spawn4 = ((Player)sender).getLocation(); sender.sendMessage(ChatColor.GREEN + "Spawn 4 set!"); break; default: sender.sendMessage(ChatColor.YELLOW + "Usage: /pvpp [1-4]"); return true; } return true; } } }
9
public void setIntArr(TIntArr node) { if(this._intArr_ != null) { this._intArr_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._intArr_ = node; }
3
public void dreheZu(double pWohinH, double pWohinV) { if ((pWohinH != this.zStiftH) || (pWohinV != this.zStiftV)) { if (pWohinH == this.zStiftH) { if (pWohinV > this.zStiftV) this.zWinkel = 270.0D; else this.zWinkel = 90.0D; } else if (pWohinV == this.zStiftV) { if (pWohinH > this.zStiftH) this.zWinkel = 0.0D; else this.zWinkel = 180.0D; } else if (pWohinH > this.zStiftH) { this.zWinkel = (Math.atan((pWohinV - this.zStiftV) / (this.zStiftH - pWohinH)) * 180.0D / 3.141592653589793D); } else { this.zWinkel = (Math.atan((pWohinV - this.zStiftV) / (this.zStiftH - pWohinH)) * 180.0D / 3.141592653589793D + 180.0D); } } while (this.zWinkel < 0.0D) this.zWinkel += 360.0D; while (this.zWinkel >= 720.0D) this.zWinkel -= 360.0D; }
9
@Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Exam other = (Exam) obj; if (mark == null) { if (other.mark != null) { return false; } } else if (!mark.equals(other.mark)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; }
9
public int numOwners(){ int ownerCounter = 0; ArrayList<String> nameOfOwners = new ArrayList<String>(); for(int i = 0; i < listOfUnits.size(); i++){ nameOfOwners.add(listOfUnits.get(i).getOwner().getName()); ownerCounter++; } for(int i = 1; i < nameOfOwners.size(); i++){ for(int j = i; j < nameOfOwners.size(); j++){ if(nameOfOwners.get(i-1).equals(nameOfOwners.get(j))){ ownerCounter--; nameOfOwners.remove(i); } } } return ownerCounter; }
4
public Future<?> execute() { while(!queue.isEmpty()) { checkToInterrupt(); if(future == null || future.isCancelled() || future.isDone()) { callee = queue.poll(); if(callee != null) { future = executor.submit(callee); return future; } } } return future; }
6
private boolean buyBuildingSpecific(Player player , CastleBuilding b) { if (player.getResource(ResourceType.GOLD) > b.cost.gold && player.getResource(ResourceType.WOOD) > b.cost.wood && player.getResource(ResourceType.ORE) > b.cost.ore && !isBuyed()) { player.addResource(ResourceType.GOLD, -b.cost.gold); player.addResource(ResourceType.WOOD, -b.cost.wood); player.addResource(ResourceType.ORE, -b.cost.ore); buyBuilding(b); return true; } return false; }
4
public void asignarABodega() { for(int i=0;i<carros.size();i++) { if(!carros.get(i).getCargado()) { //Creando nuevo Camino[] eliminando el camino a bodega (que est� en la �ltima posici�n) Camino[] nuevo = new Camino[conjuntoCaminos.get(i).length-1]; for(int j=0;j<conjuntoCaminos.get(i).length-1;j++) { nuevo[j]=conjuntoCaminos.get(i)[j]; } //Asignando el nuevo Camino[] al conjunto caminos conjuntoCaminos.remove(i); conjuntoCaminos.add(i,nuevo); } } int eliminados=0; for(int i=0;i<carros.size();i++) { if(carros.get(i).getCargado()) { conjuntoCaminosOptimizados.remove(i); conjuntoCaminosOptimizados.add(i,conjuntoCaminos.get(i-eliminados)[4]); conjuntoCaminos.remove(i-eliminados); eliminados++; } } }
5
public static GbAudio rewriteTo4bitFancy(short[] samples) { int len = samples.length / 2; int[] outSamples = new int[len * 2]; int[] soValues = new int[len]; for (int pos = 0; pos < len; pos++) { int minSoError = Integer.MAX_VALUE; int minSoErrorSo = 0; for (int so = 0; so < 8; so++) { int curSoError = 0; for (int offset = 0; offset < 2; offset++) { int minError = Integer.MAX_VALUE; for (int level = 0; level < 16; level++) { int error = Math.abs(samples[2 * pos + offset] - getSample(level, so)); error *= error; minError = Math.min(minError, error); } curSoError += minError; } if (curSoError < minSoError) { minSoError = curSoError; minSoErrorSo = so; } } for (int offset = 0; offset < 2; offset++) { int minError = Integer.MAX_VALUE; int minErrorLevel = 0; for (int level = 0; level < 16; level++) { int error = Math.abs(samples[2 * pos + offset] - getSample(level, minSoErrorSo)); if (error < minError) { minError = error; minErrorLevel = level; } } outSamples[2 * pos + offset] = minErrorLevel; } soValues[pos] = minSoErrorSo; } return new GbAudio(outSamples, soValues); }
8
public Combo_Box_Remove_Account() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { //MAIN FRAME super("Team J's Scheduler | Remove Account"); setBounds(50,50,500,300); setResizable(false); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLayout(null); setVisible(true); /*LABEL - LNAME_LABEL*/ lname_label.setLayout(null); lname_label.setLocation(20, 10); lname_label.setSize(220,25); add(lname_label); //LAST NAME INPUT BOX lname_input.setLayout(null); lname_input.setLocation(250,10); lname_input.setSize(210,25); add(lname_input); /*LABEL - FNAME_LABEL*/ fname_label.setLayout(null); fname_label.setLocation(20, 40); fname_label.setSize(220,25); add(fname_label); //FIRST NAME INPUT BOX fname_input.setLayout(null); fname_input.setLocation(250,40); fname_input.setSize(210,25); add(fname_input); //REMOVE BUTTON Remove.setLayout(null); Remove.setLocation(150, 230); Remove.setSize(170, 25); Remove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //CLOSE WINDOW WHEN REMOVE BUTTON CLICKED setVisible(false); try { sql_remove_account(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); add(Remove); //Set button to default button to select with enter key getRootPane().setDefaultButton(Remove); }
4
public void test_add_long_long() { assertEquals(567L, iField.add(567L, 0L)); assertEquals(567L + 1234000L, iField.add(567L, 1234L)); assertEquals(567L - 1234000L, iField.add(567L, -1234L)); try { iField.add(LONG_MAX, 1L); fail(); } catch (ArithmeticException ex) {} try { iField.add(1L, LONG_MAX); fail(); } catch (ArithmeticException ex) {} }
2
public Writer write(Writer writer) throws JSONException { try { boolean b = false; int len = length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } }
5
public ROJoystickHandler() { controllers = null; activeControllers = new ArrayList<JInputController>(); }
0
@Override public int compareTo(PriorityItem item) { if(this.priority != item.priority) { return this.priority - item.priority; } if( o instanceof Number) { return(((Number)this.o).intValue() - ((Number)item.o).intValue()); } return 0; }
2
public void parseFile() { Element element = xmlDocument.getDocumentElement(); NodeList nl; getFileName(element); // parse CodeLists from DSD nl = element.getElementsByTagName("CodeLists"); if(nl != null && nl.getLength() > 0) { for(int i = 0 ; i < nl.getLength();i++) { Element ele = (Element)nl.item(i); getAllCodeLists(ele); } } // parse KeyFamilies from DSD nl = element.getElementsByTagName("KeyFamilies"); if(nl != null && nl.getLength() > 0) { for(int i = 0 ; i < nl.getLength();i++) { Element ele = (Element)nl.item(i); getKeyFamilies(ele); } } // parse Concepts from DSD nl = element.getElementsByTagName("Concepts"); if(nl != null && nl.getLength() > 0) { for(int i = 0 ; i < nl.getLength();i++) { Element ele = (Element)nl.item(i); getConcepts(ele); } } produceRDF(); }
9
private void splitDown(ColorPatch patch, int x, int y) { if ( ++y < image.getHeight() ) { Color color = pixel(x, y); if ( isIncluded(x, y) ) { if ( patch.getColor().distance(color, Color.RGB_DISTANCE) < tolerance ) { patch.add(color); goLeft(patch, x, y); goRight(patch, x, y); splitDown(patch, x, y); } } exclude(x, y); } }
3
@Override public void onEnable() { if (getServer().getPluginManager().getPlugin("Vault") == null) { getLogger().severe("Disabling plugin, Vault not found"); getServer().getPluginManager().disablePlugin(this); return; } getCommand("rankup").setExecutor(new RankupCommand(this)); getServer().getPluginManager().registerEvents(new SignListener(this), this); if (!reloadRanks()) { getLogger().log(Level.SEVERE, "Disabling plugin, invalid configuration."); getServer().getPluginManager().disablePlugin(this); return; } if (!reloadTranslations()) { getLogger().log(Level.SEVERE, "Disabling plugin, invalid configuration."); getServer().getPluginManager().disablePlugin(this); return; } // Delay economy and permissions init until after all // plugins are loaded. getServer().getScheduler().runTask(this, new Runnable() { @Override public void run() { try { setupPermissions(); } catch (IllegalStateException e) { getLogger().severe(e.getMessage()); getPluginLoader().disablePlugin(Main.this); return; } try { setupEconomy(); } catch (IllegalStateException e) { getLogger().severe(e.getMessage()); getPluginLoader().disablePlugin(Main.this); } } }); }
5
@EventHandler public void craftingEvent(CraftItemEvent event) { Material mat = event.getRecipe().getResult().getType(); if(mat == Material.IRON_HELMET) helmet = true; if(mat == Material.IRON_CHESTPLATE) chestplate = true; if(mat == Material.IRON_LEGGINGS) leggings = true; if(mat == Material.IRON_BOOTS) boots = true; if(helmet && chestplate && leggings && boots) achieve(); }
8
public String getUserName( ) { return mUserName; }
0
public String getCurrentStatusString() { switch (this.currentStatus) { case NOT_STARTED: return "not started"; case RUNNING: return "running"; case PAUSED: return "paused"; case CANCELLING: return "cancelling"; case CANCELLED: return "cancelled"; case COMPLETED: return "completed"; case FAILED: return "failed"; } return "unknown"; }
7
public void modificar(int id, String valor) { try { PreparedStatement ps = MySQL_Connection.getConection() .prepareStatement("UPDATE producto SET nombre = '" + valor + "' WHERE id = " + id); ps.executeUpdate(); ps.close(); } catch (SQLException ex) { System.out.println("modificar"); } }
1
public static void call(final String mapping, final String data) throws Exception { final File mapFile = new File(mapping); final File dataFile = new File(data); // delimited by a comma // text qualified by double quotes // ignore first record final Parser pzparser = DefaultParserFactory.getInstance().newDelimitedParser(mapFile, dataFile, ',', '\"', true); final DataSet ds = pzparser.parse(); while (ds.next()) { if (ds.isRecordID("header")) { System.out.println(">>>>>>Found Header Record"); System.out.println("COLUMN NAME: RECORDINDICATOR VALUE: " + ds.getString("RECORDINDICATOR")); System.out.println("COLUMN NAME: HEADERDATA VALUE: " + ds.getString("HEADERDATA")); System.out.println("==========================================================================="); continue; } if (ds.isRecordID("trailer")) { System.out.println(">>>>>>Found Trailer Record"); System.out.println("COLUMN NAME: RECORDINDICATOR VALUE: " + ds.getString("RECORDINDICATOR")); System.out.println("COLUMN NAME: TRAILERDATA VALUE: " + ds.getString("TRAILERDATA")); System.out.println("==========================================================================="); continue; } System.out.println("COLUMN NAME: FIRSTNAME VALUE: " + ds.getString("FIRSTNAME")); System.out.println("COLUMN NAME: LASTNAME VALUE: " + ds.getString("LASTNAME")); System.out.println("COLUMN NAME: ADDRESS VALUE: " + ds.getString("ADDRESS")); System.out.println("COLUMN NAME: CITY VALUE: " + ds.getString("CITY")); System.out.println("COLUMN NAME: STATE VALUE: " + ds.getString("STATE")); System.out.println("COLUMN NAME: ZIP VALUE: " + ds.getString("ZIP")); System.out.println("==========================================================================="); } if (ds.getErrors() != null && !ds.getErrors().isEmpty()) { System.out.println("FOUND ERRORS IN FILE"); } }
5
public void processViewCommand(Command action) { // Log a message // FroshProject.getLogger().log(Level.INFO, "Message received from the view : " + action); // Check if the action is set // if (action == null) { return; } // Switch on the possible cases // switch (action) { // Quit the application // case EXIT: System.exit(0); break; // Go to the next day // case NEXTDAY: try { world.processStep(); } catch (FroshProjectException fpe) { handleErrorMessage(fpe); } break; // Initialize the simulation // case INIT: initializeSimulation(); break; // Display statistics // case STATISTICS: world.getStats(); break; // Create a new world // case RESET: initializeSimulation(); } }
7
public ForeignKey getForeignKey(String table, String column) throws SQLException { List<ForeignKey> foreignKeys = this.foreignKeys(); for (ForeignKey fk : foreignKeys) { if (fk.sourceColumn.equals(column) && fk.sourceTable.equals(table)) { return fk; } } return null; }
3
private void key(byte key[]) { int i; int koffp[] = { 0 }; int lr[] = { 0, 0 }; int plen = P.length, slen = S.length; for (i = 0; i < plen; i++) P[i] = P[i] ^ streamtoword(key, koffp); for (i = 0; i < plen; i += 2) { encipher(lr, 0); P[i] = lr[0]; P[i + 1] = lr[1]; } for (i = 0; i < slen; i += 2) { encipher(lr, 0); S[i] = lr[0]; S[i + 1] = lr[1]; } }
3
int dinicDfs(int[] ptr, int[] dist, int dest, int u, int f) { if (u == dest) return f; for (; ptr[u] < ady[u].size(); ++ptr[u]) { Edge e = ady[u].get(ptr[u]); if (dist[e.t] == dist[u] + 1 && e.f < e.cap) { int df = dinicDfs(ptr, dist, dest, e.t, Math.min(f, e.cap - e.f)); if (df > 0) { e.f += df; ady[e.t].get(e.rev).f -= df; return df; } } } return 0; }
5
private void initializeMissions() { // Full debug setup is very different. if (FreeColDebugger.getDebugLevel() >= FreeColDebugger.DEBUG_FULL) return; AIMain aiMain = getAIMain(); // Give the ship a transport mission. TransportMission tm = null; for (AIUnit aiu : getAIUnits()) { Unit u = aiu.getUnit(); if (u.isNaval() && !aiu.hasMission()) { aiu.setMission(tm = new TransportMission(aiMain, aiu)); } } // Find a colony site, give the land units build colony missions, // and add them to the ship's transport mission. Location target = null; for (AIUnit aiu : getAIUnits()) { Unit u = aiu.getUnit(); if (!u.isNaval() && !aiu.hasMission()) { if (target == null) { target = BuildColonyMission.findTarget(aiu, false); } aiu.setMission(new BuildColonyMission(aiMain, aiu, target)); tm.addToTransportList(aiu); } } }
8
public static boolean isSupported() { ContextCapabilities c = GLContext.getCapabilities(); return c.GL_ARB_shader_objects && c.GL_ARB_vertex_shader && c.GL_ARB_fragment_shader; // return c.OpenGL20; }
2
private Map<Integer, Double> getTagRecencies(List<Bookmark> bookmarks) { //Collections.sort(bookmarks); // TODO: necessary? int testIndex = bookmarks.size() + 1; Map<Integer, Integer> firstUsages = new LinkedHashMap<Integer, Integer>(); Map<Integer, Integer> lastUsages = new LinkedHashMap<Integer, Integer>(); Map<Integer, Double> resultMap = new LinkedHashMap<Integer, Double>(); for (int i = 0; i < bookmarks.size(); i++) { for (int tag : bookmarks.get(i).getTags()) { Integer firstIndex = firstUsages.get(tag); Integer lastIndex = lastUsages.get(tag); if (firstIndex == null || i < firstIndex) { firstUsages.put(tag, i); }; if (lastIndex == null || i > lastIndex) { lastUsages.put(tag, i); }; } } for (Map.Entry<Integer, Integer> firstIndex : firstUsages.entrySet()) { double firstVal = Math.log((double)(testIndex - firstIndex.getValue())); double lastVal = Math.log((double)(testIndex - lastUsages.get(firstIndex.getKey()))); Double rec = firstVal * (Math.pow(lastVal, firstVal * (-1.0))); if (!rec.isNaN() && !rec.isInfinite()) { resultMap.put(firstIndex.getKey(), rec.doubleValue()); } } return resultMap; }
9
public void setThickness(int thickness) { this.thickness = thickness; }
0
private void createFullMatchPanel() { LabelPanel.setPreferredSize(new Dimension(450, 35)); LabelPanel.setMaximumSize(new Dimension(20000, 35)); FullPanel.setLayout(new BoxLayout(FullPanel, BoxLayout.Y_AXIS)); JPanel titlePanel = new JPanel(); buildTotalTitlePanel(titlePanel); FullPanel.add(titlePanel); JTabbedPane setPanel = new JTabbedPane(); JScrollPane singleSetScroller = new JScrollPane(); int[][] setInfo = getSetInfo(); if (setInfo == null) return; for (int i = 0; i < setInfo.length; i++) { int firstMatch = setInfo[i][0]; int lastMatch = setInfo[i][1]; JScrollPane scroller = new JScrollPane(); scroller.setPreferredSize(new Dimension(300, 200)); scroller.setMinimumSize(new Dimension(300, 200)); JLabel[] columnHeaders = null; // Add and crop the header panel JPanel headPanel = new JPanel(); scroller.setColumnHeaderView(headPanel); initLayout(headPanel); for (int match = firstMatch; match < lastMatch; match++) { if (match == firstMatch) columnHeaders = buildMatchHeaders(match, headPanel, false, null); buildMatchHistory(match, headPanel, 0); } JViewport headerView = scroller.getColumnHeader(); headerView.setPreferredSize(new Dimension(300, getLargestHeight(columnHeaders)));// columnHeaders // [ // 0 // ] // . // getPreferredSize // ( // ) // . // height // ) // ) // ; int maxRounds = 0; // Add and crop the info panel JPanel infoPanel = new JPanel(); scroller.setViewportView(infoPanel); initLayout(infoPanel); // for (int match = firstMatch; match < lastMatch; match++) { for (int match = lastMatch - 1; match >= 0; match--) { if (match == firstMatch) { buildMatchHeaders(match, infoPanel, true, columnHeaders); } maxRounds += buildMatchHistory(match, infoPanel, maxRounds); } // Add the bottom filler panel JPanel filler = new JPanel(); gridbag.setConstraints(filler, fillerConstraints); infoPanel.add(filler); scroller.getVerticalScrollBar().setMaximum(infoPanel.getPreferredSize().height); //scroller.getVerticalScrollBar().setValue(infoPanel.getPreferredSize().height); if (setInfo.length > 1) setPanel.add("Set " + (i + 1), scroller); else singleSetScroller = scroller; } if (setInfo.length > 1) { FullPanel.add(setPanel); setPanel.setSelectedIndex(setPanel.getComponentCount() - 1); } else FullPanel.add(singleSetScroller); }
8
private void initTileList() { //létrehozza a csempékhez a hozzájuk tartozó nézeteket, majd páronként beteszi őket a drawables Map-be. Tile[][] tiles = geometry.getTiles(); for (int x = 0; x < tiles.length; x++) { for (int y = 0; y < tiles[0].length; y++) { if (tiles[x][y].getType().equals("FieldTile")) { FieldTileView view = new FieldTileView(this, (FieldTile) tiles[x][y]); drawables.put(tiles[x][y], view); } else if (tiles[x][y].getType().equals("PathTile")) { PathTileView view = new PathTileView(this, (PathTile) tiles[x][y]); drawables.put(tiles[x][y], view); } else if (tiles[x][y].getType().equals("EndTile")) { EndTileView view = new EndTileView(this, (EndTile) tiles[x][y]); drawables.put(tiles[x][y], view); } } } }
5
protected void doPadding(byte[] output, int outputOffset) { /* * This is slightly ugly... we need to get the still * buffered data, but the only way to get it from * DigestEngine is to input some more bytes and wait * for the processBlock() call. We set a variable * with the count of actual data bytes, so that * processBlock() knows what to do. */ onlyThis = flush(); if (onlyThis > 0) update(zeroPad, 0, 64 - onlyThis); int olen = tmpOut.length; dig.digest(tmpOut, 0, olen); dig.update(kopad); dig.update(tmpOut); dig.digest(tmpOut, 0, olen); if (outputLength >= 0) olen = outputLength; System.arraycopy(tmpOut, 0, output, outputOffset, olen); }
2
public void keyPressed(KeyEvent e) { int dr=0; if (e.getKeyCode() == KeyEvent.VK_P) { if (pause) pause = false; else pause = true; } /** if (e.getKeyCode() == KeyEvent.VK_M) { if (music) music = false; else music = true; } */ if (!pause) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { dr = -1; } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { dr = 1; } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { if (!pause) rush = true; } else if (e.getKeyCode() == KeyEvent.VK_SPACE) { game.rotatePiece(); } if (dr != 0) { game.movePiece(dr); } } repaintScreen(); }
9
@Override public boolean accept(File file) { return file.isDirectory() || file.getName().endsWith(".cer"); }
1
public boolean click(Level level, Sprite sprite, int x, int y, int button) { if (level.player.carried == null) { level.player.addString("A key is required to use this lock"); return true; } if (!(level.player.carried instanceof ItemKey)) { level.player.addString("A key is required to use this lock"); return true; } if (pressed) { level.player.addString("This lock has already been opened"); return true; } if (level.player.carried instanceof ItemKey) { if (level.player.carried != key) { level.player.addString("The key doesn't turn..."); return true; } else { pressed = !pressed; level.trigger(switchID, pressed); level.player.carried = null; } } return true; }
5
public static <E> E getTypedSelectedItemFromCombo(JComboBox<E> combo) { int index = combo.getSelectedIndex(); return index != -1 ? combo.getItemAt(index) : null; }
1
public void handleRequest(Request toHandle) { int request = toHandle.getRequest(); System.out.println("Handling request: " + request); switch (request) { case 69: theGUI.setTurnCheckBox(true); break; case 98: PopUpStats a = new PopUpStats(toHandle.getHexagonSelected(), toHandle.getRoadNames(), toHandle.getSettlementNames(), this); a.setVisible(true); break; case 99: nameHash = toHandle.getReturnName(); System.out.println("Our hash is " + nameHash); break; case 999: System.out.println("Error: " + toHandle.getMessage()); break; case 1001: System.out.println("Woot."); theGUI = new ClientSideGUIFinal(this, nameHash, toHandle.getMapTypes()); break; case 1002: System.out.println("Updating stats..."); theGUI.updateResourceNumber(toHandle.getResourceStats()); theGUI.setTurnCheckBox(false); theGUI.updateDieRolled(toHandle.getDieRolled()); break; default: System.out.println("Something bad happened."); System.exit(-100); break; } }
6
public SaveFileFormat getExportFormat(String formatName) { int index = indexOfName(formatName, exporterNames); if (index >= 0) { return (SaveFileFormat) exporters.get(index); } return null; }
1
public static final Cursor getCursor() { if (CURRENT_CURSOR == null) { CURRENT_CURSOR = new Origin(NSpace.DEFAULT_NSPACE); } return CURRENT_CURSOR; }
1
public String reverseWords(String s) { if(s.length()==0) return s; String[] arr = s.split(" "); ArrayList<String> aa = new ArrayList<String>(); if(arr.length == 0) return ""; int i =0; while(i<arr.length) { if(!(arr[i].equals(" ")||arr[i].equals(""))) { aa.add(arr[i]); } i++; } if(aa.size()==0) return ""; String ret=aa.get(aa.size()-1); for(i=aa.size()-2;i>-1;i--){ ret = ret+" "+aa.get(i); } return ret; }
7
private boolean inBattle(Territory territory){ if(defender){ if(territory==battle.getDefTerritory()) return true; for(Territory t : battle.defSupport){ if(territory==t) return true; } }else{ if(territory==battle.getAttTerritory()) return true; for(Territory t : battle.attSupport){ if(territory==t) return true; } } return false; }
7
public boolean isWithinCastle(Point point) { int castleY = castle.getPosition().getY(); int castleX = castle.getPosition().getX(); for (int y = castleY; y < castleY + getCastleHeight(); y++ ) { for (int x = castleX; x < castleX + getCastleWidth(); x++ ) { if (point.getX() == x && point.getY() == y) { return true; } } } return false; }
4
public void levelOrder( Method visit ) { ArrayQueue<BinaryTreeNode<T>> q = new ArrayQueue<>( ); BinaryTreeNode<T> t = root; while( t != null ) { try { visit.invoke( null, t ); // visit tree root } catch ( Exception e ) { System.out.println( e ); } // put t's children on queue if( t.leftChild != null ) q.put( t.leftChild ); if( t.rightChild != null ) q.put( t.rightChild ); // get next node to visit t = ( BinaryTreeNode<T> ) q.remove( ); } }
4
private int getBranchOffset(Object to) { Integer label = labels.get(to); if(label == null) { label = 0; // should result in an infinite loop if it is not fixed up ArrayList<Integer> fix = fixup.get(to); if(fix == null) { fix = new ArrayList<Integer>(); fixup.put(to, fix); } // this will be the index of the next instruction emited, // which should be our branch fix.add(code.size()); } return label - code.size(); }
2
@Override public void actionPerformed(ActionEvent action) { // TODO Auto-generated method stub // If click on button ipServer = txtIPServer.getText(); String userName = txtUserName.getText().toString(); int port = Integer.parseInt(txtPort.getText().toString()); if(!checkPortAvailability(port)){ txtPort.setText(""); }else { System.out.println("Port Availability is ok"); try { socket = new Socket(ipServer, portServer); out = new DataOutputStream(socket.getOutputStream()); in = new DataInputStream(socket.getInputStream()); out.writeUTF(Tags.START_SESSION + Tags.PEER_NAME_S + userName + Tags.PEER_NAME_E + Tags.PORT_S + port + Tags.PORT_E + Tags.END_SESSION); out.flush(); String result = in.readUTF(); ProtocolResultFromServer resultFromServer = Communicate.getProtocolResultFromServer(result); if(!resultFromServer.isAccept()){ // TODO: show message box for user enter again }else{ // ACCEPT -> new Main Form // shutdown sign in form setVisible(false); clientContacts = resultFromServer.getClientContacts(); GUIMain gUIMain = new GUIMain(userName, clientContacts, out); gUIMain.setVisible(true); // start OnlineStatusKeepingHandler OnlineStatusKeepingHandler onlineStatusKeepingHandler = new OnlineStatusKeepingHandler(socket, userName, gUIMain); onlineStatusKeepingHandler.start(); //start ServerSocket for listenning ClientListenerHandler listenThread = new ClientListenerHandler(socketListen, userName); listenThread.start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TagFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
5
private void setupVideoListener() { videoListener = new MouseAdapter() { @Override public void mouseMoved(MouseEvent e1){ Canvas videoCanvas = (Canvas) e1.getSource(); VideoPlayer videoPlayer = (VideoPlayer) videoCanvas.getParent().getParent(); int yCoordinate = e1.getY(); videoPlayer.startTimer(); if(!videoPlayer.isPlaying()) { videoPlayer.ControlPanel.setVisible(true); } else { if (yCoordinate > ((videoPlayer.overlayPanel.getHeight())- 80)){ videoPlayer.ControlPanel.setVisible(true); } else { videoPlayer.ControlPanel.setVisible(false); } } layers.setCursor(swordCursor); borderListenerProcess(e1,false,false,true); mouseMovedOnSlide(); } @Override public void mouseClicked(MouseEvent e1){ frame.requestFocusInWindow(); } }; }
2
private boolean modifyClassfile(CtClass clazz, CtClass metaobject, CtClass metaclass) throws CannotCompileException, NotFoundException { if (clazz.getAttribute("Reflective") != null) return false; // this is already reflective. else clazz.setAttribute("Reflective", new byte[0]); CtClass mlevel = classPool.get("javassist.tools.reflect.Metalevel"); boolean addMeta = !clazz.subtypeOf(mlevel); if (addMeta) clazz.addInterface(mlevel); processMethods(clazz, addMeta); processFields(clazz); CtField f; if (addMeta) { f = new CtField(classPool.get("javassist.tools.reflect.Metaobject"), metaobjectField, clazz); f.setModifiers(Modifier.PROTECTED); clazz.addField(f, CtField.Initializer.byNewWithParams(metaobject)); clazz.addMethod(CtNewMethod.getter(metaobjectGetter, f)); clazz.addMethod(CtNewMethod.setter(metaobjectSetter, f)); } f = new CtField(classPool.get("javassist.tools.reflect.ClassMetaobject"), classobjectField, clazz); f.setModifiers(Modifier.PRIVATE | Modifier.STATIC); clazz.addField(f, CtField.Initializer.byNew(metaclass, new String[] { clazz.getName() })); clazz.addMethod(CtNewMethod.getter(classobjectAccessor, f)); return true; }
3
protected static void insertarPrivate(Nodo raiz, int dato) { if((raiz.getAcumulado()+dato) < Arbol.limit) { if(raiz.getOpt1() == null) { raiz.setOpt1(new Nodo(dato)); raiz.getOpt1().setAcumulado(dato + raiz.getAcumulado()); } else if(raiz.getOpt2() == null) { raiz.setOpt2(new Nodo(dato)); raiz.getOpt2().setAcumulado(dato + raiz.getAcumulado()); } else if(raiz.getOpt3() == null) { raiz.setOpt3(new Nodo(dato)); raiz.getOpt3().setAcumulado(dato + raiz.getAcumulado()); } else if(raiz.getOpt4() == null) { raiz.setOpt4(new Nodo(dato)); raiz.getOpt4().setAcumulado(dato + raiz.getAcumulado()); } else if(raiz.getOpt1() != null) Arbol.insertarPrivate(raiz.getOpt1(), dato); else if(raiz.getOpt2() != null) Arbol.insertarPrivate(raiz.getOpt2(), dato); else if(raiz.getOpt3() != null) Arbol.insertarPrivate(raiz.getOpt3(), dato); else if(raiz.getOpt4() != null) Arbol.insertarPrivate(raiz.getOpt4(), dato); } }
9
public void run() { while(true) { try { System.out.println("Producteur : " + this.counter++); this.NEmpty.acquire(); this.NFull.release(); } catch (Exception e) { e.printStackTrace(); } } }
2
public void makePayment(int amount) { this.balance = this.balance - amount; }
0
private void addLockonUPSiteWithVar(int varIndex, Transaction transaction, boolean isWrite) { for(int i: sitesHasVar(varIndex).keySet()) { Site site = sites.get(i); if(!site.isFailed()) { site.addLock(transaction, varIndex, isWrite); } } }
2
private void recommend(String type){ Vector<String> doneProbs = FileUtil.getUserDoneProbs(Context.getUserID()); boolean done[] = new boolean[4000]; for(int i = 0;i < doneProbs.size();i++){ done[Integer.valueOf(doneProbs.get(i)) - 1000] = true; } String[] probs = FileUtil.getProbsOfType("problemType.txt", type); int counter = 0; recommendedProbs.setText(""); for(int i = 0;i < probs.length;i++){ if(!done[Integer.valueOf(probs[i]) - 1000]){ recommendedProbs.append(probs[i] + "\t"); counter++; if(counter >= 6)break; } } if(recommendedProbs.getText() == ""){ recommendedProbs.setText("系统暂时没有该类型的题目推荐给你"); } }
5
public Obuffer decodeFrame(Header header, Bitstream stream) throws DecoderException { if (!initialized) { initialize(header); } int layer = header.layer(); output.clear_buffer(); FrameDecoder decoder = retrieveDecoder(header, stream, layer); decoder.decodeFrame(); output.write_buffer(1); return output; }
1
public static void main(String[] args) { int continuar = 1; do { System.out.println("##################################"); System.out.println("## 1. Ingresar Factura ##"); System.out.println("## 2. Total Ingresos ##"); System.out.println("## 3. Venta Mayor,Venta Menor ##"); System.out.println("## 4. Salir ##"); System.out.println("##################################"); int opcion = LeerT.LeerEnt(); switch (opcion) { case 1: IngresarClientes x = new IngresarClientes(); x.Ingresar(); break; case 2: System.out .println("Total en ventas: " + FuncionesV.VentasDia()); ; break; case 3: System.out.println("Mayor Venta :" + IngresarClientes.MayorV.Cedula + "\t" + IngresarClientes.MayorV.Cliente + "\n Fecha: " + IngresarClientes.MayorV.FechaCompra + "\n Valor: " + IngresarClientes.MayorV.ValorCompra); System.out.println("Menor Venta :" + IngresarClientes.MenorV.Cedula + "\t" + IngresarClientes.MenorV.Cliente + "\n Fecha: " + IngresarClientes.MenorV.FechaCompra + "\n Valor: " + IngresarClientes.MenorV.ValorCompra); break; case 4: continuar = 0; break; default:// nada } } while (continuar == 1); }
5
public int getTripleIndexByPredicate( Vector<Vector<String>> tripleVector, String predicate) { for(int i=0; i<tripleVector.size() ;i++) { Vector<String> t = tripleVector.get(i); if( t != null ) if( t.get(1)!=null && ((String)t.get(1)).equals(predicate)) {return i;} } return -1; }//public String getTripleObjectByPredicate( triple, uris.daysURI) )
4
public JCellule(int x, int y) { this.x = x; this.y = y; r = 255; v = 255; b = 255; this.setBorder(null); }
0