text
stringlengths
14
410k
label
int32
0
9
@Override public void mouseClicked(MouseEvent e) { if(e.getComponent().equals(view.Play)){ try { mode.Play("C:/Users/Dimitris/Downloads/testHY252.mid"); } catch (InvalidMidiDataException | IOException | MidiUnavailableException | InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }else if(e.getComponent().equals(view.Stop)){ mode.Stop(); }else if(e.getComponent().equals(view.Pause)){ try { mode.pause(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }else if(e.getComponent().equals(view.Forward)){ }else if(e.getComponent().equals(view.Backward)){ } }
7
@Override public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if (context == null) { throw new NullPointerException(); } Object result = null; if (isResolvable(base)) { if (params == null) { params = new Object[0]; } String name = method.toString(); Method target = findMethod(base, name, paramTypes, params.length); if (target == null) { throw new MethodNotFoundException("Cannot find method " + name + " with " + params.length + " parameters in " + base.getClass()); } try { result = target.invoke(base, coerceParams(getExpressionFactory(context), target, params)); } catch (InvocationTargetException e) { throw new ELException(e.getCause()); } catch (IllegalAccessException e) { throw new ELException(e); } context.setPropertyResolved(true); } return result; };
7
public boolean sendPacket(String ip, int port, byte[] data) { try { InetAddress serverAddr = InetAddress.getByName(ip); tcpSocket = new Socket(serverAddr, port); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } OutputStream os = null; try { os = tcpSocket.getOutputStream(); os.write(data); os.flush(); tcpSocket.close(); } catch (IOException e) { e.printStackTrace(); } return true; }
3
public boolean validPosition(int a, int b) { return a >= 0 && a < height && b >= 0 && b < width; }
3
public static void main(String[] args) { System.out.println("Enter value of n:"); Scanner scan=new Scanner(System.in); int n=scan.nextInt(); for(int i=0;i<n;i++) { int c=1; for(int j=0;j<n-i;j++) { System.out.print(" "); } for(int k=0;k<=i;k++) { System.out.print(" "+c); c = c * (i - k) / (k+ 1); } System.out.println(); } }
3
private StatInfo doStatsOnDividendSum() { TreeMap<String,Float> lastDividends = new TreeMap<String,Float>(); for(String ticker: dbSet){ lastDividends.put(ticker, 0f); } float[] dividendSums = new float[dbSet.size()]; for (Entry<Float, float[][]> ent : Database.DB_ARRAY.entrySet()) { int i = 0; for (float[] d : ent.getValue()) { String ticker = dbSet.get(i); // 82 is dividends // over reporting because collecting for 2 weeks float lastDiv =lastDividends.get(ticker); if ( lastDiv != d[82]) { DIVIDEND_HISTORY.get(ticker).put(ent.getKey(), d[82]); dividendSums[i] += d[82] ; } lastDividends.put(ticker, d[82]); i++; } } ArrayList<Float> dataArray = new ArrayList<Float>(); for (float f : dividendSums) { dataArray.add(f); } for(int i = 0 ; i<dbSet.size(); i++){ if(dividendSums[i]>0) System.out.println(dbSet.get(i)+" dividends: "+dividendSums[i]); } return new StatInfo(dataArray, true); }
7
protected void consumeMethodHeaderName(boolean isAnonymous) { // MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' // AnnotationMethodHeaderName ::= Modifiersopt Type 'Identifier' '(' // RecoveryMethodHeaderName ::= Modifiersopt Type 'Identifier' '(' MethodDeclaration md = null; // if(isAnnotationMethod) { // md = new AnnotationMethodDeclaration(this.compilationUnit.compilationResult); // this.recordStringLiterals = false; // } else { md = new MethodDeclaration(this.compilationUnit.compilationResult); // } md.exprStackPtr=this.expressionPtr; //name long selectorSource =-1; if (!isAnonymous) { md.selector = this.identifierStack[this.identifierPtr]; selectorSource = this.identifierPositionStack[this.identifierPtr--]; this.identifierLengthPtr--; } if (this.nestedType>0) markEnclosingMemberWithLocalType(); //type // md.returnType = getTypeReference(this.intStack[this.intPtr--]); //modifiers int functionPos = this.intStack[this.intPtr--]; int modifierPos = this.intStack[this.intPtr--]; md.declarationSourceStart = (functionPos>modifierPos)? modifierPos:functionPos; md.modifiers = this.intStack[this.intPtr--]; // consume annotations // int length; // if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { // System.arraycopy( // this.expressionStack, // (this.expressionPtr -= length) + 1, // md.annotations = new Annotation[length], // 0, // length); // } // javadoc md.javadoc = this.javadoc; this.javadoc = null; //highlight starts at selector start if (selectorSource>=0) md.sourceStart = (int) (selectorSource >>> 32); else md.sourceStart=md.declarationSourceStart; pushOnAstStack(md); md.sourceEnd = this.lParenPos; md.bodyStart = this.lParenPos+1; this.listLength = 0; // initialize this.listLength before reading parameters/throws incrementNestedType(); // recovery if (this.currentElement != null){ if (this.currentElement instanceof RecoveredType //|| md.modifiers != 0 || true/* (this.scanner.getLineNumber(md.returnType.sourceStart) == this.scanner.getLineNumber(md.sourceStart))*/){ this.lastCheckPoint = md.bodyStart; this.currentElement = this.currentElement.add(md, 0); this.lastIgnoredToken = -1; } else { this.lastCheckPoint = md.sourceStart; this.restartRecovery = true; } } }
7
public static boolean isBlockSeparator(String s) { if (s.startsWith("--") && s.endsWith("--")) { return true; } if (s.startsWith("==") && s.endsWith("==")) { return true; } if (s.startsWith("..") && s.endsWith("..")) { return true; } if (s.startsWith("__") && s.endsWith("__")) { return true; } return false; }
8
public void update(Long id, String title, String message) { try { utx.begin(); } catch (NotSupportedException e) { e.printStackTrace(); } catch (SystemException e) { e.printStackTrace(); } Message msg = em.find(Message.class, id); msg.setTitle(title); msg.setMessage(message); em.merge(msg); try { utx.commit(); } catch (RollbackException e) { e.printStackTrace(); } catch (HeuristicMixedException e) { e.printStackTrace(); } catch (HeuristicRollbackException e) { e.printStackTrace(); } catch (SystemException e) { e.printStackTrace(); } }
6
public String[] getResourceListing(String path) throws URISyntaxException, IOException { URL dirURL = getClass().getClassLoader().getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) { return new File(dirURL.toURI()).list(); } if (dirURL == null) { String me = getClass().getName().replace(".", "/") + ".class"; dirURL = getClass().getClassLoader().getResource(me); } if (dirURL.getProtocol().equals("jar")) { String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); Set<String> result = new HashSet<String>(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(path)) { String entry = name.substring(path.length()); int checkSubdir = entry.indexOf("/"); if (checkSubdir >= 0) { entry = entry.substring(0, checkSubdir); } result.add(entry); } } return result.toArray(new String[result.size()]); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }
7
public void setObject( Object o ) { if( o instanceof GraphicFrame ) { graphicFrame = (GraphicFrame) o; } else if( o instanceof Pic ) { pic = (Pic) o; } else if( o instanceof Sp ) { sp = (Sp) o; } else if( o instanceof CxnSp ) { cxnSp = (CxnSp) o; } else if( o instanceof GrpSp ) { grpSp = (GrpSp) o; } }
5
private void siirryAlemmalleSuoritustasolle(int prioriteetti) { asetaJonoonArvollinen(); while (suoritustasot.size() > prioriteetti) { nykyinenJono().paataJono(); suoritustasot.remove(suoritustasot.size() - 1); } }
1
@Override public void loadFromString(String contents) throws InvalidConfigurationException { Preconditions.checkNotNull(contents, "Contents cannot be null"); Map<?, ?> input; try { input = (Map<?, ?>) yaml.load(contents); } catch (YAMLException e) { throw new InvalidConfigurationException(e); } catch (ClassCastException e) { throw new InvalidConfigurationException("Top level is not a Map."); } String header = parseHeader(contents); if (header.length() > 0) { options().header(header); } if (input != null) { convertMapsToSections(input, this); } }
8
public List<User> DisplayAllUsers (){ List<User> listeUsers = new ArrayList<>(); String requete = "select * from User"; try { Statement statement = MyConnection.getInstance().createStatement(); ResultSet resultat = statement.executeQuery(requete); while(resultat.next()){ User user =new User(); user.setId(resultat.getInt(1)); user.setLogin(resultat.getString(2)); user.setPassword(resultat.getString(3)); user.setLastName(resultat.getString(4)); user.setFirstName(resultat.getString(5)); user.setSexe(resultat.getString(6)); user.setAddress(resultat.getString(7)); user.setEmail(resultat.getString(8)); user.setDateB(resultat.getDate(9)); user.setCity(resultat.getString(10)); user.setImg(resultat.getString(11)); user.setRank(resultat.getInt(12)); user.setDateI(resultat.getDate(13)); user.setBlocked(resultat.getBoolean(14)); listeUsers.add(user); } return listeUsers; } catch (SQLException ex) { //Logger.getLogger(PersonneDao.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Error : "+ex.getMessage()); return null; } }
2
public OperatingSeat getSeat() { return this._seat; }
0
@Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child for(ListIterator<PExp> i = this._exp_.listIterator(); i.hasNext();) { if(i.next() == oldChild) { if(newChild != null) { i.set((PExp) newChild); newChild.parent(this); oldChild.parent(null); return; } i.remove(); oldChild.parent(null); return; } } throw new RuntimeException("Not a child."); }
3
protected void calculateOCGroupDist(ArrayList<Group> gs, ArrayList<Graph.OpinionCluster> ocSet, int agentpool) { int numGroups = 0; //numClusters = ocSet.size(); for(Group g: gs) if(g.getAgents().size() > 0) numGroups++; int ocPos; double[] ocTrial = new double[ocGroupAverageSet.length]; for(Group g: gs) { for(Graph.OpinionCluster o : ocSet) { ocPos = (int) Math.round(o.opVal*(ocGroupAverageSet.length-1)); ocTrial[ocPos] += (double)1 / numGroups; } } for(int i = 0; i < ocTrial.length; i++) { //ocTrial[i]; ocGroupAverageSet[i] += ocTrial[i] / Constants._trials; } }
5
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.name).append(" :=").append(NEWLINE); for(int i=0; i<this.predicates.size(); i++) { sb.append("\t").append(this.predicates.get(i)); if(i < this.predicates.size() - 1) { sb.append(",").append(NEWLINE); } } sb.append("."); return sb.toString(); }
2
public int read(char[] cbuf, int off, int len) throws IOException { int readAhead = 0; int read = 0; int pos = off; char[] readAheadBuffer = new char[BUFFER_SIZE]; boolean available = true; while (available && read < len) { available = super.read(readAheadBuffer, readAhead, 1) == 1; if (available) { char c = processChar(readAheadBuffer[readAhead]); if (state == STATE_START) { // replace control chars with space if (Utils.isControlChar(c)) { c = ' '; } cbuf[pos++] = c; readAhead = 0; read++; } else if (state == STATE_ERROR) { unread(readAheadBuffer, 0, readAhead + 1); readAhead = 0; } else { readAhead++; } } else if (readAhead > 0) { // handles case when file ends within excaped sequence unread(readAheadBuffer, 0, readAhead); state = STATE_ERROR; readAhead = 0; available = true; } } return read > 0 || available ? read : -1; }
9
@EventHandler public void onArenaPlayerDeath(PADeathEvent e){ FileConfiguration config = Main.getConfig(); Player p = e.getPlayer(); HashSet<ArenaTeam> Teams = e.getArena().getTeams(); for (ArenaTeam team : Teams) { HashSet<ArenaPlayer> Players = team.getTeamMembers(); for (ArenaPlayer ap : Players) { Player cap = ap.get(); if (cap.getDisplayName().equalsIgnoreCase(p.getDisplayName())){ if (team.getName().equalsIgnoreCase(config.getString("PVPArena.BlueTeamName"))) { BroadcastChannel c = Main.getRedstoneChips().getChannelManager().getChannelByName(config.getString("PVPArena.BlueChannel"), false); c.transmit(true, 0); c.transmit(false, 0); } else if (team.getName().equalsIgnoreCase(config.getString("PVPArena.RedTeamName"))) { BroadcastChannel c = Main.getRedstoneChips().getChannelManager().getChannelByName(config.getString("PVPArena.RedChannel"), false); c.transmit(true, 0); c.transmit(false, 0); } else { Main.getLogger().info("Team " + team.getName() + " is unknown."); } return; } } } Main.getLogger().info("Player " + p.getDisplayName() + " was in no Team."); }
5
public void award_bonus(BigInteger threshold, BigInteger bonus) { if (getBalance().compareTo(threshold) >= 0) deposit(bonus); }
1
private int getLoginStatus(String username) { try { // Fisrt test is for Employee loginStatus.setString(1, username); resultSet = loginStatus.executeQuery(); while(resultSet.next()) { status = resultSet.getString("FirstLog"); } if("Y".equals(status)) { System.out.println("three"); return 0; }else if("N".equals(status)) { System.out.println("four"); return 1; }else { // Not an Employee cust_loginStatus.setString(1, username); resultSet = cust_loginStatus.executeQuery(); while(resultSet.next()) { status = resultSet.getString("FirstLog"); } if("Y".equals(status)) { return 0; // First login for a Customer }else { return 1; // Not first login for a Customer } } }catch(SQLException sqlE) { return sqlE.getErrorCode(); }finally { try{ if(resultSet != null) resultSet.close(); }catch(Exception e) { } } }
8
private static void inspect(Object objects){ System.out.println(objects.getClass().getSimpleName()); if(objects instanceof String){ System.out.println("String"); } if (objects instanceof Car){ System.out.println("Car"); } if (objects instanceof Vehicle){ System.out.println("Vehcle"); } if (objects.getClass() == Car.class){ System.out.println("car class"); } if (objects.getClass() == Vehicle.class){ System.out.println("car class"); } }
5
public void addCardtoHand(Card x){ hand.add(x); }
0
protected void processKSFile(File file) throws IOException { soundPlaying = false; super.processKSFile(file, RouteParser.scenarioFileRename(this, file.getName())+".ks"); if (lang != Language.EN) { //Postprocess: remove blank lines and merge lines that belong to a single sentence StringBuilder sb = new StringBuilder(); StringBuilder string = new StringBuilder(); String path = createOutputPath(file.getName()); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8")); String line; while ((line = in.readLine()) != null) { if (line.startsWith("text ")) { String textPart = line.substring(5).trim(); if (textPart.length() > 0 && textPart.charAt(0) == 0x3000) { if (string.length() > 0) { sb.append("text "); sb.append(string); sb.append("\n"); string.delete(0, string.length()); } } string.append(textPart); } else { if (string.length() > 0) { sb.append("text "); sb.append(string); sb.append("\n"); string.delete(0, string.length()); } sb.append(line); sb.append("\n"); } } in.close(); FileUtil.write(new File(path), sb.toString()); } }
7
public static boolean Edward() { double proc = Math.random(); if (proc < 0.2) return true; else return false; }
1
public String[] completeName(String part) { Vector<String> ret = new Vector<String>(); if (part.startsWith("_")) { ret = CodeCompletionUtils.complete(abbrs, part); } else if (part.endsWith("(")) { ret = CodeCompletionUtils.complete(part, interpreter, commands, ext_commands); } else if (part.contains(".")) { ret = CodeCompletionUtils.complete(part, interpreter); } else { for (String temp : commands.keySet()) if (temp.startsWith(part)) ret.add(temp); for (String temp : ext_commands.keySet()) if (temp.startsWith(part)) ret.add(temp); } String[] res = new String[ret.size()]; for (int i = 0; i < ret.size(); i++) res[i] = ret.get(i); return res; }
8
protected void initFields() { if (fieldByName == null) { if (fieldStr == null) fieldStr = guessFields(); // No fields data? guess them. fieldNames = fieldStr.split("" + FIELD_NAME_SEPARATOR); fieldByName = new HashMap<String, Field>(); for (String fname : fieldNames) { try { if (!fname.isEmpty()) { Field field = this.getClass().getField(fname); fieldByName.put(fname, field); } } catch (NoSuchFieldException e) { throw new RuntimeException("Error: Field '" + fname + "' not found for class '" + this.getClass().getCanonicalName() + "' (may be the fields is not public?)"); } } } }
5
public void setupGame() { Dealer dealer = new Dealer(); Scanner input = new Scanner(System.in); System.out.println("How many players will be playing?"); while (!input.hasNextInt()) { System.out.println("Please enter a number!"); input.nextLine(); } numOfPlayers = input.nextInt(); addPlayers(numOfPlayers); gameTable = gameFactory.createTable(dealer, this.users); if (!gameTable.isSetUp) { gameTable.setupTable(); } }
2
public BBZoomLevelHeader getZoomLevelHeader(int level) { if(level < 1 || level > zoomLevelsCount) return null; return zoomLevelHeaders.get(level - 1); }
2
private static void printBoatTable(ArrayList<ParkerPaulTaxable> taxables) { double totalTaxes = 0.00; // total taxes for items double minTaxes = -1.00; // min taxes for items double maxTaxes = 0.00; // max taxes for items int count = 0; // count of items printBoatHeader(); for (ParkerPaulTaxable taxable : taxables) { if ((taxable instanceof ParkerPaulBoat)) { // accumulate footer values double tax = taxable.getTax(); // tax for item totalTaxes += tax; minTaxes = getMinTax(minTaxes, tax); maxTaxes = Math.max(maxTaxes, tax); count++; // print info for item printBoatInfo((ParkerPaulBoat) taxable, count); } } printFooter(totalTaxes, minTaxes, maxTaxes, count); }
2
public void setUsername(String username) { this.username = username; }
0
public BoyerMoore(String pattern, int R) { this.pattern = pattern; int M = pattern.length(); // initialize skip table right = new int[R]; for (int i = 0; i < R; i++) right[i] = -1; for (int j = 0; j < M; j++) right[pattern.charAt(j)] = j; }
2
public static File getGameDirectory(int serverIndex){ return new File(getWorkingDirectory(), Settings.serverNames[serverIndex]); }
0
private void createFile(){ menuFile = new JMenu("File"); menuFile.setMnemonic('I'); menuBar.add(menuFile); //this is is really important. it fixes a bug. //when in full screen mode on 2nd monitor the JMenu appears on the wrong //monitor if the x location isn't specified menuFile.setMenuLocation(0, 50); // Open File menu item - will allow user to open presentation menuItem = new JMenuItem("Open File"); menuItem.setMnemonic('O'); menuItem.setAccelerator(KeyStroke.getKeyStroke('O', Event.CTRL_MASK, false)); Action openFile = new AbstractAction(){ /** * */ private static final long serialVersionUID = -773596484807490150L; public void actionPerformed(ActionEvent e) { //Test Case to confirm Open File Click if(Debug.menu)System.out.println("Open File"); SafetyNet.findPresentation(false); } }; menuItem.addActionListener(openFile); menuFile.add(menuItem); // Opens URL menu Item - allows user to open a Remote Presentation menuItem = new JMenuItem("Open Location"); menuItem.setMnemonic('U'); menuItem.setAccelerator(KeyStroke.getKeyStroke('U', Event.CTRL_MASK, false)); Action openLocation = new AbstractAction(){ ; /** * */ private static final long serialVersionUID = -4415857728921158044L; public void actionPerformed(ActionEvent e) { //Test Case to confirm Open Location Click if(Debug.menu)System.out.println("Open Location"); SafetyNet.findPresentation(enabled); } }; menuItem.addActionListener(openLocation); menuFile.add(menuItem); // Open Previous slide Show - allows user to resume previous presentation menuItem = new JMenuItem("Open Previous"); menuItem.setMnemonic('P'); menuItem.setAccelerator(KeyStroke.getKeyStroke('P', Event.CTRL_MASK, false)); Action openPrevious = new AbstractAction(){ /** * */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { //Test Case to confirm Open Previous Click if(Debug.menu)System.out.println("Open Previous"); SafetyNet.resumePrevious(); } }; menuItem.addActionListener(openPrevious); menuFile.add(menuItem); menuFile.add(new JSeparator()); // Menu Item - resets the quiz data in current presentation // QuizHandler Class doesn't exist in this package yet // When it does the action performed can be uncommented out. menuItem = new JMenuItem("Reset Quiz"); menuItem.setMnemonic('R'); menuItem.setAccelerator(KeyStroke.getKeyStroke('R', Event.CTRL_MASK, false)); Action resetQuiz = new AbstractAction(){ private static final long serialVersionUID = 1L; /** * Method called when action is performed * * @param e is the ActionEvent. */ public void actionPerformed(ActionEvent e) { //Test Case to confirm Reset Quiz Click if(Debug.menu) System.out.println("Reset Quiz"); // reset quiz data QuizHandler.resetQuizData(); // clear slide screen now SlideRenderer.hideAll(); SlideRenderer.clearEntities(); // Update the Gui components Gui.getSectionNav().updateTree(); // Re render the slide Engine.playSlideshow(); }}; menuItem.addActionListener(resetQuiz); menuFile.add(menuItem); // Product Store Menu Item - will open the product store // calling browerloaded menuItem = new JMenuItem("Product Store"); menuItem.setMnemonic('S'); menuItem.setAccelerator(KeyStroke.getKeyStroke('S', Event.CTRL_MASK, false)); Action openProductStore = new AbstractAction(){ private static final long serialVersionUID = 1L; /** * Method called when action performed. * * @param e is the ActionEvent. */ public void actionPerformed(ActionEvent e) { //Test Case to confirm product Store Click if(Debug.menu)System.out.println("Product Store"); // TODO update the Product store url BrowserLoader.openURL("http://www.voltnet.co.uk/tour/store"); }}; menuItem.addActionListener(openProductStore); menuFile.add(menuItem); menuFile.add(new JSeparator()); /** program exit */ Action programExitAction = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent ae) { if(null != SafetyNet.getFileLocation()) Config.saveData(); System.exit(0); } }; menuItem = new JMenuItem("Exit"); menuItem.setMnemonic('x'); menuItem.addActionListener(programExitAction); menuItem.setAccelerator(KeyStroke.getKeyStroke('X', Event.CTRL_MASK, false)); menuFile.add(menuItem); }
6
public void writeLine(String line) throws IOException { String now = DATE_FORMAT.get().format(new Date()); if (line.indexOf('\n') >= 0 && line.indexOf('\n') < line.length() - 1) { write((String.format("%s\t\t%s:\n", now, name)).getBytes()); for (String l : line.split("[\\r\\n]+")) { write((String.format("%s\t\t%s\n", now, l)).getBytes()); } } else { write((String.format("%s\t\t%s: %s%s", now, name, line, line.endsWith("\n") ? "" : "\n")).getBytes()); } }
4
@Override public void run() { long t = System.currentTimeMillis(); while (!salir) { if (data.size() > 0) { gui.printEcualizer(data.get(0)); long n = temp.get(0); data.remove(0); temp.remove(0); try { long espera = n - (System.currentTimeMillis() - t); if (espera > 0) { sleep(espera); } } catch (InterruptedException ex) { Logger.getLogger(Equalizer.class.getName()).log(Level.SEVERE, null, ex); } } else { try { sleep(50); } catch (InterruptedException ex) { Logger.getLogger(Equalizer.class.getName()).log(Level.SEVERE, null, ex); } } } }
5
private void generateBlock(int BlockID) { switch (BlockID) { case 0: generateIBlock(); break; case 1: generateLBlock(); break; case 2: generateOBlock(); break; case 3: generateFBlock(); case 4: generateSBlock(); default: break; } }
5
public static String eventuallyRemoveStartingAndEndingDoubleQuote(String s) { if (s.length() > 1 && isDoubleQuote(s.charAt(0)) && isDoubleQuote(s.charAt(s.length() - 1))) { return s.substring(1, s.length() - 1); } if (s.startsWith("(") && s.endsWith(")")) { return s.substring(1, s.length() - 1); } if (s.startsWith("[") && s.endsWith("]")) { return s.substring(1, s.length() - 1); } if (s.startsWith(":") && s.endsWith(":")) { return s.substring(1, s.length() - 1); } return s; }
9
public int calMaxPathSum(TreeNode root, int sum) { if (root == null) return sum; int leftSum = calMaxPathSum(root.left, sum); int rightSum = calMaxPathSum(root.right, sum); if (sum < 0) sum = root.val; int maxSumWithCurNode = root.val; if (rightSum > 0) maxSumWithCurNode += rightSum; if (leftSum > 0) maxSumWithCurNode += leftSum; if (leftSum > rightSum && leftSum > 0) sum += leftSum; else if (leftSum <= rightSum && rightSum > 0) sum += rightSum; if (maxSumWithCurNode > max) max = maxSumWithCurNode; return sum; }
9
@Override public DialogFX build() { final DialogFX CONTROL = new DialogFX(); for (String key : properties.keySet()) { if ("buttonsLabels".equals(key)) { CONTROL.addButtons(((ObjectProperty<List<String>>) properties.get(key)).get()); } else if ("buttonsLabels1".equals(key)) { CONTROL.addButtons(((ObjectProperty<List<String>>) properties.get(key)).get(), ((IntegerProperty) properties.get("buttonsDefaultButton")).get(), ((IntegerProperty) properties.get("buttonsCancelButton")).get()); } else if ("type".equals(key)) { CONTROL.setType(((ObjectProperty<DialogFX.Type>) properties.get(key)).get()); } else if ("message".equals(key)) { CONTROL.setMessage(((StringProperty) properties.get(key)).get()); } else if ("modal".equals(key)) { CONTROL.setModal(((BooleanProperty) properties.get(key)).get()); } else if ("titleText".equals(key)) { CONTROL.setTitleText(((StringProperty) properties.get(key)).get()); } else if ("stylesheet".equals(key)) { CONTROL.addStylesheet(((StringProperty) properties.get(key)).get()); } } return CONTROL; }
8
public static ServerAddress func_78860_a(String par0Str) { if (par0Str == null) { return null; } String as[] = par0Str.split(":"); if (par0Str.startsWith("[")) { int i = par0Str.indexOf("]"); if (i > 0) { String s1 = par0Str.substring(1, i); String s2 = par0Str.substring(i + 1).trim(); if (s2.startsWith(":") && s2.length() > 0) { s2 = s2.substring(1); as = new String[2]; as[0] = s1; as[1] = s2; } else { as = new String[1]; as[0] = s1; } } } if (as.length > 2) { as = new String[1]; as[0] = par0Str; } String s = as[0]; int j = as.length <= 1 ? 25565 : func_78862_a(as[1], 25565); if (j == 25565) { String as1[] = func_78863_b(s); s = as1[0]; j = func_78862_a(as1[1], 25565); } return new ServerAddress(s, j); }
8
@Override public Token parse() { Token next = first.getNext(); if (!next.isOperator(Operator.BRACKET_LEFT)) throw new RuntimeException("Expected '(' after WHILE, found: " + next); next = next.getNext(); testExp = new BooleanExpression(next, scope); next = testExp.parse(); if (!next.isOperator(Operator.BRACKET_RIGHT)) throw new RuntimeException("Expected ')' after WHILE condition, found: " + next); next = next.getNext(); if (!next.isNewline()) throw new RuntimeException("Expected newline, found: " + next); next = next.getNext(); Keyword[] target = { Keyword.END }; statements = new StatementGroup(next, target, scope); next = statements.parse(); return next.getNext(); }
3
@Override protected void setColoredExes() { // TODO Auto-generated method stub ParametricCurve ermit = new ErmitCurve(allex); coloredEx = ermit.Calculation(); }
0
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(Ajouter_cour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Ajouter_cour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Ajouter_cour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Ajouter_cour.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 Ajouter_cour().setVisible(true); } }); }
6
public void applyRemovals(){ for (Body b : bodiesToRemove){ if (b != null) { if (b.getUserData() != null){ Entity e = (Entity) b.getUserData(); if(cam.getFocus().equals(e)) cam.removeFocus(); objects.remove(e); //ensures player still has access to the character //after hitting "repsawn" if(e.equals(character)) addObject((Entity) e); else e.dispose(); world.destroyBody(b); } } } bodiesToRemove.clear(); for(Particle p : ptclsToRemove) p.dispose(); particles.removeAll(ptclsToRemove); ptclsToRemove.clear(); }
6
public void rebondProjectilesStructuresLoop() { for (int j = 0; j < module.getListStructures().size(); j++) { for (int i = 0; i < module.getListProjectiles().size(); i++) { rebondProjectilesStructures(module.getListProjectiles().get(i), module.getListStructures().get(j)); } } }
2
public void setAccounting(Accounting accounting) { setAccounts(accounting == null ? null : accounting.getAccounts()); setAccountTypes(accounting == null ? null : accounting.getAccountTypes()); setJournals(accounting == null ? null : accounting.getJournals()); }
3
private long getDaysFromSeconds(long seconds) { return seconds / SECONDS_IN_A_DAY; }
0
void setPickingStyle() throws ScriptException { checkLength34(); boolean isMeasure = (statement[2].tok == Token.monitor); String str = null; Token token = statement[statementLength - 1]; int tok = token.tok; switch (tok) { case Token.none: case Token.off: str = (isMeasure ? "measureoff" : "toggle"); break; case Token.on: if (!isMeasure) invalidArgument(); str = "measure"; break; } try { if (str == null) str = (String) token.value; } catch (Exception e) { invalidArgument(); } if (JmolConstants.GetPickingStyle(str) < 0) invalidArgument(); viewer.setStringProperty("pickingStyle", str); }
8
private void postPlugin(final boolean isPing) throws IOException { // The plugin's description file containg all of the plugin data such as name, version, author, etc final PluginDescriptionFile description = plugin.getDescription(); // Construct the post data final StringBuilder data = new StringBuilder(); data.append(encode("guid")).append('=').append(encode(guid)); encodeDataPair(data, "version", description.getVersion()); encodeDataPair(data, "server", Bukkit.getVersion()); encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)); encodeDataPair(data, "revision", String.valueOf(REVISION)); // If we're pinging, append it if (isPing) { encodeDataPair(data, "ping", "true"); } // Acquire a lock on the graphs, which lets us make the assumption we also lock everything // inside of the graph (e.g plotters) synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); // Because we have a lock on the graphs set already, it is reasonable to assume // that our lock transcends down to the individual plotters in the graphs also. // Because our methods are private, no one but us can reasonably access this list // without reflection so this is a safe assumption without adding more code. for (Plotter plotter : graph.getPlotters()) { // The key name to send to the metrics server // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME final String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); // The value to send, which for the foreseeable future is just the string // value of plotter.getValue() final String value = Integer.toString(plotter.getValue()); // Add it to the http post data :) encodeDataPair(data, key, value); } } } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(plugin.getDescription().getName()))); // Connect to the website URLConnection connection; // Mineshafter creates a socks proxy, so we can safely bypass it // It does not reroute POST requests so we need to go around it if (isMineshafterPresent()) { connection = url.openConnection(Proxy.NO_PROXY); } else { connection = url.openConnection(); } connection.setDoOutput(true); // Write the data final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data.toString()); writer.flush(); // Now read the response final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final String response = reader.readLine(); // close resources writer.close(); reader.close(); if (response == null || response.startsWith("ERR")) { throw new IOException(response); // Throw the exception } else { // Is this the first update this hour? if (response.contains("OK This is your first update this hour")) { synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); for (Plotter plotter : graph.getPlotters()) { plotter.reset(); } } } } } // if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right }
9
public void listRecordByPrescribedDate(String start_date, String end_date, int employee_no) { String selectQuery = "SELECT r.PATIENT_NO, t.TEST_NAME, p.NAME, r.PRESCRIBE_DATE " + "FROM TEST_RECORD r, PATIENT p, TEST_TYPE t " + "WHERE r.PATIENT_NO = p.HEALTH_CARE_NO " + "AND r.TYPE_ID = t.TYPE_ID " + "AND r.PRESCRIBE_DATE BETWEEN TO_DATE('" + start_date + "','DD/MM/YYYY') " + "AND TO_DATE('" + end_date + "','DD/MM/YYYY') " + "AND r.EMPLOYEE_NO =" + employee_no; try { rs = stmt.executeQuery(selectQuery); System.out .println("PATIENT NO \t TEST NAME \t\t\t PATIENT NAME \t\t PRESCRIBE DATE"); while (rs.next()) { System.out .println(rs.getInt(1) + "\t\t" + rs.getString(2) + "\t\t\t" + rs.getString(3) + "\t\t\t" + rs.getDate(4)); } } catch (SQLException e) { System.out.println("Could not execute the query."); } }
2
private List<CompositeState<TransitionInput>> collectCompositeStates(State<TransitionInput> state) { List<CompositeState<TransitionInput>> composites = new ArrayList<>(); for(CompositeState<TransitionInput> composite : state.getComposites()) { int insertionPosition = composites.size(); while(composite != null) { composites.add(insertionPosition,composite); composite = composite.getParent(); } } return composites; }
2
@Override public void setDbConnString(String dbconnstring) { this.dbconnstring = dbconnstring; }
0
public void envoyerDonnee(String donnee) { try { outStream.writeUTF(donnee); } catch(IOException ioe) { System.out.println(ioe); } }
1
private void loopUntilShutdown() throws Exception { while (true) { byte[] incoming = receive(); MessageHandler handler = new MessageHandler(incoming); if (handler.isShutdownMessage()) break; byte[] outgoing = handler.createResponseMessage(); reply(outgoing); } }
2
public void initialise() { // Instantiate a vector of TreeEntity's treeEntityVector = new Vector <TreeEntity>(); // Fill the vector with the relevant TreeEntity's if they exist. if(SafetyNet.getSlideShow() != null) treeEntityVector = SafetyNet.getSlideShow().getTree(); // Remove any current images if(imageFlow != null) panel.remove(imageFlow); // Try and create a coverflow from the vector. try {imageFlow = new ImageFlow(treeEntityVector);} catch(Exception e) { System.out.println("Could not create coverflow images"); } // If ImageFlow was created add it to the panel if(imageFlow != null) { panel.add(imageFlow); panel.setComponentZOrder(imageFlow, 0); panel.setComponentZOrder(bkgndPanel, 1); imageFlow.setBounds(0, 0, panel.getWidth(), panel.getHeight()); } }
4
public Transaction bindToTransaction(Map<String, String[]> parameterMap){ Transaction transaction = new Transaction(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); transaction.setTimestamp(dateFormat.format(cal.getTime())); boolean isTransaction = false; Iterator iter = parameterMap.entrySet().iterator(); System.out.print("<<<<<<< Parameter Map >>>>>>>>"); while ( iter.hasNext() ) { Map.Entry entry = (Map.Entry)iter.next() ; String name = (String)entry.getKey() ; String[] values = (String[])entry.getValue(); System.out.println("Name: " + name + " Values : " + values + "\n"); if(values[0].split("#").length == 3){ //name 1 values => 1#Plane#8, if(isTransaction == false) { isTransaction = true;} Pizza pizza = new Pizza(); pizza.setId(name); String[] tokens; if(1 <= values.length){ int valueRank = ((1 == values.length)?0:1); tokens = values[valueRank].split("#"); pizza.setId(tokens[0]); pizza.setName(tokens[1]); pizza.setPrice(Integer.valueOf(tokens[2])); if(valueRank == 1)pizza.setDescription(tokens[6]); } for ( int i = 1; i < values.length ; ++i ) { // id#name#price#id#name#price#pizza description tokens = values[i].split("#"); Topping topping = new Topping(); topping.setId(tokens[3]); topping.setName(tokens[4]); topping.setPrice(Integer.valueOf(tokens[5])); pizza.addTopping(topping); } transaction.addPizza(pizza); } } if(isTransaction) {return transaction;} System.out.print("<<<<<<< Parameter Map >>>>>>>>"); return null; }
8
public static String fileExt(File f) { String fileName = f.getName(); int i = fileName.lastIndexOf('.'); if (i > 0) { return fileName.substring(i+1); } return ""; }
1
public String encode(String plain) { //Assume plain has a length which is multiply of 25 //Need to generate a key of length x, 25x=length of plain // if(!is_valid(plain)) // return null; //add 'X' till the length is a multiply of 25 // if(plain.endsWith("mess")) /* if(plain.startsWith("thisiswhatdictionariesusedtolooklike")) { System.err.println("test"); }*/ String new_plain=add_comp(plain); // int key_len=plain.length()/25; // key=generate_key_len(key_len); if (period!=key.length() || new_plain.length()/25!=period) { return null; } char[][] matrix=generate_matrix(key,new_plain); int[] order=generate_order(key); Integer[] order_i=new Integer[order.length]; for(int i=0;i<order.length;i++) { order_i[i]=Integer.valueOf(order[i]); } char[][] cipher_text=new char[25][period]; int cur_col=1; while(cur_col<=period) { int col_index=Arrays.asList(order_i).indexOf(cur_col); char k=key.charAt(col_index); if(k=='V') { k='W'; } int k_index=get_index(k); // int k_index=Arrays.asList(key_array).indexOf(k); for(int i=0;i<25;i++) { cipher_text[i][cur_col-1]=matrix[k_index][col_index]; if(k_index==24) { k_index=0; } else { k_index++; } } cur_col++; } StringBuilder sb=new StringBuilder(); for(int row=0;row<25;row++) { for(int col=0;col<period;col++) { sb.append(cipher_text[row][col]); } } return sb.toString().toUpperCase(); // int[] order=Generic_Func.generate_random_perm(1, period); }
9
private void initMainFrameButtonActions() { mainFrame.getButtonGo().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (mainFrame.getAddressField().getText().isEmpty()) { mainFrame.getButtonGo().setEnabled(false); } else { mainFrame.setTitle(""); mainFrame.getTreeModel().clearTree(mainFrame.getTreeNode()); mainFrame.getTableProductModel().clearTable(); String url = mainFrame.getAddressField().getText(); try { mainModel.getParser().connect(url); getHtmlTree(); getProducts(); } catch (ParseException ex) { LOGGER.error("Invalid url!", ex); JOptionPane.showMessageDialog(mainFrame, "Invalid url!", "Error", JOptionPane.ERROR_MESSAGE); } } } }); mainFrame.getButtonAddToDB().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (Product product : products) { try { mainModel.getdBLogic().insertProduct(product); mainFrame.getButtonAddToDB().setEnabled(false); } catch (DBException ex) { LOGGER.error(ex.getMessage(), ex); } } } }); }
4
private void createCellArray(String mapFile) { // Scanner object to read from map file Scanner fileReader; ArrayList<String> lineList = new ArrayList<String>(); // Attempt to load the maze map file try { fileReader = new Scanner(new File(mapFile)); while (true) { String line = null; try { line = fileReader.nextLine(); } catch (Exception eof) { // throw new A5FatalException("Could not read resource"); } if (line == null) { break; } lineList.add(line); } tileHeight = lineList.size(); tileWidth = lineList.get(0).length(); // Create the cells cells = new Cell[tileHeight][tileWidth]; for (int row = 0; row < tileHeight; row++) { String line = lineList.get(row); for (int column = 0; column < tileWidth; column++) { char type = line.charAt(column); cells[row][column] = new Cell(column, row, type); } } } catch (FileNotFoundException e) { System.out.println("Maze map file not found"); } }
6
@Override public void sort(int[] array) { for( int i = array.length-1; i > 0; i--){ for (int j = 0; j < i; j++) { if(array[j]>array[j+1]){ swap(array, j ,j+1); } } } }
3
private void masaSureKontrol(){ System.out.println("111111"); for(Bilgisayar b : bilgisayarlar){ if(b.getDurum() == Bilgisayar.Durum.SURELI_ACIK || b.getDurum() == Bilgisayar.Durum.SINIRSIZ_ACIK){ if(b.gecenSureyiArtir()){ suresiBitmisDurumaAl(b); } }else if(b.getDurum() == Bilgisayar.Durum.BEKLEMEDE || b.getDurum() == Bilgisayar.Durum.SURESI_BITMIS_BEKLEMEDE){ b.gecenBeklemeSuresiniArtir(); } } if(CalisanC.ana.masalarV1.seciliLabel!=null){ //dakika geçince seçili masa bilgilerin güncellenmesi için CalisanC.ana.masalarV1.seciliMasaDegis(CalisanC.ana.masalarV1.seciliLabel); } }
7
public List<TileType> getRelatedTileTypes(TileType tileType) { List<TileType> relatedTileTypes = new ArrayList<TileType>(); for (TileType t : tileTypes) { for (String s : tileType.getTags()) { if (!s.equals("COMMON") && t.getTags().contains(s)) { relatedTileTypes.add(t); break; } } } return relatedTileTypes; }
4
public void update() { tryattack(); xa = 0; ya = 0; if (!attacking) { randommovement(); } if (anim < 40) anim++; else { anim = 0; } if (xa != 0 || ya != 0) { walking = true; move(xa, ya); } else { walking = false; } if (hit) { if (anim2 < 40) anim2++; else { anim2 = 0; hit = false; OverHead = ""; } } if (checkattack) { checkattack = false; checkattack(this); } }
7
public static void main(String[] args) { BaseAccount[] list = new BaseAccount[5]; list[0] = new SavingsAccount("Fred"); list[1] = new ChequeAccount("Jim"); list[2] = new ChequeAccount("Sue"); list[3] = new SavingsAccount("Jim"); list[4] = new SavingsAccount("Jill"); // In the following loops do NOT use your knowledge // of which member of list[] is of which type // Modified the 'for' loops to end at list[] array length System.out.println("Set credit limits of accounts to 50.0"); for (BaseAccount account : list) { /* Insert code setting 50.0 credit limits */ // Only objects of ChequeAccount type have a credit limit // finding instances of ChequeAccount as we iterate through the // the loop if (account instanceof ChequeAccount) ((ChequeAccount) account).setCreditLimit(50.0); System.out.println(account); } System.out.println("\nDeposit 20.0 in each account"); for (BaseAccount account : list) { /* Insert code depositing 20.0 in each account */ // All derived class of BaseAccount have a deposit method account.deposit(20.0); System.out.println(account); } System.out.println("\nWithdraw 25.0 from each account"); for (BaseAccount account : list) { /* Insert code withdrawing 25.0 from each account */ // I have introduced a Transaction interface which implements a withdraw method; // any class that implements this interface will therefore feature the required // withdraw method. The if statement filters objects of the interface type // the list item is then cast to a transaction type and the relevant method is called // from within the derived object if (account instanceof Transaction){ if (((Transaction) account).withdraw(25.0)) System.out.println(account); else System.out.println(account + "\tInsufficient funds"); } } System.out.println("\nAdd 8.0% interest to the accounts"); /* Insert code adding 8.0% interest as applicable */ for (BaseAccount account : list) { // Only objects of SavingsAccount type have an addInterest method // finding instances of SavingsAccount as we iterate through the // the loop if(account instanceof SavingsAccount) ((SavingsAccount)account).addInterest(8.0); System.out.println(account); } System.out.println("\nSort accounts by name"); /* Insert code to sort the accounts by owner's name */ // Using the java.util.Array.sort to output a sorted list // of our declared BaseAccount array for (int i = 0; i < list.length; i++){ java.util.Arrays.sort(list); System.out.println(list[i]); } /* Just some testing of the class methods // Check the equals method works correctly System.out.println("\nCheck the equals method works correctly"); BaseAccount b = list[1]; for (i = 0; i < list.length; i++){ System.out.printf("Compare new BaseAccount object to list[%s] = %s\n", i, b.equals(list[i])); } // Checks the compare to statement for consistency System.out.println("\nCheck the equals method works correctly"); System.out.println("Object b = " + b); for (i = 0; i < list.length; i++){ int a = b.compareTo(list[i]); int c = -1 * list[i].compareTo(b); System.out.printf("b.compareTo(list[%s]) : list[%s].compareTo(b)= %s : %s\n",i,i, a, c); } */ }
9
@Override public void run() { while(true) { try { String s = "up pressed: " + isUpPressed + ", down pressed: " + isDownPressed + ", spacePressed: " + isSpacePressed; f.setTitle(s); Thread.sleep(200); } catch(Exception exc) { exc.printStackTrace(); break; } } }
2
public String getName() { return name; }
0
static double grad(int hash, double x, double y, double z) { int h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE double u = h<8 ? x : y, // INTO 12 GRADIENT DIRECTIONS. v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); }
6
@Override public Object getMetaPacket(Object watcher) { Class<?> DataWatcher = Util.getCraftClass("DataWatcher"); Class<?> PacketPlayOutEntityMetadata = Util.getCraftClass("PacketPlayOutEntityMetadata"); Object packet = null; try { packet = PacketPlayOutEntityMetadata.getConstructor(new Class<?>[] { int.class, DataWatcher, boolean.class }) .newInstance(id, watcher, true); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } return packet; }
9
public static boolean moveFile(File src, File dest, boolean eraseOldDirs) { makeDirs(dest); if (!src.renameTo(dest)) { return false; } if (eraseOldDirs) { while ((src = src.getParentFile()) != null) { if (src.isDirectory() && src.listFiles().length == 0) { src.delete(); } else { break; } } } return true; }
5
private void lockProgrammProcess(Shell shell) { System.out.println("Try to get program lock"); initDataDir(); File locker = new File(VCNConstants.LOCK_FILE_PATH); locker.delete(); boolean isAlreadyLocked = locker.isFile(); if (isAlreadyLocked) { MessageOKDialog md = new MessageOKDialog(shell, "VCN: Program already running", "Program locked by other instance.\r\n" + "Just one program instance can be executed from a same directory."); md.open(); System.out.println("Program locked by other instance"); System.exit(0); } try { locker.createNewFile(); programLocker = new FileOutputStream(locker); } catch (Exception ex) { UI.messageDialog(shell, "VCN: Error loading program", "Can't create required files. \r\n" + "Failed to work with the file system.\r\n" + "Can't get program lock."); System.out.println("Can not get program lock"); ex.printStackTrace(); System.exit(0); } System.out.println("Got program lock"); }
2
@EventHandler public void SilverfishHarm(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getSilverfishConfig().getDouble("Silverfish.Harm.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getSilverfishConfig().getBoolean("Silverfish.Harm.Enabled", true) && damager instanceof Silverfish && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.HARM, plugin.getSilverfishConfig().getInt("Silverfish.Harm.Time"), plugin.getSilverfishConfig().getInt("Silverfish.Harm.Power"))); } }
6
private void addToValidPositions(Unit unit, List<Position> validPositions, MovementHelper helper, List<Unit> units) { boolean hasDifferentColorUnit = false; if (units == null) { return; } for (Unit otherUnit : units) { // If the unit has a different color if (!unit.getPlayer().equals(otherUnit.getPlayer())) { hasDifferentColorUnit = true; } } if (units.isEmpty() || hasDifferentColorUnit) { validPositions.add(helper.getPosition()); } }
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (ip != null ? !ip.equals(user.ip) : user.ip != null) return false; if (mac != null ? !mac.equals(user.mac) : user.mac != null) return false; if (name != null ? !name.equals(user.name) : user.name != null) return false; return true; }
9
public TerrainService clone() { TerrainService t = super.clone(); for(int i=0;i<super.getNombreColonnes();i++) { for(int j=0; j<super.getNombreLignes(); j++) { if(!(t.getBloc(i, j)==super.getBloc(i, j))) throw new PostConditionError("getNombresColonnes(clone(T)) != getNombresColonnes(T) * getNombresLignes(clone(T)) != getNombresLignes(T)"); } } return t; }
3
public static void main(String[] args) { String number = "12"; System.out.println("test val : "+(0-'0')+","+((0-'0')-'0')+",'0' is "+('0')); int sum = 0; for (char c : number.toCharArray()) { sum = sum - (0 - c) - '0'; while (sum >= 3) { sum -= 3; } } System.out.print("divisible by 3? "); System.out.println(sum == 0); }
2
public static String[] getOptionValues(String option) { // Try and parse the list on the ";" separator. String arguments_to_parse = null; if (CommandLineUtilities._command_line.hasOption(option)) arguments_to_parse = CommandLineUtilities._command_line.getOptionValue(option); if (CommandLineUtilities._properties.containsKey(option)) { arguments_to_parse = (String)CommandLineUtilities._properties.getProperty(option); } return arguments_to_parse.split(":"); }
2
private boolean r_postlude() { int among_var; int v_1; // repeat, line 70 replab0: while(true) { v_1 = cursor; lab1: do { // (, line 70 // [, line 72 bra = cursor; // substring, line 72 among_var = find_among(a_1, 3); if (among_var == 0) { break lab1; } // ], line 72 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 73 // <-, line 73 slice_from("i"); break; case 2: // (, line 74 // <-, line 74 slice_from("u"); break; case 3: // (, line 75 // next, line 75 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_1; break replab0; } return true; }
8
private void envoyerFichier() { try { File file = new File(this.pCheminCible); // Ouverture file if (file.exists() && file.canRead()) { //file dans stream Http.syslog.info("file content:" + this.pCheminCible); setStatus(CodeResponse.OK.getCode()); } else { if (file.exists() && !file.canRead()) { Http.syslog.warn("403"); setStatus(CodeResponse.FORBIDDEN.getCode()); this.pCheminCible = "./Error.html/HTTP_FORBIDDEN.html"; file = new File(this.pCheminCible); } else { Http.syslog.warn("404"); setStatus(CodeResponse.NOT_FOUND.getCode()); this.pCheminCible = "./Error.html/HTTP_NOT_FOUND.html"; file = new File(this.pCheminCible); } } this.filestream = new BufferedInputStream( new FileInputStream(file)); setLength(file.length()); setMime(); } catch (FileNotFoundException e) { setStatus(CodeResponse.NOT_FOUND.getCode()); this.filestream = null; System.out.println(e); } catch (Exception e) { this.filestream = null; setStatus(CodeResponse.INTERNAL_ERROR.getCode()); System.out.println(e); } }
6
public static void deleteWorld(int ID) { if (ID < 0 || ID > 4) { if (ChristmasCrashers.isDebugModeEnabled()) System.err.println("Failed to delete world " + ID + " - invalid world ID (must be between 0 and 4, inclusive)."); return; } if (worlds[ID] == null) { if (ChristmasCrashers.isDebugModeEnabled()) System.err.println("Failed to delete world " + ID + " - world does not exist."); return; } World[] worldsToDelete = {worlds[ID]}; new Thread(new DeleteWorldsTask(worldsToDelete)).start(); worlds[ID] = null; }
5
public int countTokens(String line, int ich) { int tokenCount = 0; if (line != null) { int ichMax = line.length(); char ch; while (true) { while (ich < ichMax && ((ch = line.charAt(ich)) == ' ' || ch == '\t')) ++ich; if (ich == ichMax) break; ++tokenCount; do { ++ich; } while (ich < ichMax && ((ch = line.charAt(ich)) != ' ' && ch != '\t')); } } return tokenCount; }
9
public Set<Pair> getHBonds() { // positions that are bonded together //TODO: find ideal way Set<Pair> hBonds = new HashSet<Pair>(); Set<Integer> usedPoints = new HashSet<Integer>(); int i = 0; for(Iterator<Point> iter = this.iterator(); iter.hasNext();) { Point p = iter.next(); RNABasePair pair = this.getPair(i++); int j = i; // intentionally one more for(Point p2: iterable(iter)) { RNABasePair pair2 = this.getPair(j++); //System.out.printf("%d,%d:%s%s\n",i-1,j-1,pair,pair2); if( j - i > 2 && pair.bondsWith(pair2) && !usedPoints.contains(i-1) && !usedPoints.contains(j-1) && p.isAdjacent(p2)){ hBonds.add(new Pair(i-1,j-1)); usedPoints.add(i-1); usedPoints.add(j-1); } } } return hBonds; }
7
String fileTypeString(int filetype) { if (filetype == SWT.IMAGE_BMP) return "BMP"; if (filetype == SWT.IMAGE_BMP_RLE) return "RLE" + imageData.depth + " BMP"; if (filetype == SWT.IMAGE_OS2_BMP) return "OS/2 BMP"; if (filetype == SWT.IMAGE_GIF) return "GIF"; if (filetype == SWT.IMAGE_ICO) return "ICO"; if (filetype == SWT.IMAGE_JPEG) return "JPEG"; if (filetype == SWT.IMAGE_PNG) return "PNG"; if (filetype == SWT.IMAGE_TIFF) return "TIFF"; return bundle.getString("Unknown_ac"); }
8
public void PlayerFileAccessor(JavaPlugin plugin, String fileName) { if (plugin == null) throw new IllegalArgumentException("plugin cannot be null"); if (!plugin.isInitialized()) throw new IllegalArgumentException("plugin must be initiaized"); this.plugin = plugin; this.fileName = fileName; File dataFolder = plugin.getDataFolder(); if (dataFolder == null) throw new IllegalStateException(); this.configFile = new File(plugin.getDataFolder(), fileName); }
3
public void remover(AreaConhecimento areaconhecimento) throws Exception { String sql = "DELETE FROM areaconhecimento WHERE id = ?"; try { PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql); stmt.setLong(1, areaconhecimento.getId()); stmt.executeUpdate(); } catch (SQLException e) { throw e; } }
1
private boolean r_postlude() { int among_var; int v_1; // repeat, line 62 replab0: while(true) { v_1 = cursor; lab1: do { // (, line 62 // [, line 63 bra = cursor; // substring, line 63 among_var = find_among(a_1, 3); if (among_var == 0) { break lab1; } // ], line 63 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 64 // <-, line 64 slice_from("\u00E3"); break; case 2: // (, line 65 // <-, line 65 slice_from("\u00F5"); break; case 3: // (, line 66 // next, line 66 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_1; break replab0; } return true; }
8
public static void main(String[] args) throws IOException { if(args.length != 2 || args[0].equalsIgnoreCase("help")) { System.out.println("Argument is empty! Please provide the path of the input.txt"); System.out.println("B-Tree Path/to/input.txt Path/to/output.txt"); return; } FileOutputStream fos = new FileOutputStream(args[1]); OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8"); ArrayList<Integer> inputArray = new ArrayList<Integer>(); BTree myBTree = new BTree(5); // Parameter: t value of B-Tree int i=0, index=0; Integer deleteKey; // Get an array of number from input.txt /* * input.txt assumption: * 1) all numbers are integer * 2) one line only has one number * 3) number should not out of the range of int data type * 4) args[0] provide the path of input.txt */ Scanner sc = new Scanner(new File(args[0])); while (sc.hasNextInt()) inputArray.add(new Integer(sc.nextInt())); sc.close(); // Insert the Numbers long startTime=0, endTime=0; System.out.println("Start to do the B-Tree Insert, and the Current Time is " + (startTime=System.nanoTime())); for (i = 0; i < inputArray.size(); i++) myBTree.insert(inputArray.get(i)); System.out.println("Finish the B-Tree Insertion, and the End time is " + (endTime=System.nanoTime())); System.out.println("Total Execution Time is " + (endTime-startTime) + " nanoseconds"); // Output the result to output.txt // In Ascending Order // Each Line shows the values of one node's keys and the type of the node {LEAF, INTERNAL, ROOT} myBTree.printTree(out); // Please use the following cases one by one, not at the same time! /*-----------------1. Manually Find and Delete One Node (Begin)----------------------------*/ /* Scanner in = new Scanner(System.in); System.out.println("Input a key to specify which node to delete: "); deleteKey = new Integer(in.nextInt()); System.out.println("The key you want to delete is: " + deleteKey.toString()); in.close(); int locatedAt[] = new int[1]; locatedAt[0] = -1; BTreeNode node; = myBTree.find(deleteKey, locatedAt); if(node != null) { System.out.println("The node is found!"); System.out.println("Node is " + (node!=myBTree.root?(node.isLeaf?"LEAF":"INTERNAL"):"ROOT") + ";"); System.out.println("deleteKey is located at the node's key's " + locatedAt[0] + "th position"); myBTree.delete(deleteKey); node = myBTree.find(deleteKey, locatedAt); if(node == null) System.out.println("Key is deleted!"); else System.out.println("Error in delete()!"); } else System.out.println("The node is not found!"); out.write ("-------------After manually delete-------------\n"); myBTree.printTree(out); */ /*-----------------1. Manually Find and Delete One Node (END)----------------------------*/ /*-----------------2. Delete the first half of the input numbers (Begin)----------------------------*/ /* for (i = 0; i < inputArray.size()/2; i++) { System.out.println("Delete " + i + "th item: " + inputArray.get(i).intValue()); myBTree.delete(inputArray.get(i)); } out.write ("-------------After delete the first half of the input numbers-------------\n"); myBTree.printTree(out); */ /*-----------------2. Delete the first half of the input numbers (END)----------------------------*/ /*-----------------3. Random choose the input number and then delete, the chosen number is removed from the Input Array (BEGIN)--------------------*/ i = inputArray.size()/2; while(i>0) { index = (int)(Math.random()*inputArray.size()); deleteKey = new Integer(inputArray.get(index)); inputArray.remove(index); myBTree.delete(deleteKey); i--; } out.write ("-------------After Random Delete-------------\n"); myBTree.printTree(out); /*-----------------3. Random choose the input number and then delete, the chosen number is removed from the Input Array (END)-----------------------*/ /* The Smallest Number should be located at the leftmost, and the Largest Number should be located at the rightmost, * and they should share the same height */ int h[] = new int[1]; myBTree.successor(myBTree.root, h); System.out.println("Smallest Number at depth: " + h[0]); h[0] = 0; myBTree.predecessor(myBTree.root, h); System.out.println("Largest Number at depth: " + h[0]); out.close(); }
5
public static MetaData parseMap(final Reader xmlStreamReader, final Parser pzparser) throws JDOMException, IOException { final Map map = parse(xmlStreamReader, pzparser); final List<ColumnMetaData> col = (List<ColumnMetaData>) map.get(FPConstants.DETAIL_ID); map.remove(FPConstants.DETAIL_ID); final Map m = (Map) map.get(FPConstants.COL_IDX); map.remove(FPConstants.COL_IDX); // loop through the map and remove anything else that is an index of FPConstancts.COL_IDX + _ // these were put in for the writer. // TODO maybe these shoudld be thrown into the MetaData instead of just discarded, but they are unused // in the Reader the moment. This parseMap is not utilized in the writer so it is safe to remove them here final Iterator entrySetIt = map.entrySet().iterator(); while (entrySetIt.hasNext()) { final Entry e = (Entry) entrySetIt.next(); if (((String) e.getKey()).startsWith(FPConstants.COL_IDX + "_")) { entrySetIt.remove(); } } return new MetaData(col, m, map); }
2
public void actionPerformed(ActionEvent e) { Object o = e.getSource(); // if it is the Logout button if(o == logout) { client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, "")); return; } // if it the who is in button if(o == whoIsIn) { client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, "")); return; } // ok it is coming from the JTextField if(connected) { // just have to send the message client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, tf.getText())); tf.setText(""); return; } if(o == login) { // ok it is a connection request String username = tf.getText().trim(); // empty username ignore it if(username.length() == 0) return; // empty serverAddress ignore it String server = tfServer.getText().trim(); if(server.length() == 0) return; // empty or invalid port numer, ignore it String portNumber = tfPort.getText().trim(); if(portNumber.length() == 0) return; int port = 0; try { port = Integer.parseInt(portNumber); } catch(Exception en) { return; // nothing I can do if port number is not valid } // try creating a new Client with GUI client = new Client(server, port, username, this); // test if we can start the Client if(!client.start()) return; tf.setText(""); label.setText("Enter your message below"); connected = true; // disable login button login.setEnabled(false); // enable the 2 buttons logout.setEnabled(true); whoIsIn.setEnabled(true); // disable the Server and Port JTextField tfServer.setEditable(false); tfPort.setEditable(false); // Action listener for when the user enter a message tf.addActionListener(this); } }
9
private boolean allWagonsLoaded() { boolean condition = true; java.util.List listOfWagons = getWorld().getObjects(Wagon.class); if(listOfWagons.size() > 0){ for(int i = 0; i < listOfWagons.size(); i++) { Wagon x =(Wagon) listOfWagons.get(i); if(!x.checkLoadingState()){ condition = false; } } if(condition){ return true; } else{ return false; } } else{ return false; } }
4
private void searchIndex() { // if at least one file has been parsed if( fileIndex.numOfFilesParsed() != 0 ) { // show an input dialog box and get the file name from user String searchWord = (String) JOptionPane.showInputDialog( new JFrame(), "Enter word to search for:", "Word to Search for", JOptionPane.OK_OPTION, new ImageIcon( PATH + INDEX_SEARCH_ICON ), null, ""); // if the user has clicked the cancel button or clicked the ok button without entering in a search term if( searchWord == null || searchWord.length() == 0 ) { // show an error dialog box JOptionPane.showMessageDialog( new JFrame(), "Canceled 'Search For' operation." ); return; } // get the search results String searchResults = fileIndex.searchFor( searchWord, "<br/>" + tab ); // there is at least one search result if( searchResults.length() > 0 ) { // output the resutls to the screen mainContentLabel.setText( htmlParagraphPrefix + tab + searchResults + htmlParagraphSuffix ); } else { // let the user no search terms were found JOptionPane.showMessageDialog( new JFrame(), searchWord + " was not found." ); mainContentLabel.setText( htmlParagraphPrefix + tab + searchWord + " was not found." + htmlParagraphSuffix ); } } // no files have been added to the index so it's not possible to search for words else { JOptionPane.showMessageDialog( new JFrame(), "ERROR: There are no words to search for because the file index is empty." ); mainContentLabel.setText( htmlParagraphPrefix + tab + "ERROR: There are no words to search for because the file index is empty." + htmlParagraphSuffix ); } }
4
public short[] naive(Node[] nodes) { short[] tour = new short[nodes.length]; boolean used[] = new boolean[nodes.length]; used[0] = true; for (short i = 1; i < nodes.length; i++) { short best = -1; for (short j = 0; j < nodes.length; j++) { if (!used[j] && (best == -1 || dist(tour[i - 1], j, nodes) < dist( tour[i - 1], best, nodes))) best = j; } tour[i] = best; used[best] = true; } return tour; }
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BSTNode bstNode = (BSTNode) o; if (value != null ? !value.equals(bstNode.value) : bstNode.value != null) return false; return true; }
5
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!sender.hasPermission(pluginMain.pluginManager.getPermission("thf.kick"))){ sender.sendMessage(ChatColor.DARK_RED + "You cannot KICK ME!"); return true; } if(args.length == 0){ sender.sendMessage(ChatColor.DARK_AQUA + "You need arguments! Argue!"); return true; } if(args.length == 1){ Player player = Bukkit.getPlayer(args[0]); if(player == null){ sender.sendMessage(ChatColor.DARK_RED + "FAIL! /ban [Player] [Reason]"); return true; } if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.kick.exempt"))){ sender.sendMessage(ChatColor.DARK_RED + "He can't be kicked! Noooooooo!"); return true; } player.kickPlayer("[THF] you have been kicked by " + sender.getName()); }else{ Player player = Bukkit.getPlayer(args[0]); if(player == null){ sender.sendMessage(ChatColor.DARK_RED + "They're not here!"); return true; } if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.kick.exempt"))){ sender.sendMessage(ChatColor.DARK_RED + "You can't kick me! I'm exempt!"); return true; } player.kickPlayer(ChatColor.stripColor("[THF] Kicked: " + convertArgs(args))); } return true; }
7
public void run() { MessageHandler<E> p = null; try { p = c.newInstance(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // int i = 0; while(true){ try { if (!queue.isEmpty()) { p.consume(queue.poll()); } i++; } catch (Exception e) { e.printStackTrace(); } // 每执行100次 if(10==i){ synchronized (this) { try { i = 0; wait(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
7
public Object rest() { if (size() == 0) { throw new RuntimeException("Cannot remove first element of an empty list."); } else if ((super.size() == 1) && (!this.isProperList)) { return this.getDottedElement(); } final CycList<E> cycList = new CycList<E>(this); cycList.remove(0); return cycList; }
3
public List<Type> levelOrderBFT() { ArrayList<Type> result = new ArrayList<Type>(); LinkedList<BinaryNode> queue = new LinkedList<BinaryNode>(); if(root == null) return result; queue.addLast(root); while(!queue.isEmpty()){ BinaryNode n = queue.removeFirst(); result.add(n.getData()); if(n.getLeft() != null) queue.add(n.getLeft()); if(n.getRight() != null) queue.add(n.getRight()); } return result; }
4
static <E extends Enum<E>> String toString(EnumSet<E> set) { if (set == null || set.isEmpty()) { return ""; } else { final StringBuilder b = new StringBuilder(); final Iterator<E> i = set.iterator(); b.append(i.next()); for (; i.hasNext();) { b.append(',').append(i.next()); } return b.toString(); } }
3