method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
5a094523-38a8-49dd-8050-f80ce79b7025
5
private void createDropTypes(Composite parent) { parent.setLayout(new RowLayout(SWT.VERTICAL)); Button textButton = new Button(parent, SWT.CHECK); textButton.setText("Text Transfer"); textButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Button b = (Button)e.widget; if (b.getSelection()) { addDropTransfer(TextTransfer.getInstance()); } else { removeDropTransfer(TextTransfer.getInstance()); } } }); Button b = new Button(parent, SWT.CHECK); b.setText("RTF Transfer"); b.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Button b = (Button)e.widget; if (b.getSelection()) { addDropTransfer(RTFTransfer.getInstance()); } else { removeDropTransfer(RTFTransfer.getInstance()); } } }); b = new Button(parent, SWT.CHECK); b.setText("HTML Transfer"); b.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Button b = (Button)e.widget; if (b.getSelection()) { addDropTransfer(HTMLTransfer.getInstance()); } else { removeDropTransfer(HTMLTransfer.getInstance()); } } }); b = new Button(parent, SWT.CHECK); b.setText("URL Transfer"); b.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Button b = (Button)e.widget; if (b.getSelection()) { addDropTransfer(URLTransfer.getInstance()); } else { removeDropTransfer(URLTransfer.getInstance()); } } }); b = new Button(parent, SWT.CHECK); b.setText("File Transfer"); b.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Button b = (Button)e.widget; if (b.getSelection()) { addDropTransfer(FileTransfer.getInstance()); } else { removeDropTransfer(FileTransfer.getInstance()); } } }); // initialize state textButton.setSelection(true); addDropTransfer(TextTransfer.getInstance()); }
6c4eb383-0d5e-4309-8d57-c4b1eedb5c29
8
protected String getAction(String xml) { if (xml == null) return null; Document document; try { document = DocumentBuilderFactory .newInstance() .newDocumentBuilder() .parse(new ByteArrayInputStream(xml.getBytes())); } catch (Exception ex) { throw new RuntimeException(ex); } Element root = document.getDocumentElement(); NodeList childNodes = root.getChildNodes(); Element element = null; for (int i = 0; i < childNodes.getLength(); i++) { if (childNodes.item(i).getNodeType() != Node.ELEMENT_NODE) continue; element = (Element) childNodes.item(i); } if (element == null) return null; childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { if (childNodes.item(i).getNodeType() != Node.ELEMENT_NODE) continue; element = (Element) childNodes.item(i); } if (element == null) return null; return element.getTagName(); }
3f05af4c-d7a2-433c-9622-3bd7d04cbc7e
2
public static int readFileToArray(int[] array, int array_len, String filename) throws IOException { File file = new File(filename); BufferedReader br = new BufferedReader(new FileReader(file)); String line = br.readLine(); int i = 0; while (line != null && i<array_len) { array[i] = Integer.parseInt(line.trim()); line = br.readLine(); i++; } br.close(); return i; }
bc425a58-6ce4-4c74-a5e0-03aad0870681
8
public void gradient(double x[], double g[]) { double f,sq1,sq2,sq3,f1,f2,f3,f4,fac,c1,c2,s1,s2; double theta,x1,x2,x3,x4; double f1d1,f1d2,f1d3; double f2d1,f2d2,f2d3; double f3d1,f3d2,f3d3; double thd1,thd2; if (id_f_to_min == 0) { g[1] = 2.0*x[1]; } else if (id_f_to_min == 1) { g[1] = 2.0*(x[1] - c); g[2] = 2.0*(x[2] - d); } else if (id_f_to_min == 2) { g[1] = 2.0*(x[1] - c); g[2] = 2.0*(x[2] - d); g[3] = 2.0*(x[3] - e); } else if (id_f_to_min == 3) { g[2] = 200.0*(x[2] - x[1]*x[1]); g[4] = 200.0*(x[4] - x[3]*x[3]); g[1] = -g[2]*2.0*x[1] - 2.0*(1.0 - x[1]); g[3] = -g[4]*2.0*x[3] - 2.0*(1.0 - x[3]); } else if (id_f_to_min == 4) { f1 = x[1] + 10.0*x[2]; f2 = x[3] - x[4]; f3 = x[2] - 2.0*x[3]; f4 = x[1] - x[4]; g[1] = 2.0*f1 + 40.0*f4*f4*f4; g[2] = 20.0*f1 + 4.0*f3*f3*f3; g[3] = 10.0*f2 - 8.0*f3*f3*f3; g[4] = -(10.0*f2 + 40.0*f4*f4*f4); } else if (id_f_to_min == 5) { c1 = Math.cos(x[1]); c2 = Math.cos(x[2]); s1 = Math.sin(x[1]); s2 = Math.sin(x[2]); f1 = 1.0 - (c1 + (1.0 - c1) - s1); f2 = 2.0 - ((c1 + 2.0*(1 - c2) - s2) + (c2 + 2.0*(1 - c2) - s2)); f1d1 = c1; f1d2 = 0.0; f2d1 = s1; f2d2 = -3.0*s2 + 2.0*c2; g[1] = 2.0*f1*f1d1 + 2.0*f2*f2d1; g[2] = 2.0*f2*f2d2; } else if (id_f_to_min == 6) { if (x[1] > 0.0) { theta = one_d_twopi*Math.atan(x[2]/x[1]); } else { theta = one_d_twopi*Math.atan(x[2]/x[1]) + .5; } f1 = 10.0*(x[3] - 10.0*theta); f2 = 10.0*(Math.sqrt(x[1]*x[1] + x[2]*x[2]) - 1.0); f3 = x[3]; fac = 1.0/(1.0 + x[2]*x[2]/(x[1]*x[1])); thd2 = one_d_twopi*fac/x[1]; thd1 = -thd2*x[2]/x[1]; f1d1 = -100.0*thd1; f1d2 = -100.0*thd2; f1d3 = 10.0; fac = 1.0/Math.sqrt(x[1]*x[1] + x[2]*x[2]); f2d1 = 10.0*x[1]*fac; f2d2 = 10.0*x[2]*fac; f2d3 = 0.0; f3d1 = 0.0; f3d2 = 0.0; f3d3 = 1.0; g[1] = 2.0*(f1*f1d1 + f2*f2d1 + f3*f3d1); g[2] = 2.0*(f1*f1d2 + f2*f2d2 + f3*f3d2); g[3] = 2.0*(f1*f1d3 + f2*f2d3 + f3*f3d3); } else { x1 = x[1]; x2 = x[2]; x3 = x[3]; x4 = x[4]; g[1] = 400.0*x1*(x1*x1 - x2) - 2.0*(1.0 - x1); g[2] = -200.0*(x1*x1 - x2) - 20.2*(1.0 - x2) - 19.8*(1.0 - x4); g[3] = 360.0*x3*(x3*x3 - x4) - 2.0*(1.0 - x3); g[4] = -180.0*(x3*x3 - x4) - 20.2*(1.0 - x4) - 19.8*(1.0 - x2); } }
65e7d30b-ec6c-4710-a563-7a5b941e01c9
9
public void run() { long fps = 0; long frames = 0; long updateTimer = 0; long framesPerSecondTimer = 0; long timestamp = 0; long sleepTime = 0; firstGame = true; long t1=0; while(true) { System.out.print(""); if(menu) continue; if(!initialized) { if(!firstGame) { resetGame(); } //System.out.println(firstGame); timestamp = System.nanoTime(); updateTimer = timestamp; framesPerSecondTimer = timestamp; statusbar.initializeClock(DISCO_OPEN_FROM, DISCO_CLOSE_AT, ONE_SECOND/60); initialized = true; firstGame = false; } //Updates if(!statusbar.isTimeOut()) { asManager.updateComponents(); //System.out.println("___________________________"); //System.out.println("Performance Check Player:"); t1 = System.nanoTime(); player.stepNextPosition(); //System.out.println("Insgesamte Dauer:\nZeit in Nanosekunden: "+(System.nanoTime()-t1)); statusbar.updateBars(player); statusbar.updateClock(); frames++; player.decreaseStatusOverTime(); asManager.decreaseStatusForAll(); updateTimer += UPDATE_TIME_INTERVALL; if(player.getActivityTimer()>0){ player.decActivityTimer(); } } else { gameView.animateGameOverScreen(); } //FPS Berechnung if(System.nanoTime()-framesPerSecondTimer >= FPS_DISPLAY_INTERVALL) { fps = frames*(ONE_SECOND/(System.nanoTime()-framesPerSecondTimer)); // gameView.fps.setText("FPS "+fps); frames = 0; framesPerSecondTimer += FPS_DISPLAY_INTERVALL; } timestamp = System.nanoTime(); sleepTime = convertToMilliseconds(UPDATE_TIME_INTERVALL-(System.nanoTime()-updateTimer)); if(sleepTime > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } } }
5b8b124b-b290-4612-a65c-9440762d575e
3
void AppendTable() { responseContent.append("<html>\n" + "<head>\n" + "<title></title>\n" + "<body>\n" + "<h3> Total requests number: " + controller.getCount() + "</h3>" + "<h3> Number of the unique requests: " + controller.getUniqueIpCount() + "</h3>" + "<h3> Request Counter for each IP</h3>" + "<p><table border=\"2\">\n" + "<tr>\n" + "<th> IP</th>\n" + "<th> Request quantity</th>\n" + "<th> Time of last request</th> \n" + "</tr>\n"); Map<String, IpData> src_ip = controller.getIpMap(); for (String key : src_ip.keySet()) { responseContent.append("<tr>\n" + "<td>" + key + "</td>\n" + "<td>" + src_ip.get(key).getCount() + "</td>\n" + "<td>" + src_ip.get(key).getTime() + "</td>\n" + "</tr>\n"); } responseContent.append("</table> " + "</p>\n"); responseContent.append("<h3>Number of redirection by Url</h3>" + "<table border=\"1\">\n" + "<tr>\n" + "<th> URL</th>\n" + "<th> Redirection quantity</th>\n" + "</tr>\n"); Map<String, Integer> urlMap = controller.getUrlMap(); for (String key : urlMap.keySet()) { responseContent.append("<tr>\n" + "<td>" + key + "</td>\n" + "<td>" + urlMap.get(key) + "</td>\n" + "</tr>\n"); } responseContent.append("</table> " + "</p>\n"); responseContent.append("<h3> Number of opened connections: " + HelloHandler.getConnectionsCount() + "</h3>"); responseContent.append("<h3>Log of the last 16 processed connections</h3>" + "<table border=\"2\">\n" + "<tr>\n" + "<th>src_ip</th>\n" + "<th>URI</th>\n" + "<th>timestamp</th>\n" + "<th>sent_bytes</th>\n" + "<th>received_bytes</th>\n" + "<th>speed (bytes/sec)</th>\n" + "</tr>\n"); Deque<RequestData> last16Connections = StatisticsController.getLogRequestQue(); for (RequestData d : last16Connections) { responseContent.append("<tr>\n" + "<td>" + d.getIp() + "</td>\n" + "<td>" + d.getUrl() + "</td>\n" + "<td>" + d.getTime() + "</td>\n" + "<td>" + d.getSentBytes() + "</td>\n" + "<td>" + d.getReceivedBytes() + "</td>\n" + "<td>" + d.getSpeed() + "</td>\n" + "</tr>\n"); } responseContent.append( "</table> " + "</p>\n" + "</body>\n" + "</html>"); }
14233bfc-aa7e-40fd-911f-b273f345cd67
3
public void lookForUpdates() { System.out.println("Searching for updates ...."); String cmds[] = checkForNewVersion(); if (cmds.length > 1) { System.out.println("New version found : " + cmds[0]); System.out.println("Downloading FabFileBot.jar ..."); String loadPath = settings.get("updateServer", defaultBasePath) + settings.get("fabfilebot", defaultBotRemotePath); System.out.println("Remote location : " + loadPath); downloadFile(loadPath, localBotName); System.out.println("Done."); System.out.println("Starting slavebot for update."); File currentJavaJarFile = new File(MainGui.class.getProtectionDomain() .getCodeSource().getLocation().getPath()); String currentJavaJarFilePath = currentJavaJarFile.getAbsolutePath(); if (currentJavaJarFilePath.contains(".jar")) { ProcessBuilder bot = new ProcessBuilder("java", "-jar", localBotName, remoteFilePath, currentJavaJarFilePath); try { bot.start(); System.out.println("Done."); System.exit(1); } catch (Exception e) { e.printStackTrace(); System.out.println("Failed starting slavebot for update."); } } else { System.out .println("Could not found executed jar file. Are you running this programm from Eclipse ?"); } } else { System.out.println("No new version available."); } }
e4796b8d-239a-4099-b50e-5aa9399adcce
7
private void adminGeneral(){ userList = new JList(); userList.setBackground(Color.white); updateuserList(); JScrollPane scroll= new JScrollPane(userList); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scroll.setViewportView(userList); scroll.setBounds(3, 3, 395, 250); scroll.setLayout(new ScrollPaneLayout()); ((JPanel)father.getComponentAt(0)).add(scroll); JButton searchUserID=new JButton("Search User ID"); searchUserID.setBounds(3, 253, 185, 35); ((JPanel)father.getComponentAt(0)).add(searchUserID); final JTextField userField=new JTextField(); userField.setBackground(Color.white); userField.setBounds(190, 258, 185, 23); ((JPanel)father.getComponentAt(0)).add(userField); JButton showUsers=new JButton("Show all users"); showUsers.setBounds(3, 307, 185, 35); ((JPanel)father.getComponentAt(0)).add(showUsers); final JButton modifyUser=new JButton("Modify User Credit"); modifyUser.setBounds(3, 280, 185, 35); modifyUser.setEnabled(false); ((JPanel)father.getComponentAt(0)).add(modifyUser); final JTextField creditField=new JTextField(); creditField.setBackground(Color.white); creditField.setBounds(190, 284, 185, 23); ((JPanel)father.getComponentAt(0)).add(creditField); JButton showItems=new JButton("Show all Items"); showItems.setBounds(190, 306, 190, 35); ((JPanel)father.getComponentAt(0)).add(showItems); final JButton delete=new JButton("Delete User"); final JPopupMenu menu = new JPopupMenu(); menu.add(delete); //Listeners showUsers.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateuserList(); } }); searchUserID.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateuserList(admin.findUserID(userField.getText())); } }); userList.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent me) { menu.setVisible(false); if(me.getClickCount()==2 && me.getButton()==MouseEvent.BUTTON1 && !userList.getSelectedValue().getClass().getName().equals("shop2.Test")){ aux=((TestUser)userList.getSelectedValue()).getData(); modifyUser.setEnabled(true); } if(me.getButton()==MouseEvent.BUTTON3 && !userList.isSelectionEmpty() && !userList.getSelectedValue().getClass().getName().equals("shop2.Test")){ aux=((TestUser)userList.getSelectedValue()).getData(); menu.setLocation(me.getLocationOnScreen()); menu.setVisible(true); delete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { admin.deleteUser((String)aux.get("id")); menu.setVisible(false); updateuserList(); } }); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); modifyUser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(!creditField.getText().equals("")){ admin.modifyUser((String)(((TestUser)userList.getSelectedValue()).getData().get("name")), (String)(((TestUser)userList.getSelectedValue()).getData().get("id")),(String)(((TestUser)userList.getSelectedValue()).getData().get("password")), Double.parseDouble(creditField.getText()) ); modifyUser.setEnabled(false); creditField.setText(""); updateuserList(); } } }); showItems.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateallList(); } }); }
6215355f-09c8-421f-a72b-b099f0da3dc6
2
private Map<String, Object> getDefaultFileProperties() { Map<String, Object> properties = new HashMap<String, Object>(); if (repositoryType == REP_TYPE_ALFRESCO) { properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document,P:loc:readiness,P:notification:notified"); } else if (repositoryType == REP_TYPE_NUXEO) { properties.put(PropertyIds.OBJECT_TYPE_ID, "File"); } GregorianCalendar publishDate = new GregorianCalendar(2012, 4, 1, 5, 0); properties.put("loc:readytoprocess", "notready"); properties.put("loc:processref", "sampleref"); properties.put("loc:readyat", publishDate); properties.put("loc:revised", false); properties.put("loc:notified", false); properties.put("loc:priority", "low"); properties.put("loc:completeby", publishDate); properties.put("loc:globix", "sample"); // properties.put("notification:notificationsent", false); return properties; }
0ec881b2-485a-4ffd-8480-cf1209287c7e
2
private void makeBehaviorCache(CtMember.Cache cache) { List list = getClassFile2().getMethods(); int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); if (minfo.isMethod()) { CtMethod newMethod = new CtMethod(minfo, this); cache.addMethod(newMethod); } else { CtConstructor newCons = new CtConstructor(minfo, this); cache.addConstructor(newCons); } } }
c2f995f9-9d16-4ddf-a995-ee394ca85eaa
6
public String searchImage(int rawId, int action) { int Action=action/32;//0-3 int Direction=(action/4)%8; int FrameId=action%4; if(Action==0){ int newActionId=this.generateActionId(0, Direction, 1); return image_table.get(this.processID(rawId)).get(newActionId); } if(Action==1){ return image_table.get(this.processID(rawId)).get(action); } if(Action==2){ if(FrameId==3||FrameId==1){ int newActionId=this.generateActionId(0, Direction, 1); return image_table.get(this.processID(rawId)).get(newActionId); } else{ int newActionId=this.generateActionId(0, Direction, FrameId); return image_table.get(this.processID(rawId)).get(newActionId); } } if(Action==3) return image_table.get(this.processID(rawId)).get(100); return "Error Not Found"; }
261ac962-0f7c-4ed3-886c-c56676652fd6
6
public boolean inInterval(double value) { boolean returnValue = true; if(boundLeft <= value && value <= boundRight) { if(isOpenedLeft && value == boundLeft) returnValue = false; if(isOpenedRight && value == boundRight) returnValue = false; } else { returnValue = false; } return returnValue; }
b3564ecd-9722-4841-8046-8789aaf1922e
4
@Override public void deserialize(Buffer buf) { worldX = buf.readShort(); if (worldX < -255 || worldX > 255) throw new RuntimeException("Forbidden value on worldX = " + worldX + ", it doesn't respect the following condition : worldX < -255 || worldX > 255"); worldY = buf.readShort(); if (worldY < -255 || worldY > 255) throw new RuntimeException("Forbidden value on worldY = " + worldY + ", it doesn't respect the following condition : worldY < -255 || worldY > 255"); }
e086509f-a48c-4bf3-aece-f5e76197426e
1
public void testWithField3() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); try { test.withField(DateTimeFieldType.dayOfMonth(), 6); fail(); } catch (IllegalArgumentException ex) {} }
cd99d7db-9779-499c-88bc-20d0a63b668c
2
public void testPropertySetMonthOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.monthOfYear().setCopy(12); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-12-09T00:00:00.000Z", copy.toString()); test = new DateTime(2004, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().setCopy(2); assertEquals("2004-02-29T00:00:00.000Z", copy.toString()); try { test.monthOfYear().setCopy(13); fail(); } catch (IllegalArgumentException ex) {} try { test.monthOfYear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} }
4995be0b-c258-449f-9416-8e5499917736
0
public String getMatch() {return match;}
9b818798-7f21-44db-a7f8-719445917dc8
7
private JPanel createIconDialogBox() { JButton showItButton = null; final int numButtons = 6; JRadioButton[] radioButtons = new JRadioButton[numButtons]; final ButtonGroup group = new ButtonGroup(); final String plainCommand = "plain"; final String infoCommand = "info"; final String questionCommand = "question"; final String errorCommand = "error"; final String warningCommand = "warning"; final String customCommand = "custom"; radioButtons[0] = new JRadioButton("Plain (no icon)"); radioButtons[0].setActionCommand(plainCommand); radioButtons[1] = new JRadioButton("Information icon"); radioButtons[1].setActionCommand(infoCommand); radioButtons[2] = new JRadioButton("Question icon"); radioButtons[2].setActionCommand(questionCommand); radioButtons[3] = new JRadioButton("Error icon"); radioButtons[3].setActionCommand(errorCommand); radioButtons[4] = new JRadioButton("Warning icon"); radioButtons[4].setActionCommand(warningCommand); radioButtons[5] = new JRadioButton("Custom icon"); radioButtons[5].setActionCommand(customCommand); for (int i = 0; i < numButtons; i++) { group.add(radioButtons[i]); } radioButtons[0].setSelected(true); showItButton = new JButton("Show it!"); showItButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String command = group.getSelection().getActionCommand(); // no icon if (command == plainCommand) { JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "A plain message", JOptionPane.PLAIN_MESSAGE); // information icon } else if (command == infoCommand) { JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "Inane informational dialog", JOptionPane.INFORMATION_MESSAGE); // XXX: It doesn't make sense to make a question with // XXX: only one button. // XXX: See "Yes/No (but not in those words)" for a better // solution. // question icon } else if (command == questionCommand) { JOptionPane.showMessageDialog(frame, "You shouldn't use a message dialog " + "(like this)\n" + "for a question, OK?", "Inane question", JOptionPane.QUESTION_MESSAGE); // error icon } else if (command == errorCommand) { JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "Inane error", JOptionPane.ERROR_MESSAGE); // warning icon } else if (command == warningCommand) { JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "Inane warning", JOptionPane.WARNING_MESSAGE); // custom icon } else if (command == customCommand) { JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "Inane custom dialog", JOptionPane.INFORMATION_MESSAGE, icon); } } }); return create2ColPane("JOptionPane" + ":", radioButtons, showItButton); }
eeb879ef-7fd5-40b5-866d-29b8828a55d4
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; }
50a885a0-7c6a-4bd2-b337-059323ff098f
3
void setExampleWidgetState () { super.setExampleWidgetState (); if (!instance.startup) { setWidgetMinimum (); setWidgetMaximum (); setWidgetSelection (); } Widget [] widgets = getExampleWidgets (); if (widgets.length != 0) { if (orientationButtons) { horizontalButton.setSelection ((widgets [0].getStyle () & SWT.HORIZONTAL) != 0); verticalButton.setSelection ((widgets [0].getStyle () & SWT.VERTICAL) != 0); } borderButton.setSelection ((widgets [0].getStyle () & SWT.BORDER) != 0); } }
e15abf51-4db0-4b71-8abb-c1b4453fbd73
6
private boolean userIsStillAbleToWin(Card userCard) { if (cardStack.size() > 0) { return true; } int userCardValue = userCard.getValue(); int cardValue; int diff; for (int i = 0; i < NUMBER_OF_ROWS; i++) { for (int j = 0; j < NUMBER_OF_COLS; j++) { if (cards[i][j] != null) { cardValue = cards[i][j].getValue(); diff = Math.abs(cardValue - userCardValue); if (diff == 1 || diff == 12) { return true; } } } } return false; }
b4de9db4-2663-4e63-b18e-01d3a7184f0b
3
public String needlessReplacement(String s){ List<Character> list = new ArrayList<Character>(); for(int i=0; i<s.length(); i++){ if(s.charAt(i) == ' '){ list.add('%'); list.add('2'); list.add('0'); } else{ list.add(s.charAt(i)); } } char[] array = new char[list.size()]; for(int i=0; i<list.size(); i++){ array[i] = list.get(i); } return String.valueOf(array); }
5db6ca68-9614-4b72-968e-bc3cd95f5a00
6
public static void main(String args) { /* Если аргументы отсутствуют, порт принимает значение поумолчанию */ int port = 20143; /* Создаем серверный сокет на полученном порту */ ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); Service.WriteLog("Server started on port: " + serverSocket.getLocalPort()); } catch (IOException e) { Service.WriteLog("Port " + port + " is blocked."); //System.exit(-1); } a=true; /* * Если порт был свободен и сокет был успешно создан, можно переходить к * следующему шагу - ожиданию клинтов */ while (true) { try { Socket clientSocket = serverSocket.accept(); if (!a){ Service.WriteLog("Service thread is stop"); t.stop(); a=false; ClientSession session = new ClientSession(clientSocket); t=new Thread(session); if(cashe_machine.id_payment!="") Service.WriteLog("Service thread is start"); t.start(); } else{ a=false; ClientSession session = new ClientSession(clientSocket); t=new Thread(session); if(cashe_machine.id_payment!="") Service.WriteLog("Service thread is start"); t.start(); } /* Для обработки запроса от каждого клиента создается * * отдельный объект и отдельный поток */ } catch (IOException e){ Service.WriteLog("Failed to establish connection."); Service.WriteLog(e.getMessage()); //System.exit(-1); } } }
224473fa-8a4a-49e9-a6f9-b9ba9d352742
5
public static String ccase(String str)//for capitalized each word(title) { mystr=""; boolean status=true; for(int k=0;k<str.length();k++) { my=str.charAt(k)+""; if(status==true) mystr=mystr+my.toUpperCase(); else mystr=mystr+my.toLowerCase(); if(str.charAt(k)==32 || str.charAt(k)==9 || str.charAt(k)==10) status=true; else status=false; } return mystr; }
2c092383-b104-4e08-8480-7fddaf7729f0
3
public void loadSupplier(){ supplierDataAccessor dataAccessObject=new supplierDataAccessor(); List<supplier> supList=new ArrayList(); DefaultTableModel patientDataTable=new DefaultTableModel(); Object[ ] columnNames=new Object[5]; Object[ ] fieldValues=new Object[5]; Patient myPatient=null; try{ supList=dataAccessObject.retrieveSupplierData(); } catch(SQLException e){ System.out.println(e.getMessage()); } columnNames[0]="Name"; columnNames[1]="ContactDetails"; columnNames[2]="PhnNo"; columnNames[3]="E-mail"; columnNames[4]="Amount"; patientDataTable.setColumnIdentifiers(columnNames); if(supList.size()>0){ for (supplier patientList1 : supList) { tempSupplier = patientList1; fieldValues[0]=tempSupplier.getName(); fieldValues[1]=tempSupplier.getContactDetails(); fieldValues[2]=tempSupplier.getPhnNo(); fieldValues[3]=tempSupplier.getMail(); fieldValues[4]=tempSupplier.getAmount(); patientDataTable.addRow(fieldValues); } this.jTable1.setModel(patientDataTable); } }
5ea6c164-1222-494f-bf41-6529fddb8ba6
5
private void openWebPage(String urlName) { try { URL u = new URL(urlName); Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) desktop.browse(u.toURI()); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e2) { e2.printStackTrace(); } }
fccceeb2-e801-4141-858a-f1221b9a484b
5
public static int partition (int[] array, int start, int end) { int pValue = array[start]; while (start < end) { while (start < end && array[end] >= pValue) { end--; } array[start] = array[end]; while (start < end && array[start] <= pValue) { start++; } array[end] = array[start]; } array[start] = pValue; return start; }
8f9eee4b-b3ad-477d-a18c-070424b50132
0
public void actionPerformed(ActionEvent event) { Date now = new Date(); System.out.println("At the tone, the time is " + now); Toolkit.getDefaultToolkit().beep(); }
9dabc0e8-84f5-4fc5-988d-d65a34de1345
7
@Override @SuppressWarnings("UnnecessaryReturnStatement") public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { switch (evt.getPropertyName()) { case "value": { throw new PropertyVetoException("cannot set value directly", evt); } case "components": { if (evt.getNewValue() == null) { throw new PropertyVetoException("cannot set components to null", evt); } if (evt.getNewValue() instanceof List) { setComponents((List<Property<T>>) evt.getNewValue()); } else { throw new PropertyVetoException("components must be list", evt); } return; } case "accumulator": { if (evt.getNewValue() == null) { throw new PropertyVetoException("cannot set accumulator to null", evt); } if (evt.getNewValue() instanceof Accumulator) { setAccumulator((Accumulator<T>) evt.getNewValue()); } else { throw new PropertyVetoException("accumulator is not the right class", evt); } return; } } }
76953371-2927-4752-b81f-840d97fe4d0b
2
@Override public boolean reachesDestination(Packet p) { // TODO Auto-generated method stub Iterator<Edge> edgeIt = p.origin.outgoingConnections.iterator(); EdgeBetEtt e; while(edgeIt.hasNext()){ e = (EdgeBetEtt) edgeIt.next(); if(e.endNode.equals(p.destination)){ etxLink = e.getEtx(); } } double r = ud.nextSample(); System.out.println("r = "+String.format("%.2f", r)+", extLink = "+String.format("%.2f", etxLink)); return r >= etxLink; }
e8f4a829-193d-47e5-b7d8-22c282d4827a
6
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(RSA_Dictionary.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RSA_Dictionary.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RSA_Dictionary.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RSA_Dictionary.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 RSA_Dictionary().setVisible(true); } }); }
2e2262a6-e23f-4c5d-94cd-92c7673608a2
8
String getDrawType() { switch (drawType) { case Mesh.DRAW_MULTIPLE: return "multiple"; case Mesh.DRAW_ARROW: return "arrow"; case Mesh.DRAW_CIRCLE: return "circle"; case Mesh.DRAW_CURVE: return "curve"; case Mesh.DRAW_POINT: return "point"; case Mesh.DRAW_LINE: return "line"; case Mesh.DRAW_TRIANGLE: return "triangle"; case Mesh.DRAW_PLANE: return "plane"; } return "type is not identified in mesh.getDrawType()"; }
a3c3578f-dd89-45d6-8acc-7b84bec284c6
3
private double influenceConverter(int magnitude) { double convertedMagnitude; if (magnitude == Relationship.HIGH) convertedMagnitude = 1.0; else if (magnitude == Relationship.MEDIUM) convertedMagnitude = 0.5; else if (magnitude == Relationship.LOW) convertedMagnitude = 0.25; else convertedMagnitude = 0; return convertedMagnitude; }
a11ebbbe-b953-4ed4-b951-70722e94eca6
2
@Override public void drawSprite(SpriteSheet sheet, int index, double startX, double startY, double endX, double endY, double transparency, boolean flipX, boolean flipY, Color color) { double texMinX = ((double) sheet.getStartX(index) / ((double) sheet .getSheet().getWidth())); double texMinY = ((double) sheet.getStartY(index) / ((double) sheet .getSheet().getHeight())); double texMaxX = texMinX + ((double) sheet.getSpriteWidth()) / ((double) sheet.getSheet().getWidth()); double texMaxY = texMinY + ((double) sheet.getSpriteHeight()) / ((double) sheet.getSheet().getHeight()); if (flipX) { double temp = texMinX; texMinX = texMaxX; texMaxX = temp; } if (!flipY) { double temp = texMinY; texMinY = texMaxY; texMaxY = temp; } target.drawRect(sheet.getSheet().getDeviceID(), IRenderDevice.BlendMode.SPRITE, startX, startY, endX, endY, texMinX, texMinY, texMaxX, texMaxY, color, transparency); }
46abf3ce-db60-410c-aadc-1dea76501f98
9
public boolean UnlockAll(int xid) { // if any parameter is invalid, then return false if (xid < 0) { return false; } TrxnObj trxnQueryObj = new TrxnObj(xid, "", -1); // Only used in elements() call below. synchronized (this.lockTable) { Vector vect = this.lockTable.elements(trxnQueryObj); TrxnObj trxnObj; Vector waitVector; WaitObj waitObj; int size = vect.size(); for (int i = (size - 1); i >= 0; i--) { trxnObj = (TrxnObj) vect.elementAt(i); this.lockTable.remove(trxnObj); DataObj dataObj = new DataObj(trxnObj.getXId(), trxnObj.getDataName(), trxnObj.getLockType()); this.lockTable.remove(dataObj); // check if there are any waiting transactions. synchronized (this.waitTable) { // get all the transactions waiting on this dataObj waitVector = this.waitTable.elements(dataObj); int waitSize = waitVector.size(); for (int j = 0; j < waitSize; j++) { waitObj = (WaitObj) waitVector.elementAt(j); if (waitObj.getLockType() == LockManager.WRITE) { if (j == 0) { // get all other transactions which have locks on the // data item just unlocked. Vector vect1 = this.lockTable.elements(dataObj); // remove interrupted thread from waitTable only if no // other transaction has locked this data item if (vect1.size () == 0) { this.waitTable.remove(waitObj); try { synchronized (waitObj.getThread()) { waitObj.getThread().notify(); } } catch (Exception e) { System.out.println("Exception on unlock\n" + e.getMessage()); } } else { // some other transaction still has a lock on // the data item just unlocked. So, WRITE lock // cannot be granted. break; } } // stop granting READ locks as soon as you find a WRITE lock // request in the queue of requests break; } else if (waitObj.getLockType() == LockManager.READ) { // remove interrupted thread from waitTable. this.waitTable.remove(waitObj); try { synchronized (waitObj.getThread()) { waitObj.getThread().notify(); } } catch (Exception e) { System.out.println("Exception e\n" + e.getMessage()); } } } } } } return true; }
d3bbdaa7-5a26-46c5-8488-eb304d8a8087
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ResponseMessage other = (ResponseMessage) obj; if (_correlationId == null) { if (other._correlationId != null) return false; } else if (!_correlationId.equals(other._correlationId)) return false; return true; }
4d4746a4-45b5-4a37-99e1-87c5ae899dd4
8
private static String escapeJSON(String text) { StringBuilder builder = new StringBuilder(); builder.append('"'); for (int index = 0; index < text.length(); index++) { char chr = text.charAt(index); switch (chr) { case '"': case '\\': builder.append('\\'); builder.append(chr); break; case '\b': builder.append("\\b"); break; case '\t': builder.append("\\t"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; default: if (chr < ' ') { String t = "000" + Integer.toHexString(chr); builder.append("\\u" + t.substring(t.length() - 4)); } else { builder.append(chr); } break; } } builder.append('"'); return builder.toString(); }
9c031943-e6b4-4a0f-956c-0e2b41a32d91
4
public void left(float a) { for (float i = 0; i < a; i++) { if (!this.touchRobotRotate()) { this.rotateRobot(-1); if (this.checkTouchBullet()) { this.onHitByBullet(); return; } try { Thread.sleep(this.velMov); } catch (InterruptedException ex) { Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex); } } else { this.onTouchRobot(); } } }
5f6bedfe-bf1f-4005-aa82-bad1b866043a
6
@Override public boolean deleteChild(Condition<?> n) { if (!(n instanceof BinaryBooleanOperator)) { return false; } if (children.get(0).equals(n))//left { children.set(0, ((Condition<?>) (n.randomChild()))); } else if (children.get(1).equals(n))//right { children.set(1, ((Condition<?>) (n.randomChild()))); } else { return false; } return true; }
d821001b-1b79-4a8b-9a0f-1cb0494f096a
7
public Problem validate(final Object instance, final AllowOnly annotation, final Object target, final CharSequence value) { if (value == null || value.length() < 1) { if (annotation.required()) { return new Problem(instance, annotation, target, value); } return null; } /* * Iterate over the list of valid values and see if there is a match. */ for (String s : annotation.value()) { if (annotation.ignoreCase()) { if (s.equalsIgnoreCase(value.toString())) { return null; } } else { if (s.equals(value)) { return null; } } } /* * No matches were found so the value is not valid. */ return new Problem(instance, annotation, target, value); }
093bdb1f-66a1-40df-9e96-15bc31b8bba8
4
public void afficher(){ for(int elem : tabMarq){ // On affiche d'abord les biens placés if(elem == 1) System.out.print("☻"); } for(int elem : tabMarq){ // On affiche les mal placés if(elem == 2) System.out.print("☺"); } }
6a531d0b-0247-484f-a8b3-4df1d31531b8
2
private void enableMetrics() { if(config.getBoolean("Metrics.enabled")) { try { console.sendMessage(pre + "§aMetrics starting!"); new Metrics(this).start(); console.sendMessage(pre + "§aMetrics started!"); } catch(IOException e) { console.sendMessage(pre + "§cMetrics did not start!"); } } }
7316b646-59c8-4815-bbd4-182b76dce2ef
0
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
095ad7d2-1464-4b5c-9840-07932248c0d0
4
@Override public void doCommand() { // if the player can afford the update of the tower we do nothing if (tower.getOwner().getBank().getMoney() < tower.getUpgradePrice()) { System.out.println("The player is too poor to update the tower !"); return; } if (tower instanceof GunTower) { System.out.println("version: "+ ((GunTower) tower).getVersion()); GunTower.Version version = ((GunTower) tower).getVersion(); // we switch the current version to know which version to set switch (version) { case NORMAL: System.out.println("on passe à SUPER"); ((GunTower) tower).setVersion(GunTower.Version.SUPER); tower.getOwner().getBank().addMoney(-tower.getUpgradePrice()); break; case SUPER: System.out.println("on passe à CHUCKNORRIS"); ((GunTower) tower).setVersion(GunTower.Version.CHUCKNORRIS); tower.getOwner().getBank().addMoney(-tower.getUpgradePrice()); break; default: System.out.println("pas d'évolution"); break; } } }
03ebf1f4-1ba1-4df5-b8e1-f92d61de25dc
5
protected AlberoBin<T> cercaNodo(T x) { if (coll == null) return null; AlberoBin<T> curr = coll; while (!curr.val().equals(x)) { if (curr.val().compareTo(x) < 0) { if (curr.des() == null) return curr; curr = curr.des(); } else { if (curr.sin() == null) return curr; curr = curr.sin(); } } return curr; }
1acf052d-cfc5-4628-80ab-f18546e19799
2
public void set(EmpresaBean oEmpresaBean) throws Exception { try { oMysql.conexion(enumTipoConexion); oMysql.initTrans(); if (oEmpresaBean.getId() == 0) { oEmpresaBean.setId(oMysql.insertOne("empresa")); } UsuarioDao oUsuarioDao = new UsuarioDao(enumTipoConexion); oUsuarioDao.set(oEmpresaBean.getUsuario()); oEmpresaBean.setUsuario(oUsuarioDao.getFromLogin(oEmpresaBean.getUsuario())); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "id_usuario", Integer.toString(oEmpresaBean.getUsuario().getId())); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "nombre", oEmpresaBean.getNombre()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "cif", oEmpresaBean.getCif()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "direccion", oEmpresaBean.getDireccion()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "localidad", oEmpresaBean.getLocalidad()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "provincia", oEmpresaBean.getProvincia()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "pais", oEmpresaBean.getPais()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "telefono", oEmpresaBean.getTelefono()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "fax", oEmpresaBean.getFax()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "actividad", oEmpresaBean.getActividad()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "nombrecontacto", oEmpresaBean.getNombrecontacto()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "emailcontacto", oEmpresaBean.getEmailcontacto()); oMysql.updateOne(oEmpresaBean.getId(), "empresa", "validada", oEmpresaBean.getValidada()); oMysql.commitTrans(); } catch (Exception e) { oMysql.rollbackTrans(); throw new Exception("EmpresaDao.setEmpresa: Error: " + e.getMessage()); } finally { oMysql.desconexion(); } }
531a5f68-7684-4fb1-94e7-9748b64f1892
6
@Override public void run(int interfaceId, int componentId) { switch (stage) { case -1: stage = 0; sendEntityDialogue(Dialogue.SEND_1_TEXT_CHAT, new String[] { player.getDisplayName(), "Hello, Ozan. I'm new here. Please guide me?" }, IS_PLAYER, player.getIndex(), 9827); break; case 0: stage = 1; sendEntityDialogue(Dialogue.SEND_1_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Alright, let's start. Take this teletab and break it." }, IS_NPC, npcId, 9810); break; case 1: sendEntityDialogue(Dialogue.SEND_NO_CONTINUE_1_TEXT_CHAT, new String[] { "", "Ozan gave you a teletab." }, IS_ITEM, LumbiTutorial.TELETAB, 1); player.getPackets().sendIComponentText(372, 3, "Break the tele tab."); player.getInventory().addItem(LumbiTutorial.TELETAB, 1); break; case 3: stage = 4; sendEntityDialogue(Dialogue.SEND_1_TEXT_CHAT, new String[] { player.getDisplayName(), "Thanks a lot, ozan." }, IS_PLAYER, player.getIndex(), 9846); break; case 4: stage = 5; sendEntityDialogue(Dialogue.SEND_1_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Your welcome. Take your starter stuff." }, IS_NPC, npcId, 9848); break; case 5: player.getControlerManager().getControler().forceClose(); end(); break; default: end(); break; } }
7d17022d-58b6-4b09-967b-10c72ca404cc
5
static String bestimmeRichtung(Item kuchen, String richtigeRichtung, String[] moeglicheRichtungen) { if(kuchen == Item.UKuchen || kuchen == Item.IKuchen) { return richtigeRichtung; } if(kuchen == Item.UGiftkuchen || kuchen == Item.IGiftkuchen) { List<String> richtungen = new ArrayList<String>( Arrays.asList(moeglicheRichtungen)); richtungen.remove(richtigeRichtung); String falscheRichtung = FancyFunction.getRandomEntry(richtungen); // Falls der Raum nur einen Ausgang hat. if(falscheRichtung == null) falscheRichtung = richtigeRichtung; return falscheRichtung; } return null; }
80d1d0c0-5fe8-4c4a-916d-564c468c17b4
4
public static String promptStaffStatus(){ Scanner myKey = new Scanner(System.in); String status = null; boolean successful = false; do{ System.out.println("What is the status of this StaffMember?\nPress 1 Permanent\nPress 2 for Temporary\nPress 3 Other\n"); int userEntryStatus = myKey.nextInt(); switch(userEntryStatus){ case 1: { status = "PERM_STAFF"; successful = true; break; } case 2: { status = "TEMP_STAFF"; successful = true; break; } case 3: { status = "OTHER"; successful = true; break; } default:{ System.out.println("INVALID ENTRY! TRY AGAIN: "); } } } while(successful == false); return status; }
4f8722e4-7555-40bf-97e3-56a7d1bdf0cf
0
@Override public void destroy() { myProcess.destroy(); }
33736c08-9507-41e0-a07f-38ac324db763
2
public void AddStartMenuElement() { if (elementStart != null) return; elementStart = APXUtils.addResource("start_" + scrUniq, scrName, scrTooltip, scrHotkey, scrIcon, APXUtils.scriptRootNew, new MenuElemetUseListener(new String(filename)) { @Override public void use(int button) { if (info instanceof String) { JSScriptInfo script = script_list.get(info); script.Run(); } } }); }
fa90d792-af02-4d7e-824e-8480f640ce3e
3
public boolean saveUpdateSubProcess() { try { String subProcessName = txtSubProcessName.getText(); int minTime = Integer.parseInt(txtMinTime.getText()); int idealTime = Integer.parseInt(txtIdealTime.getText()); int maxTime = Integer.parseInt(txtMaxTime.getText()); if (subProcess == null) { subProcess = Service.createSubProcess(productType, productType .getSubProcesses().size(), subProcessName, minTime, idealTime, maxTime); } else { Service.updateSubProcess(subProcess, subProcess.getOrder(), subProcessName, minTime, idealTime, maxTime); } } catch (SubProcessException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return false; } catch (Exception e) { JOptionPane.showMessageDialog(this, "Check the data in fields", "Bad Data", JOptionPane.WARNING_MESSAGE); return false; } return true; }
e8dff447-236f-47b8-86e2-9024cbd28ae6
4
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) public void bucketEmpty(PlayerBucketEmptyEvent pbee) { Material bucket = pbee.getBucket(); if (Material.LAVA_BUCKET == bucket) { Block block = pbee.getBlockClicked(); BlockFace face = pbee.getBlockFace(); Block relativeBlock = block.getRelative(face); // Protection for reinforced rails types from direct lava bucket drop. if (Material.RAILS == relativeBlock.getType() || Material.POWERED_RAIL == relativeBlock.getType() || Material.DETECTOR_RAIL == relativeBlock.getType()) { boolean isReinforced = maybeReinforcementDamaged(relativeBlock); pbee.setCancelled(isReinforced); } } }
09e9f906-3715-4363-b105-9b1587005f7d
1
public int newUTF8(final String value) { key.set(UTF8, value, null, null); Item result = get(key); if (result == null) { pool.putByte(UTF8).putUTF8(value); result = new Item(index++, key); put(result); } return result.index; }
c9593e98-2305-42c4-8498-5ec91b1b7ae9
5
public String formatCriteria(){ String formattedCriteria; switch(operand){ case RIGHTLIKE: formattedCriteria = "`" + field + "` like '" + value + "%' " ; break; case LEFTLIKE: formattedCriteria = "`" + field + "` like '%" + value + "' " ; break; case LIKE: formattedCriteria = "`" + field + "` like '%" + value + "%' " ; break; case IN: formattedCriteria = "`" + field + "` in (" + value + ") " ; break; case NOTIN: formattedCriteria = "`" + field + "` notin (" + value + ") " ; break; default: formattedCriteria = "`" + field + "` "+ operand.getValue() + " '" + value + "' "; break; } return formattedCriteria; }
1c252545-0cf3-4118-9f29-78da6151a759
4
private void readParameterAnnotations(int v, final String desc, final char[] buf, final boolean visible, final MethodVisitor mv) { int i; int n = b[v++] & 0xFF; // workaround for a bug in javac (javac compiler generates a parameter // annotation array whose size is equal to the number of parameters in // the Java source file, while it should generate an array whose size is // equal to the number of parameters in the method descriptor - which // includes the synthetic parameters added by the compiler). This work- // around supposes that the synthetic parameters are the first ones. int synthetics = Type.getArgumentTypes(desc).length - n; AnnotationVisitor av; for (i = 0; i < synthetics; ++i) { // virtual annotation to detect synthetic parameters in MethodWriter av = mv.visitParameterAnnotation(i, "Ljava/lang/Synthetic;", false); if (av != null) { av.visitEnd(); } } for (; i < n + synthetics; ++i) { int j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { av = mv.visitParameterAnnotation(i, readUTF8(v, buf), visible); v = readAnnotationValues(v + 2, buf, true, av); } } }
d103cd9b-f4a0-4558-9d77-fdbf97bbd451
3
private void numberStart() { startTokenPos = pos; while (pos < numRead) { if (isDelimiter(buf[pos])) { break; } pos++; } if (pos < numRead) { // push the number stack.push(Float.parseFloat(new String(buf, startTokenPos, pos - startTokenPos))); } parseNextState(); }
5a327aa3-cfe0-4044-93fd-1ff13a50f2dd
6
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onExplode(final EntityExplodeEvent event) { final Location loc = event.getLocation(); if (Variables.prevent_block_damage) { for (final Location location : locations) { if (location.getX() == loc.getX() && location.getY() == loc.getY() && loc.getZ() == location.getZ() && loc.getWorld() == location.getWorld()) { event.blockList().clear(); locations.remove(location); return; } } } }
b500e568-de8c-4334-a112-2badaf07f6e3
3
private synchronized void winner (String v) throws JMSException { QueueConnection qc =null; QueueSession qs =null; ///prova mess try { qc = qcf.createQueueConnection(); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { this.sender = qs.createSender( altro); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); }//manda al rivale CreateMessage Mess = new CreateMessage(this.name, this.room, this.name, 1); //STEP Message ObjectMessage j = qs.createObjectMessage(Mess); j.setBooleanProperty("multy", true); j.setJMSReplyTo(que); qc.start(); System.out.println("Invio messaggio di vittoria a " + altro.toString()); this.sender = this.senderSession.createSender(altro); this.sender.send(j); qc.close(); //manda in topic via House CreateMessage creMess = new CreateMessage(this.name, this.room, this.name, 1); // winner ObjectMessage roomObjectMess = this.senderSession.createObjectMessage(creMess); roomObjectMess.setBooleanProperty("multy", true); roomObjectMess.setJMSReplyTo(que); this.sender = this.senderSession.createSender(queue); this.sender.send(roomObjectMess); }
2b316a87-7d94-4820-b9fc-8f86c5c02bd6
9
public static void main(String[] args) { for(int i=0; i<10; i++){ if(i==2 || i==4){ System.out.println("Now i = " + i); }else{ System.out.println("Value of i : " + i); } } for(int i=10; i>=0; i--){ if(i!=0){ System.out.println("i is NOT equal to 0, value of i : " + i); }else{ System.out.println("i is now 0"); } } String fname = "Maciej"; String sname = "Cygan"; if(fname.equals("Megan")){ // } else if(fname.equals("Maciej")){ if(sname.equals("Foo")){ // } else if(sname.equals("Cygan")){ System.out.println("Person correctly identified"); } }else{ // } }
94a67508-bc69-4470-8ca0-683ed79785b6
7
public Symbol parse() throws java.lang.Exception { /* the current action code */ int act; /* the Symbol/stack element returned by a reduce */ Symbol lhs_sym = null; /* information about production being reduced with */ short handle_size, lhs_sym_num; /* set up direct reference to tables to drive the parser */ production_tab = production_table(); action_tab = action_table(); reduce_tab = reduce_table(); /* initialize the action encapsulation object */ init_actions(); /* do user initialization */ user_init(); /* get the first token */ cur_token = scan(); /* push dummy Symbol with start state to get us underway */ stack.removeAllElements(); stack.push(getSymbolFactory().startSymbol("START", 0, start_state())); tos = 0; /* continue until we are told to stop */ for (_done_parsing = false; !_done_parsing; ) { /* Check current token for freshness. */ if (cur_token.used_by_parser) throw new Error("Symbol recycling detected (fix your scanner)."); /* current state is always on the top of the stack */ /* look up action out of the current state with the current input */ act = get_action(stack.peek().parse_state, cur_token.sym); /* decode the action -- > 0 encodes shift */ if (act > 0) { /* shift to the encoded state by pushing it on the stack */ cur_token.parse_state = act-1; cur_token.used_by_parser = true; stack.push(cur_token); tos++; /* advance to the next Symbol */ cur_token = scan(); } /* if its less than zero, then it encodes a reduce action */ else if (act < 0) { /* perform the action for the reduce */ lhs_sym = do_action((-act)-1, this, stack, tos); /* look up information about the production */ lhs_sym_num = production_tab[(-act)-1][0]; handle_size = production_tab[(-act)-1][1]; /* pop the handle off the stack */ for (int i = 0; i < handle_size; i++) { stack.pop(); tos--; } /* look up the state to go to from the one popped back to */ act = get_reduce(stack.peek().parse_state, lhs_sym_num); /* shift to that state */ lhs_sym.parse_state = act; lhs_sym.used_by_parser = true; stack.push(lhs_sym); tos++; } /* finally if the entry is zero, we have an error */ else if (act == 0) { /* call user syntax error reporting routine */ syntax_error(cur_token); /* try to error recover */ if (!error_recovery(false)) { /* if that fails give up with a fatal syntax error */ unrecovered_syntax_error(cur_token); /* just in case that wasn't fatal enough, end parse */ done_parsing(); } else { lhs_sym = stack.peek(); } } } return lhs_sym; }
46f3ef58-b2e8-40b6-96cf-5b1e3613e5a0
8
final boolean method733(int i, int i_11_, int i_12_, int i_13_) { int i_14_; int i_15_; int i_16_; if (!aBoolean1223) { i_14_ = anInt1225 - i; i_15_ = anInt1216 - i_11_; i_16_ = anInt1229 - i_12_; ((Class72) this).anInt1232 = (int) Math.sqrt((double) (i_14_ * i_14_ + i_15_ * i_15_ + i_16_ * i_16_)); if (((Class72) this).anInt1232 == 0) ((Class72) this).anInt1232 = 1; i_14_ = (i_14_ << 8) / ((Class72) this).anInt1232; i_15_ = (i_15_ << 8) / ((Class72) this).anInt1232; i_16_ = (i_16_ << 8) / ((Class72) this).anInt1232; } else { ((Class72) this).anInt1232 = 1073741823; i_14_ = anInt1225; i_15_ = anInt1216; i_16_ = anInt1229; } int i_17_ = (int) (Math.sqrt((double) (i_14_ * i_14_ + i_15_ * i_15_ + i_16_ * i_16_)) * 256.0); if (i_17_ > 128) { i_14_ = (i_14_ << 16) / i_17_; i_15_ = (i_15_ << 16) / i_17_; i_16_ = (i_16_ << 16) / i_17_; anInt1217 = anInt1218 * i_13_ / (aBoolean1223 ? 1024 : ((Class72) this).anInt1232); } else anInt1217 = 0; if (anInt1217 < 8) { aClass105_1221 = null; return false; } int i_18_ = Class33.method340(anInt1217, (byte) 108); if (i_18_ > i_13_) i_18_ = Class348_Sub40_Sub1.method3051(i_13_, 4096); if (i_18_ > 512) i_18_ = 512; if (i_18_ != anInt1220) anInt1220 = i_18_; anInt1231 = (int) (Math.asin((double) ((float) i_15_ / 256.0F)) * 2607.5945876176133) & 0x3fff; anInt1219 = (int) (Math.atan2((double) i_14_, (double) -i_16_) * 2607.5945876176133) & 0x3fff; aClass105_1221 = null; return true; }
a18e25de-ef09-441e-a3d7-6e48a05b4442
4
public void setBorderStyle(Side side, Border style) { switch (side) { case TOP: topBorder = new Border(style); break; case LEFT: leftBorder = new Border(style); break; case BOTTOM: bottomBorder = new Border(style); break; case RIGHT: rightBorder = new Border(style); break; } }
899ab8aa-6ccd-47fe-9d32-28730cef22be
1
public void clearInformations() { for (Iterator<String> e = informations.iterator(); e.hasNext();) { data.setUse((String) e.next(), false); } informations.clear(); notifyZElement(); }
8ddcd7a8-ce9d-4058-add6-148075b4e159
4
@Override public boolean equals(Object ob) { if(ob instanceof Genotipo) { Genotipo g = (Genotipo)ob; if(g.numGenes!=this.numGenes) { return false; } for(int i=0; i<this.numGenes; i++) { if(this.getGen(i)!=g.getGen(i)) { return false; } } return true; } return false; }
56817054-8c56-430b-aaaa-cdb7abe6eb49
9
@Override public void mousePressed(MouseEvent event) { if (!this.mainGUI.isDraggingFiguresEnabled()) { return; } int x = event.getPoint().x; int y = event.getPoint().y; for (int i = this.guiFigures.size()-1; i >= 0; i--) { FigureGUI figureGUI = this.guiFigures.get(i); if (figureGUI.isCaptured()) continue; if (mouseOverFigure(figureGUI, x, y)) { if ((this.mainGUI.getGameState() == Game.GAME_STATE_WHITE && figureGUI.getColor() == Figure.COLOR_WHITE) || (this.mainGUI.getGameState() == Game.GAME_STATE_BLACK && figureGUI.getColor() == Figure.COLOR_BLACK)) { this.dragOffsetX = x - figureGUI.getX(); this.dragOffsetY = y - figureGUI.getY(); this.mainGUI.setDragFigure(figureGUI); this.mainGUI.repaint(); break; } } } if (this.mainGUI.getDragFigure() != null) { this.guiFigures.remove(this.mainGUI.getDragFigure()); this.guiFigures.add(this.mainGUI.getDragFigure()); } }
5395c1a2-24a9-41db-872f-783075694c52
6
public void testPerms(CommandSender sender, String[] args) { if (args.length == 1) { sender.sendMessage(pre + red + "Must specify permission and player!"); return; } if (args.length == 2) { if (sender.hasPermission(args[1])) { sender.sendMessage(pre + green + "You have permission for '" + args[1] + "'."); } else { sender.sendMessage(pre + red + "You do not have permission for '" + args[1] + "'."); } } if (args.length == 3) { Player target = Bukkit.getPlayer(args[2]); if (target == null) { sender.sendMessage(pre + red + "Player not found!"); } else { if (target.hasPermission(args[1])) { sender.sendMessage(pre + green + target.getName() + " has permission for " + args[1]); } else { sender.sendMessage(pre + red + target.getName() + " does not have permission for " + args[1]); } } } }
ef9753f2-4e81-4fce-9cac-a0e053e35591
6
private static void shortestRep(String line) { String shortestRep = ""; int i = 1; int length = line.length(); if(length == 0) System.out.println("0"); else if(length == 1) System.out.println("1"); else{ shortestRep += line.charAt(0); while(i<length){ if(shortestRep.charAt(0) == line.charAt(i)){ int count = countSubstrings(shortestRep,line.substring(i)); if(count*i == line.substring(i).length()){ System.out.println("" + i); return; } else{ shortestRep += line.charAt(i); } } else{ shortestRep += line.charAt(i); } i++; if(i == length) System.out.println("" + i); } } }
295637a5-77de-4d52-b72d-a019b0248c08
0
public SqliteWriter(String databaseName, String tableName) { this.databaseName = databaseName; this.tableName = tableName; }
8ba818c7-f299-4c41-b821-a6737ff869f0
7
private static final int getOpenBraceCount(RSyntaxDocument doc) { int openCount = 0; Element root = doc.getDefaultRootElement(); int lineCount = root.getElementCount(); for (int i=0; i<lineCount; i++) { Token t = doc.getTokenListForLine(i); while (t!=null && t.isPaintable()) { if (t.type==Token.SEPARATOR && t.textCount==1) { char ch = t.text[t.textOffset]; if (ch=='{') { openCount++; } else if (ch=='}') { openCount--; } } t = t.getNextToken(); } } return openCount; }
1128225e-15bf-4d8c-82bb-581ccd70e488
2
public void exibir(String num){ String res = null; for(int i = 0; i < telefonesBR.size(); i++){ if( telefonesBR.get(i).equals(num)){ res = telefonesBR.get(i); } } System.out.println("(55)"+res.substring(0, 4)+"-"+res.substring(4, 8)); }
bc53af94-571b-4012-877c-3cab3a63d8b2
6
public void checkAllowedWay(){ for(int i = 0; i < currentNode.listOut.size() ; i++ ){ boolean inRoute; int j = 0; inRoute = false; int currentNodeID = currentNode .listOut .get(i) .getFinishGNode() .getId(); if (route.size() !=0 && currentNode.listOut.size() != 0 ){ while (j != route.size() ) { if(currentNodeID == route.get(j)){ inRoute = true; break; } else j++; } } if (inRoute == false){ allowedWay.add(currentNodeID); } } }
1b6cb2c2-c2e4-43f0-94ed-7db88a269dfa
5
public boolean onItemUse(ItemStack var1, EntityPlayer var2, World var3, int var4, int var5, int var6, int var7) { int var8 = var3.getBlockId(var4, var5, var6); int var9 = var3.getBlockId(var4, var5 + 1, var6); if((var7 == 0 || var9 != 0 || var8 != Block.grass.blockID) && var8 != Block.dirt.blockID) { return false; } else { Block var10 = Block.tilledField; var3.playSoundEffect((double)((float)var4 + 0.5F), (double)((float)var5 + 0.5F), (double)((float)var6 + 0.5F), var10.stepSound.stepSoundDir2(), (var10.stepSound.getVolume() + 1.0F) / 2.0F, var10.stepSound.getPitch() * 0.8F); if(var3.multiplayerWorld) { return true; } else { var3.setBlockWithNotify(var4, var5, var6, var10.blockID); var1.damageItem(1, var2); return true; } } }
82e3fe86-0a8e-4823-b756-c303b68f4337
0
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed programmerThread.stop(); lastPane = programmerFrame; hidePanels(lastPane); }//GEN-LAST:event_jButton10ActionPerformed
a411f814-e7eb-4c6d-9d14-c8b329337328
9
public static Method getAsMethodOfPublicBase(Class c, Method m){ for(Class iface : c.getInterfaces()) { for(Method im : iface.getMethods()) { if(im.getName().equals(m.getName()) && Arrays.equals(m.getParameterTypes(), im.getParameterTypes())) { return im; } } } Class sc = c.getSuperclass(); if(sc == null) return null; for(Method scm : sc.getMethods()) { if(scm.getName().equals(m.getName()) && Arrays.equals(m.getParameterTypes(), scm.getParameterTypes()) && Modifier.isPublic(scm.getDeclaringClass().getModifiers())) { return scm; } } return getAsMethodOfPublicBase(sc, m); }
9148f18d-d7ab-4179-b551-12a68330b47e
4
public void validateFile() throws FileNotFoundException, IOException, InvalidPropertiesFormatException { String extension = fileForValidationPath.substring(fileForValidationPath.lastIndexOf(".") + 1); if(!extension.equals(ALLOWED_EXTENSION)) throw new FileSystemException("Invalid file extension\n" + "Only " +ALLOWED_EXTENSION + " extension is allowed!"); BufferedReader br = new BufferedReader(new FileReader(fileForValidationPath)); String line; int rowCounter = 1; // used for tracking the current number of line clearFile(); while ((line = br.readLine()) != null) { String[] splitedLine = line.split(VALIDATOR_DELIMITER); if(!checkLineForm(splitedLine[0], 0)){ br.close(); throw new InvalidPropertiesFormatException("File format contains errors at line: " +rowCounter +"\nLine: " +splitedLine[0]); } if(!checkLineForm(splitedLine[1], 1)){ br.close(); throw new InvalidPropertiesFormatException("File format contains errors at line: " +rowCounter +"\nLine: " +splitedLine[1]); } boolean result = validateLine(splitedLine[0], splitedLine[1], rowCounter); writeToFile(line, result); rowCounter++; } br.close(); }
9862074f-0cec-4b71-b99a-bf57b71ea451
8
static void ProcessWorkload(String filename, WeightedGraph g){ String t = null; int blocked = 0; float time = 0; int passed = 0; int total = 0; int totalHoc = 0; int totalprob = 0; try{ FileInputStream tempfile = new FileInputStream(filename); DataInputStream tempdata = new DataInputStream(tempfile); BufferedReader buffer = new BufferedReader(new InputStreamReader(tempdata)); while ((t = buffer.readLine()) != null){ char v1,v2; float start,duration; StringTokenizer OrderBreaker = new StringTokenizer(t); String OrderReader = OrderBreaker.nextToken(" "); start = Float.valueOf(OrderReader.trim()).floatValue(); OrderReader = OrderBreaker.nextToken(" "); v1 = OrderReader.charAt(0); OrderReader = OrderBreaker.nextToken(" "); v2 = OrderReader.charAt(0); OrderReader = OrderBreaker.nextToken(" "); duration = Float.valueOf(OrderReader.trim()).floatValue(); char [] route = tempDijstra.dijkstra(g, v1, v2); float dietime = start + duration; //do update & check maxlink int i = 0; total++; time = start; while(!g.dieQ.isEmpty() && (g.dieQ.element().dieTime <= start)){ char a = g.dieQ.element().getVert1(); char b = g.dieQ.element().getVert2(); g.graph[(int)a - 65][(int)b - 65].runTimeLink--; g.dieQ.poll(); } int subprob = 0; for(i = 0;route[i] != v2;i++){ if (g.ProcessLink(route[i],route[i+1])){ subprob = subprob + g.graph[(int)route[i]-65][(int)route[i+1]-65].getProbagation(); }else{ totalHoc = totalHoc - i; blocked++; break; } } if(route[i] == v2){ for(i = 0;route[i] != v2;i++){ g.graph[(int)route[i] - 65][(int)route[i+1] - 65].runTimeLink++; g.dieQ.add(g.inputLink(route[i], route[i+1], dietime)); totalHoc++; } passed++; totalprob = totalprob + subprob; } } tempdata.close(); System.out.println("total number of virtual circuit requests: " + total); System.out.println("number of successfully routed requests:" + passed); System.out.println("percentage of routed request: " + (float)passed/total*100); System.out.println("number of blocked requests: "+ blocked); System.out.println("percentage of blocked requests: "+ (float)blocked/total*100); System.out.println("average number of hops per circuit: " + (float)totalHoc/passed); System.out.println("average cumulative propagation delay per circuit: " + (float)totalprob/passed); }catch (Exception error){ System.out.println("WRONNG####!!!! error" + error); } }
a06ce9ae-5001-4ce4-aa00-474f30a57ca6
3
public void setPersonDeletionPercentage(double perCent){ this.personDeletionPercentage = perCent; this.personDeletionPercentageSet = true; if(this.itemDeletionPercentageSet && this.replacementOptionSet){ this.allNoResponseOptionsSet = true; if(this.dataEntered){ this.preprocessData(); } } }
81b23aaf-fd4f-417b-8f6d-60e6f0e8376f
4
public static String recognizeConfiguration(String cfgPath) { for(String t : registeredGameTypes.keySet()) { try{ Game g = getGameFactory(t).buildGame(cfgPath); if(g.validate() && !g.usesInternalBoard()) { return t; } }catch(Exception ex) {} } return null; }
de11cecc-e576-4200-bb3c-f666a66633bf
9
public static void main(String[] args) { //declaração de variáveis int i, j, k, rep = 0, temp, tamA = 10, tamB = 6, tamC = 16; int[] listaA = {2, -5, -121, 102, -35, -2, 0, -125, 802, -10}, listaB = {6, 99, -1, 12, 102, -2}, listaC = new int[tamC]; //unir os arrays for (i = 0; i < tamA; i++) { listaC[i] = listaA[i]; } for (j = 0; j < tamB; j++, i++) { //encontrar repetidos for (k = 0; k < tamA; k++) { if (listaA[k] == listaB[j]) { rep++; } } listaC[i] = listaB[j]; } System.out.println("A união dos arrays é:"); for (i = 0; i < tamC; i++) { System.out.print(listaC[i] + " "); } System.out.println("\nNo array resultado existem " + rep + " elementos repetidos"); //array ordenado - Bubble sort System.out.println("O array ordenado: "); for (i = 0; i <= tamC - 2; i++) { for (j = 0; j <= tamC - 2 - i; j++) { if (listaC[j] > listaC[j + 1]) { temp = listaC[j]; listaC[j] = listaC[j + 1]; listaC[j + 1] = temp; } } } //imprimir array ordenado for (i = 0; i < tamC; i++) { System.out.print(listaC[i] + " "); } System.out.println(""); }
8bd86daa-b994-443f-8676-1ba1e5ccc2e4
9
@Override protected void done() { try { model = (MarketTableModel) get(); jTableMarketPrice.setModel(model); sorter = new TableRowSorter<>(model); jTableMarketPrice.setRowSorter(sorter); TableColumnModel columnModel = jTableMarketPrice.getColumnModel(); for(int i = 0; i < jTableMarketPrice.getColumnCount(); i++) { if( i == 0 || i == 1 || i == 2 || i == 4 || i == 5 || i == 29) { columnModel.getColumn(i).setPreferredWidth(0); columnModel.getColumn(i).setMinWidth(0); columnModel.getColumn(i).setMaxWidth(0); } } // jTableMarketPrice.removeColumn(columnModel.getColumn(29)); // jTableMarketPrice.removeColumn(columnModel.getColumn(5)); // jTableMarketPrice.removeColumn(columnModel.getColumn(4)); // jTableMarketPrice.removeColumn(columnModel.getColumn(3)); // jTableMarketPrice.removeColumn(columnModel.getColumn(2)); // jTableMarketPrice.removeColumn(columnModel.getColumn(1)); // jTableMarketPrice.removeColumn(columnModel.getColumn(0)); } catch (InterruptedException ex) { Application.getLogger().log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { Application.getLogger().log(Level.SEVERE, null, ex); } finally { indicator.dispose(); } }
fe233963-7e02-4dab-9796-bdf0328a0894
0
public void putRawFile(File file) throws InterruptedException { queue.put(file); LOG.info(StringUtil.concatenateStrings( "A new entity was successfully added to Raw Entity Store. Total size of store now is - ", new Integer( queue.size()).toString())); // LOG.info("Failed to put a new entity to the Raw Entity Store.", e); }
0eba1897-5160-4504-9b5e-13362a1754bd
1
public SearchResponse(String request, WordIndex wordIndex) { this.request = request; this.wordIndex = wordIndex; try { tryCreateAmbits(); } catch (IOException e) { e.printStackTrace(); } }
fcd6fb15-4c94-4cc8-a617-63713606c6dd
9
private GamePiece alphaBetaDestroy(GameBoard board, Team other){ GamePiece destroy = null; //piece to destroy Team cloneOther = new Team(other); ArrayList<GamePiece> canBeDestroyed = board.getAllDestroyable(cloneOther); for(GamePiece p : canBeDestroyed){ if (!board.setupMode) { //move phase GameBoard destroyedBoard = new GameBoard(board); Team simOther = (destroyedBoard.CURRENT_TURN == GameBoard.PLAYER1_TURN) ? destroyedBoard.getTeam2() : destroyedBoard.getTeam1(); //first check if we can win by making the enemy have no moves destroyedBoard.removePiece(simOther, p.getR(), p.getP()); if (destroyedBoard.getAllMoves(simOther).size() <= 0){ //destroying this piece will make them have no moves, making the ai win return p; //kill this one } } boolean highPriorityTarget; //search for pieces that are almost in a mill, and axe one of them if you find one. if (difficulty == AI_IMPOSSIBLE) { highPriorityTarget = impossibleAlmostMill(board, p, cloneOther); //better detection (checks for blocks) } else { highPriorityTarget = almostMill(board,p,cloneOther); //normal detection (doesn't check for blocked mills) } if(highPriorityTarget){ if(destroy == null) { destroy = p; } else if(r.nextInt(3)==0) { //50% chance we'll change if we find another one that is almost in a mill. destroy = p; } } /*if (isBlockingMill(board, p)){ System.out.println("Destroy enemy blocking mill: "+p); destroy = p; } */ } //None are next to each other, destroy a random piece if(destroy == null) { destroy = canBeDestroyed.get(r.nextInt(canBeDestroyed.size())); } return destroy; }
885b8b65-212c-4ba7-824e-e66d78f0b7fe
7
public Object invoke(final Map<String, ?> context) throws EvalError { final NameSpace nameSpace = new NameSpace(_interpreter.getClassManager(), "BeanshellExecutable"); nameSpace.setParent(_interpreter.getNameSpace()); final BshMethod method = new BshMethod(_method.getName(), _method.getReturnType(), _method.getParameterNames(), _method.getParameterTypes(), _method.methodBody, nameSpace, _method.getModifiers()); for (final Map.Entry<String, ?> entry : context.entrySet()) { try { final Object value = entry.getValue(); nameSpace.setVariable(entry.getKey(), value != null ? value : Primitive.NULL, false); } catch (final UtilEvalError e) { throw new EvalError("cannot set variable '" + entry.getKey() + '\'', null, null, e); } } final Object result = method.invoke(new Object[0], _interpreter); if (result instanceof Primitive) { if (((Primitive) result).getType() == Void.TYPE) { return null; } return ((Primitive) result).getValue(); } return result; }
da66e40e-18ad-4da5-9f6d-865dfb95a84b
1
public void layoutContainer(Container parent) { preferredLayoutSize(parent); // sets left, right Component[] components = parent.getComponents(); Insets insets = parent.getInsets(); int xcenter = insets.left + left; int y = insets.top; for (int i = 0; i < components.length; i += 2) { Component cleft = components[i]; Component cright = components[i + 1]; Dimension dleft = cleft.getPreferredSize(); Dimension dright = cright.getPreferredSize(); int height = Math.max(dleft.height, dright.height); cleft.setBounds(xcenter - dleft.width, y + (height - dleft.height) / 2, dleft.width, dleft.height); cright.setBounds(xcenter + GAP, y + (height - dright.height) / 2, dright.width, dright.height); y += height; } }
35db7e12-6c68-4aa4-9452-70f4f672cb1e
1
@Override public List<Integer> delete(Criteria criteria, GenericDeleteQuery deleteGeneric, Connection conn) throws DaoQueryException { List paramList = new ArrayList<>(); StringBuilder sb = new StringBuilder(DELETE_QUERY); String queryStr = new QueryMapper() { @Override public String mapQuery() { Appender.append(DAO_ID_DIRSTAY, DB_DIRSTAY_ID_STAY, criteria, paramList, sb, AND); Appender.append(DAO_DIRSTAY_NO, DB_DIRSTAY_STAY_NO, criteria, paramList, sb, AND); Appender.append(DAO_DIRSTAY_STATUS, DB_DIRSTAY_STATUS, criteria, paramList, sb, AND); Appender.append(DAO_ID_DIRECTION, DB_DIRSTAY_ID_DIRECTION, criteria, paramList, sb, AND); Appender.append(DAO_ID_HOTEL, DB_DIRSTAY_ID_HOTEL, criteria, paramList, sb, AND); return sb.toString(); } }.mapQuery(); try { return deleteGeneric.sendQuery(queryStr, paramList.toArray(), conn); } catch (DaoException ex) { throw new DaoQueryException(ERR_DIR_STAY_DELETE, ex); } }
4b1ef534-8814-49af-a34e-96aa63485948
0
public AlgorithmParametersType getAlgorithmParameters() { return algorithmParameters; }
6d466e81-532f-4cec-aaff-aaf518c7e434
8
public void setGameboard(Gameboard gameboard) { Field[][] fields = gameboard.getFields(); if (DEBUG) { System.out.println("\n---- turn " + turn++ +"--------"); printFields(fields); } //reset destination information, "direction" variable remembers the last state distToDest = distToDestX = distToDestY = destX = destY = 99; updateBoard(fields); //update inDoorway, foodInFields, OtherAntInField and isOtherAntAdjacent if (DEBUG) { printBoard(); } if (inDoorway) { clearBoard(); markDoorICameThroughAndPlaceMe(direction); if (DEBUG) { printBoard(); } sendMove(direction); return; } else if (otherAntIsAdjacent || foodInFields) { //destination set in updateBoard() } else { scanBoard(); if (!boardHasUnseen && !boardHasUneaten) { findClosestDoor(DOOR); } } String move = nextMoveToDest(gameboard); //do move updateMe(move); sendMove(move); }
61d85dfc-848b-451a-832f-c2b3f30a0076
1
public void pokemonExperience() { expGain = experienceGain(); GameFile.pokemonExp[0] = GameFile.pokemonExp[0] + expGain; while (GameFile.pokemonExp[0] >= expReq) { GameFile.pokemonLevels[0] = GameFile.pokemonLevels[0] + 1; } }
46e29d36-6377-4d90-b0f8-8a97304f4250
9
public int tryHit(Coordinate c) { // Ensure coordinates are within grid if (c.x < 0 || c.y < 0 || c.x >= 10 || c.y >= 10) { return -1; // Invalid coordinates } // Ensure board hasn't been shot at these coordinates if (boardHits[c.x][c.y] == null) { // Iterate through battleships, checking if segment coordinates match shot coordinates for (Battleship b : battleShips) { for (BattleshipSegment s : b.battleShipSegments) { if (s.coordinate.equals(c)) { // If hit, change status of grid, segment, and check if battleship is sunk boardHits[c.x][c.y] = true; s.isHit = true; if (b.checkIfSunk()) return 2; // Successful hit, battleship sunk return 1; // Successful hit } } } boardHits[c.x][c.y] = false; return 0; // Unsuccessful hit } else return -1; // Invalid coordinates (already shot at) }
67a073b6-1974-49c3-b377-960055a7b9f6
5
protected void extract_pvalue_list(ArrayList<String> argv) { ArrayList<Double> pvalues_tmp = new ArrayList<Double>(); try { while (!argv.isEmpty()) { pvalues_tmp.add(Double.valueOf(argv.get(0))); argv.remove(0); } } catch (NumberFormatException e) { } if (IOExtensions.hasNonTTYInput()) { try { IOExtensions.extract_doubles_from_input_stream(System.in, pvalues_tmp); } catch (IOException e) { } } if (pvalues_tmp.size() != 0) { pvalues = ArrayExtensions.toPrimitiveArray(pvalues_tmp); } }
a2d5a342-938e-4c2d-8f2b-b467998c0866
9
public int[] kmeans(double[] data, double dataMin, double dataMax, int max_itr) {//kϖ@Bef[^_ŏɑNX^̃CfbNXlƂϔzԂB int size = data.length; int[] cluster = new int[size]; //NX^S double[] centers = new double[clusterMax]; for (int k=0; k<clusterMax; k++) { centers[k] = dataMin + (dataMax - dataMin)*Math.random(); } //Ce[^ for (int itr=0; itr<max_itr; itr++) { //łS̋߂NX^Ƀf[^z for(int i=0; i<size; i++) { double minval = Double.MAX_VALUE; int index = 0; for(int k=0; k<clusterMax; k++){ double dist = Math.abs(data[i] - centers[k]); if(dist < minval) { minval = dist; index = k; } cluster[i] = index; } } //SČvZ int[] dataNum = new int[clusterMax]; for(int k=0; k<clusterMax; k++){ centers[k] = 0.0; } for(int i=0; i<size; i++) { int index = cluster[i]; centers[index] += data[i]; dataNum[index]++; } for(int k=0; k<clusterMax; k++) { if(dataNum[k]==0) continue; centers[k] /= dataNum[k]; } } return cluster; }
2f521c16-0cd4-4e75-8a4f-e8a26d289788
9
public static void sort3(int x) throws FileNotFoundException, IOException { RandomAccessFile a = new RandomAccessFile("C:/Users/Tom/Documents/Code/Java/Ticks/1B/tick 0/test-suite/test"+x+"a.dat","rw"); RandomAccessFile a2 = new RandomAccessFile("C:/Users/Tom/Documents/Code/Java/Ticks/1B/tick 0/test-suite/test"+x+"a.dat","rw"); RandomAccessFile b = new RandomAccessFile("C:/Users/Tom/Documents/Code/Java/Ticks/1B/tick 0/test-suite/test"+x+"b.dat","rw"); RandomAccessFile b2 = new RandomAccessFile("C:/Users/Tom/Documents/Code/Java/Ticks/1B/tick 0/test-suite/test"+x+"b.dat","rw"); DataOutputStream dos1; DataOutputStream dos2; DataInputStream dis; long mem = Runtime.getRuntime().totalMemory(); int memdiv = (int)(mem/16); //int memdiv = 655360; //int memdiv = 8192; long off = 0; int bin; long length = a.length()/4; dis = new DataInputStream(new BufferedInputStream(new FileInputStream(a.getFD()),memdiv)); for (int i = 0; i<length; i++) { int temp = dis.readInt(); if ((temp&1) == 0) { off++; } } a.seek(0); RandomAccessFile w1; RandomAccessFile w2; for (int i = 0; i<31; i++) { bin = 1<<i; if (i%2 == 0) { b2.seek(off*4); off = 0; dos1 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(b.getFD()), memdiv)); dos2 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(b2.getFD()), memdiv)); dis = new DataInputStream(new BufferedInputStream(new FileInputStream(a.getFD()), memdiv)); } else { a2.seek(off*4); off = 0; dos1 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(a.getFD()), memdiv)); dos2 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(a2.getFD()), memdiv)); dis = new DataInputStream(new BufferedInputStream(new FileInputStream(b.getFD()), memdiv)); } for (int j = 0; j<length; j++) { int temp = dis.readInt(); //System.out.println(new StringBuilder(Integer.toBinaryString(temp)).reverse().toString()); if ((temp&bin) == 0) { dos1.writeInt(temp); } else { dos2.writeInt(temp); } if ((temp&(bin<<1)) == 0) { off++; } } //System.out.println(); dos1.flush(); dos2.flush(); a.seek(0); b.seek(0); } a2.seek(b2.length()-(off*4)); dos1 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(a.getFD()), memdiv)); dos2 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(a2.getFD()), memdiv)); dis = new DataInputStream(new BufferedInputStream(new FileInputStream(b.getFD()), memdiv)); for (int k = 0; k<length; k++) { int temp = dis.readInt(); //System.out.println(new StringBuilder(Integer.toBinaryString(temp)).reverse().toString()); if (temp<0) { dos1.writeInt(temp); } else { dos2.writeInt(temp); } } //System.out.println(); dos1.flush(); dos2.flush(); }
622d6733-3367-4fc4-820d-5a3523639463
0
public static void writePCData(StringBuffer buf, String text) { buf.append(escapeXMLText(text)); }
4232f7a9-77ae-4000-8e85-d31d7a4b5d01
4
public static String Md5(String plainText) { StringBuilder sb = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { sb.append("0"); } sb.append(Integer.toHexString(i)); } return sb.toString();//32位的加密 // return sb.toString().substring(8, 24);//16位的加密 } catch (NoSuchAlgorithmException ex) { Logger.getLogger(StringUtils.class.getName()).log(Level.SEVERE, null, ex); } return null; }
3f3c6a1c-aa07-4893-8f75-698b413fc9a5
7
private void moveChicken() { if (model.getChicken().isMoveRight()) { //Is the user attempting to move the chicken outside the right boundary? if (model.getChicken().getLocation().x >= Constants.FRAME_WIDTH - view.getChickenImage().getWidth(null)) { model.getChicken().setMoveRight(false); return; } if (model.getChicken().getLocation().x % 3 == 0) { view.switchCurrChickenImage(); } model.getChicken().moveRight(); } else if (model.getChicken().isMoveLeft()) { //Is the user attempting to move the chicken outside of the left boundary? if (model.getChicken().getLocation().x <= 0) { model.getChicken().setMoveLeft(false); return; } if (model.getChicken().getLocation().x % 3 == 0) { view.switchCurrChickenImage(); } model.getChicken().moveLeft(); } if (model.getChicken().isMoveUp()) { model.getChicken().moveUp(); } }
b9170693-e2a7-4ae0-bb3a-f7e095f5bd58
1
public Integer call() throws InterruptedException { int sum = 0; for (int i = 0; i < 100000; i++) { sum += i; } System.out.println(numberOfThread); return numberOfThread; }
de5ccdd5-39ee-417d-8247-8f83dc5e9c80
5
public static void unregisterDirectory(File directory) { if ((pathToWatchKey.containsKey(directory.toPath()) && !pathToWatchKey.containsKey(directory.getParentFile().toPath())) || !directory.exists()) { // stop watching this directory WatchKey key = pathToWatchKey.get(directory.toPath()); key.cancel(); // remove references to the directory pathToWatchKey.remove(directory.toPath()); watchKeyToPath.remove(key); // recursively unregister the sub-directories of this directory for (int i = registeredDirectories.size() - 1; i >= 0; i--) if (registeredDirectories.get(i).getParent().equals(directory.getPath())) unregisterDirectory(registeredDirectories.get(i)); // remove the directory from the list of watched directories, update // the user interface, and save the SmartFolders to the user's settings registeredDirectories.remove(directory); UserInterfaceManager.getSmartFolderFrame().getSmartFolderPanel().updateMonitoredDirectoriesTree(registeredDirectories); SettingsManager.updateSmartFolders(); } }
61c972c2-4458-4b02-9742-7f72064aa800
6
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(VentanaPaqueteExitoso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VentanaPaqueteExitoso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VentanaPaqueteExitoso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VentanaPaqueteExitoso.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 VentanaPaqueteExitoso().setVisible(true); } }); }
736ba08e-2883-4768-bb57-9684d6e8b45a
6
public static void displayProgress(Graphics g, GameController gc, ImageLoader il, int x, int y, int progress, String displayText) { int xPos, yPos; int progressWidth; BufferedImage bi; x = x - (PROGRESS_CONTAINER_WIDTH / 2); y = y + PROGRESS_CONTAINER_HEIGHT; //progress bar container bi = il.getImage("Misc/ProgressContainer"); if(bi != null) { xPos = gc.mapToPanelX(x); yPos = gc.mapToPanelY(y); //flip the yPos since drawing happens top down versus bottom up yPos = gc.getPHeight() - yPos; //subtract the block height since points are bottom left and drawing starts from top left yPos -= gc.getBlockHeight(); g.drawImage(bi, xPos, yPos, null); } //progress bar background bi = il.getImage("Misc/ProgressBG"); if(bi != null) { xPos = gc.mapToPanelX(x + PROGRESS_BAR_OFFSET_X); yPos = gc.mapToPanelY(y - PROGRESS_BAR_OFFSET_Y); //flip the yPos since drawing happens top down versus bottom up yPos = gc.getPHeight() - yPos; //subtract the block height since points are bottom left and drawing starts from top left yPos -= gc.getBlockHeight(); //yPos += PROGRESS_BAR_OFFSET_Y; g.drawImage(bi, xPos, yPos, null); } //progress bar bi = il.getImage("Misc/ProgressBar"); if(bi != null) { if(progress < 0) { progress = 0; } if(progress > 100) { progress = 100; } progressWidth = (PROGRESS_AREA_WIDTH * progress) / 100; xPos = gc.mapToPanelX(x + PROGRESS_AREA_OFFSET_X); yPos = gc.mapToPanelY(y - PROGRESS_AREA_OFFSET_Y); //flip the yPos since drawing happens top down versus bottom up yPos = gc.getPHeight() - yPos; //subtract the block height since points are bottom left and drawing starts from top left yPos -= gc.getBlockHeight(); g.drawImage(bi, xPos, yPos, progressWidth, PROGRESS_AREA_HEIGHT, null); } //text if(!displayText.isEmpty()) { xPos = gc.mapToPanelX(x + PROGRESS_TEXT_OFFSET_X); yPos = gc.mapToPanelY(y - PROGRESS_TEXT_OFFSET_Y); //flip the yPos since drawing happens top down versus bottom up yPos = gc.getPHeight() - yPos; //subtract the block height since points are bottom left and drawing starts from top left yPos -= gc.getBlockHeight(); g.setColor(Color.white); g.setFont(new Font("SansSerif", Font.PLAIN, 14)); g.drawString(displayText, xPos, yPos); } }