method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
85c46205-3cb0-47a7-864b-bb5525d27b20
0
public void mend() { }
4a45dda0-5c8f-4b5e-a1a0-1ad1bbd2f398
7
public SplashPicture(String pathToFile) { BufferedImage bimg = null; try { bimg = ImageIO.read(new File(pathToFile)); img = new ImageIcon(bimg).getImage(); } catch (Exception e) { } if (img == null || bimg == null) { try { bimg = ImageIO.read(new File("/splash.png")); img = new ImageIcon(bimg).getImage(); } catch (Exception e) { } } if (img == null || bimg == null) { try { img = new ImageIcon(getClass().getResource("/splash.png")).getImage(); } catch (Exception e) { } } repaint(); }
ca935443-78b7-4a09-baf9-3186a69ca28a
2
public ResultSet checkDoctor(String doctor_info) { try { // checking whether the user enters employee no or doctor name if (Helper.isInteger(doctor_info)) { String selectDoctorByNoQuery = "SELECT * FROM DOCTOR WHERE employee_no = " + Integer.parseInt(doctor_info); rs = stmt.executeQuery(selectDoctorByNoQuery); } else { String selectDoctorByNameQuery = "SELECT * FROM PATIENT p, DOCTOR d " + "WHERE p.health_care_no = d.health_care_no AND UPPER(name) = UPPER('" + doctor_info + "')"; rs = stmt.executeQuery(selectDoctorByNameQuery); } } catch (SQLException e) { System.out.println("Could not find the doctor."); } return rs; }
99fab762-2789-4307-983d-3c504ec449d2
5
private boolean _uacExists(String target) { Connection conn = null; int count = 0; try { //Class.forName("com.mysql.jdbc.Driver").newInstance(); String usern = "ultracam"; String passw = "nogales"; String url = "jdbc:mysql://" + UAC_DATABASE_HOST + "/uac"; conn = DriverManager.getConnection(url,usern,passw); Statement s = conn.createStatement(); s.executeQuery("SELECT id FROM objects WHERE names LIKE '%" + target + "%' LIMIT 1;"); ResultSet rs = s.getResultSet(); while (rs.next()) { ++count; logPanel.add("Found UAC id <strong>" + rs.getString("id") + ".</strong>",LogPanel.OK,true); } } catch (SQLException e) { System.out.println(e);} finally { if (conn != null) { try { conn.close(); } catch (Exception e) {} } } if (count > 0) { return true; } else { return false; } }
d0df30b3-8a77-4723-9435-c56a2ef5d14d
5
private void processHeaders(HttpURLConnection conn) throws Exception{ headers = new HashMap<String, String>(); cookies = new HashMap<String, String>(); //================================= //get headers, cookies, etc. for (int i=0; ; i++) { //get headers from header field String headerName = conn.getHeaderFieldKey(i); String headerValue = conn.getHeaderField(i); //end of headers -> break if(headerName == null && headerValue == null){ break; } //cookies if(headerName != null && headerName.equals("Set-Cookie")){ //process cookies! processCookies(headerValue); //we don't need the Set-Cookie anymore continue; } //put header field headers.put(headerName, headerValue); } }
d8f6229a-e0fc-420b-81ea-6d9652129278
3
public void plusBonusScore(PinCount knockOverCount) { Integer knockOverPinCount = knockOverCount.intValue(); if (getScoreStatus() == ScoreStatus.NEXT_BALL) { score += knockOverPinCount; } if (scoreStatus == ScoreStatus.NEXT_TWO_BALL) { scoreStatus = ScoreStatus.NEXT_BALL; } else if (scoreStatus == ScoreStatus.NEXT_BALL) { scoreStatus = ScoreStatus.FINAL; } }
3d0a118b-fac1-4304-9b8e-02ddbe5eccc8
1
public boolean isWithinCastlePixelPos(Enemy currentEnemy) { if ( isWithinCastle(getPosOnGrid(currentEnemy.getCenterOfObject()))) { return true; } return false; }
ff072b07-21e1-4e81-ae93-03f6ef54e32c
2
public static Codec[] makeFilters() { // Set up the file filters. Universe.CHOOSER.resetChoosableFileFilters(); List decoders = Universe.CODEC_REGISTRY.getDecoders(); Iterator it = decoders.iterator(); while (it.hasNext()) Universe.CHOOSER.addChoosableFileFilter((FileFilter) it.next()); Universe.CHOOSER.setFileFilter(Universe.CHOOSER .getAcceptAllFileFilter()); // Get the decoders. Codec[] codecs = null; FileFilter filter = Universe.CHOOSER.getFileFilter(); if (filter == Universe.CHOOSER.getAcceptAllFileFilter()) { codecs = (Codec[]) decoders.toArray(new Codec[0]); } else { codecs = new Codec[1]; codecs[0] = (Codec) filter; } return codecs; }
72f92c11-e5ac-44d0-8d6a-e8c4ec5ba968
0
public void scrub() { append(" Detergent.scrub()"); super.scrub(); // Call base-class version }
83c5b948-b8fa-4733-8c63-b912ee659c1c
9
public String convert(String s, int nRows) { if(nRows<=1){ return s; } int len = s.length(); String[] temp = new String[nRows]; for (int i =0;i<nRows;i++) temp[i] = ""; int size = 2*(nRows-1); for(int i=0;i<nRows;i++){ for (int c=0;c<len;c+=size){ if(c+i<len) temp[i]+=s.charAt(c+i); if(i != 0&&i!=nRows-1&&c+size-i<len) temp[i] += s.charAt(c+size-i); } } String result = ""; for (int i =0;i<nRows;i++) result += temp[i]; return result; }
44ec06aa-398c-4d89-90e6-83f183b6b646
4
private void setCodeAndMessage( int code, String m ) throws InvalidDataException { if( m == null ) { m = ""; } // CloseFrame.TLS_ERROR is not allowed to be transfered over the wire if( code == CloseFrame.TLS_ERROR ) { code = CloseFrame.NOCODE; m = ""; } if( code == CloseFrame.NOCODE ) { if( 0 < m.length() ) { throw new InvalidDataException( PROTOCOL_ERROR, "A close frame must have a closecode if it has a reason" ); } return;// empty payload } byte[] by = Charsetfunctions.utf8Bytes( m ); ByteBuffer buf = ByteBuffer.allocate( 4 ); buf.putInt( code ); buf.position( 2 ); ByteBuffer pay = ByteBuffer.allocate( 2 + by.length ); pay.put( buf ); pay.put( by ); pay.rewind(); setPayload( pay ); }
afbcdf45-2b0f-4aa3-b025-e0320e753f0d
9
private boolean checkForErrors(DatagramPacket packet, int expectedtype, DatagramSocket socket){ DatagramPacket err = null; boolean goodPacket = true; if(packet.getData()[1] == 5){ System.out.println(ExtractErrorMsg(packet)); return false; } if(packet.getData()[0] != 0){ err = FormError.illegalTFTP("First Opcode digit must be 0"); goodPacket= false; } else if(expectedtype != packet.getData()[1] ) { err = FormError.illegalTFTP("Wrong opcode got " + (packet.getData()[1]) + " expected " + PACKETTYPES[expectedtype -1]); goodPacket= false; } else if((packet.getData()[1]) < 1 || (packet.getData()[1])> 5) { err = FormError.illegalTFTP((packet.getData()[1]) + " is an invalid Opcode"); goodPacket= false; } if((packet.getData()[1]) == 5){ goodPacket= false; return goodPacket; //dont repond to error packets } if(err!= null){ err.setAddress(packet.getAddress()); err.setPort(packet.getPort()); try{ socket.send(err); } catch(java.net.SocketException se) { se.printStackTrace(); System.exit(1); }catch(java.io.IOException io) { io.printStackTrace(); System.exit(1); } } return goodPacket; }
948467f9-b17f-425c-91b1-38534a351f3e
9
public void update() { if (timer > 10000) { Random rand = new Random(); boolean ok = false; while(!ok) { int randomInt = rand.nextInt(100); if (randomInt <= pbedroom1) { room = map.getRooms().get(0); if(room.getHumans() == 0) ok = true; } else if (randomInt <= pbedroom2) { room = map.getRooms().get(1); if(room.getHumans() == 0) ok = true; } else if (randomInt <= pkitchen) { room = map.getRooms().get(2); if(room.getHumans() < 2) ok = true; } else { room = map.getRooms().get(3); if(room.getHumans() < 3) ok = true; } } positionX = room.getPositionX()+room.getWidth()/2; positionY = room.getPositionY()+room.getHeight()/2; this.getRoom().action(this); } }
e97d6915-3808-4183-8028-9308f85ac8ff
8
public boolean check(int dir, int cnt) { cnt++; if((dir<0)) dir=7; if((dir>7)) dir=0; Coordinate Coo = ausDirzuCoo(dir); // Diese Methode �berpr�ft anhand der Richtung, die �bergeben wird, die n�chste Koordinate und schaut, if(checkFreePosition(Coo.getXCoordinate(),Coo.getYCoordinate())){ // ob diese frei ist. Falls ja, wird die Richtung des Menschen entsprechend gesetzt. setDirection(dir); // Falls diese Koordinate nicht frei ist, ruft sich die Methode selber erneut auf und pr�ft die n�chste Richtung } // Sind alle 8 Richtungen einmal durchgepr�ft, gibt die Methode false zur�ck. else { // Der Integer cnt z�hlt sich bei jedem Durchlauf um einen hoch und schaut somit, ob alle Richtungen gepr�ft worden sind. if (cnt <= 8) { if ((this.target.getY0() > this.position.getY0()) && (this.target.getX0() < this.position.getX0())) { if (!check(--dir, cnt)) { return false; } } else { if (!check(++dir, cnt)) { return false; } } /* * if((dir == 4) && !check(3,7) && !check(2,7) && (this.position.getY0()-1 == this.target.getY0())) { * } * * else if((this.target.getY0() < this.position.getY0()) && * (this.target.getX0() < this.position.getX0())) { * if(!check(++dir,cnt)) { return false; } } else * if((this.target.getY0() > this.position.getY0()) && * (this.target.getX0() > this.position.getX0())) { * if(!check(++dir,cnt)) { return false; } } else * if((this.target.getY0() < this.position.getY0()) && * (this.target.getX0() > this.position.getX0())) { * if(!check(++dir,cnt)) { return false; } } else * if(this.target.getY0() == this.position.getY0()) * if(!check(++dir,cnt)) { return false; } } else * if(this.target.getX0() == this.position.getX0()) { * if(!check(--dir,cnt)) { return false; } } */ } } return true; }
777b8189-5c7a-4a79-8ca7-29a6495f5512
8
public static Timing fromLineIndexAndMeasureSize(int lineIndex, int numberLinesInMeasure) { int length; if (lineIndex != 0) { int gcd = getGCD(numberLinesInMeasure, lineIndex); length = numberLinesInMeasure / gcd; } else { return Timing.L1ST; } switch(length) { case 8: return Timing.L8TH; case 12: return Timing.L12TH; case 16: return Timing.L16TH; case 24: return Timing.L24TH; case 32: return Timing.L32ND; case 48: return Timing.L48TH; case 64: return Timing.L64TH; default: return Timing.L4TH; } }
36e3fc60-72d3-45ae-ba7d-d0c9308c456b
1
@SuppressWarnings("deprecation") public void testIsContiguous_RP() { YearMonthDay ymd = new YearMonthDay(2005, 6, 9); assertEquals(true, DateTimeUtils.isContiguous(ymd)); TimeOfDay tod = new TimeOfDay(12, 20, 30, 0); assertEquals(true, DateTimeUtils.isContiguous(tod)); Partial year = new Partial(DateTimeFieldType.year(), 2005); assertEquals(true, DateTimeUtils.isContiguous(year)); Partial hourOfDay = new Partial(DateTimeFieldType.hourOfDay(), 12); assertEquals(true, DateTimeUtils.isContiguous(hourOfDay)); Partial yearHour = year.with(DateTimeFieldType.hourOfDay(), 12); assertEquals(false, DateTimeUtils.isContiguous(yearHour)); Partial ymdd = new Partial(ymd).with(DateTimeFieldType.dayOfWeek(), 2); assertEquals(false, DateTimeUtils.isContiguous(ymdd)); Partial dd = new Partial(DateTimeFieldType.dayOfMonth(), 13).with(DateTimeFieldType.dayOfWeek(), 5); assertEquals(false, DateTimeUtils.isContiguous(dd)); try { DateTimeUtils.isContiguous((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} }
e8eb845f-7795-4f93-be2a-e95be781893c
8
private static String getFullMachineID() throws Exception { String MachineID = null; String localIP=null; String timestamp=null; try{ Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()){ NetworkInterface current = interfaces.nextElement(); //System.out.println(current); if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue; Enumeration<InetAddress> addresses = current.getInetAddresses(); while (addresses.hasMoreElements()){ InetAddress current_addr = addresses.nextElement(); if (current_addr.isLoopbackAddress()) continue; if (current_addr instanceof Inet4Address) localIP = current_addr.getHostAddress(); } } long unixTime = System.currentTimeMillis(); timestamp = Long.toString(unixTime); MachineID = localIP; MachineID += "+"; MachineID += timestamp; } catch (SocketException e) { System.out.println("Unable to get Local Host Address"); System.exit(1); } return MachineID; }
d9611cc5-85fb-4eb8-97b1-b29836dd72fd
7
@Override public boolean find(E d) { if(list == null) return false; if (list.data.compareTo(d) == 0) { return true; } else if (list.data.compareTo(d) < 0) { while (list.next != null) { list = list.next; if (list.data.compareTo(d) == 0) { return true; } } } else { while (list.prior != null) { list = list.prior; if (list.data.compareTo(d) == 0) { return true; } } } return false; }
6f2fd893-4b3e-4500-97c9-1de20a69c05d
7
public About(){ // anti-aliasing on System.setProperty("awt.useSystemAAFontSettings", "on"); editorPane = new JEditorPane(); editorPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); editorPane.setFont(new Font("Arial", Font.BOLD, 13)); editorPane.setPreferredSize(new Dimension(540,300)); editorPane.setEditable(false); editorPane.setContentType("text/html"); editorPane.setText( "<html>" + "<body>" + "<table border='0px' cxellpadding='10px' height='100%'>" + "<tr>" + "<td valign='center'>" + "<br /><img src='" + About.class.getResource("/resources/Utech-logo.png").toExternalForm() + "'>" + "</td>" + "<td>" + "<h2>" + "Advanced Programming Using Java" +"</h2>" + "Group Project issued by the University of Technology, Jamaica <br /><br />" + "Group Members: <br />" + "- Ashani Kentish <br />-" + "<a href=\"http://www.reliqartz.com/\"><b> Patrick Reid</b></a><br />" + "- Brandon Franklyn <br />" + "- Rajiv Manderson <br />" + "- Warren Harding <br />" + "<br />" + "Tutor:" + "<br />" + "<a href=\"jm.linkedin.com/pub/julian-jarrett/7a/a6/715\"><b>Julian Jarrett</b></a>" + "<br /><br />Github Repository" + "<br />" + "<a href=\"https://github.com/Yondaimeku/AP-project\"><b>AP-Project</b></a>" + "</td>" + "</tr>" + "</table>" + "</body>" + "</html>" ); editorPane.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged(HierarchyEvent e) { Window window = SwingUtilities.getWindowAncestor(editorPane); if (window instanceof Dialog) { Dialog dialog = (Dialog)window; if (dialog.isResizable()) { dialog.setResizable(false); } } } }); editorPane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) { EventQueue.invokeLater(new Runnable() { public void run() { SwingUtilities.getWindowAncestor(editorPane).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); // editorPane.setToolTipText(e.getURL().toExternalForm()); } }); } else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { EventQueue.invokeLater(new Runnable() { public void run() { SwingUtilities.getWindowAncestor(editorPane).setCursor(Cursor.getDefaultCursor()); // editorPane.setToolTipText(null); } }); } else if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(e.getURL().toURI()); } catch (Exception ex) { Logger.getLogger(About.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } } } } }); }
8849f467-8484-4a57-9bf0-7c5099899c15
0
public DarkSnakeLord(int room) { super(new FrostDiver(), new DarkBreath(), 83.00*room, 164.00*room, 80.00*room, 2.0*room, 70.0*room, 62.0*room, "Dark Snake Lord"); } // End DVC
bb36e832-bf29-4db2-863d-8f7a9927b64c
5
static final byte[] method850(boolean flag, Object obj, int i) { if (obj == null) { return null; } if (obj instanceof byte[]) { byte abyte0[] = (byte[]) obj; if (!flag) { return abyte0; } else { return Class52.method618(11301, abyte0); } } if (obj instanceof Class131) { Class131 class131 = (Class131) obj; return class131.method1163(11635); } if (i > -68) { method851(-103); } throw new IllegalArgumentException(); }
c9784575-baa7-4696-bcb5-8dc2dd257326
9
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((affected!=null) &&(affected instanceof MOB) &&(msg.amISource((MOB)affected)) &&((msg.sourceMinor()==CMMsg.TYP_DEATH) ||(msg.sourceMinor()==CMMsg.TYP_QUIT) ||(msg.sourceMinor()==CMMsg.TYP_RECALL) ||(msg.sourceMinor()==CMMsg.TYP_LEAVE) ||(destR==null) ||(msg.source().location()!=boxR))) { destR=null; unInvoke(); } return super.okMessage(myHost,msg); }
a5d1780d-7f00-4b2e-9d8b-b5ad0b3c8bee
8
public void setSuccessors() { for(String key1: this.getActiveKeys()) { long min = 10000007L; long max = 0L; long temp = 10000007L; String result = ""; for(String key: this.getActiveKeys()) { if(!this.getMember(key).isDeletable()) { if(getHashValue(key) < min) { min = getHashValue(key); } if(max < getHashValue(key)) { max = getHashValue(key); } if(getHashValue(key) > getHashValue(key1) && getHashValue(key) < temp) { temp = getHashValue(key); } } } //if max = processId then set successor to min if(getHashValue(key1) == max) { result = getProcessIdByHash(min); } else { result = getProcessIdByHash(temp); } this.getMember(key1).setHashKey(getHashValue(key1)); this.getMember(key1).setSuccessor(result); } }
ff2347ac-1253-4a4e-9b60-55a02662475d
6
public void save() { switches = "@Switch:"; if(rdbtnA.isSelected()) { switches += "a:"; } else if(rdbtnB.isSelected()) { switches += "b:"; } else if(rdbtnC.isSelected()) { switches += "c:"; } else if(rdbtnD.isSelected()) { switches += "d:"; } if(rdbtnEnable.isSelected()) { switches += "true"; } else if(rdbtnDisable.isSelected()) { switches += "false"; } }
ee244b0f-1bd1-4510-a951-f0db63e8f373
7
public static JavaScriptObject getJsObj(NameValuePair[] nameValuePairs) { JavaScriptObject paramObj = JsoHelper.createObject(); if (nameValuePairs == null) return paramObj; for (int i = 0; i < nameValuePairs.length; i++) { NameValuePair param = nameValuePairs[i]; switch (param.getType()) { case STRING: { JsoHelper.setAttribute(paramObj, param.getName(), param.getValue()); break; } case BOOLEAN: { JsoHelper.setAttribute(paramObj, param.getName(), param.getValueAsBoolean()); break; } case FLOAT: { JsoHelper.setAttribute(paramObj, param.getName(), param.getValueAsFloat()); break; } case INT: { JsoHelper.setAttribute(paramObj, param.getName(), param.getValueAsInt()); break; } case DATE: { JsoHelper.setAttribute(paramObj, param.getName(), param.getValueAsDate()); break; } default: { JsoHelper.setAttribute(paramObj, param.getName(), param.getValue()); } } } return paramObj; }
7d2fb737-1812-4afa-942c-aabf4b79782e
4
@Override public void render(GameContainer container, Graphics g) { switch (side) { case TOP: g.setColor(Color.red); break; case LEFT: g.setColor(Color.green); break; case BOTTOM: g.setColor(Color.blue); break; case RIGHT: g.setColor(Color.yellow); break; } g.fill(new Rectangle(x - 8, y - 8, 16, 16)); }
39c1bdf6-4ca9-497c-ae21-a27ef40bb969
1
@Test public void TestImage() { MarketSession session = new MarketSession(); session.login("antoine.souchet@gmail.com", "coucou2031"); //v2:com.sg.js.Doubles:1:3 //-7934792861962808905 GetImageRequest imgReq = GetImageRequest.newBuilder().setAppId("8885807488756673114") .setImageUsage(AppImageUsage.ICON) .setImageId("1") .build(); session.append(imgReq, new Callback<GetImageResponse>() { @Override public void onResult(ResponseContext context, GetImageResponse response) { try { File file = new File("/Temps/ico.png"); FileOutputStream fos = new FileOutputStream(file); fos.write(response.getImageData().toByteArray()); fos.close(); } catch(Exception ex) { ex.printStackTrace(); } } }); session.flush(); }
2adf8772-8a00-4c60-ab50-f75f304587d4
1
private void Slowdown(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Slowdown if (currSpeed > 1) { --currSpeed; world.setSpeed(currSpeed); speedCounter.setText("Speed: " + currSpeed); } }//GEN-LAST:event_Slowdown
0c416f7f-b270-4054-8df2-e4cf13e8a255
7
private Word checkConnector(int begin, int end) { if (end == -1) { // check connector on the left if (!currSen.connector.isEmpty()) { for (Word w : currSen.connector) { int pos = WPos2Chunk(w.pos); if (pos == begin || pos - 1 == begin) { return w; } } } } else {// check connector between begin and end for (Word w : currSen.connector) { int pos = WPos2Chunk(w.pos); if (between(begin + 1, end, pos)) { return w; } } } return null; }
8cc0363a-e198-468c-a1d6-3522d1dc56a8
7
private static void readProperties(NodeList children, Properties props) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if ("property".equalsIgnoreCase(child.getNodeName())) { final String key = getAttributeValue(child, "name"); String value = getAttributeValue(child, "value"); if (value == null) { Node grandChild = child.getFirstChild(); if (grandChild != null) { value = grandChild.getNodeValue(); if (value != null) value = value.trim(); } } if (value != null) props.setProperty(key, value); } else if ("properties".equals(child.getNodeName())) { readProperties(child.getChildNodes(), props); } } }
6bf3b140-cd36-4916-a743-0bb1d6cd1503
0
public void stop() { stop = true; sock.close(); }
3ad57750-04d7-4bc1-af9a-eaa1441f2844
6
public Facelet getFace(Face face) { switch(face) { case FRONT: return getFrontFace(); case LEFT: return getLeftFace(); case RIGHT: return getRightFace(); case BOTTOM: return getBottomFace(); case TOP: return getTopFace(); case BACK: return getBackFace(); } return Facelet.NONE; }
a84998f4-359a-4f2a-92b8-bd949d6f0f22
8
public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || nums.length == 0 || nums.length < k) { return new int[0]; } int[] result = new int[nums.length - k + 1]; ArrayDeque<Integer> deque = new ArrayDeque<Integer>(); for (int i = 0; i < nums.length; i++) { while (!deque.isEmpty() && deque.getLast() < nums[i]) { deque.removeLast(); } deque.offer(nums[i]); if (i < k - 1) { continue; } result[i - k + 1] = deque.getFirst(); if (result[i - k + 1] == nums[i - k + 1]) { deque.removeFirst(); } } return result; }
22e63aba-4c17-4c12-a015-2e364ff5ba1f
7
public ListNode partition(ListNode head, int x) { ListNode smallerHead = null, smallerTail = null, biggerHead = null, biggerTail = null; while (head != null) { int val = head.val; if (val < x) { if (smallerHead == null) { smallerHead = head; smallerTail = head; } else { smallerTail.next = head; smallerTail = head; } } else { if (biggerHead == null) { biggerHead = head; biggerTail = head; } else { biggerTail.next = head; biggerTail = head; } } head = head.next; } if (biggerTail != null) { biggerTail.next = null; } if (smallerTail != null) { smallerTail.next = biggerHead; } return smallerHead == null ? biggerHead : smallerHead; }
364f1eeb-61b8-401d-94dc-7785f6eb23c7
3
public int reverse(int x) { if (x == Integer.MIN_VALUE) throw new NumberFormatException("Can not revese" + x); boolean negative = x < 0; if (negative) x = -x; StringBuffer it = new StringBuffer(); it.append(x); it.reverse(); return negative ? -Integer.parseInt(it.toString()) : Integer .parseInt(it.toString()); }
d1d86ae7-c4b3-4fbe-95bd-3312f208a862
0
private boolean remove(int target) { // Student will replace this return statement with their own code: return false; }
17176c72-491d-4221-b33c-62b1201393ea
0
public void setNewValue(String newValue){ this.newValue.setText(newValue); }
9a672846-d3e1-4332-96de-07eb4a6fd1a2
1
public int getUpperLeftY() { if (y1 > y2) { return y1; } else { return y2; } }
195757cc-1405-4cbf-bf7b-80622a7b6be0
4
public void guiForSavingTheOutputFileWithXmlOrSpecialChars() { frmSavingTheOutputFileWithXmlOrSpecialChars.setSize(400, 300); frmSavingTheOutputFileWithXmlOrSpecialChars .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmSavingTheOutputFileWithXmlOrSpecialChars.setVisible(true); frmSavingTheOutputFileWithXmlOrSpecialChars .add(pnlSavingTheOutputFileWithXmlOrSpecialChars); frmSavingTheOutputFileWithXmlOrSpecialChars.setLocationRelativeTo(null); frmSavingTheOutputFileWithXmlOrSpecialChars .setTitle("XML Tool: Saving The File Either with Xml or Special Chars"); pnlSavingTheOutputFileWithXmlOrSpecialChars.setLayout(null); pnlSavingTheOutputFileWithXmlOrSpecialChars.setVisible(true); pnlSavingTheOutputFileWithXmlOrSpecialChars .add(btnForSavingFileAfterParticularDatedXmlIsExtractedOrSpecialCharsChecked); pnlSavingTheOutputFileWithXmlOrSpecialChars .add(btnForCancellingAndMovingBackToMainHomeScreenForSavingForm); pnlSavingTheOutputFileWithXmlOrSpecialChars .add(btnForSelectingFileOrCreatingNewFileForStoringResult); pnlSavingTheOutputFileWithXmlOrSpecialChars.add(txtPathOfFileOfSave); pnlSavingTheOutputFileWithXmlOrSpecialChars.add(txtNumberOfXml); pnlSavingTheOutputFileWithXmlOrSpecialChars .add(lblSaveAsSavingTheOutputFileWithXmlOrSpecialChars); pnlSavingTheOutputFileWithXmlOrSpecialChars .add(lblNumberOfXmlInLogFileAfterRemovingSpecialChars); pnlSavingTheOutputFileWithXmlOrSpecialChars.add(lblDone); btnForSavingFileAfterParticularDatedXmlIsExtractedOrSpecialCharsChecked .setBounds(100, 200, 80, 30); btnForSavingFileAfterParticularDatedXmlIsExtractedOrSpecialCharsChecked .setVisible(false); btnForCancellingAndMovingBackToMainHomeScreenForSavingForm.setBounds( 200, 200, 80, 30); btnForCancellingAndMovingBackToMainHomeScreenForSavingForm .setVisible(true); btnForSelectingFileOrCreatingNewFileForStoringResult.setBounds(300, 75, 80, 30); btnForSelectingFileOrCreatingNewFileForStoringResult.setVisible(true); txtPathOfFileOfSave.setBounds(80, 75, 200, 30); txtPathOfFileOfSave.setEditable(false); txtNumberOfXml.setBounds(230, 150, 100, 30); txtNumberOfXml.setEditable(false); txtNumberOfXml.setText(WritingXmlFromLogFileToTxtFile.temp2); lblSaveAsSavingTheOutputFileWithXmlOrSpecialChars.setBounds(10, 75, 80, 30); lblNumberOfXmlInLogFileAfterRemovingSpecialChars.setBounds(40, 150, 250, 30); lblNumberOfXmlInLogFileAfterRemovingSpecialChars.setVisible(true); lblDone.setBounds(150, 230, 80, 30); lblDone.setVisible(false); /* * Button listener for selecting or creating a file where we need to * save the end result i.e. either result set based on Query or special * chars */ try { btnForSelectingFileOrCreatingNewFileForStoringResult .addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub SelectingXmlFileToWriteSpecialChar objSelectingXmlFileToWriteSpecialChar = new SelectingXmlFileToWriteSpecialChar(); objSelectingXmlFileToWriteSpecialChar .savingXmlFileAfterSearchingForDataOrSpecialChars(); if (WritingXmlFromLogFileToTxtFile.fileCreatedAfterXmlIsExtractedFromLogFile .exists()) { btnForSavingFileAfterParticularDatedXmlIsExtractedOrSpecialCharsChecked .setVisible(true); txtPathOfFileOfSave .setText(objSelectingXmlFileToWriteSpecialChar.PathOfFileOfSave); } } }); } catch (Exception e) { e.printStackTrace(); } /* * Button listener to save and execute the special char query */ try { btnForSavingFileAfterParticularDatedXmlIsExtractedOrSpecialCharsChecked .addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub writingSpecialCharsToFileAfterSearchingForDataOrSpecialChars(); lblDone.setVisible(true); } }); } catch (Exception e) { e.printStackTrace(); } /* * Button Listener to cancel the action and move back to Home screen */ try { btnForCancellingAndMovingBackToMainHomeScreenForSavingForm .addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub MainHomePageForApplication objMainHomePageForApplication = new MainHomePageForApplication(); objMainHomePageForApplication.frmMainHomePage .setVisible(true); objMainHomePageForApplication.guiForMainHomePage(); objMainHomePageForApplication.btnfindingSpecialCharInMainHome.setVisible(true); objMainHomePageForApplication.btnQueringForXmlDataBasedOnDateinMainHomePage.setVisible(true); frmSavingTheOutputFileWithXmlOrSpecialChars .setVisible(false); //System.exit(0); } }); } catch (Exception e) { e.printStackTrace(); } }
95168abb-a0ee-4aad-bbb3-7078a88ec7be
4
private LocalVarEntry find(int addr) { LocalVarEntry li = list; while (li != null && li.endAddr < addr) li = li.next; if (li == null || li.startAddr > addr) { return null; } return li; }
4c09a766-7725-404d-ad37-c528cddf3e97
4
private static List<int[]> startFolkRankCreationForResources(BookmarkReader reader, int sampleSize) { int size = reader.getBookmarks().size(); int trainSize = size - sampleSize; List<Map<Integer, Integer>> userMaps = Utilities.getUserMaps(reader.getBookmarks()); System.out.println("\nStart FolkRank Calculation for Resources"); // TODO: should not use whole size! //LeavePostOutFolkRankDataDuplicator dupl = new LeavePostOutFolkRankDataDuplicator(); FactReader factReader = new WikipediaFactReader(reader, size, 3); FactPreprocessor prep = new FactReaderFactPreprocessor(factReader); prep.process(); FolkRankData facts = prep.getFolkRankData(); FolkRankParam param = new FolkRankParam(); FolkRankPref pref = new FolkRankPref(new double[] {1.0, 1.0, 1.0}); int tagCounts = facts.getCounts()[0].length; System.out.println("Tags: " + tagCounts); int usrCounts = facts.getCounts()[1].length; System.out.println("Users: " + usrCounts); int resCounts = facts.getCounts()[2].length; System.out.println("Resources: " + resCounts); double[] countVals = new double[]{usrCounts, usrCounts, usrCounts, usrCounts, usrCounts}; double[][] prefWeights = new double[][]{new double[]{}, countVals, new double[]{}}; // start FolkRank List<int[]> results = new ArrayList<int[]>(); for (int userID : reader.getUniqueUserListFromTestSet(trainSize)) { List<Integer> topResources = new ArrayList<Integer>(); int u = userID; int[] tPrefs = new int[]{}; int[] uPrefs = getBestUsers(userMaps, u, 5); int[] rPrefs = new int[]{}; pref.setPreference(new int[][]{tPrefs, uPrefs, rPrefs}, prefWeights); FolkRankAlgorithm folk = new FolkRankAlgorithm(param); FolkRankResult result = folk.computeFolkRank(facts, pref); SortedSet<ItemWithWeight> topKTags = ItemWithWeight.getTopK(facts, result.getWeights(), 100, 2); // TODO int count = 0; List<Integer> userResources = Bookmark.getResourcesFromUser(reader.getBookmarks().subList(0, trainSize), userID); for (ItemWithWeight item : topKTags) { if (count < 10) { if (!userResources.contains(item.getItem())) { topResources.add(item.getItem()); count++; } } else { break; } } results.add(Ints.toArray(topResources)); } return results; }
497a3c93-089c-4d08-8e0d-646321278154
7
public String toString() { String sql = "REPLACE "+table; if(expressions != null && columns != null ) { //the SET col1=exp1, col2=exp2 case sql += " SET "; //each element from expressions match up with a column from columns. for (int i = 0, s = columns.size(); i < s; i++) { sql += ""+columns.get(i)+"="+expressions.get(i); sql += (i<s-1)?", ":""; } } else if( columns != null ) { //the REPLACE mytab (col1, col2) [...] case sql += " "+PlainSelect.getStringList(columns, true, true); } if( itemsList != null ) { //REPLACE mytab SELECT * FROM mytab2 //or VALUES ('as', ?, 565) if( useValues ) { sql += " VALUES"; } sql += " "+itemsList; } return sql; }
39cd47db-3a82-4b9d-9926-d04fec4be487
4
public int get(int x, int y) { if (x < 0 || y < 0 || x > 3 || y > 3) throw new IllegalArgumentException("The position must be on range"); return this.board[x][y]; }
b4cbe4c7-2222-4881-b17d-a940ecb77088
9
public boolean equals (Object o) { if (!(o instanceof Argument)) return false; Argument a = (Argument)o; return ((a.arg_label == arg_label) || (a.arg_label != null && a.arg_label.equals(arg_label))) && ((a.mod_label == mod_label) || (a.mod_label != null && a.mod_label.equals(mod_label))) && ((a.location == location) || (a.location != null && a.location.equals(location))); }
6ea24bfb-cfe5-4eeb-8f02-aaee2e24a865
7
public boolean isPreselectionValid(final SettingsData settingsData) { if(settingsData.getObjects().size() != 1){ _tooltipText = "Genau ein Objekt muss ausgewählt sein."; return false; } if(settingsData.getObjects().get(0) instanceof ClientApplication && (settingsData.getAttributeGroup() == null || settingsData.getAspect() == null)){ // Anmeldungen für Applikation return true; } if(!super.isPreselectionValid(settingsData)) { _tooltipText = "Genau eine Applikation oder eine Attributgruppe und ein Aspekt muss ausgewählt sein."; return false; } // ATGV prüfen final AttributeGroupUsage atgUsage = settingsData.getAttributeGroup().getAttributeGroupUsage(settingsData.getAspect()); if(atgUsage == null || atgUsage.isConfigurating()) { _tooltipText = "Es muss eine Online-Attributgruppenverwendung ausgewählt werden."; return false; } _tooltipText = "Auswahl übernehmen"; return true; }
7004030d-0071-4cf8-9955-026db8effc2c
2
public void visitIntInsn(final int opcode, final int operand) { if (opcode == SIPUSH) { minSize += 3; maxSize += 3; } else { minSize += 2; maxSize += 2; } if (mv != null) { mv.visitIntInsn(opcode, operand); } }
b20c6831-03f1-4936-8e2c-c4a2836b5552
2
public boolean isAccepted() { Iterator it = myConfigurations.iterator(); while(it.hasNext()) { MealyConfiguration config = (MealyConfiguration) it.next(); if(config.isAccept()) return true; } return false; }
0c146bb3-d5db-42b6-aeca-2a53153b25a2
9
private void field_sit_frente_ivaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_field_sit_frente_ivaFocusLost if((field_sit_frente_iva.isEditable())&&(validar.isInt(field_calle.getText()))){ boolean es_componente=false; //voy a preguntar si la componente que me saco el foco es algun campo del panel de datos de asientos int i=0; Component[] components = panel_datos.getComponents(); while ((!es_componente)&&(i<components.length)){ if (components[i]==evt.getOppositeComponent()){ es_componente=true; } i++; } if((es_componente)&&(field_codigo.isEditable())){ String id_sfi=field_sit_frente_iva.getText(); if(!id_sfi.equals("")){ String descripcion =get_Tipo_Sit_frente_Iva(id_sfi); if (!descripcion.equals("")){ lab_tipo_imp.setText("("+descripcion+")"); } else{ field_sit_frente_iva.requestFocus(); this.generarAyuda_Situacion_Frente_Iva(); } } else{ this.mostrar_Msj_Error("El tipo de Situacion Frente IVA esta vacio, debe ingresar un valor"); field_sit_frente_iva.requestFocus(); } } else{ this.ocultar_Msj(); } } }//GEN-LAST:event_field_sit_frente_ivaFocusLost
c7e58f88-1aac-4068-b294-d51239bf7c29
4
private byte[] fetchClassFromFS(String path) throws FileNotFoundException, IOException { InputStream is = new FileInputStream(new File(path)); // Get the size of the file long length = new File(path).length(); if (length > Integer.MAX_VALUE) { // File is too large } // Create the byte array to hold the data byte[] bytes = new byte[(int)length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file "+path); } // Close the input stream and return bytes is.close(); return bytes; }
86158a09-e3ff-4905-a954-0f706b7f53a9
8
public static <T, S> void selectGroupedFields(CriteriaBuilder cb, CriteriaQuery<S> criteria, Root<T> root, List<String> group) { List<Selection<?>> listSelection = new ArrayList<Selection<?>>(); if (group != null) { for (String currentVal : group) { /** * separate field and function */ String[] splitCurrentVal = currentVal.split(","); Path<String> path = getPath(root, splitCurrentVal[0]); if (path != null) { /** * if have aggregation function */ if (splitCurrentVal.length == 2) { /** * aggregation functions */ Expression<?> expr = getExpressionPathAndFunctions(cb, path, splitCurrentVal[0], splitCurrentVal[1]); if (expr != null) { listSelection.add(expr); } } listSelection.add(path); } } } criteria.multiselect(listSelection); }
4526962e-b3a8-463c-b981-2174c9b7dcc7
5
public static List<Measurement> loadMeasurements(Mouse mouse) { ArrayList<Measurement> measurements = new ArrayList<>(); try (BufferedReader measurementReader = new BufferedReader( new FileReader(mouse.getFileName()))) { String measurementString; while ((measurementString = measurementReader.readLine()) != null) { if (measurementString.isEmpty()) { continue; } Measurement mes; if ((mes = Measurement.loadMeasurementString(measurementString)) != null) { measurements.add(mes); } } } catch (FileNotFoundException e) { } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return measurements; }
41862cbb-4643-4f73-9b4f-d938632b8336
3
@Override public void itemStateChanged(ItemEvent e) { //To change body of implemented methods use File | Settings | File Templates. if (e.getStateChange() == ItemEvent.SELECTED) { Object item = e.getItem(); // do something with object if(item instanceof Persoon) { this.selectedPerson = (Persoon) item; System.out.println("object persoon" + selectedPerson); } else { System.out.println("null"); this.selectedPerson = null; } if (item instanceof Rekening) { this.rekening = (Rekening) item; setOverzicht(rekening); System.out.println("object rekening geselecteerd " + rekening); } else { System.out.println("null"); this.rekening = null; } } }
28682e06-efd1-47c8-acc7-e3eae394ed21
4
public com.novativa.www.ws.streamsterapi.Trade[] getTrades() throws java.rmi.RemoteException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[3]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("GetTrades"); _call.setEncodingStyle(null); _call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE); _call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("", "GetTrades")); setRequestHeaders(_call); setAttachments(_call); try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {}); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException)_resp; } else { extractAttachments(_call); try { return (com.novativa.www.ws.streamsterapi.Trade[]) _resp; } catch (java.lang.Exception _exception) { return (com.novativa.www.ws.streamsterapi.Trade[]) org.apache.axis.utils.JavaUtils.convert(_resp, com.novativa.www.ws.streamsterapi.Trade[].class); } } } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } }
d9917678-148e-41d1-b11e-3a97c016bce4
2
@SuppressWarnings("deprecation") public static void createPet(LivingEntity e, UUID toFollow) { try { Object nms_entity = ((CraftLivingEntity) e).getHandle(); if (nms_entity instanceof EntityInsentient) { PathfinderGoalSelector goal = (PathfinderGoalSelector) goalSelector.get(nms_entity); PathfinderGoalSelector target = (PathfinderGoalSelector) targetSelector.get(nms_entity); gsa.set(goal, new UnsafeList<Object>()); gsa.set(target, new UnsafeList<Object>()); goal.a(0, new PathfinderGoalFloat((EntityInsentient) nms_entity)); goal.a(1, new PathfinderGoalWalktoTile((EntityInsentient) nms_entity, toFollow)); } else { throw new IllegalArgumentException(e.getType().getName() + " is not an instance of an EntityInsentient."); } } catch (Exception ex) { ex.printStackTrace(); } }
3c57545d-b9db-489d-9fd3-9c8dbcfcedc9
1
public static Type getObjectType(final String internalName) { char[] buf = internalName.toCharArray(); return new Type(buf[0] == '[' ? ARRAY : OBJECT, buf, 0, buf.length); }
e36c0907-72ed-4c62-aad3-6f2000ef8ca9
2
public CommandLineMode(String propertyFileName, Controller controller){ this.controller = this.controller; try { controller.loadPropertiesFromFile(new File(propertyFileName)); int width = controller.getPanelWidth(); int height = controller.getPanelHeight(); FileOutputStream outputBin = new FileOutputStream(new File("output.bin")); BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); int[] bits = bimage.getRGB( 0, 0, width, height, null, 0, width); controller.fillMemory(bits); bimage.setRGB( 0, 0, width, height, bits, 0, width); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bimage, "png", baos); outputBin.write(baos.toByteArray()); outputBin.close(); } catch (InvalidPropertiesFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
71c1c4e9-a254-44cc-9144-27d8e09b1962
6
public void Loading(){ ServerUp=true; isPainted=false; while(ServerUp){ repaint(); try{Thread.sleep(OPTIMAL_TIME/1000000);}catch (Exception e) {} if(isServer&&sendMap){ server.sendData(("2 "+Main.mapaS+" ").getBytes()); } if(!isServer) client.sendData("1 ".getBytes()); if(polaczono){ sendMap=false; gameLoop(); break; } } }
bfc77323-5413-4fc2-9833-e2fceff9a0eb
8
private JPanel buildButtons() { JPanel panel = new JPanel(new BorderLayout()); panel.setMaximumSize(new Dimension(2000,50)); JButton deleteButton = new JButton("Delete"); deleteButton.setFocusable(false); deleteButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { List<String> selectedItems = itemsList.getSelectedValuesList(); if(selectedItems.size() != 0 && !(selectedItems.size() == 1 && selectedItems.get(0).equals(FIRST_LIST_ENTRY))){ LinkedList<TimeDuration> timesList = model.getTimes(); for(String period: selectedItems){ TimeDuration periodToDelete = null; for(TimeDuration time: timesList){ if(time.getFormattedTimeDuration().equals(period)){ periodToDelete = time; } } model.deleteTime(periodToDelete); } info.setText("Delete or edit Time Periods!"); refresh(); }else{ info.setText("Please choose atleast one time to delete!"); } } }); JButton continueButton = new JButton("Continue ->"); continueButton.setFocusable(false); continueButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { List<String> selectedItems = itemsList.getSelectedValuesList(); if(!(selectedItems.size()==1)){ info.setText("Please choose one time to continue!"); }else{ info.setText("Delete or edit Time Periods!"); if(!selectedItems.get(0).equals(FIRST_LIST_ENTRY)){ timeToEdit = model.getTime(selectedItems.get(0)); toField.setTime(timeToEdit.getToTime()); fromField.setTime(timeToEdit.getFromTime()); }else{ timeToEdit = null; toField.reset(); fromField.reset(); } //editPanel.fill(itemToEdit); showEditPanel(); pack(); } } }); panel.add(deleteButton, BorderLayout.WEST); panel.add(continueButton, BorderLayout.EAST); return panel; }
07fc2f16-d822-494d-a25a-68d801d5bf6d
4
@Override void handleInput(Input input, boolean isMousePressed) { if (input.isKeyPressed(Input.KEY_ENTER) && !hasMadeChoice()) { makeChoice(selectedChoice); } int numberOfButtons = choiceButtons.getNumberOfButtons(); if (input.isKeyPressed(Input.KEY_RIGHT)) { selectedChoice = (selectedChoice + 1) % numberOfButtons; } if (input.isKeyPressed(Input.KEY_LEFT)) { selectedChoice = (selectedChoice + numberOfButtons - 1) % numberOfButtons; } setHighlighted(selectedChoice); Point upperLeft = new Point((int) choiceButtons.getNthButtonRectangle( selectedChoice + 1).getX(), (int) choiceButtons .getNthButtonRectangle(selectedChoice + 1).getY() - 20); tooltip = hud.createButtonTooltip(upperLeft, choiceButtons.getTooltipOfButtonWithIndex(selectedChoice)); }
4bcf03e3-037b-46d0-b58d-6428b23f680e
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(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Splash.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 Splash().setVisible(true); } }); }
6fc21b12-ba6d-479d-b060-35524ca87e36
3
public ArrayList<Tayte> haeFantasiaTaytteet(int tayteId1, int tayteId2, int tayteId3, int tayteId4) throws DAOPoikkeus { ArrayList<Tayte> fantasiataytteet = new ArrayList<Tayte>(); // Avataan yhteys Connection yhteys = avaaYhteys(); try { // Haetaan tietokannasta täytteet Fantasiapizzaa varten String fantasiaQuery = "SELECT nimi, tayteID from Tayte where tayteID = ?"; PreparedStatement haku = yhteys.prepareStatement(fantasiaQuery); // Luodaan lista, johon voidaan tallentaa nämä neljä Fantasiapizzan täytettä // jotta ne voidaan hakea erillisinä riveinä tietokannasta. List<Integer> taytteet = new ArrayList<Integer>(); taytteet.add(tayteId1); taytteet.add(tayteId2); taytteet.add(tayteId3); taytteet.add(tayteId4); for (int i = 0; i < taytteet.size(); i++) { // Sijoitetaan listasta haettava täyte lauseeseen. haku.setInt(1, taytteet.get(i)); // Suoritetaan haku ResultSet tulokset = haku.executeQuery(); while(tulokset.next()) { int id = tulokset.getInt("tayteID"); String nimi = tulokset.getString("nimi"); Tayte tayte = new Tayte(nimi, id); fantasiataytteet.add(tayte); } } } catch(Exception e) { // Tapahtuiko jokin virhe? throw new DAOPoikkeus("Tietokantahaku aiheutti virheen!", e); } finally { // Lopulta aina suljetaan yhteys! suljeYhteys(yhteys); } return fantasiataytteet; }
edb35d05-9427-4ae8-afc0-eca9cb7451aa
4
public void validateForFile(ScriptRunner pScriptRunner, PromotionFile pPromotionFile) throws ExPromote { List<Closeable> lStreamsToClose = new ArrayList<Closeable>(); try { for(ScriptExecutable lExecutable : mExecutableList){ if(lExecutable instanceof ScriptSQL){ //If this fails an error will be thrown String lStatementString = ((ScriptSQL) lExecutable).getParsedSQL(); try { //Replace substitution variables in the statement lStatementString = replaceSubstitutionVariables(lStatementString, pPromotionFile); //"practice" a bind with a null prepared statement bind(null, ((ScriptSQL) lExecutable).getBindList(), pScriptRunner, pPromotionFile, null); } catch (ExLoader e) { throw new ExPromote("Validation of " + mName + " loader failed for file " + pPromotionFile.getFilePath() + ": " + e.getMessage(), e); } catch (SQLException e) { throw new ExPromote("Validation of prepare " + mName + " loader failed for file " + pPromotionFile.getFilePath() + ": " + e.getMessage(), e); } } } } finally { //Close all open FileInputStreams and Readers closeCloseables(pPromotionFile, lStreamsToClose); } }
77298a4a-a4ec-4da6-9065-ae6d64ab53ee
4
public void hit(Entity e, Level level) { if (e instanceof CoinEntity) { CoinEntity ce = ((CoinEntity) e); if (!ce.collected) { score++; Sound.coin.play(); ce.collected = true; } } if (e instanceof SoildEntity) { health--; System.out.println(health); System.out.println(MAX_HEALTH); invTimer = 300; if(health == 0) { death(level); } } }
330b33ed-1713-4263-8c34-eec9cefa3dfa
5
private static void doFind() throws MVDToolException { try { char[] pattern = new char[findString.length()]; findString.getChars(0,pattern.length,pattern,0); if ( pattern.length > 0 ) { MVD mvd = loadMVD(); BitSet bs = new BitSet(); if ( version == 0 ) { for ( int i=1;i<=mvd.numVersions();i++ ) bs.set( i ); } else bs.set( version ); Match[] matches = mvd.search( pattern, bs, true ); for ( int i=0;i<matches.length;i++ ) { out.print( matches[i] ); } out.print("\n"); } else throw new MVDToolException( "Empty search text" ); } catch ( Exception e ) { throw new MVDToolException( e ); } }
5d21d6e7-a886-43b8-a1b2-10e8764ef2e9
5
private int getfittestParticle(Vector<Integer> particles) { if(maximum){ double fitness = solutionFitness.get(particles.get(0)); int result = particles.get(0); for(int i = 1; i < particles.size(); i++){ double temp = solutionFitness.get(particles.get(i)); if(temp > fitness){ fitness = temp; result = particles.get(i); } } return result; }else{ double fitness = solutionFitness.get(particles.get(0)); int result = particles.get(0); for(int i = 1; i < particles.size(); i++){ double temp = solutionFitness.get(particles.get(i)); if(temp < fitness){ fitness = temp; result = particles.get(i); } } return result; } }
6c5c66e9-5e2a-4bfb-bca4-a143f756ab31
4
public static void main(String[] args) { TalkToMe ttm; if (args.length != 0 && args[0].equalsIgnoreCase("g")) { ttm = new TalkToMe(args); try { ttm.readFile(ttm.filename); } catch (Exception ex) { ttm.guiMode.setMsgToChat(ERROR_READ_FILE + ex); ttm.logWriteComp(ERROR_READ_FILE + ex); } ttm.guiMode.setMsgToChat(ttm.sayHello()); ttm.logWriteComp(ttm.sayHello()); } else { ttm = new TalkToMe("Console"); try { ttm.readFile(ttm.filename); } catch (Exception ex) { System.err.println(ERROR_READ_FILE + ex); ttm.logWriteComp(ERROR_READ_FILE + ex); } ttm.answer(ttm.sayHello()); ttm.talk(); ttm.disconnect(); } }
bfd7e4a0-8c9c-46f6-9509-bd48622638b5
6
public void initialize() { setLayout(new MigLayout("wrap 1", "", "")); add(question, "wrap 20"); int recruitPrice = 0; Player player = getMyPlayer(); if ((getGame() != null) && (player != null)) { int production = 0; for (Colony colony : player.getColonies()) { production += colony.getTotalProductionOf(getSpecification() .getGoodsType("model.goods.crosses")); } int turns = 100; if (production > 0) { int immigrationRequired = (player.getImmigrationRequired() - player.getImmigration()); turns = immigrationRequired / production; if (immigrationRequired % production > 0) { turns++; } } recruitPrice = player.getRecruitPrice(); question.setText(Messages.message(StringTemplate.template("recruitDialog.clickOn") .addAmount("%money%", recruitPrice) .addAmount("%number%", turns))); for (int index = 0; index < NUMBER_OF_PERSONS; index++) { UnitType unitType = player.getEurope().getRecruitable(index); ImageIcon unitIcon = getLibrary().getUnitImageIcon(unitType, 0.66); person[index].setText(Messages.message(unitType.getNameKey())); person[index].setIcon(unitIcon); person[index].setEnabled(player.checkGold(recruitPrice)); add(person[index], "growx"); } } add(cancelButton, "newline 20, tag cancel"); setSize(getPreferredSize()); }
3ae11d04-0d6b-4d82-9970-3d6fc47f159d
0
public void actionPerformed(ActionEvent e) { beginQuit(); }
a86de31a-6cc2-4e99-a4a5-0ab5a7e7709b
7
public void print(Byte[] jeu){ for (int i=0; i < 37; i++){ if (i==4 || i==9 || i==15 || i==22 || i==28 || i==33) System.out.println(); System.out.print(jeu[i]); } System.out.println(); }
4c4767e0-254f-4e97-ae4b-c757d4cb5334
2
public boolean promoteUser(String name){ //op a user by name UserAccount user = users.get(name.toLowerCase()); if (user==null) return false; user.setIsAdmin(true); if (user.getThread()!=null) user.getThread().send("You are now op!"); return true; }
9d35c174-4545-4d37-89ff-16b033504fff
5
@Override protected Object standardSchemeReadValue(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TField field) throws org.apache.thrift.TException { _Fields setField = _Fields.findByThriftId(field.id); if (setField != null) { switch (setField) { case TITAN_ID: if (field.type == TITAN_ID_FIELD_DESC.type) { Long titanId; titanId = iprot.readI64(); return titanId; } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); return null; } case T_EDGE: if (field.type == T_EDGE_FIELD_DESC.type) { TEdge tEdge; tEdge = new TEdge(); tEdge.read(iprot); return tEdge; } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); return null; } default: throw new IllegalStateException("setField wasn't null, but didn't match any of the case statements!"); } } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); return null; } }
dd71df52-c77b-471e-96a7-10f83d5ec568
2
@Override public void main() { cleanOutput(); List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); Iterator<String> it = list.iterator(); String s; while(it.hasNext()) { s = it.next(); if (s.equals("4")) { it.remove(); continue; } addOutput("item: " + s); } super.main("Iterator"); }
238185b5-121a-4cad-a0e5-599e7997670b
6
public void stop() { if (isMovingRight() == false && isMovingLeft() == false) { playerSpeedX = 0; } if (isMovingRight() == false && isMovingLeft() == true) { moveLeft(); } if (isMovingRight() == true && isMovingLeft() == false) { moveRight(); } }
91867066-172c-483a-8fea-738427e310a4
6
private static void createAndShowGUI() { //Check the SystemTray support if (!SystemTray.isSupported()) { System.out.println("SystemTray is not supported"); return; } final PopupMenu popup = new PopupMenu(); // Create a popup menu components MenuItem aboutItem = new MenuItem("About"); CheckboxMenuItem cb1 = new CheckboxMenuItem("Notifications"); CheckboxMenuItem cb2 = new CheckboxMenuItem("Error Notifications"); CheckboxMenuItem cb3 = new CheckboxMenuItem("GUI Visible"); MenuItem exitItem = new MenuItem("Exit"); //Add components to popup menu popup.add(aboutItem); popup.addSeparator(); popup.add(cb1); popup.addSeparator(); popup.add(cb2); popup.add(cb3); popup.addSeparator(); popup.add(exitItem); trayIcon.setPopupMenu(popup); trayIcon.setImageAutoSize(true); trayIcon.setToolTip("LoL Streams"); cb1.setState(true); cb2.setState(true); cb3.setState(true); try { tray.add(trayIcon); } catch (AWTException e) { System.out.println("TrayIcon could not be added."); return; } trayIcon.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Main.gui.setState(0); Main.gui.setVisible(true); Main.gui.toFront(); // JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray"); } }); aboutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "LoL Streams is out of beta. Created by Dwarfeh"); } }); cb1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { int cb1Id = e.getStateChange(); streamNotifications = cb1Id == ItemEvent.SELECTED; } }); cb2.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { int cb2Id = e.getStateChange(); errorNotifications = cb2Id == ItemEvent.SELECTED; } }); cb3.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { int cb3Id = e.getStateChange(); Main.gui.setVisible(cb3Id == ItemEvent.SELECTED); } }); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { MenuItem item = (MenuItem)e.getSource(); //TrayIcon.MessageType type = null; System.out.println(item.getLabel()); if ("Error".equals(item.getLabel())) { //type = TrayIcon.MessageType.ERROR; trayIcon.displayMessage("Sun TrayIcon Demo", "This is an error message", TrayIcon.MessageType.ERROR); } else if ("Warning".equals(item.getLabel())) { //type = TrayIcon.MessageType.WARNING; trayIcon.displayMessage("Sun TrayIcon Demo", "This is a warning message", TrayIcon.MessageType.WARNING); } else if ("Info".equals(item.getLabel())) { //type = TrayIcon.MessageType.INFO; trayIcon.displayMessage("Sun TrayIcon Demo", "This is an info message", TrayIcon.MessageType.INFO); } else if ("None".equals(item.getLabel())) { //type = TrayIcon.MessageType.NONE; trayIcon.displayMessage("Sun TrayIcon Demo", "This is an ordinary message", TrayIcon.MessageType.NONE); } } }; exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tray.remove(trayIcon); System.exit(0); } }); }
c13b9234-030c-48ab-a5bd-a50e750a8b6b
0
public String getCode() { return code; }
027e6ba0-88aa-421d-8f4d-db7beeceaae9
7
public static String computeCommonLispFileExtension(Keyword type) { if (!(Stella.runningAsLispP())) { throw ((StellaException)(StellaException.newStellaException("Shouldn't call COMPUTE-COMMON-LISP-FILE-EXTENSION unless running in Lisp").fillInStackTrace())); } { String suffix = null; if (type == Stella.KWD_LISP_BINARY) { suffix = null; if (((List)(Stella.$CURRENT_STELLA_FEATURES$.get())).membP(Stella.KWD_USE_COMMON_LISP_STRUCTS)) { suffix = "s" + suffix; } else if (((List)(Stella.$CURRENT_STELLA_FEATURES$.get())).membP(Stella.KWD_USE_COMMON_LISP_VECTOR_STRUCTS)) { suffix = "vs" + suffix; } else { } } else if (type == Stella.KWD_LISP) { if (((List)(Stella.$CURRENT_STELLA_FEATURES$.get())).membP(Stella.KWD_USE_COMMON_LISP_STRUCTS)) { suffix = ".slisp"; } else if (((List)(Stella.$CURRENT_STELLA_FEATURES$.get())).membP(Stella.KWD_USE_COMMON_LISP_VECTOR_STRUCTS)) { suffix = ".vslisp"; } else { suffix = ".lisp"; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + type + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } return ("." + suffix); } }
5f8983ae-bec5-4e52-adc5-f3543fc18b39
9
public static BufferedImage rotate(BufferedImage src, Rotation rotation) throws IllegalArgumentException, ImagingOpException { long t = System.currentTimeMillis(); if (src == null) throw new IllegalArgumentException("src cannot be null"); if (rotation == null) throw new IllegalArgumentException("rotation cannot be null"); if (DEBUG) log(0, "Rotating Image [%s]...", rotation); /* * Setup the default width/height values from our image. * * In the case of a 90 or 270 (-90) degree rotation, these two values * flip-flop and we will correct those cases down below in the switch * statement. */ int newWidth = src.getWidth(); int newHeight = src.getHeight(); /* * We create a transform per operation request as (oddly enough) it ends * up being faster for the VM to create, use and destroy these instances * than it is to re-use a single AffineTransform per-thread via the * AffineTransform.setTo(...) methods which was my first choice (less * object creation); after benchmarking this explicit case and looking * at just how much code gets run inside of setTo() I opted for a new AT * for every rotation. * * Besides the performance win, trying to safely reuse AffineTransforms * via setTo(...) would have required ThreadLocal instances to avoid * race conditions where two or more resize threads are manipulating the * same transform before applying it. * * Misusing ThreadLocals are one of the #1 reasons for memory leaks in * server applications and since we have no nice way to hook into the * init/destroy Servlet cycle or any other initialization cycle for this * library to automatically call ThreadLocal.remove() to avoid the * memory leak, it would have made using this library *safely* on the * server side much harder. * * So we opt for creating individual transforms per rotation op and let * the VM clean them up in a GC. I only clarify all this reasoning here * for anyone else reading this code and being tempted to reuse the AT * instances of performance gains; there aren't any AND you get a lot of * pain along with it. */ AffineTransform tx = new AffineTransform(); switch (rotation) { case CW_90: /* * A 90 or -90 degree rotation will cause the height and width to * flip-flop from the original image to the rotated one. */ newWidth = src.getHeight(); newHeight = src.getWidth(); // Reminder: newWidth == result.getHeight() at this point tx.translate(newWidth, 0); tx.rotate(Math.toRadians(90)); break; case CW_270: /* * A 90 or -90 degree rotation will cause the height and width to * flip-flop from the original image to the rotated one. */ newWidth = src.getHeight(); newHeight = src.getWidth(); // Reminder: newHeight == result.getWidth() at this point tx.translate(0, newHeight); tx.rotate(Math.toRadians(-90)); break; case CW_180: tx.translate(newWidth, newHeight); tx.rotate(Math.toRadians(180)); break; case FLIP_HORZ: tx.translate(newWidth, 0); tx.scale(-1.0, 1.0); break; case FLIP_VERT: tx.translate(0, newHeight); tx.scale(1.0, -1.0); break; } // Create our target image we will render the rotated result to. BufferedImage result = createOptimalImage(src, newWidth, newHeight); Graphics2D g2d = (Graphics2D) result.createGraphics(); /* * Render the resultant image to our new rotatedImage buffer, applying * the AffineTransform that we calculated above during rendering so the * pixels from the old position are transposed to the new positions in * the resulting image correctly. */ g2d.drawImage(src, tx, null); g2d.dispose(); if (DEBUG) log(0, "Rotation Applied in %d ms, result [width=%d, height=%d]", System.currentTimeMillis() - t, result.getWidth(), result.getHeight()); return result; }
eb535e47-0693-4126-8b61-45ef78329dd9
5
public static String readFile2(String file) throws IOException{ //System.out.println("path : " + path + " reading..."); Watch t = new Watch();t.start(); System.out.println("read......"); String sJSON = ""; Path path = Paths.get(file); List<String> text =Files.readAllLines(path,StandardCharsets.UTF_8); //number of threads int threadNumber = 4; Thread[] array= new Thread[threadNumber]; int size= text.size(); str= new String [threadNumber]; int d = size/threadNumber; for (int i=0; i<threadNumber;i++){ int min = d*i; int max = d*(i+1); if(i==threadNumber-1)max=size; Thread a = new Thread(new threadReader(i,text,min,max)); a.start(); array[i]=a; } for(Thread is:array){ try { is.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block is.interrupt(); } } for(String jsonPart : str){ sJSON += jsonPart; } t.stop(); System.out.println("stop ...... "+t.getElapsedTime() +"ms"); //System.exit(0); return sJSON; }
5ce4e222-2ec8-4507-a111-e307dc403855
1
public void broadcastPQ(final BigInteger p, final BigInteger q, final int numUsers) throws InterruptedException, IOException { final Subscription pqSub = elvin.subscribe(NOT_TYPE + " == '" + BROADCAST_PQ_REPLY + "' && " + GAME_ID + " == '" + gameHost.getID() + "'"); Notification pqnot = new Notification(); numResponses = 1; pqSub.addListener(new NotificationListener() { public void notificationReceived(NotificationEvent e) { numResponses++; if (numResponses >= numUsers) { synchronized (pqSub) { pqSub.notify(); } } } }); pqnot.set(GAME_ID, gameHost.getID()); pqnot.set(NOT_TYPE, BROADCAST_PQ); pqnot.set("p", p.toString()); pqnot.set("q", q.toString()); elvin.send(pqnot); synchronized (pqSub) { elvin.send(pqnot); // wait until received reply pqSub.wait(); } // short sleep before returning Thread.sleep(100); return; }
f4417cf2-1e5a-42aa-9821-779c75776ce9
1
public float median() { Collections.sort(data); if (data.size() % 2 == 0) { return (data.get(data.size() / 2 - 1) + data.get(data.size())) / 2; } return data.get(data.size() / 2); }
66191ecc-781f-4635-9735-d0849a69a2fa
2
public KiesOnderwerp(Spel spel) { setBounds(0, 0, 773, 318); setLayout(new MigLayout("", "[100px:100px:100px,grow][700px,grow][100px:100px:100px]", "[173.00px][150.00][150px][173.00px,grow]")); /** * De titel "Kies een onderwerp" */ JLabel lblNewLabel = new JLabel("Kies een onderwerp"); lblNewLabel.setForeground(Color.WHITE); lblNewLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 47)); add(lblNewLabel, "flowx,cell 1 1,alignx center,aligny center"); JPanel panel = JPanelFactory.createBackgroundJPanel(); add(panel, "cell 1 2,alignx center,aligny center"); panel.setLayout(new MigLayout("", "[40px,grow][40px,grow][40px,grow][40px,grow][40px,grow]", "[]")); try { List<Onderwerp> onderwerpen; onderwerpen = spel.getOnderwerpen(); for (Onderwerp onderwerp : onderwerpen) panel.add(new views.panels.Onderwerp(onderwerp, spel)); } catch (DataException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
746a3f9f-80da-43ed-9f7a-c43d17a3220e
3
/* */ public static String excutePost(String targetURL, String urlParameters) /* */ { /* 54 */ HttpURLConnection connection = null; /* */ try /* */ { /* 57 */ URL url = new URL(targetURL); /* 58 */ connection = (HttpURLConnection)url.openConnection(); /* 59 */ connection.setRequestMethod("POST"); /* 60 */ connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); /* */ /* 62 */ connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); /* 63 */ connection.setRequestProperty("Content-Language", "en-US"); /* */ /* 65 */ connection.setUseCaches(false); /* 66 */ connection.setDoInput(true); /* 67 */ connection.setDoOutput(true); /* */ /* 70 */ DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); /* 71 */ wr.writeBytes(urlParameters); /* 72 */ wr.flush(); /* 73 */ wr.close(); /* */ /* 76 */ InputStream is = connection.getInputStream(); /* 77 */ BufferedReader rd = new BufferedReader(new InputStreamReader(is)); /* */ /* 79 */ StringBuffer response = new StringBuffer(); /* */ String line; /* 80 */ while ((line = rd.readLine()) != null) /* */ { /* 81 */ response.append(line); /* 82 */ response.append('\r'); /* */ } /* 84 */ rd.close(); /* 85 */ String str1 = response.toString(); /* */ return str1; /* */ } /* */ catch (Exception e) /* */ { /* 89 */ e.printStackTrace(); /* */ return null; /* */ } /* */ finally /* */ { /* 94 */ if (connection != null) /* 95 */ connection.disconnect(); /* */ } /* 97 */ //throw localObject; /* */ }
112289bd-564b-4e3f-a09a-2a43016517c8
8
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Timing that = (Timing) o; if (Double.compare(that.ioResponseTime, ioResponseTime) != 0) return false; if (Double.compare(that.worstReadeTime, worstReadeTime) != 0) return false; if (Double.compare(that.worstSamplingTime, worstSamplingTime) != 0) return false; if (Double.compare(that.worstUpdateTime, worstUpdateTime) != 0) return false; if (Double.compare(that.worstWriteTime, worstWriteTime) != 0) return false; return true; }
19234abf-d90a-411e-a1a0-5a33ead58017
2
public Plateau() { this.plateau = new EtatDesCases[LONGUEUR_DE_LA_MAP][LARGEUR_DE_LA_MAP]; for (int indiceParcoursLongueurMap=0; indiceParcoursLongueurMap<LONGUEUR_DE_LA_MAP; indiceParcoursLongueurMap++) for (int indiceParcoursLargeurMap=0; indiceParcoursLargeurMap<LARGEUR_DE_LA_MAP; indiceParcoursLargeurMap++) this.plateau[indiceParcoursLongueurMap][indiceParcoursLargeurMap] = EtatDesCases.LIBRE; }
2ec5592b-eef1-4ec6-8eeb-ee2f6d129ed9
9
private static List<? extends Tuple> toList(Object[][] table) { List<Tuple> list = new ArrayList<>(table.length); for (Object[] aTable : table) { List<Value> row = new ArrayList<>(aTable.length); for (Object val : aTable) { if (val instanceof DataType) { row.add(Value.nullOf((DataType) val)); } else if (val instanceof Float || val instanceof Double) { row.add(Value.of(((Number) val).doubleValue())); } else if (val instanceof Integer || val instanceof Long) { row.add(Value.of(((Number) val).longValue())); } else if (val instanceof String) { row.add(Value.of(val.toString())); } else { throw new IllegalArgumentException("Unsupported value type: " + val.getClass()); } } list.add(new SimpleListTuple(row)); } return list; }
b3a4f970-d490-4065-9fa4-9bdd60241f0c
9
public void writeResultFile() { try { FileWriter fstream = new FileWriter(resultFile); StringBuilder sb = new StringBuilder(); BufferedWriter out = new BufferedWriter(fstream); sb.append("StartNr; Namn; "); if(!(driverAttributes == null) && !driverAttributes.isEmpty()){ for(int i = 0; i < driverAttributes.size(); i++){ sb.append(driverAttributes.get(i) + "; "); } } sb.append("Totaltid; "); sb.append("#Etapper; "); for (int i = 0; i < stages; i++) { sb.append("Etapp" + (i + 1) + "; "); } for (int i = 0; i < stages - 1; i++) { sb.append("Start" + (i + 1) + "; Mål" + (i + 1) + "; "); } sb.append("Start" + (stages) + "; Mål" + stages); // Vi antar att vi har alla starttime och finishtime för alla // ettapper i index TreeMap. // dvs finishtime[0] - starttime[0] = etapp[1], finishtime[1] - // starttime[1] = etapp[2], Mål = etapp[0]+etapp[1]... Driver tDriver; mapOfDiffRaceClasses = new HashMap<String, TreeMap<Integer, Driver>>(); ArrayList<Driver> notSortedDrivers = new ArrayList<Driver>(); for (Integer i : index.keySet()) { tDriver = index.get(i); String classes = tDriver.getRaceClass(); mapOfDiffRaceClasses.put(classes, addTreeMap(classes, i, tDriver)); notSortedDrivers.add(tDriver); } //Skriver ut till fil //Hämtar TreeMap med className som key så att vi får ut alla som tillhör klassen. for (String className : mapOfDiffRaceClasses.keySet()) { TreeMap<Integer, Driver> tm = mapOfDiffRaceClasses.get(className); out.write(className + "\n"); out.write(sb.toString()); for (Integer i : tm.keySet()) { tDriver = tm.get(i); out.write(checkErrorStageRace(i, tDriver)); } } out.close(); } catch (Exception e) { System.err.println("Error: Misslyckades med att skriva resultatfilen för etapplopp"); System.exit(1); } }
279a5f4d-1cac-48f6-b118-4f0827394597
2
public void addValue(double dist, Object value) { // If there is still room in the heap if (values < size) { // Insert new value at the end data[values] = value; distance[values] = dist; upHeapify(values); values++; } // If there is no room left in the heap, and the new entry is lower // than the max entry else if (dist < distance[0]) { // Replace the max entry with the new entry data[0] = value; distance[0] = dist; downHeapify(0); } }
35880125-7169-43d1-9ecc-ccc8bdbbffc9
0
public int getForce() { return force; }
f8cf743a-001a-4a6c-a012-c48b46ed5121
0
@BeforeClass public static void initServices() throws Exception { ServiceManager.getServices().initializeServices( new Object[] { new TestRailwayRepository()}); }
d6f17d9a-1fc5-44e1-92c8-0524fc90756e
4
public static final float atan2(float y, float x) { float add, mul; if (x < 0) { if (y < 0) { y = -y; mul = 1; } else mul = -1; x = -x; add = -3.141592653f; } else { if (y < 0) { y = -y; mul = -1; } else mul = 1; add = 0; } float invDiv = 1 / (((x < y) ? y : x) * INV_ATAN2_DIM_MINUS_1); int xi = (int) (x * invDiv); int yi = (int) (y * invDiv); return (atan2[yi * ATAN2_DIM + xi] + add) * mul; }
e4f8a45f-49bd-4bbb-ab60-db8aac5c7cd8
9
@Override protected List<Chromosome> filter(List<Chromosome> children) { List<Chromosome> newChildren = new ArrayList<Chromosome>(); int repeats = 0; // Remove children which are too similar for (Chromosome c : children) { boolean unique = true; for (Chromosome c2 : children) { if (c == c2) continue; if (Math.abs(c.similarityIndex(c2)) < 0.001) { // too similar unique = false; break; } } if (unique) { // remove children which are too similar to parents for (Chromosome p : population) { if (Math.abs(c.similarityIndex(p)) < 0.001) { unique = false; break; } } } if (unique) newChildren.add(c); else { repeats++; try { // Add replacement freshie and collect its fitness Chromosome newGuy = c.getClass().getConstructor().newInstance(); newChildren.add(newGuy); } catch (java.lang.Exception e) { e.printStackTrace(); } } } System.out.println("Repeats: " + repeats); return newChildren; }
474f6cef-d07a-4524-bf99-68b985d47c9e
1
public void setMaxCapacity(int maxCapacity) throws CarriageException { if (maxCapacity >= 0) { this.maxCapacity = maxCapacity; } else { throw new CarriageException("Maximum capacity is under zero"); } }
e672302a-4cab-413f-b47b-a604a4362aa5
7
public Problem11(){ loadData(); for(int x1 = 0; x1<20;x1++){ for(int y1=0;y1 < 20;y1++){ if(grid[x1][y1] > 0){ long dow = down(x1,y1); long acc = across(x1,y1); long dia1 = diagP(x1,y1); long diaN = diagN(x1,y1); long highest1 = (dow > acc)?dow:acc; long highest2 = (dia1 > diaN)?dia1:diaN; long highest = (highest1>highest2)?highest1:highest2; if(highest > answer){ answer = highest; } } } } }
f504633c-2282-441c-8aa3-643ff05f600a
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Article)) { return false; } Article other = (Article) object; if ((this.articleID == null && other.articleID != null) || (this.articleID != null && !this.articleID.equals(other.articleID))) { return false; } return true; }
6ffe2890-6304-4e1e-9b8e-1861a8a222a4
7
public static void preE(Topic root) { // Fetching the edge set for the topic ArrayList<SparseMatrix> getset = root.Get_edgeset(); //System.out.println("Edge size" + getset.size()); // Fetching the Max word it of the topic Integer MaxWordId = root.Get_Maxwordid(); // Fetching the edge weight across sub topics(children) float[][] edgeweight = root.Get_edgeweight(); int edgeweight_i = root.Get_edgeweight().length; int edgeweight_j = root.Get_edgeweight()[0].length; // Number of columns // or topics // Fetching original rho value (initially set to 0.0) float[] rho = root.Get_rho_z(); for (int j = 0; j < edgeweight_j; j++) { for (int i = 0; i < edgeweight_i; i++) { rho[j] = rho[j] + edgeweight[i][j]; } } // ROOT SETTING RHO : Setting the newly calculated rho values for each subtopic root.Set_rho_zM(rho); //System.out.println("[EM] rho set"); // printing edge weight // for(int i = 0; i < edgeweight_i; i++){ // for(int j = 0 ; j < edgeweight_j; j++){ // System.out.print(edgeweight[i][j] + " "); // } // System.out.println(); // } //printing rho array for the present topic's children // for(int f = 0 ; f < rho.length; f++){ // System.out.print(rho[f] + " "); // } // // Calculate theta i for everyword in each subtopic float[][] sumthetai = new float[root.Get_thetai().length][root.Get_thetai()[0].length]; for(int i = 0; i< root.Get_thetai()[0].length; i++ ){ Arrays.fill(sumthetai[i], 0); } // System.out.println("rows: " + sumthetai.length); // System.out.println("cols: " + sumthetai[0].length); // Iterator<SparseMatrix> it = getset.iterator(); int ew = 0; while (it.hasNext()) { SparseMatrix current = it.next(); for (int t = 0; t < sumthetai[0].length; t++) { sumthetai[current.getwordid1() - 1][t] = sumthetai[current.getwordid1() - 1][t] + edgeweight[ew][t]; sumthetai[current.getwordid2() - 1][t] = sumthetai[current.getwordid2() - 1][t] + edgeweight[ew][t]; } ew++; } // For printing the theta value of each word across the topics int aa = sumthetai.length; int bb = sumthetai[0].length; // System.out.println("-------sum theta>>>>>>>-----"); // for(int a = 0; a < aa ; a++){ // for(int b = 0; b < bb; b++){ // System.out.print(sumthetai[a][b] + " "); // } // System.out.println(""); // } // float[][] thetaiEM = new float[sumthetai.length][sumthetai[0].length]; for (int i = 0; i < sumthetai.length; i++) { for (int j = 0; j < sumthetai[0].length; j++) { thetaiEM[i][j] = sumthetai[i][j] / rho[j]; } } //System.out.println("Calling thetai set to set the preEM values of theta i"); root.Set_thetai(thetaiEM); // int nn = thetaiEM.length; // int mm = thetaiEM[0].length; // System.out.println("-------Theta of each word in each topic-----"); // for(int i = 0; i < nn ; i++){ // for(int j = 0; j < mm; j++){ // System.out.print(thetaiEM[i][j] + " "); // } // System.out.println(""); // } // Creating a Thetai in array format to return to the Build Tree // function //System.out.println("thetai set"); }
f9dcc1d0-91c6-41fd-86e8-02c533a38c21
7
public Instance convertInstance(Instance instance) throws Exception { if (m_s == null) { throw new Exception("convertInstance: Latent Semantic Analysis not " + "performed yet."); } // array to hold new attribute values double [] newValues = new double[m_outputNumAttributes]; // apply filters so new instance is in same format as training instances Instance tempInstance = (Instance)instance.copy(); if (!instance.dataset().equalHeaders(m_trainHeader)) { throw new Exception("Can't convert instance: headers don't match: " + "LatentSemanticAnalysis\n" + instance.dataset().equalHeadersMsg(m_trainHeader)); } // replace missing values m_replaceMissingFilter.input(tempInstance); m_replaceMissingFilter.batchFinished(); tempInstance = m_replaceMissingFilter.output(); // normalize if (m_normalize) { m_normalizeFilter.input(tempInstance); m_normalizeFilter.batchFinished(); tempInstance = m_normalizeFilter.output(); } // convert nominal attributes to binary m_nominalToBinaryFilter.input(tempInstance); m_nominalToBinaryFilter.batchFinished(); tempInstance = m_nominalToBinaryFilter.output(); // remove class/other attributes if (m_attributeFilter != null) { m_attributeFilter.input(tempInstance); m_attributeFilter.batchFinished(); tempInstance = m_attributeFilter.output(); } // record new attribute values if (m_hasClass) { // copy class value newValues[m_outputNumAttributes - 1] = instance.classValue(); } double [][] oldInstanceValues = new double[1][m_numAttributes]; oldInstanceValues[0] = tempInstance.toDoubleArray(); Matrix instanceVector = new Matrix(oldInstanceValues); // old attribute values instanceVector = instanceVector.times(m_transformationMatrix); // new attribute values for (int i = 0; i < m_actualRank; i++) { newValues[i] = instanceVector.get(0, i); } // return newly transformed instance if (instance instanceof SparseInstance) { return new SparseInstance(instance.weight(), newValues); } else { return new Instance(instance.weight(), newValues); } }
27f4355e-0f50-4d68-b410-199b7f82e7f4
3
public void printMatrix() { // Column attributes stuff System.out.println(columnAttributes); System.out.println(); // Column names for (int i = 0; i < getNumCols(); i++) { System.out.printf("%15s", columnAttributes.get(i).getName()); } System.out.println(); // Data for (int i = 0; i < getNumRows(); i++) { List<Double> row = getRow(i); for (int j = 0; j < getNumCols(); j++) { System.out.printf("%15s ", row.get(j)); } System.out.println(); } }
4ff15c84-808a-4723-ba57-c91d6ce98f07
5
@SuppressWarnings("unchecked") private void readFile() { FileInputStream gfis = null, gcfis = null; ObjectInputStream gois = null, gcois = null; try { gfis = new FileInputStream(goodsURL); gcfis = new FileInputStream(goodsClassURL); if(gfis.available() > 0) gois = new ObjectInputStream(gfis); if(gcfis.available() > 0) gcois = new ObjectInputStream(gcfis); goodsList = (ArrayList<GoodsPO>) gois.readObject(); goodsClassList = (ArrayList<GoodsClassPO>) gcois.readObject(); } catch (FileNotFoundException e) { System.out.println("goodsPO.out or goodsClassPO.out not found"); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { System.out.println(".out读取问题"); } }
5ac32221-d697-49cc-9d2e-c773c51fdb08
2
public Match requestNextMatch(int userID) { alstNewMatchRequests.add(userID); int userCount = 0; for (Team team : playmode.getTeams()) { userCount += team.getUser().length; } Match nextMatch = upcomingMatches.peek(); if((alstNewMatchRequests.size() - alstLeftUser.size()) == userCount){ nextMatch(userID); alstNewMatchRequests.clear(); } return nextMatch; }
89a50938-c1e3-4278-9e9a-6235a654a5ce
3
public static String coverttoText(String rtfText) { byte[] rtfBytes = rtfText.getBytes(); RTFEditorKit rtfParser = new RTFEditorKit(); Document document = rtfParser.createDefaultDocument(); try { rtfParser.read(new ByteArrayInputStream(rtfBytes), document, 0); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } String text = ""; try { text = document.getText(0, document.getLength()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return text; }