method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
8aec188e-a591-44f1-b244-dacdab016503
2
public static void ChooseHarrish () { if (Game.characterChoice == 1) { Game.CharacterOne = "Harrish"; Game.CharacterOneHP = CharacterStats.HarrishHP; Game.CharacterOneAttack = CharacterStats.HarrishAttack; Game.CharacterOneMana = CharacterStats.HarrishMana; Game.CharacterOneRegen = CharacterStats.HarrishRegen; Game.MovesOne = CharacterMoves.HarrishMoves; Game.MoveOneValue [0] = CharacterStats.HarrishAttack; Game.MoveOneValue [1] = CharacterMoves.GivesUp; Game.MoveOneValue [2] = CharacterMoves.Motivation; Game.MoveOneValue [3] = CharacterMoves.Cower; Game.MoveOneValue [4] = CharacterMoves.Hide; Game.MoveOneCost [0] = CharacterMoves.AttackCost; Game.MoveOneCost [1] = CharacterMoves.GivesUpCost; Game.MoveOneCost [2] = CharacterMoves.MotivationCost; Game.MoveOneCost [3] = CharacterMoves.CowerCost; Game.MoveOneCost [4] = CharacterMoves.HideCost; Game.OptionsOne [0] = "Attack (" + CharacterMoves.AttackCost + " mana)"; Game.OptionsOne [1] = "GivesUp (" + CharacterMoves.GivesUpCost + " mana)"; Game.OptionsOne [2] = "Motivation (" + CharacterMoves.MotivationCost + " mana)"; Game.OptionsOne [3] = "Cower (" + CharacterMoves.CowerCost + " mana)"; Game.OptionsOne [4] = "Hide (" + CharacterMoves.HideCost + " mana)"; Game.ActionOne [0] = Game.CharacterOne + " attacks " + Game.CharacterTwo + "."; Game.ActionOne [1] = "Harrish gives up."; Game.ActionOne [2] = "Harrish is motivated."; Game.ActionOne [3] = "Harrish cowers in fear."; Game.ActionOne [4] = "Harrish hides, confusing the enemy."; } else if (Game.characterChoice == 2) { Game.CharacterTwo = "Harrish"; Game.CharacterTwoHP = CharacterStats.HarrishHP; Game.CharacterTwoAttack = CharacterStats.HarrishAttack; Game.CharacterTwoMana = CharacterStats.HarrishMana; Game.CharacterTwoRegen = CharacterStats.HarrishRegen; Game.MovesTwo = CharacterMoves.HarrishMoves; Game.MoveTwoValue [0] = CharacterStats.HarrishAttack; Game.MoveTwoValue [1] = CharacterMoves.GivesUp; Game.MoveTwoValue [2] = CharacterMoves.Motivation; Game.MoveTwoValue [3] = CharacterMoves.Cower; Game.MoveTwoValue [4] = CharacterMoves.Hide; Game.MoveTwoCost [0] = CharacterMoves.AttackCost; Game.MoveTwoCost [1] = CharacterMoves.GivesUpCost; Game.MoveTwoCost [2] = CharacterMoves.MotivationCost; Game.MoveTwoCost [3] = CharacterMoves.CowerCost; Game.MoveTwoCost [4] = CharacterMoves.HideCost; Game.OptionsTwo [0] = "Attack (" + CharacterMoves.AttackCost + " mana)"; Game.OptionsTwo [1] = "GivesUp (" + CharacterMoves.GivesUpCost + " mana)"; Game.OptionsTwo [2] = "Motivation (" + CharacterMoves.MotivationCost + " mana)"; Game.OptionsTwo [3] = "Cower (" + CharacterMoves.CowerCost + " mana)"; Game.OptionsTwo [4] = "Hide (" + CharacterMoves.HideCost + " mana)"; Game.ActionTwo [0] = Game.CharacterTwo + " attacks " + Game.CharacterOne + "."; Game.ActionTwo [1] = "Harrish gives up."; Game.ActionTwo [2] = "Harrish is motivated."; Game.ActionTwo [3] = "Harrish cowers in fear."; Game.ActionTwo [4] = "Harrish hides, confusing the enemy."; } }
29e57695-0531-427d-9784-14053f8a57f6
2
public void operateMatrix(Matrix[]... srcs) { Matrix[] srcU = srcs[0]; Matrix[] srcV = srcs[1]; for (int colNo = 0; colNo < super.matWidth; colNo++) { multiplyAndStackUV(srcU[0].getArray(), srcV[0].transpose().getArray(), super.arrY, colNo, srcV[0].getColumnDimension(), srcU[0].getRowDimension()); if (codeCbCr) { multiplyAndStackUV(srcU[1].getArray(), srcV[1].transpose().getArray(), super.arrCb, colNo, srcV[1].getColumnDimension(), srcU[1].getRowDimension()); multiplyAndStackUV(srcU[2].getArray(), srcV[2].transpose().getArray(), super.arrCr, colNo, srcV[2].getColumnDimension(), srcU[2].getRowDimension()); } } }
78e03176-0760-4bb7-85a9-a266a61da797
3
public String getTooltipExtraText(final Province current) { // Default is to only show extra text for land provinces if (!editor.Main.map.isLand(current.getId())) return ""; final String prop = mapPanel.getModel().getHistString(current.getId(), name); if (prop == null || prop.length() == 0) return ""; return name + ": " + prop; }
4b652ac1-ec22-49d6-beeb-1f00d68959a7
0
@Before public void setUp() throws Exception { }
34937123-9ea8-4dfc-b8eb-07fc4b644b47
0
public UpperCaseField(int cols) { super(cols); }
003de739-e67a-4655-a5ea-d8de2fd30673
5
public static void main(String[] args) { // TODO code application logic here String cadena1 = ""; String cadena2 = ""; cadena1 = (JOptionPane.showInputDialog("Ingrese Cadena 1:")); cadena2 = (JOptionPane.showInputDialog("Ingrese Cadena 2:")); int longitud1 = cadena1.length(); int longitud2 = cadena2.length(); char[] frase1 = cadena1.toCharArray(); char[] frase2 = cadena2.toCharArray(); for (int i = 0; i < longitud1; i++) { for (int j = 0; j < longitud2; j++) { if (frase1[i] == frase2[j]) { frase1[i] = ' '; } } } for (int i = 0; i < frase1.length; i++) if (frase1[i] != ' ') { System.out.print(frase1[i]); } System.out.println(" "); }
1654c38a-5095-4ad3-979e-b6eb92d0f440
0
public void setRap_num(int rap_num) { this.rap_num = rap_num; }
58b19cbd-af1e-4c2e-970c-2e1e9c20012e
6
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(args.length == 0) { return false; } if(args[0].equalsIgnoreCase("create")) { doCreateCommand(sender, cmd, label, args); } else if(args[0].equalsIgnoreCase("list")) { doListCommand(sender, cmd, label, args); } else if(args[0].equalsIgnoreCase("get")) { doGetCommand(sender, cmd, label, args); } else if(args[0].equalsIgnoreCase("sign")) { doSignCommand(sender, cmd, label, args); } else if(args[0].equalsIgnoreCase("close")) { doCloseCommand(sender, cmd, label, args); } else { return false; } return true; }
8c821757-61e6-4b6d-b29c-169e3fc018a9
3
public String getLyricsFromURL(String url) { InputStream lyricsPageInputStream = this.getInputStream(url); BufferedReader br = new BufferedReader(new InputStreamReader(lyricsPageInputStream)); StringBuilder sb = new StringBuilder(); String line = ""; try { while((line = br.readLine()) != null) { sb.append(line +"\n"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO: Throw exception if sb is empty Pattern lyricsPattern = Pattern.compile("&lt;lyrics\\>(.*?)&lt;/lyrics\\>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); Matcher lyricsMatcher = lyricsPattern.matcher(sb); lyricsMatcher.find(); String lyrics = ""; try { lyrics = lyricsMatcher.group(1); } catch (IllegalStateException e) { // No match found } return lyrics; }
b40ea121-1550-4236-8a28-639b3401bc96
0
public final Result getUpdateStatus() { return this.result; }
b6d9eab0-afdd-4443-9861-f72f063f57b7
6
private static Image getImage(String filename) { // to read from file ImageIcon icon = new ImageIcon(filename); // try to read from URL if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) { try { URL url = new URL(filename); icon = new ImageIcon(url); } catch (Exception e) { /* not a url */ } } // in case file is inside a .jar if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) { URL url = StdDraw.class.getResource(filename); if (url == null) throw new RuntimeException("image " + filename + " not found"); icon = new ImageIcon(url); } return icon.getImage(); }
a4c23531-3f5b-4a44-b656-f053168b1a16
5
private boolean versionCheck(String title) { if (this.type != UpdateType.NO_VERSION_CHECK) { final String version = this.plugin.getDescription().getVersion(); if (title.split(" v").length == 2) { final String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number if (this.hasTag(version) || version.equalsIgnoreCase(remoteVersion)) { // We already have the latest version, or this build is tagged for no-update this.result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); this.plugin.getLogger().warning("Please notify the author of this error."); this.result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; }
fca8f14d-8e70-4a4d-8042-ae0ee98de8cd
3
@Override public boolean abort() throws LoginException { if (debug) { LOG.debug("aborting authentication"); } if (!succeeded) { return false; } if (!commitSucceeded) { resetData(); succeeded = false; } else { logout(); } return true; }
83fe0874-28d9-4f15-a433-ed766cba09d0
6
private void removeReservation(ServerReservation res) { boolean inProg = res.getReservationStatus() == ReservationStatus.IN_PROGRESS; // returns the time slot to the profile profile.addTimeSlot(res.getStartTime(), res.getExpectedFinishTime(), res.getPERangeList()); LinkedList<ScheduleItem> removedGridlets = new LinkedList<ScheduleItem>(); Iterator<SSGridlet> iterGrl = inProg ? runningJobs.iterator() : waitingJobs.iterator(); // removes all gridlets that are associated to the reservation while(iterGrl.hasNext()) { SSGridlet gridlet = iterGrl.next(); if(gridlet.getReservationID() == res.getID() && gridlet.getStatus() != Gridlet.SUCCESS && gridlet.getStatus() != Gridlet.FAILED) { gridlet.setStatus(Gridlet.CANCELED); gridlet.finalizeGridlet(); removedGridlets.add(gridlet); iterGrl.remove(); super.sendFinishGridlet(gridlet.getGridlet()); } } //---------------- USED FOR DEBUGGING PURPOSES ONLY ---------------- if(removedGridlets.size() > 0) { visualizer.notifyListeners(super.get_id(), ActionType.ITEM_CANCELLED, false, removedGridlets); } }
66b328a4-44be-4e3a-8009-3c6353fa9333
2
public boolean isFriend(User user){ for (int i=0; i<friends.size();i++) if (friends.get(i)==user) return true; return false; }
60664069-04a2-46a2-a46d-34bbbda0eaa2
2
private LinkInfo getCachedInfo(String videoID) { for (LinkInfo li : cache) if ( li.hasVideoID(videoID) ) return li; return null; }
a37722ff-d322-417d-a545-4717cf55b7d2
2
public boolean updatePosListaPrecioDisable(final PosListaPrecio itemOracle){ Session hbSessionOracle = getSession(); // SESSION ORACLE Transaction tsOracle = hbSessionOracle.beginTransaction(); boolean successOracle = false; try { getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery( "update PosListaPrecio set pcaEstado = 'D'" + " where pcaPosId = ? and pcaIdElemento = ? " ); query.setInteger(0, itemOracle.getPcaPosId()); query.setInteger(1, itemOracle.getPcaIdElemento()); query.executeUpdate(); return null; //To change body of implemented methods use File | Settings | File Templates. } }); successOracle = true; } catch (DataAccessException e) { e.printStackTrace(); // return false; } finally { if (!successOracle) { tsOracle.rollback(); hbSessionOracle.flush(); hbSessionOracle.close(); } else { tsOracle.commit(); hbSessionOracle.flush(); hbSessionOracle.close(); } } getHibernateTemplate().flush(); return successOracle; }
ebc90255-bd24-4012-99e2-929bf424757a
5
static final void method3189(int i, String[] strings) { if (i == 0) { anInt9537++; if (strings.length > 1) { for (int i_4_ = 0; i_4_ < strings.length; i_4_++) { if (strings[i_4_].startsWith("pause")) { int i_5_ = 5; try { i_5_ = Integer.parseInt(strings[i_4_].substring(6)); } catch (Exception exception) { /* empty */ } ClientApplet.addConsoleMessage(("Pausing for " + i_5_ + " seconds...")); Class50_Sub1.aStringArray5223 = strings; Class121.anInt1794 = i_4_ - -1; Class299_Sub1_Sub1.aLong8694 = (long) (i_5_ * 1000) + Class62.getCurrentTimeMillis(); break; } Class363.aString4461 = strings[i_4_]; Class59_Sub1.method555(false, 0); } } else { Class363.aString4461 += (String) strings[0]; Class348_Sub38.anInt7006 += strings[0].length(); } } }
c3b6aec9-1f05-4619-ae17-0fd6b64a2d58
5
static public String trimNumber(String s) { if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; }
054cedee-1422-4f0e-868f-b390dafb8090
1
public void testToStandardHours() { Days test = Days.days(2); Hours expected = Hours.hours(2 * 24); assertEquals(expected, test.toStandardHours()); try { Days.MAX_VALUE.toStandardHours(); fail(); } catch (ArithmeticException ex) { // expected } }
6be0a037-0db8-4f2c-907c-1484cbb5ae45
4
public char toLowCase(char c){ if(c>= '0' && c <='9') return c; else if(c>= 'A' && c<='Z'){ return (char) (c-'A'+'a'); } return c; }
c66aa6a0-1040-4d73-8c9c-bffbee5cd8a3
4
public void dprint(){ System.out.println("-------"); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { int v = 0; if (grid.get(i).get(j) != null) v = grid.get(i).get(j).getValue(); if (v != 0) { System.out.print("|" + v + "|\t"); }else{ System.out.print("| |\t"); } } System.out.println(); } System.out.println("-------"); }
453f5de9-0f3b-4a1f-9678-d54a738509f6
0
public static void main(String[] args) { Cups.cup1.f(99); }
e8d6f990-80a2-4e8d-ab3b-48cfe3dd7dba
9
protected void calcLaValue() { // 拉格朗日插值的运算 double t = 0.0; int i, j, k; double result = 0.0; double[] x = new double[Def.N]; double[] y = new double[Def.N]; try { t = Double.parseDouble(laTTextField.getText()); } catch (NumberFormatException e) { // t值输入格式错误 JOptionPane.showMessageDialog(null, ErrMessage.T_WRONG); laTTextField.requestFocus(); laTTextField.selectAll(); } String xstr = laXTextField.getText(); String ystr = laYTextField.getText(); Scanner xs = new Scanner(xstr); Scanner ys = new Scanner(ystr); k = 0; while (ys.hasNextDouble()) { y[k] = ys.nextDouble(); k++; } j = k; k = 0; while (xs.hasNextDouble()) { x[k] = xs.nextDouble(); k++; } i = k; if (i != 2) { if (i != j) { // x与y的个数不匹配 JOptionPane.showMessageDialog(null, ErrMessage.NOT_MATCH); laXTextField.requestFocus(); laXTextField.selectAll(); } else { for (k = 0; k < i - 1; k++) { for (int m = k + 1; m < i; m++) { if (x[k] == x[m]) { // x输入有重复 JOptionPane.showMessageDialog(null, ErrMessage.X_REPEAT); laXTextField.requestFocus(); laXTextField.selectAll(); } } } result = Interpolation.getValueLagrange(j, x, y, t); } } else { if (j < 2) { // x与y的个数不匹配 JOptionPane.showMessageDialog(null, "输入格式错误,请检查重输。"); laXTextField.requestFocus(); laXTextField.selectAll(); } else { result = Interpolation.getValueLagrange(j, x[0], x[1], y, t); } } laResultTextField.setText(result + ""); }
7b56d605-659b-4845-9552-fa16cf0ba78a
5
private void center() { float[] min = new float[] {Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE}; float[] max = new float[] {Float.MIN_VALUE, Float.MIN_VALUE, Float.MIN_VALUE}; for(Vertex v : vertices) { for(int a = 0; a < 3; a++) { min[a] = Math.min(min[a], v.data[a]); max[a] = Math.max(max[a], v.data[a]); } } float[] avg = new float[3]; for(int a = 0; a < 3; a++) { avg[a] = min[a] + (max[a] - min[a])/2; } for(Vertex v : vertices) { for(int a = 0; a < 3; a++) { v.data[a] -= avg[a]; } } }
6c88776a-acde-43cd-90c9-43dc5b864482
2
public void buildrightomposite() { GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 1; gridLayout.marginWidth = gridLayout.marginHeight = 0; rightComposite.setLayout(gridLayout); Composite titleComposite = new Composite(rightComposite, SWT.NONE); GridData gd = new GridData(GridData.FILL_BOTH); gd.heightHint = 120; titleComposite.setLayoutData(gd); Image titleImage = new Image(display, "image/title.jpg"); titleComposite.setBackgroundImage(titleImage); Composite customerComposite = new Composite(rightComposite, SWT.BORDER); gd = new GridData(GridData.FILL_BOTH); gd.heightHint = 360; customerComposite.setLayoutData(gd); customerComposite.setLayout(new FormLayout()); Composite messageComposite = new Composite(rightComposite, SWT.NONE); gd = new GridData(GridData.FILL_BOTH); gd.heightHint = 120; messageComposite.setLayoutData(gd); gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.marginWidth = gridLayout.marginHeight = 0; messageComposite.setLayout(gridLayout); Composite staticMessage = new Composite(messageComposite, SWT.BORDER); gd = new GridData(GridData.FILL_BOTH); gd.widthHint = 120; staticMessage.setLayoutData(gd); gridLayout = new GridLayout(); gridLayout.numColumns = 1; gridLayout.marginHeight = gridLayout.marginWidth = 0; staticMessage.setLayout(gridLayout); moneyLabel = new Label(staticMessage, SWT.NONE); gd = new GridData(GridData.FILL_BOTH); gd.heightHint = 30; moneyLabel.setLayoutData(gd); customerLabel = new Label(staticMessage, SWT.NONE); gd = new GridData(GridData.FILL_BOTH); gd.heightHint = 70; customerLabel.setLayoutData(gd); customerComposite.setLayout(new FormLayout()); FormData data = new FormData(); data.top = new FormAttachment(6); data.left = new FormAttachment(4); data.bottom = new FormAttachment(94); data.right = new FormAttachment(97); Composite customerBox = new Composite(customerComposite, SWT.BORDER); customerBox.setLayoutData(data); Image bkImage = new Image(display, "image/dengzi.jpg"); customerBox.setBackgroundImage(bkImage); gridLayout = new GridLayout(); gridLayout.numColumns = 5; gridLayout.marginWidth = gridLayout.marginHeight = 0; customerBox.setLayout(gridLayout); //System.out.println(seatsList.length); //System.out.println(eatingLabels.length); for (int i = 0; i < eatingLabels.length; i++) { eatingLabels[i] = new Label(customerBox, SWT.NONE); gd = new GridData(GridData.FILL_BOTH); Image eatingImage = new Image(display, "image/eating.jpg"); eatingLabels[i].setBackgroundImage(eatingImage); eatingLabels[i].setLayoutData(gd); eatingLabels[i].setVisible(false); } rollingLabels = new Label[4]; Composite rollingMessage = new Composite(messageComposite, SWT.NONE); gd = new GridData(GridData.FILL_BOTH); gd.widthHint = 420; rollingMessage.setLayoutData(gd); gridLayout = new GridLayout(); gridLayout.numColumns = 1; gridLayout.marginHeight = gridLayout.marginWidth = 0; rollingMessage.setLayout(gridLayout); for (int i = 0; i < 4; i++) { gd = new GridData(GridData.FILL_BOTH); gd.widthHint = 100; rollingLabels[i] = new Label(rollingMessage, SWT.BORDER); rollingLabels[i].setLayoutData(gd); //rollingLabels[i].setText("显示即时信息"); } }
2f6a5ec9-8f3a-4d73-a0ee-e0677d8edb41
7
public String readCEWWBracket(Title title, Reader reader, String type) throws IOException { int val = 0; StringBuilder builder = new StringBuilder(); while ((val = reader.read()) > -1) { switch (val) { case ')': String data = builder.toString().trim(); if (CEWWType.BOOK.isEqual(type) || CEWWType.UNVERI.isEqual(type)) { title.addDate(data); return null; } else if (CEWWType.PEIODI.isEqual(type)) { if (data.toLowerCase().startsWith("also as various titles, including")) { String titles[] = data.substring(33).trim().split("and"); for (String alternate : titles) { title.addOtherTitle(WordUtils.capitalizeFully(alternate.trim())); } } else { title.addPlace(WordUtils.capitalizeFully(data)); } return null; } return builder.toString().trim(); default: builder.append((char) val); } } return builder.toString(); }
8b330ec9-1d5e-43a4-8a0f-ac67189adc84
9
public static final String removeMnemonics(final String text) { int index = text.indexOf('&'); if (index == -1) { return text; } int len = text.length(); StringBuffer sb = new StringBuffer(len); int lastIndex = 0; while (index != -1) { // ignore & at the end if (index == len - 1) { break; } // handle the && case if (text.charAt(index + 1) == '&') { ++index; } // DBCS languages use "(&X)" format if (index > 0 && text.charAt(index - 1) == '(' && text.length() >= index + 3 && text.charAt(index + 2) == ')') { sb.append(text.substring(lastIndex, index - 1)); index += 3; } else { sb.append(text.substring(lastIndex, index)); // skip the & ++index; } lastIndex = index; index = text.indexOf('&', index); } if (lastIndex < len) { sb.append(text.substring(lastIndex, len)); } return sb.toString(); }
dc8df08c-2d01-42ba-80d6-8954b3ee4b9d
0
protected GameElement(Rectangle masse, IntHolder unit) { super(masse); this.unit = unit; }
7a6b1035-0358-497b-9a55-24427f3224c5
0
public static ResultSet _find(String tableName, String field, String value) throws SQLException { PreparedStatement statement = connect.prepareStatement(" select * from `" + tableName + "` where `" + field + "` = ? " ); statement.setString(1, value); ResultSet result = statement.executeQuery(); return result; }
4de8c497-bc00-4d80-9c6c-ea00838d6b6a
8
@Override public ArrayList<Move> generateMovesForThisPiece(Chessboard chessboard) { int toX = -1, toY = -1; final ArrayList<Move> moves = new ArrayList<Move>(); final String positionPiece = chessboard.getPositionPiece(this); final int getX = Helper.getXfromString(positionPiece); final int getY = Helper.getYfromString(positionPiece); // 4 direction for (int direction = 0; direction < 4; direction++) // Max 8 moves { for (int length = 1; length < 9; length++) { if (direction == 0) { toX = getX + length; toY = getY; } if (direction == 1) { toX = getX; toY = getY + length; } if (direction == 2) { toX = getX - length; toY = getY; } if (direction == 3) { toX = getX; toY = getY - length; } final Move move = checkThis(toX, toY, chessboard); // Si déplacement est nul, plus possible de ce déplacer dans // cette direction pour la tour if (move != null) { moves.add(move); if (move.isAttack()) { break; } } else { break; } } } return moves; }
45fb0c8b-64eb-4184-926a-5942103b4cc3
1
public static final boolean badPosition(int pos) { if (pos == -1) { new ErrorLog("Falsche Position\n\n" + Control.current.lastResponse); return true; } return false; }
20e51023-cb15-42e3-b9fe-343c8c991d8c
7
@Override public void run() { MongoClient mongoClient = null; // First verify there is stuff to work with - this is hiding the bug // that this thread should not start unless the data is good to go if ((myDb == null) || (myCollection == null) || (myFilter == null)) { return; } try { // TODO - more of the connection details could be applied here // Establish connection mongoClient = new MongoClient(myConnection.getHost()); // Get the DB data DB db = mongoClient.getDB(myDb); DBCollection collection = db.getCollection(myCollection); DBCursor cursor = collection.find(myFilter); // Publish data while ((!isInterrupted()) && (cursor.hasNext())) { String document = cursor.next().toString(); myTwitterThread.update(null, document); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // close db connection if (mongoClient != null) { mongoClient.close(); } } }
9ed8cf12-ff63-4c74-a2a9-8053a24437a3
1
private void checkExistsPseudo(String psd) throws Exception { UserModel user = DataStore.getUserByPseudo(psd); if(user !=null) { throw new Exception( "Ce pseudo n'est pas disponible." ); } }
63c6d4f3-41fa-48b2-b786-9c723a9812a5
7
public static void outPutBlockToTrack(Track[] t){ try{ jxl.Workbook readWorkBook = jxl.Workbook.getWorkbook(new File("Output_File.xls")); //唯讀的Excel工作薄物件 jxl.write.WritableWorkbook writeWorkBook = Workbook.createWorkbook(new File("Output_File.xls"), readWorkBook); //寫入 jxl.write.WritableSheet writeSheet = writeWorkBook.createSheet("block_to_track_assignment", 1); //建立一個工作表名字,然後0表示為第一頁 writeSheet.addCell(new Label(0, 0, "Track")); writeSheet.addCell(new Label(1, 0, "Block")); writeSheet.addCell(new Label(2, 0, "Day No")); writeSheet.addCell(new Label(3, 0, "Starting Time")); writeSheet.addCell(new Label(4, 0, "Ending time")); for(int i=0 ; i<t.length ; i++){ for(BlockToTrack bt : t[i].btt){ writeSheet.addCell(new Label(0, i+1, "C" + (bt.trackNo + 1))); writeSheet.addCell(new Label(1, i+1, bt.blockName)); writeSheet.addCell(new Label(2, i+1, Integer.toString(bt.dayNo))); writeSheet.addCell(new Label(3, i+1, changeToFormatTime(bt.startingTime))); writeSheet.addCell(new Label(4, i+1, changeToFormatTime(bt.endingTime))); } } writeWorkBook.write(); writeWorkBook.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } }
9be3471e-3d1a-4d99-9449-b77095fa4613
1
public XMLReaderStAX getStAXReader() { if (staxReader == null) { staxReader = new XMLReaderStAX(); } return staxReader; }
894fb362-8501-4cfd-bea9-61d0fd2814b5
1
public static void main (String [ ] args) { int x = 1; int y = 1; while (x < 5) { y = x - y; System.out.print (x + "" + y + " "); x = x + 1; } System.out.println ( ); }
8773c07b-a338-4ba2-97ad-a0b51111f72f
4
private static boolean filtersAcceptComponent(EntityRef clientEntity, EntityRef entity, Class<? extends Component> componentClass, Iterable<? extends EntityComponentFieldFilter> componentFieldFilters) { for (EntityComponentFieldFilter componentFieldFilter : componentFieldFilters) { if (componentFieldFilter.isComponentRelevant(clientEntity, entity, componentClass)) { return true; } } return false; }
f8712296-1b72-4264-a64b-57360f643064
1
public void setImageIcon(String name, ImageIcon icon) { Component comp = fetchComponent(null, name); if (comp instanceof JLabel) { JLabel label = (JLabel) comp; label.setIcon(icon); } }
1f55a94d-d958-4cab-aea0-84059ca8e5be
5
public void processInput(String input) { String[] words = input.split(" "); if(words[0].equalsIgnoreCase("clear")) { td.clear(); } else if(words[0].equalsIgnoreCase("disablecomp")) { Application.get().getLogic().disableComponent(words[1]); } else if(words[0].equalsIgnoreCase("enablecomp")) { Application.get().getLogic().enableComponent(words[1]); } else if(words[0].equalsIgnoreCase("volume")) { float vol = Float.parseFloat(words[1]); Application.get().getOptions().setVolume(vol); Application.get().getOptions().save(); } if(!input.equals("")) { td.addText(input); } }
805f64c2-a8b6-411f-b211-20c282481364
1
@Override public void sortedStructure() { for (int i = 0; i < data.kitSize(); i++){ Arrays.sort((String[]) data.getFromKit(i)); } data.setState("Sorted"); }
154ed949-9dde-4055-88d3-fef258f53ac9
3
public Leaderboard(FileConfigurationWrapper fcw_, String name_, String header_, String countSuffix_) { name = name_; header = header_; fcw = fcw_; countSuffix = countSuffix_; playerNameList = getNames(); playerCountList = getCounts(); //If the topkillers board hasn't been made yet, then.... if (playerNameList.size() == 0 && playerCountList.size() == 0) { //Create five default bounties. for (int i = 0; i < 5; i++) { playerNameList.add("[Nobody]"); playerCountList.add(-1); } //Update the names and counts. updateConfigLists(); } }
a5547ef3-9eb8-473a-b403-c72fcac02cfb
3
private void initializeLogger() { this.log = Logger.getLogger(this.getClass().getName()); try { FileHandler fh = new FileHandler(this.getClass().getName() .replace("class ", "") + ".log"); fh.setFormatter(new SimpleFormatter()); this.log.addHandler(fh); } catch (SecurityException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (this.verbose == 0) this.log.setUseParentHandlers(false); else this.log.setUseParentHandlers(true); this.log.setLevel(Level.ALL); }
da722c16-75ab-4fa8-af4b-f28c9241314e
5
@Override public void delete(Element element, String outerBlockNames) throws RemoteException { if((null == element.toString()) || ("" == element.toString())){ return; } // outerBlockNames is "" search all conf if("".equals(outerBlockNames.trim())){ confText = ReadConf(); //confText not contains element, return @ String editconfText = BlockDeleteElement(confText,element); // write to local conf file WriteConf(editconfText); } else{ if(CheckOuterBlockNames(outerBlockNames)){ throw new RemoteException("outerBlockNames is not correct,outerBlockNames ="+outerBlockNames); } //If there is no index in outerBlockNames, default the first block. if(!outerBlockNames.contains(":")){ outerBlockNames += ":0"; } HashMap<String,String> objHashMap=EditCommon(outerBlockNames); String BlockText = objHashMap.get("blocktext"); int BlockLength = Integer.parseInt(objHashMap.get("blocklength")); int nblockNameNum = Integer.parseInt(objHashMap.get("nblocknamenum")); //BlockText not contains element, return @ String editBlockText = BlockDeleteElement(BlockText,element); String newConfText = GetPreBlockText(confText,nblockNameNum)+editBlockText +GetSufBlockText(confText,nblockNameNum+BlockLength); // write to local conf file WriteConf(newConfText); } WriteRemoteConf(); }
01dd4a26-429d-4151-9978-da2da34c2eb0
6
private boolean validOr(String filter, String value) { filter = filter.trim(); filter = filter.substring(1, filter.length() - 1);// clear ( ) String[] temp = filter.split(OR); int require = temp.length; int op[] = new int[temp.length]; String filterValue[] = new String[temp.length]; int cnt = 0; for (String rule : temp) { rule = rule.trim(); for (int i = 0; i < OP.length; i++) { if (rule.contains(OP[i])) { op[cnt] = i; String tmp = rule.split(OP[i])[1].trim(); if (tmp.contains(APOSTROPHE)) { tmp = tmp.substring(1, tmp.length() - 1); } filterValue[cnt] = tmp; cnt++; break; } } } cnt = 0; int result = -2; for (int i = 0; i < require; i++) { result = value.compareTo(filterValue[i]); if (finalCheck(result, op[i])) { cnt++; } } return cnt > 0; }
805e5743-fbc2-4806-8b8a-8edf12f6e521
0
private ChokeMessage(ByteBuffer buffer) { super(Type.CHOKE, buffer); }
8e6d8f42-d286-4ede-9eff-c2b430860657
5
public void populate(int input, int hidden, int output) { //add neurons for(int i=0;i<input; i++) { addInputNode(); } for(int i=0;i<hidden; i++) { Neuron newron = addHiddenNode(); //add connections from previous layer for(Neuron n : inputNeurons) { n.addConnection(newron); } } for(int i=0;i<output; i++) { Neuron newron = addOutputNode(); //add connections from previous layer for(Neuron n : hiddenNeurons) { n.addConnection(newron); } } }
a8c34326-f5aa-4bb5-94e3-f1c9f4f96e11
2
@Override public int compareTo(Object card2) throws ClassCastException{ if (!(card2 instanceof Card)) throw new ClassCastException("A Card object expected."); if(this.cmc == ((Card) card2).getCmc()) return this.cardName.compareTo(((Card) card2).getCardName()); return ((Card) card2).getCmc() - this.cmc; }
a35e7484-d30d-40f4-81a7-c46b8686d4e2
9
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); int t = Integer.parseInt(in.readLine().trim()); for (int i = 0; i < t; i++) { int n = Integer.parseInt(in.readLine().trim()); Item[] items = new Item[n]; for (int j = 0; j < n; j++) items[j] = new Item(readInts(in.readLine())); int g = Integer.parseInt(in.readLine()); int groups[] = new int[g], MAX_W = 0; for (int j = 0; j < g; j++) { groups[j] = Integer.parseInt(in.readLine().trim()); MAX_W = Math.max(MAX_W, groups[j]); } long[][] dp = new long[n + 1][MAX_W + 1]; Arrays.fill(dp[0], -1); dp[0][0] = 0; long[] bestCol = new long[MAX_W + 1]; for (int r = 1; r <= n; r++) { dp[r-1][0] = 0; for (int c = 0; c <= MAX_W; c++) { dp[r][c] = dp[r-1][c]; if (c>=items[r - 1].w && dp[r - 1][c - items[r - 1].w] != -1) dp[r][c] = Math.max(dp[r][c], dp[r - 1][c- items[r - 1].w]+ items[r - 1].p); bestCol[c] = Math.max(bestCol[c], dp[r][c]); } } long ans = 0, theBest = 0; long[] best = new long[MAX_W+1]; for (int j = 0; j < best.length; j++) best[j] = (theBest= Math.max(theBest, bestCol[j])); for (int j = 0; j < groups.length; j++) ans += best[groups[j]]; out.append(ans + "\n"); } System.out.print(out); }
242cbbd1-fb24-4388-a847-4449088638ed
6
public boolean nextP() { { QuerySolutionTableIterator self = this; { QuerySolutionTable table = self.theTable; QuerySolution cursor = self.cursor; QuerySolution previous = cursor; if (self.firstIterationP) { previous = null; cursor = table.first; self.firstIterationP = false; } else { previous = cursor; cursor = cursor.next; } while ((cursor != null) && cursor.deletedP()) { cursor = cursor.next; } self.cursor = cursor; if (cursor != null) { if (previous == null) { table.first = cursor; } else { previous.next = cursor; } self.key = cursor.bindings; self.value = cursor; return (true); } else if (previous != null) { previous.next = null; table.last = previous; } return (false); } } }
057bbe62-f79d-429f-951d-db003e95ced3
7
public static String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
fd16ec90-49e4-4e7c-b83c-f71a5fb293f1
0
@XmlElementDecl(namespace = "http://www.w3.org/2000/09/xmldsig#", name = "X509SKI", scope = X509DataType.class) public JAXBElement<byte[]> createX509DataTypeX509SKI(byte[] value) { return new JAXBElement<byte[]>(_X509DataTypeX509SKI_QNAME, byte[].class, X509DataType.class, ((byte[]) value)); }
b4f06269-aa26-4cc5-b581-8361ba856b6e
1
@Override public void save(IArticle article) throws ArticleWriteException { try { em.getTransaction().begin(); persistResources(article); em.persist(article); em.getTransaction().commit(); } catch (IOException e) { throw new ArticleWriteException(e.getMessage(), e); } }
5ab0145c-f021-4dd2-bf35-7bc269e9b26f
1
private void login(String userName, char[] password){ //load login information logAc = logAc.load(logAc); if ((mode = Doctor.checkLogin(db,logAc,userName,password))!=0){ //when password match, saved mode : 1:Doctor 2:admin this.userName = userName; doctorID = userName; db = db.load(db); menuPage(); cardLayout.show(contentPane, "Menu"); //change panel setJMenuBar(menubar); //show the menu bar } else JOptionPane.showMessageDialog(null, "Please retry","Login Failed", JOptionPane.ERROR_MESSAGE); //password not patch, show error message box }
b78bdd81-cb08-43c7-ae10-ece3fe8e5942
5
public Vector substitution(Matrix matrix, Vector b, SubstitutionDirection direction) throws ArithmeticException { Double term0 = 0d; Double term1 = 0d; Double term2 = 0d; Vector y = new Vector(); if (direction == SubstitutionDirection.FORWARD) { y.set(0, b.get(0)); for (int row = 1; row < 2; row++) { term0 = term0 + matrix.values[row][0] * y.get(0); term1 = b.get(row) - term0; term2 = term1 / matrix.values[row][row]; y.set(row, term2); } } if (direction == SubstitutionDirection.BACKWARD) { int dim = 1; y.set(dim, b.get(dim) / matrix.values[dim][dim]); for (int row = dim; row >= 0; row--) { term0 = 0d; for (int i = 0; i < dim - row; i++) { term0 = term0 + matrix.values[row][dim - i] * y.get(dim - i); } term1 = b.get(row) - term0; term2 = term1 / matrix.values[row][row]; y.set(row, term2); } } return y; }
b3f8b413-1506-48fd-a2c6-32b8a0c90ed1
7
public Sprite(BufferedImage ss, BufferedImage ds, BufferedImage cs, BufferedImage ts) { for(int i = 0; i < uROWS; i++) { for(int j = 0; j < uCOLUMNS; j++) { unit[i][j] = ss.getSubimage(j * Game.TILESIZE, i * Game.TILESIZE, Game.TILESIZE, Game.TILESIZE); } } for(int i = 0; i < dCOLUMNS; i++) { damage[i] = ds.getSubimage(i * dmwDIM, 0, dmwDIM, dmhDIM); } for(int i = 0; i < cROWS; i++) { for(int j = 0; j < cCOLUMNS; j++) { cursor[i][j] = cs.getSubimage(j * 32, i * 32, 32, 32); } } for(int i = 0; i < tROWS; i++) { for(int j = 0; j < tCOLUMNS; j++) { tile[i][j] = ts.getSubimage(j * Game.TILESIZE, i * Game.TILESIZE, Game.TILESIZE, Game.TILESIZE); } } }
6207d189-01ba-4906-97db-e121cbab439d
7
public void reset() { if(comboMaterial.getItemCount() > 0) { comboMaterial.setSelectedIndex(0); } if(comboMachine.getItemCount() > 6) { comboMachine.setSelectedIndex(6); }else { if (comboMachine.getItemCount() > 0) { comboMachine.setSelectedIndex(0); } } if(comboCylinder.getItemCount() > 0) { comboCylinder.setSelectedIndex(0); } if(comboDyePreset.getItemCount() > 0) { comboDyePreset.setSelectedIndex(0); } if(comboDyeType.getItemCount() > 0) { comboDyeType.setSelectedIndex(0); } if(comboDyeCylinder.getItemCount() > 0) { comboDyeCylinder.setSelectedIndex(0); } textFAmount.setText(""); textFWidth.setText(""); textFHeight.setText(""); textFSideGap.setText("6"); textFBetweenGap.setText("3"); textFTracks.setText(""); textFDyeCover.setText(""); textFPregCover.setText(""); textFDomborCost.setText("5000"); textFTitle.setText(""); textFClient.setText(""); textFDiscount.setText("0"); textFClicheCost.setText("0"); textFStancCost.setText("0"); textFOtherCost.setText("0"); textFPackingCost.setText("6000"); textFPackingTime.setText("0"); textFRollWidth.setText("0"); textFAmountPerRoll.setText("0"); textFPackingSumCost.setText("0"); textFEuro.setText("310"); listDyeType.removeAll(); PPC.calcObj.resetAddedDyes(); checkPreg.setSelected(false); checkDombor.setSelected(false); textASum.setText(""); textABelowButton.setVisible(true); hideExportButton(); }
6e2cc979-b242-4f41-a972-d2042c6a0b9c
4
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //TilastointiService service = new TilastointiService(); ArrayList<Integer> vuodet; String vuosistr = ""; if(request.getSession().getAttribute("vuosi") != null) { vuosistr = (String)request.getSession().getAttribute("vuosi"); } else { vuosistr = "2014"; } TilastointiFormBean formbean = new TilastointiFormBean(vuosistr); try { TilastointiService service = new TilastointiService(); int vuosi = formbean.validateAndConvert(); HashMap<Integer, Tilastointi> kktilaukset = service.haeTilaukset(vuosi); double vuosimyynti = service.haeVuosimyynti(vuosi); int vuodentilaukset = service.haeVuodentilaukset(vuosi); // System.out.println("Vuosimyynti: " + vuosimyynti); // System.out.println("Vuodentilaukset: " + vuodentilaukset); request.setAttribute("tilaukset", kktilaukset); request.setAttribute("vuosi", vuosi); request.setAttribute("vuosimyynti", vuosimyynti); request.setAttribute("vuodentilaukset", vuodentilaukset); ArrayList<Toppizzat> pizzatop = service.haeToppizzat(); request.setAttribute("toplista", pizzatop); vuodet = service.haeVuodet(); request.setAttribute("vuodet", vuodet); //request.getRequestDispatcher("tilastot.jsp").forward(request, response); /* * Luodaan Admin-luokan olio, jotta voidaan tarkistaa, että onko käyttäjä kirjautunut sisään. * Request vastaanottaa Admin-luokan olion Object-luokan oliona. Kaikki luokat, * jotka eivät periydy toisesta "tavallisesta" luokasta periytyvät Object-luokasta. * Tästä syystä getAttribute()-funktiosta saatu olio täytyy * typecastaa Object luokasta periydytetyksi Admin-luokan olioksi. */ Admin admin = (Admin)request.getSession().getAttribute("kayttajatiedot"); /* * Jos käyttäjä löytyy sessiosta päästetään käyttäjä halutulle sivulle. Muuten forwardataan kirjautumissivulle. */ if(admin == null) { request.getSession().setAttribute("page", "tilastot"); request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); } else { System.out.println("Sisäänkirjautuminen onnistui."); request.getRequestDispatcher("/WEB-INF/jsp/secure/tilastot.jsp").forward(request, response);; } } catch (DAOPoikkeus e) { request.setAttribute("virhe", e); request.getRequestDispatcher("virhe.jsp").forward(request, response); } catch (ValidointiPoikkeus e) { // TODO Auto-generated catch block e.printStackTrace(); } }
c7b77553-be41-4d0e-bb4c-ac439f226b10
8
@Override public boolean exists() { try { URL url = getURL(); if (ResourceUtils.isFileURL(url)) { // Proceed with file system resolution... return getFile().exists(); } else { // Try a URL connection content-length header... URLConnection con = url.openConnection(); ResourceUtils.useCachesIfNecessary(con); HttpURLConnection httpCon = (con instanceof HttpURLConnection ? (HttpURLConnection) con : null); if (httpCon != null) { httpCon.setRequestMethod("HEAD"); int code = httpCon.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { return true; } else if (code == HttpURLConnection.HTTP_NOT_FOUND) { return false; } } if (con.getContentLength() >= 0) { return true; } if (httpCon != null) { // no HTTP OK status, and no content-length header: give up httpCon.disconnect(); return false; } else { // Fall back to stream existence: can we open the stream? InputStream is = getInputStream(); is.close(); return true; } } } catch (IOException ex) { return false; } }
3955cc84-80f5-4015-92d9-6008fd77ec51
8
@Override public String getSVG( HashMap<String, Double> chartMetrics, HashMap<String, Object> axisMetrics, ChartSeries s ) { double x = chartMetrics.get( "x" ); double y = chartMetrics.get( "y" ); double w = chartMetrics.get( "w" ); double h = chartMetrics.get( "h" ); double max = chartMetrics.get( "max" ); double min = chartMetrics.get( "min" ); Object[] categories = s.getCategories(); ArrayList series = s.getSeriesValues(); String[] seriescolors = s.getSeriesBarColors(); String[] legends = s.getLegends(); if( series.size() == 0 ) { log.error( "Bar.getSVG: error in series" ); return ""; } StringBuffer svg = new StringBuffer(); int shape = cf.getBarShape(); if( (shape == ChartConstants.SHAPECONE) || (shape == ChartConstants.SHAPECYLINDER) || (shape == ChartConstants.SHAPEPYRAMID) ) { ; // TODO: SOMETHING!!! Interpret Shape for Pyramid, etc. charts } int[] dls = getDataLabelInts(); // get array of data labels (can be specific per series ...) int n = series.size(); svg.append( "<g>\r\n" ); double barw = 0; // double yfactor = 0; barw = h / ((categories.length + 1.0) * (n + 1)); // bar width= height/total number of bars+separators if( max != 0 ) { yfactor = w / max; // w/yMax= scale unit } int rf = 1; //(!yAxisReversed?1:-1); double y0 = (h + y) - (barw * 0.5); //start at bottom and work up (unless reversed) // for each series for( int i = 0; i < n; i++ ) { // each series group i.e. each bar with a different color svg.append( "<g>\r\n" ); double[] curseries = (double[]) series.get( i ); String[] curranges = (String[]) s.getSeriesRanges().get( i ); for( int j = 0; j < curseries.length; j++ ) { // each category (group of series) // double y= y0 - barw*(i+1)*rf - (j*n*barw*1.5)*rf; // y goes from 1 series to next, corresponding to bar/column color double yy = y0 - (barw * (n + 1) * 1.1 * (j)) - (barw * (i + 1)) - ((barw * 1.5) * rf) /* start */; double ww = yfactor * curseries[j]; // width of bar -- measure of series svg.append( "<rect " + getScript( curranges[j] ) + " fill='" + seriescolors[i] + "' fill-opacity='1' stroke='black' stroke-opacity='1' stroke-width='1' stroke-linecap='butt' stroke-linejoin='miter' stroke-miterlimit='4'" + " x='" + x + "' y='" + yy + "' width='" + ww + "' height='" + barw + "' fill-rule='evenodd'/>" ); String l = getSVGDataLabels( dls, axisMetrics, curseries[j], 0, i, legends, categories[j].toString() ); if( l != null ) { svg.append( "<text x='" + (x + ww + 10) + "' y='" + (yy + (barw * rf)) + "' " + getDataLabelFontSVG() + ">" + l + "</text>\r\n" ); } } svg.append( "</g>\r\n" ); // each series group } svg.append( "</g>\r\n" ); return svg.toString(); }
a2b4f35b-318a-4885-8208-86bd24d8f114
5
@Override public void saveOrder(List<FoodCombo> orderList) throws RuntimeException { try { List colDescriptors = new ArrayList(); List colValues = new ArrayList(); db.openConnection(FoodOrderDAO.DRIVER, FoodOrderDAO.URL, FoodOrderDAO.USER, FoodOrderDAO.PWD); for (FoodCombo item : orderList) { colDescriptors.add("name"); colValues.add(item.getName()); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("M/d/yyyy"); String dateStr = sdf.format(date); colValues.add(dateStr + "-" + ++orderCount); colDescriptors.add("order_id"); // Usuallly you want the connection to be closed when the db // method finishes (second parameter = true). The reason is that // if you leave it open (second parameter = false) then you risk // the database connection might time out and close on its own. db.insertRecord("order_history", colDescriptors, colValues, false); colDescriptors.clear(); colValues.clear(); } db.closeConnection(); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex.getMessage(), ex); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex.getMessage(), ex); } catch (SQLException ex) { throw new RuntimeException(ex.getMessage(), ex); } catch (Exception ex) { throw new RuntimeException(ex.getMessage(), ex); } }
6f91e4ee-9e25-43ae-a289-3aa74b7cd74a
5
public static void checkForMIFUUpdate(){ //Check latest version available String latest = null; Download.downloadfile(CONSTS.FILEZ+"/mifuv.txt", CONSTS.MIFUDIRS, "/version.txt"); try { File file = new File(CONSTS.MIFUDIR+"/version.txt"); FileReader fileReader = new FileReader(file); StringBuffer stringBuffer = new StringBuffer(); int numCharsRead; char[] charArray = new char[1024]; while ((numCharsRead = fileReader.read(charArray)) > 0) { stringBuffer.append(charArray, 0, numCharsRead); } fileReader.close(); latest = stringBuffer.toString(); System.out.println("Current version: "+CONSTS.MIFUV); System.out.println("Latest version: v"+latest); } catch(IOException e) { e.printStackTrace(); } //Compare versions String[] lversion = latest.split("\\."); int lmajor = Integer.parseInt(lversion[0]); int lminor = Integer.parseInt(lversion[1]); int lpatch = Integer.parseInt(lversion[2]); if(lmajor > CONSTS.MAJOR){ System.out.println("NEW MAJOR"); updateMIFU(); }else if(lminor > CONSTS.MINOR){ System.out.println("NEW MINOR"); updateMIFU(); }else if(lpatch > CONSTS.PATCH){ System.out.println("NEW PATCH"); updateMIFU(); }else{ System.out.println("MIFU IS UP TO DATE"); } }
865aeaca-3d92-449f-9f97-4cd83ef8199e
9
public boolean iterate(Board board) { if(board.getRemainingBlocks().isEmpty()) { return checkWinStatus(board); } Direction direction; for(Block b : board.getRemainingBlocks()) { for(int i = 0; i < 4; i++) { Board copy = board.copy(); switch(i) { case 0: direction = Direction.UP; break; case 1: direction = Direction.LEFT; break; case 2: direction = Direction.RIGHT; break; case 3: direction = Direction.DOWN; break; default: direction = null; } boolean successful = b.move(copy, direction); b.reset(); if(successful) { copy.getRemainingBlocks().remove(b); boolean foundSolution = iterate(copy); if(foundSolution) { String instruction = "Move " + b.getName() + " at " + b.getOrigin().toString() + " " + direction.toString() + "."; answerInstructions.add(instruction); return true; } } } } return false; }
2ca5d144-1d76-495b-bf0e-e22cf0b9aab7
8
public List<Integer> findSubstring(String S, String[] L) { Map<String, Integer> numOfSubstrings = new LinkedHashMap<>(); for (int i = 0; i < L.length; i++) { if (numOfSubstrings.containsKey(L[i])) { numOfSubstrings.put(L[i], numOfSubstrings.get(L[i]) + 1); } else { numOfSubstrings.put(L[i], 1); } } List<Integer> results = new ArrayList<>(); int eachLength = L[0].length(); for (int i = 0; i <= S.length() - L.length * eachLength; i++) { int count = 0; Map<String, Integer> temp = new LinkedHashMap<>(numOfSubstrings); for (int n = 0; n < L.length; n++) { String substring = S.substring(i + n * eachLength, i + (n + 1) * eachLength); if (temp.containsKey(substring) && (temp.get(substring) > 0)) { // temp.remove(substring); temp.put(substring, temp.get(substring) - 1); count++; } else { break; } if (count == L.length) { break; } } if (count == L.length) { results.add(i); } } return results; }
5c941bec-bf09-4e75-ac19-2547df408155
1
@Override public void run() { arr_data = Ticket.showAll(); data = new Object[arr_data.size()][]; for (int i = 0; i < arr_data.size(); i++) { data[i] = arr_data.get(i).Array(); } this.fireTableDataChanged(); }
ef4920ca-92f0-49e5-bfbe-0d4ff99e5790
0
public Employee(String n, double s) { name = n; salary = s; }
5738ef65-3392-4b9d-9925-0ad02fe4146d
0
public void reset() { state = STATE_RELEASED; amount = 0; }
fb968695-c944-4d8c-a146-c73f82e48850
0
private void setReadyButtonClick() { _view.active.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Map<String, Object> m = new HashMap<String, Object>(); m.put("action", "ready"); _model.sendMessage(m); _view.active.setEnabled(false); _view.active.setText("Actived"); } }); }
6a03d7e2-99fc-449c-91f1-6e4f960623df
0
@Override public void stop() throws Exception { super.stop(); ConnectionPool.close(); }
33695018-8972-42f7-8921-fbd7f2958bd7
5
public static int findPeakElement(int[] num) { if (null == num || 0 == num.length) return -1; int len = num.length; int low = 0, high = len - 1; int mid = 0; if (1 == len) return 0; while (low < high) { mid = (low + high) >> 1; if (num[mid] < num[mid + 1]) low = mid + 1; else high = mid; } return low; }
d261e9aa-4896-4062-8001-cfed1a776469
3
public static List<TestInstanceInfo> getTestInstances(HierarchicalConfiguration testsetData) { List<TestInstanceInfo> testInstances = null; List<HierarchicalConfiguration> testInstancesData = testsetData.configurationsAt(TESTINSTANCE_TAG); if (testInstancesData != null && !testInstancesData.isEmpty()) { testInstances = new ArrayList<TestInstanceInfo>(); for (HierarchicalConfiguration testInstanceData : testInstancesData) { TestInstanceInfo testInstance = getTestInstanceInfo(testInstanceData); testInstances.add(testInstance); } } return testInstances; }
95f10633-e696-489c-b9fc-5f8920ef9ab4
1
@Override public void putAll(CSProperties p) { super.putAll(p); for (String s : p.keySet()) { Map<String, String> m = p.getInfo(s); setInfo(s, m); } getInfo().putAll(p.getInfo()); }
c0c31c95-ec3b-461a-9135-fa9224e0cbba
2
private EnemyView getEnemyView(Enemy e) { for (EnemyView ev : enemies) { if (ev.getEnemy().equals(e)) { return ev; } } //if it's not already in the list create a new and add it EnemyView ev = new EnemyView(e); enemies.add(ev); return ev; }
3df84dcb-5505-4a73-be8a-37aa6b97b84e
8
public Vector2 getNextObj(Vector2 start, int direction){ MenuObj m = getObj(start); float x = projections.get(m).x; float y = projections.get(m).y; Vector2 next = start.cpy(); switch (direction){ case 1: // UP y = y > 0 ? y - 1 : vertical.size - 1; next = vertical.get((int) y).getMenuMapping(); break; case 2: // RIGHT x = x < horizontal.size-1 ? x + 1 : x; next = horizontal.get((int) x).getMenuMapping(); break; case 3: // DOWN y = y < vertical.size-1 ? y + 1 : 0; next = vertical.get((int) y).getMenuMapping(); break; case 4: // LEFT x = x > 0 ? x - 1 : x; next = horizontal.get((int) x).getMenuMapping(); break; } return next; }
b867666d-6f44-4e9f-8e6c-fd959ff37b57
9
@Override public void paintComponent(Graphics graphics) { int xOrigin = (int) (xOffset - ((getCanvasWidth() * getScale()) / 2D)); int yOrigin = (int) (yOffset - ((getCanvasHeight() * getScale()) / 2D)); for (int x = 0; x < getCanvasWidth(); x += 8) { for (int y = 0; y < getCanvasHeight(); y += 8) { graphics.setColor(((x / 8) + ((y / 8) % 2 == 0 ? 1 : 0)) % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE); graphics.fillRect((int) (xOrigin + (x * getScale())), (int) (yOrigin + (y * getScale())), (int) (8 * getScale()), (int) (8 * getScale())); } } graphics.setColor(Color.BLACK); graphics.drawRect(xOrigin, yOrigin, (int) (canvasWidth * getScale()), (int) (canvasHeight * getScale())); Graphics2D graphics2D = (Graphics2D) graphics; graphics2D.translate(xOffset, yOffset); graphics2D.scale(scale, scale); frames.get(frame).render(graphics); if (workingPivot != null && mousePressed && getToolboxPanel().isConnectorSelected()) { graphics.setColor(Color.ORANGE); graphics.drawLine((int) workingPivot.getLocation().getX(), (int) workingPivot.getLocation().getY(), mouseX, mouseY); } if (mousePressed && getToolboxPanel().isLightSourceSelected()) { graphics.setColor(new Color(255, 255, 128)); int dy = startY - mouseY; int dx = startX - mouseX; int radius = (int) Math.round(Math.sqrt(dy * dy + dx * dx)); graphics.drawOval(startX - radius, startY - radius, radius * 2, radius * 2); } graphics2D.scale(1D / scale, 1D / scale); graphics2D.translate(-xOffset, -yOffset); }
3db2ae22-8fec-4496-aba8-d51404ed3dd2
5
public static void main(String[] args) { long startTime = System.currentTimeMillis(); int limit = 10000000; boolean[] isNotPrime = new boolean[limit+1]; for (int i=2;i<=Math.sqrt(limit) ;i++ ) { if(!isNotPrime[i]) { for (int j=i;j*i<=limit;j++ ) { isNotPrime[j*i] = true; } } } int noPrimeNo = 0; for (int i=2;i<=limit ;i++ ) { if(!isNotPrime[i]) noPrimeNo++; } System.out.println( "No of prime number from 1 till " + limit + " is: " + noPrimeNo); long endTime = System.currentTimeMillis(); System.out.println("Time in mili sec: " + (endTime-startTime)); }
a2bd61ed-c81a-42b6-aa35-46203294f723
4
private void SelectJButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SelectJButtonMouseClicked //if merchant was not selected then pop warning int[] rowsSelected = merchantJTable.getSelectedRows(); if(rowsSelected.length > 0 && rowsSelected.length < 2){ //store the selected merchant in the selectedMerchant variable try{ selectedMerchant = new Merchant((int)merchantJTable.getValueAt(rowsSelected[0], 0)); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } //close the frame this.setVisible(false); this.dispose(); } else if(rowsSelected.length > 1){ //warn user that they can only select one merchant JOptionPane.showMessageDialog(this, "You have selected too many row. Please select one row.", "Selection Error", JOptionPane.WARNING_MESSAGE); } else{ //warn the user they must select a merchant first JOptionPane.showMessageDialog(this, "You did not select any row. Please select a row.", "Selection Error", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_SelectJButtonMouseClicked
45d87b36-abeb-48f1-9c87-7643b99a52da
8
@Override public void run() { try { while(!Thread.interrupted() ) { try { setupSocket(hostname, portNumber); } catch (IOException e1) { Thread.sleep(rand.nextInt(1000)); continue; } int numAttempts = rand.nextInt(10); for (int i =0; i< numAttempts; i++) { boolean doClose = i == numAttempts-1; try { if (tryConnect(hostname, doClose) == false) { fails++; } else { oks++; } Thread.sleep(rand.nextInt(10)); } catch (IOException e) { System.err.println(e.toString()); //java.net.ConnectException: Cannot assign requested address //https://groups.google.com/forum/#!topic/jvm-languages/E-8QyckBmf4 exceptions++; } catch (InterruptedException e) { break; } } try { shutdownSocket(); } catch (IOException e) { } } } catch (InterruptedException e) { //done } }
798af045-9560-4529-a1c8-a27ae92a6d46
2
public void addNgrambyup(Connection conn,Ngram ngram) throws Exception{ String wordAfterHandle = ""; for(int i=0;i<ngram.getWordGroup().length();i++) { char c = ngram.getWordGroup().charAt(i); if(c == '\'') { wordAfterHandle += "\\\'"; } else { wordAfterHandle += c; } } String sql = "insert into " + tableName +"(wordGroup,wordAttribute,frequence,count) values('" + wordAfterHandle + "','" + ngram.getWordAttribute() + "','0','1')" + "on duplicate key update count=count+1"; //System.out.println("sql is : " + sql); PreparedStatement stat = JDBC.getSatement(conn, sql); stat.executeUpdate(); JDBC.close(stat); }
66d32def-f91e-426d-a8f7-9253c383ee16
5
private void comen1(char []codigo){ int let = 0; //Para eliminar el comentario sencillo while(let<codigo.length-1){ if(codigo[let]=='/' && codigo[let+1]=='/'){ codigo[let] = ' '; codigo[let+1] = ' '; let++; let++; while(let<codigo.length && codigo[let]!='\n' ){ codigo[let] = ' '; let++; } } else{ let++; } } }
04562a59-0854-430e-9eaa-f5780284bfc4
8
public void endGame(){ String stillWalking = (s.whoseTurn() == "red")?"blue" : "red"; MyList blankPos = s.ownees(null); s.fill(blankPos,stillWalking,board); int redScore =s.getnRed() + ((stillWalking == "red")?s.getnEmpty():0); int blueScore = s.getnBlue() + ((stillWalking == "blue")?s.getnEmpty():0); board.setScore(redScore,blueScore); board.setPlayer(s.whoseTurn().equals("red") ? 1 : 2 ); String winner = redScore > blueScore ? "Red "+Hexxagon.getPlayerType(Hexxagon.p1Type)+" is the winner!" : (blueScore==redScore)? "Draw!" : "Blue "+Hexxagon.getPlayerType(Hexxagon.p2Type)+" is the winner!"; System.err.println(s.whoseTurn() + " did not produce a legal move. Ending game."); GameLoopState.effector.openEffect("charge.wav"); String[] choices = { "Restart Game","Return to Title" }; int response = JOptionPane.showOptionDialog(null // Center in // window. , winner // Message , "Game Ended!" // Title in titlebar , JOptionPane.YES_NO_OPTION // Option type , JOptionPane.PLAIN_MESSAGE // messageType , null // Icon (none) , choices // Button text as above. , "None of your business" // Default button's label ); if (response == 0){ Hexxagon.resetMatch(); } else if (response==1){ Hexxagon.restartApplication(); } }
f3463da3-c18b-4f83-b235-eb7e85dfff33
3
public void onDisable(){ log.info("Saving open slots..."); for(Player p : getServer().getOnlinePlayers()){ if(bm.getSlot(p.getName()) != null){ try { loader.saveSlot(bm.getCurrentSlotContents(p.getName()), p.getName(), bm.getSlot(p.getName())); } catch (Exception e) { log.severe("ERROR: Failed saving slot " + p.getName() + "/" + bm.getSlot(p.getName())); printException(e); } bm.setCurrentSlotContents(p.getName(), null); bm.setSlot(p.getName(), null); } } log.info(description.getName() + " " + description.getVersion() + " has been disabled."); }
4657057b-8e64-4f63-b834-d5ce52ed81e4
2
public void persistRuleSet(RuleSet ruleSet) { String sqlStatement; dao.connect(); sqlStatement = generateInsertStmt(ruleSet); if(dao.getErrorLogs().getErrorMsgs().size() == 0){ dao.executeUpdate(sqlStatement); } if(dao.getErrorLogs().getErrorMsgs().size() == 0){ dao.disconnect(); } }
0449ad5a-48f4-4be8-9000-5a773d4201e7
3
public OceanLifeGui (String test, Ocean ocean) { super(test); width = ocean.getWidth(); depth = ocean.getDepth(); setLayout(null); setResizable(false); setLocation((((int)dim.getWidth() - width) / 2),(((int)dim.getHeight()- depth) / 2)); PaintArea oceanArea = new PaintArea(ocean); oceanArea.setVisible(true); if(width < 800){ oceanArea.setBounds(((800 - width) / 2), 60, width, depth); } else{ oceanArea.setBounds(0, 60, width, depth); } add(oceanArea); ButtonsPanel buttonsView = new ButtonsPanel(ocean, oceanArea); if (width < 800){ buttonsView.setBounds(0, 0, widthSafe, 60); } else { buttonsView.setBounds(0, 0, width, 60); } add(buttonsView); buttonsView.setVisible(true); OceanData oceanData = new OceanData(ocean); oceanData.setVisible(true); if (width < 800) { oceanData.setBounds(0, depth + 80, widthSafe, 20); } else { oceanData.setBounds(0, depth + 80, width, 20); } add(oceanData); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); }
eac8e413-69c4-47ba-9e94-fcd4bd345369
1
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { buf.setLength(0); buf.append(tab).append('@'); appendDescriptor(FIELD_DESCRIPTOR, desc); buf.append('('); text.add(buf.toString()); TraceAnnotationVisitor tav = createTraceAnnotationVisitor(); text.add(tav.getText()); text.add(visible ? ")\n" : ") // invisible\n"); return tav; }
cc01fa45-a95c-4553-8129-7a7e7114458a
8
public Element build(ServerPlayer serverPlayer) { List<Change> c = new ArrayList<Change>(changes); List<Element> elements = new ArrayList<Element>(); List<Change> diverted = new ArrayList<Change>(); Document doc = DOMMessage.createNewDocument(); // For all sorted changes, if it is notifiable to the target // player then convert it to an Element, or divert for later // attachment. Then add all consequence changes to the list. Collections.sort(c, changeComparator); while (!c.isEmpty()) { Change change = c.remove(0); if (change.isNotifiable(serverPlayer)) { if (change.convertsToElement()) { elements.add(change.toElement(serverPlayer, doc)); } else { diverted.add(change); } c.addAll(change.consequences(serverPlayer)); } } elements = collapseElementList(elements); // Decide what to return. If there are several parts with // children then return multiple, if there is one viable part, // return that, if there is none return null unless there are // attributes in which case they become viable as an update. Element result; switch (elements.size()) { case 0: if (diverted.isEmpty()) return null; result = doc.createElement("update"); break; case 1: result = elements.get(0); break; default: result = doc.createElement("multiple"); for (Element e : elements) result.appendChild(e); break; } doc.appendChild(result); for (Change change : diverted) change.attachToElement(result); return result; }
ae7d562c-4cb2-4296-8e3d-9fb599a752c4
6
public void removeChar(String delStr) { int i; CharList tmpNode; CharList prevNode; firstNode = this; for (i = 0; i < delStr.length(); i++) { tmpNode = firstNode; prevNode = firstNode; while (tmpNode != null && tmpNode.ch == delStr.charAt(i)) { prevNode = tmpNode; tmpNode = tmpNode.next; } firstNode = tmpNode; if (tmpNode == null) { continue; } while (tmpNode != null) { if (tmpNode.ch == delStr.charAt(i)) { prevNode.next = tmpNode.next; } else { prevNode = tmpNode; } tmpNode = tmpNode.next; } } }
72086e9f-427c-4343-bea6-cf23966b2d4f
2
@Override public ClienteBean set(ClienteBean oClienteBean) throws Exception { try { oMysql.conexion(enumTipoConexion); oMysql.initTrans(); if (oClienteBean.getId() == 0) { oClienteBean.setId(oMysql.insertOne("cliente")); } oMysql.updateOne(oClienteBean.getId(), "cliente", "nombre", oClienteBean.getNombre()); oMysql.updateOne(oClienteBean.getId(), "cliente", "ape1", oClienteBean.getApe1()); oMysql.updateOne(oClienteBean.getId(), "cliente", "ape2", oClienteBean.getApe2()); oMysql.updateOne(oClienteBean.getId(), "cliente", "email", oClienteBean.getEmail()); oMysql.commitTrans(); } catch (Exception e) { oMysql.rollbackTrans(); throw new Exception("ClienteDao.setCliente: Error: " + e.getMessage()); } finally { oMysql.desconexion(); } return oClienteBean; }
8092a5cc-616c-44ba-b16a-4766be95ba12
5
@Override public void layout () { float regionWidth, regionHeight; if (drawable != null) { regionWidth = drawable.getMinWidth(); regionHeight = drawable.getMinHeight(); } else return; float width = getWidth(); float height = getHeight(); Vector2 size = scaling.apply(regionWidth, regionHeight, width, height); imageWidth = size.x; imageHeight = size.y; if ((align & Align.left) != 0) imageX = 0; else if ((align & Align.right) != 0) imageX = width - imageWidth; else imageX = width / 2 - imageWidth / 2; if ((align & Align.top) != 0) imageY = height - imageHeight; else if ((align & Align.bottom) != 0) imageY = 0; else imageY = height / 2 - imageHeight / 2; }
25d179b3-6ee8-4b9c-b628-d07b112106e7
0
public static HandlerList getHandlerList() { return handlers; }
56a0c784-ad4a-4d6c-a1bd-bbd03b1e2418
9
public static Class convertPrimitiveClass(final Class obj) { if (!obj.isPrimitive()) { return obj; } if (obj == Boolean.TYPE) { return Boolean.class; } if (obj == Byte.TYPE) { return Byte.class; } if (obj == Character.TYPE) { return Character.class; } if (obj == Short.TYPE) { return Short.class; } if (obj == Integer.TYPE) { return Integer.class; } if (obj == Long.TYPE) { return Long.class; } if (obj == Float.TYPE) { return Float.class; } if (obj == Double.TYPE) { return Double.class; } throw new IllegalArgumentException("Class 'void' is not allowed here"); }
1291115b-8494-4444-adcf-4e65a7685dca
4
public List<Article> getItems() { System.out.println(baseUrl); List<Article> articles=new ArrayList<Article>(); try { URL feedUrl = new URL(baseUrl); /* SyndFeedInput: parser to process RSS feeds into SyndFeed instance*/ SyndFeedInput input = new SyndFeedInput(); /* Load the RSS feed * XmlReader: reading an XML document * SyndFeed: rss feed */ SyndFeed feed = input.build(new XmlReader(feedUrl)); // Iterate through feed items, display each item title Iterator entryIter = feed.getEntries().iterator(); ArticleDao ad = ArticleDao.getInstance(); int id = ad.findAll().size(); while (entryIter.hasNext()) { SyndEntry entry = (SyndEntry) entryIter.next(); Article article=new Article(id++,entry.getTitle(), entry.getDescription().getValue(), new Date(entry.getPublishedDate().getTime())); articles.add(article); } } catch (IOException ex) { Logger.getLogger(RssFeadReader.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { Logger.getLogger(RssFeadReader.class.getName()).log(Level.SEVERE, null, ex); } catch (FeedException ex) { Logger.getLogger(RssFeadReader.class.getName()).log(Level.SEVERE, null, ex); } return articles; }
f5f8de17-40ea-4789-b002-6336f9f76813
7
public static void startupMemoize() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.$STELLA_MODULE$); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { _StartupMemoize.helpStartupMemoize1(); } if (Stella.currentStartupTimePhaseP(4)) { Stella.$ALL_MEMOIZATION_TABLES$ = List.newList(); { Symbol self073 = Symbol.newSymbol("MEMOIZED-NULL-VALUE"); self073.homeContext = null; Stella.MEMOIZED_NULL_VALUE = self073; } } if (Stella.currentStartupTimePhaseP(5)) { { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("MEMOIZATION-TABLE", "(DEFCLASS MEMOIZATION-TABLE (STANDARD-OBJECT) :DOCUMENTATION \"Table that maps argument values onto computed results for\none individual memoization site.\" :SLOTS ((HASH-TABLE :TYPE (INTEGER-HASH-TABLE OF INTEGER (CONS OF CONS)) :DOCUMENTATION \"The table holding the memoized values.\nWe use an integer table, since we explicitly compute a hash code by combining\nhash codes of argument values.\") (TABLE-NAME :TYPE SURROGATE :DOCUMENTATION \"The surrogate used to point to this table.\nUsed at the memoization site for quick memo table lookup.\") (CURRENT-TIMESTAMP :TYPE CONS :DOCUMENTATION \"Marker value used to indicate valid memoized entries.\nThis marker changes everytime one of the `timestamps' gets bumped.\") (TIMESTAMPS :TYPE (CONS OF KEYWORD) :INITIALLY NIL :DOCUMENTATION \"Names of timestamps that trigger invalidation of\nmemoized entries when they get bumped.\")))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.stella.MemoizationTable", "newMemoizationTable", new java.lang.Class [] {}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.stella.MemoizationTable", "accessMemoizationTableSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MemoizationTable"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } Stella.$MEMOIZATION_ENABLEDp$ = true; { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("MRU-MEMOIZATION-TABLE", "(DEFCLASS MRU-MEMOIZATION-TABLE (MEMOIZATION-TABLE) :SLOTS ((MRU-BUCKETS-VECTOR :TYPE (VECTOR OF (CONS OF CONS))) (LRU-BUCKETS-VECTOR :TYPE (VECTOR OF (CONS OF CONS))) (MRU-BUCKETS :TYPE (NATIVE-VECTOR OF (CONS OF CONS))) (LRU-BUCKETS :TYPE (NATIVE-VECTOR OF (CONS OF CONS))) (MRU-TIMESTAMP :TYPE CONS) (LRU-TIMESTAMP :TYPE CONS) (NOF-BUCKETS :TYPE INTEGER) (FREE-ENTRIES :TYPE INTEGER) (MAX-ENTRIES :TYPE INTEGER)))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.stella.MruMemoizationTable", "newMruMemoizationTable", new java.lang.Class [] {}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.stella.MruMemoizationTable", "accessMruMemoizationTableSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MruMemoizationTable"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("MEMOIZABLE-ITERATOR", "(DEFCLASS MEMOIZABLE-ITERATOR (ITERATOR) :DOCUMENTATION \"Iterator class with value buffering that can be used to memoize some\n`base-iterator' without having to generate all its values first. The\nmemoized iterator needs to be cloned to allow multiple iterations over\nthe collection represented by the memoized iterator. Use the following\nidiom to memoize some arbitrary iterator and return a properly cloned value:\n \n (clone-memoized-iterator\n (memoize (...) <options>*\n (new MEMOIZABLE-ITERATOR\n :base-iterator <base-iterator>)))\n \nThis will ensure that <base-iterator> is exhausted exactly once even if\nthere are multiple clones for the same memoized value, and that each value\nis generated as late as absolutely possible. THIS IS NOT YET THREAD SAFE!\" :PUBLIC? TRUE :SLOTS ((BASE-ITERATOR :TYPE ITERATOR :REQUIRED? TRUE :DOCUMENTATION \"This slot is only needed to pass the base iterator\nto the constructor. Once `self' is initialized it will be cleared.\") (ITERATOR-AND-VALUES :TYPE CONS :INITIALLY NULL :DOCUMENTATION \"Holds the base iterator and the values generated\nso far. This slot is structure shared between the memoized iterator and\nall its clones to make sure everybody sees any new values generated by\nany one of the clones, and that everybody can see when the base iterator\nis exhausted.\") (CURSOR :TYPE CONS :INITIALLY NULL :DOCUMENTATION \"Trailing cursor to the list of values generated\nso far. Once the end of the list is reached this slot is used to add new\nvalues to the end of `iterator-and-values'.\")) :INITIALIZER INITIALIZE-MEMOIZABLE-ITERATOR)"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.stella.MemoizableIterator", "newMemoizableIterator", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Iterator")}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.stella.MemoizableIterator", "accessMemoizableIteratorSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MemoizableIterator"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { Stella.defineFunctionObject("ENABLE-MEMOIZATION", "(DEFUN ENABLE-MEMOIZATION () :COMMAND? TRUE :PUBLIC? TRUE :DOCUMENTATION \"Enable memoization and use of memoized expression results.\")", Native.find_java_method("edu.isi.stella.Stella", "enableMemoization", new java.lang.Class [] {}), null); Stella.defineFunctionObject("DISABLE-MEMOIZATION", "(DEFUN DISABLE-MEMOIZATION () :COMMAND? TRUE :PUBLIC? TRUE :DOCUMENTATION \"Enable memoization and use of memoized expression results.\")", Native.find_java_method("edu.isi.stella.Stella", "disableMemoization", new java.lang.Class [] {}), null); Stella.defineFunctionObject("HASH-MEMOIZED-ARGUMENTS", "(DEFUN (HASH-MEMOIZED-ARGUMENTS INTEGER) ((ARG1 OBJECT) (ARG2 OBJECT) (ARG3 OBJECT) (ARG4 OBJECT) (EQVECTOR INTEGER)))", Native.find_java_method("edu.isi.stella.Stella_Object", "hashMemoizedArguments", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Integer.TYPE}), null); Stella.defineFunctionObject("HASH-MEMOIZED-ARGUMENTSN", "(DEFUN (HASH-MEMOIZED-ARGUMENTSN INTEGER) ((TUPLE CONS) (EQVECTOR INTEGER)))", Native.find_java_method("edu.isi.stella.Cons", "hashMemoizedArgumentsn", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), java.lang.Integer.TYPE}), null); Stella.defineFunctionObject("MAKE-MEMOIZED-VALUE-ENTRY", "(DEFUN (MAKE-MEMOIZED-VALUE-ENTRY (CONS OF CONS)) ((VALUE OBJECT) (ARG1 OBJECT) (ARG2 OBJECT) (ARG3 OBJECT) (ARG4 OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "makeMemoizedValueEntry", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("MAKE-MEMOIZED-VALUE-ENTRYN", "(DEFUN (MAKE-MEMOIZED-VALUE-ENTRYN (CONS OF CONS)) ((VALUE OBJECT) (ARGS CONS)) :GLOBALLY-INLINE? TRUE (RETURN (CONS VALUE ARGS)))", Native.find_java_method("edu.isi.stella.Stella_Object", "makeMemoizedValueEntryn", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Cons")}), null); Stella.defineFunctionObject("FIND-MEMOIZED-VALUE-ENTRY", "(DEFUN (FIND-MEMOIZED-VALUE-ENTRY CONS) ((BUCKET (CONS OF CONS)) (ARG1 OBJECT) (ARG2 OBJECT) (ARG3 OBJECT) (ARG4 OBJECT) (EQVECTOR INTEGER) (DELETEENTRY? BOOLEAN)))", Native.find_java_method("edu.isi.stella.Cons", "findMemoizedValueEntry", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Integer.TYPE, java.lang.Boolean.TYPE}), null); Stella.defineFunctionObject("FIND-MEMOIZED-VALUE-ENTRYN", "(DEFUN (FIND-MEMOIZED-VALUE-ENTRYN CONS) ((BUCKET (CONS OF CONS)) (TUPLE CONS) (EQVECTOR INTEGER) (DELETEENTRY? BOOLEAN)))", Native.find_java_method("edu.isi.stella.Cons", "findMemoizedValueEntryn", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.Cons"), java.lang.Integer.TYPE, java.lang.Boolean.TYPE}), null); Stella.defineFunctionObject("LOOKUP-MEMOIZED-VALUE", "(DEFUN (LOOKUP-MEMOIZED-VALUE CONS) ((MEMOTABLE MEMOIZATION-TABLE) (ARG1 OBJECT) (ARG2 OBJECT) (ARG3 OBJECT) (ARG4 OBJECT) (EQVECTOR INTEGER)))", Native.find_java_method("edu.isi.stella.MemoizationTable", "lookupMemoizedValue", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MemoizationTable"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Integer.TYPE}), null); Stella.defineFunctionObject("LOOKUP-MEMOIZED-VALUEN", "(DEFUN (LOOKUP-MEMOIZED-VALUEN CONS) ((MEMOTABLE MEMOIZATION-TABLE) (ARGS CONS) (EQVECTOR INTEGER)))", Native.find_java_method("edu.isi.stella.MemoizationTable", "lookupMemoizedValuen", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MemoizationTable"), Native.find_java_class("edu.isi.stella.Cons"), java.lang.Integer.TYPE}), null); Stella.defineFunctionObject("INITIALIZE-MRU-BUCKET-TABLES", "(DEFUN INITIALIZE-MRU-BUCKET-TABLES ((MEMOTABLE MRU-MEMOIZATION-TABLE)))", Native.find_java_method("edu.isi.stella.MruMemoizationTable", "initializeMruBucketTables", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MruMemoizationTable")}), null); Stella.defineFunctionObject("LOOKUP-MRU-MEMOIZED-VALUE", "(DEFUN (LOOKUP-MRU-MEMOIZED-VALUE CONS) ((MEMOTABLE MRU-MEMOIZATION-TABLE) (ARG1 OBJECT) (ARG2 OBJECT) (ARG3 OBJECT) (ARG4 OBJECT) (EQVECTOR INTEGER)))", Native.find_java_method("edu.isi.stella.MruMemoizationTable", "lookupMruMemoizedValue", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MruMemoizationTable"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Integer.TYPE}), null); Stella.defineFunctionObject("LOOKUP-MRU-MEMOIZED-VALUEN", "(DEFUN (LOOKUP-MRU-MEMOIZED-VALUEN CONS) ((MEMOTABLE MRU-MEMOIZATION-TABLE) (ARGS CONS) (EQVECTOR INTEGER)))", Native.find_java_method("edu.isi.stella.MruMemoizationTable", "lookupMruMemoizedValuen", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MruMemoizationTable"), Native.find_java_class("edu.isi.stella.Cons"), java.lang.Integer.TYPE}), null); Stella.defineFunctionObject("INITIALIZE-MEMOIZATION-TABLE", "(DEFUN INITIALIZE-MEMOIZATION-TABLE ((MEMOTABLESURROGATE SURROGATE) (OPTIONS STRING)))", Native.find_java_method("edu.isi.stella.Surrogate", "initializeMemoizationTable", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Surrogate"), Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("CLEAR-ALL-MEMOIZATION-TABLES", "(DEFUN CLEAR-ALL-MEMOIZATION-TABLES ())", Native.find_java_method("edu.isi.stella.Stella", "clearAllMemoizationTables", new java.lang.Class [] {}), null); Stella.defineFunctionObject("CLEAR-MEMOIZATION-TABLES", "(DEFUN CLEAR-MEMOIZATION-TABLES ((TIMESTAMPNAME KEYWORD)))", Native.find_java_method("edu.isi.stella.Keyword", "clearMemoizationTables", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Keyword")}), null); Stella.defineFunctionObject("BUMP-MEMOIZATION-TIMESTAMP", "(DEFUN BUMP-MEMOIZATION-TIMESTAMP ((TIMESTAMPNAME KEYWORD)))", Native.find_java_method("edu.isi.stella.Keyword", "bumpMemoizationTimestamp", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Keyword")}), null); Stella.defineFunctionObject("MAKE-MEMOIZATION-TABLE-SURROGATE", "(DEFUN (MAKE-MEMOIZATION-TABLE-SURROGATE SURROGATE) ((MEMONAME SYMBOL)))", Native.find_java_method("edu.isi.stella.Symbol", "makeMemoizationTableSurrogate", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol")}), null); Stella.defineFunctionObject("PARSE-MEMOIZE-OPTIONS", "(DEFUN (PARSE-MEMOIZE-OPTIONS PROPERTY-LIST) ((OPTIONS CONS)))", Native.find_java_method("edu.isi.stella.Cons", "parseMemoizeOptions", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null); Stella.defineFunctionObject("MEMOIZE", "(DEFUN MEMOIZE ((INPUTARGS CONS) |&BODY| (BODY CONS)) :TYPE OBJECT :MACRO? TRUE :DOCUMENTATION \"Compute the value of an expression and memoize it relative to\n the values of `inputArgs'.\n`inputArgs' should characterize the complete set of values upon which\n the computation of the result depended.\nCalls to `memoize' should be of the form\n\n (memoize (<arg>+) {:<option> <value>}* <expression>)\n\n and have the status of an expression.\n The following options are supported:\n\n :timestamps A single or list of keywords specifying the names of\n timestamps which when bumped should invalidate all\n entries currently memoized in this table.\n :name Names the memoization table so it can be shared by other\n memoization sites. By default, a gensymed name is used.\n CAUTION: IT IS ASSUMED THAT ALL ENTRIES IN A MEMOZATION\n TABLE DEPEND ON THE SAME NUMBER OF ARGUMENTS!!\n :max-values The maximum number of values to be memoized. Only the\n `:max-values' most recently used values will be kept\n in the memoization table, older values will be discarded\n and recomputed if needed. Without a `:max-values'\n specification, the memoization table will grow\n indefinitely.\n\nPERFORMANCE NOTES: For most efficient lookup, input arguments that vary the most\nshould be listed first. Also, arguments of type STANDARD-OBJECT (and all its\nsubtypes) can be memoized more efficiently than arguments of type OBJECT or\nwrapped literals (with the exception of BOOLEANs).\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Cons", "memoize", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.Cons")}), null); Stella.defineMethodObject("(DEFMETHOD INITIALIZE-MEMOIZABLE-ITERATOR ((SELF MEMOIZABLE-ITERATOR)))", Native.find_java_method("edu.isi.stella.MemoizableIterator", "initializeMemoizableIterator", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineFunctionObject("CLONE-MEMOIZED-ITERATOR", "(DEFUN (CLONE-MEMOIZED-ITERATOR (ITERATOR OF (LIKE (ANY-VALUE SELF)))) ((SELF MEMOIZABLE-ITERATOR)) :DOCUMENTATION \"Clone the memoized iterator `self' so it can be used to\niterate over the collection represented by `self', while allowing to iterate\nover it multiple times via multiple clones.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.MemoizableIterator", "cloneMemoizedIterator", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MemoizableIterator")}), null); Stella.defineMethodObject("(DEFMETHOD (ALLOCATE-ITERATOR (ITERATOR OF (LIKE (ANY-VALUE SELF)))) ((SELF MEMOIZABLE-ITERATOR)) :DOCUMENTATION \"Alias for `clone-memoized-iterator'.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.MemoizableIterator", "allocateIterator", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (NEXT? BOOLEAN) ((SELF MEMOIZABLE-ITERATOR)) :DOCUMENTATION \"Generate the next value of the memoized iterator `self' (or\none of its clones) by either using one of the values generated so far or by\ngenerating and saving the next value of the `base-iterator'.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.MemoizableIterator", "nextP", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineFunctionObject("STARTUP-MEMOIZE", "(DEFUN STARTUP-MEMOIZE () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella._StartupMemoize", "startupMemoize", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(Stella.SYM_STELLA_STARTUP_MEMOIZE); KeyValueList.setDynamicSlotValue(function.dynamicSlots, Stella.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupMemoize"), Stella.NULL_STRING_WRAPPER); } } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("STELLA"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *ALL-MEMOIZATION-TABLES* (LIST OF MEMOIZATION-TABLE) (NEW LIST) :DOCUMENTATION \"Holds all currently active memoization tables for timestamp\nmaintenance and clearance purposes.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MEMOIZATION-ENABLED?* BOOLEAN FALSE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT MEMOIZED-NULL-VALUE SYMBOL (NEW SYMBOL :SYMBOL-NAME \"MEMOIZED-NULL-VALUE\" :HOME-CONTEXT NULL) :DOCUMENTATION \"Used by memoization to indicate that a NULL value\nwas cached. Needed to distinguish between an undefined value and a\ncached NULL.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *TOTAL-MEMOIZATION-LOOKUPS* INTEGER 0)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *FAILED-MEMOIZATION-LOOKUPS* INTEGER 0)"); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
0cea5ca6-38e9-4338-8d8c-6a88dd764802
7
@Override public void write(ICTMC ctcm, String pathname) throws Exception { BufferedWriter outputStrm = new BufferedWriter(new FileWriter(pathname)); Matrix tmpM; List<Matrix> tmpTra; int i = -1; int max = -1; int j = -1; int maxT = -1; try { tmpM = ctcm.getQ(); max = tmpM.getRowDimension(); outputStrm.write("n=" + max); outputStrm.write(";"); outputStrm.write(" h=" + String.format("%.16e", ctcm.getH())); outputStrm.write(";"); outputStrm.write(" T=" + String.format("%.16e", ctcm.getT())); outputStrm.write(";"); outputStrm.write(" epsilon=" + String.format("%.16e", ctcm.getEpsilon())); outputStrm.write(";"); outputStrm.write(" k=" + ctcm.getK()); outputStrm.newLine(); outputStrm.write("Q"); outputStrm.newLine(); outputStrm.write(this.matrixToString(tmpM, "%.16e")); if(ctcm.isIrreducible()) { outputStrm.newLine(); outputStrm.write("Irreducible CTMC steady state solution"); outputStrm.newLine(); tmpM = ctcm.getStazionario(); outputStrm.write(this.matrixToString(tmpM, "%.16e")); } outputStrm.newLine(); outputStrm.write("**********"); outputStrm.newLine(); tmpTra = ctcm.getTransitorio(); maxT = tmpTra.size(); for(j=0;j<maxT;++j) { if((j%ctcm.getK())==0) { if(j>0) { outputStrm.newLine(); } outputStrm.write("t="+j+"*h"); outputStrm.newLine(); tmpM = tmpTra.get(j); max = tmpM.getColumnDimension(); for (i = 0;i<max;++i) { if(i>0) { outputStrm.write(";"); } outputStrm.write(String.format("%.16e", tmpM.get(0, i))); } } } } catch (Exception e) { e.printStackTrace(); } finally { outputStrm.close(); } }
49d78aea-234a-4f46-b5a0-c4185fedbf27
9
String indentMaker(String setting, double spaces) { String list = ""; if (setting.equals("total")) { int x = endInd; if (paragraphOn && !_endnoteMode) { x = parIndent + indent; } else if (paragraphOn && _endnoteMode) { x = endParInd + endInd; } else if (!_endnoteMode) { x = indent; } while (x > 0) { list += " "; x--; } } if (setting.equals("space")) { while (spaces != 0) { list += " "; spaces--; } } return list; }
57024d39-340d-4fc0-8300-802a21c901b8
5
@Override public void update() { try { if(currentAchievement == null) { currentAchievement = queue.removeFirst(); lastTime = System.currentTimeMillis(); x = BlockyMain.width/2-100; y=-80; } else { if(System.currentTimeMillis()-lastTime < 4000) y+=2; else y-=1; if(y > 50) y = 50; if(y < -80) currentAchievement = null; } } catch(NoSuchElementException e) { } }
d99c0ac7-b06e-482d-bdaf-80a86952e002
5
public void setCipherKey(String cipherKey) { if (cipherKey == null || cipherKey.length() == 0) throw new IllegalArgumentException(); for (int i = 0; i < cipherKey.length(); i++) { if(cipherKey.charAt(i)<97 || cipherKey.charAt(i)>122) throw new IllegalArgumentException(); } this.cipherKey = cipherKey.toLowerCase(); }
f6dcfab2-52f7-4926-ab30-6d03ec7e6d40
1
public void testSubstituteDestructive() { System.out.println("\n*** testSubstituteDestructive ***"); try { CycFormulaSentence sentence = getCyc().makeCycSentence("(#$likesAsFriend ?X ?Y)"); sentence = sentence.substituteNonDestructive(CycObjectFactory.makeCycVariable("X"), CycObjectFactory.makeCycVariable("Z")); assertTrue(sentence.equalsAtEL(getCyc().makeCycSentence("(#$likesAsFriend ?Z ?Y)"))); } catch (Exception e) { failWithException(e); } System.out.println("*** testSubstituteDestructive OK ***"); }
c8cdec8d-8e6f-40e6-bcf5-ddbaf8ea2bd8
7
private int[] genericActionListener() { int laCases = -1; int nycCases = -1; int chicagoCases = -1; int atlantaCases = -1; int denverCases = -1; int dallasCases = -1; int miamiCases = -1; //la try { laCases = Integer.parseInt(this.losAngelesTF.getText()); } catch (NumberFormatException nfe) { this.losAngelesTF.setText("Fix Me"); return null; } //nyc try { nycCases = Integer.parseInt(this.nycTF.getText()); } catch (NumberFormatException nfe) { this.nycTF.setText("Fix Me"); return null; } //chicago try { chicagoCases = Integer.parseInt(this.chicagoTF.getText()); } catch (NumberFormatException nfe) { this.chicagoTF.setText("Fix Me"); return null; } //atlanta try { atlantaCases = Integer.parseInt(this.atlantaTF.getText()); } catch (NumberFormatException nfe) { this.atlantaTF.setText("Fix Me"); return null; } //denver try { denverCases = Integer.parseInt(this.denverTF.getText()); } catch (NumberFormatException nfe) { this.denverTF.setText("Fix Me"); return null; } //dallas try { dallasCases = Integer.parseInt(this.dallasTF.getText()); } catch (NumberFormatException nfe) { this.dallasTF.setText("Fix Me"); return null; } //miami try { miamiCases = Integer.parseInt(this.miamiTF.getText()); } catch (NumberFormatException nfe) { this.miamiTF.setText("Fix Me"); return null; } int totalCases = laCases + nycCases + chicagoCases + atlantaCases + denverCases + dallasCases + miamiCases; this.totalKnownTF.setText(Integer.toString(totalCases)); return new int[]{ laCases, nycCases, chicagoCases, atlantaCases, denverCases, dallasCases, miamiCases }; }
59115bab-b79e-4e94-adff-743fd2132dd6
1
public static void hypothesizeUseless(GrammarEnvironment env, Grammar g) { UselessProductionRemover remover = new UselessProductionRemover(); /* * Grammar g2 = remover.getUselessProductionlessGrammar(g); if * (g2.getProductions().length < g.getProductions().length) { * UselessPane up = new UselessPane(env, g); env.add(up, "Useless * Removal", new CriticalTag() {}); env.setActive(up); return; } * hypothesizeChomsky(env, g); */ Grammar g2 = UselessProductionRemover .getUselessProductionlessGrammar(g); Production[] p1 = g.getProductions(); Production[] p2 = g2.getProductions(); if (p1.length > p2.length) { UselessPane up = new UselessPane(env, g); env.add(up, "Useless Removal", new CriticalTag() { }); env.setActive(up); return; } hypothesizeChomsky(env, g); }