method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
7bd072ea-e1ff-41e8-a73c-21823cd65722
3
public void renderHealth(){ float px = 0 - Main.px; float py = 0 + Main.py; if(health < 3){ glColor4d(1, 0.2, 0.2, 0.5); glBegin(GL_QUADS); { glVertex2f(px, py); glVertex2f(px + Main.WIDTH, py); glVertex2f(px + Main.WIDTH, py + Main.HEIGHT); glVertex2f(px, py + Main.HEIGHT); } glEnd(); } for(int i = 0; i < maxHealth; i++){ if(health <= i){ glColor4d(0.6, 0.6, 0.6, 0.6); }else{ glColor4d(1, 1, 1, 1); } renderHeart(Main.WIDTH - 48 + px, i * 48 + 8 + py); } }
2e8f6a22-9bee-49b6-b3fc-87cad2ac409c
6
private MapEntry getExceptionProcessor(ExceptionResolver exceptionResolver, Exception ex) { if (exceptionResolver == null) { return null; } MapEntry[] exceptionProcessors = exceptionResolver.value(); for (MapEntry exceptionProcessor : exceptionProcessors) { Class<? extends Exception>[] handlerExceptions = exceptionProcessor .exceptions(); for (Class<? extends Exception> handlerException : handlerExceptions) { if (handlerException.isInstance(ex)) { return exceptionProcessor; } } } return null; }
93ad3b33-f42a-443a-91b6-e0695b572cb5
2
public static void main(String[] args) { for (Path part : path) { System.out.println(part); } Path parentPath = path.getParent(); System.out.println(parentPath); if (parentPath.compareTo(path) < 0) { Path anotherPath = Paths.get("/home/xander"); System.out.println(anotherPath); Path relativePath = anotherPath.relativize(path); // Documents/Java System.out.println(relativePath); Path joinBackTogether = anotherPath.resolve(relativePath); System.out.println(joinBackTogether); } }
640857f3-52eb-4c5d-867e-b5ed759d525e
6
static final aa_Sub1 method4009(int i, int[] is, int[] is_0_, int i_1_, OpenGlToolkit var_ha_Sub2, int i_2_) { try { anInt4597++; byte[] is_3_ = new byte[i * i_2_]; for (int i_4_ = i_1_; (i_2_ ^ 0xffffffff) < (i_4_ ^ 0xffffffff); i_4_++) { int i_5_ = i * i_4_ - -is[i_4_]; for (int i_6_ = 0; (is_0_[i_4_] ^ 0xffffffff) < (i_6_ ^ 0xffffffff); i_6_++) is_3_[i_5_++] = (byte) -1; } return new aa_Sub1(var_ha_Sub2, i, i_2_, is_3_); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("kg.C(" + i + ',' + (is != null ? "{...}" : "null") + ',' + (is_0_ != null ? "{...}" : "null") + ',' + i_1_ + ',' + (var_ha_Sub2 != null ? "{...}" : "null") + ',' + i_2_ + ')')); } }
8b32abba-2300-4186-a8db-6b427388ae60
2
private void setGroupNames(String username, String[] groups) { Vector<String> v = null; if (groups == null) { v = emptyVector; } else { v = new Vector<String>(groups.length + 1); for (int i = 0; i < groups.length; i++) { v.add(groups[i]); } } synchronized (this) { groupCache.put(username, v); } }
4a90ffb5-1249-4c26-a961-151e00e003d7
1
public synchronized void stop() { try { thread.join(); System.exit(0); } catch (InterruptedException e) { e.printStackTrace(); } }
3537695b-e4f2-4374-acc0-3fc7ec6e8ec6
5
public boolean isValidWith(int[] concepts){ if(this.isUniversal()) return true; int finded = 0; for (int concept : concepts) { if(s==concept || p==concept || o==concept){ finded++; } } return finded==this.nonUniversalConcepts(); }
3a6fe777-88d0-46b6-87a9-5b7374d31fb0
0
@Override public String toString() { return "[sysMessage=" + sysMessage + "]"; }
9a98326e-44ed-4764-b3cb-aba7386e11eb
3
public Elements siblingElements() { if (parentNode == null) return new Elements(0); List<Element> elements = parent().children(); Elements siblings = new Elements(elements.size() - 1); for (Element el: elements) if (el != this) siblings.add(el); return siblings; }
91b26cea-428c-4062-9cd6-8f67dcb39d4b
5
public static TextAngleStrategy angleParallel() { return new TextAngleStrategy() { @Override public double getAngle( TextStrategyParameters parameters ) { Point2D normal = parameters.getPath().getNormalAt( parameters.getPosition() ); double dx = normal.getX(); double dy = normal.getY(); if( dx == 0 && dy == 0 ) { return 0.0; } double angle = Math.atan2( dy, dx ) + Math.PI / 2; if( angle < 0 ) { angle += Math.PI * 2; } if( angle > Math.PI / 2 && angle < 3 * Math.PI / 2 ) { angle -= Math.PI; } return angle; } }; }
56db6d4e-7aa2-4113-85c1-cf8a07ab18ea
5
public void DataEnd() { if (mDone == true) return ; if (mItems == 2) { if ((mVerifier[mItemIdx[0]].charset()).equals("GB18030")) { Report(mVerifier[mItemIdx[1]].charset()) ; mDone = true ; } else if ((mVerifier[mItemIdx[1]].charset()).equals("GB18030")) { Report(mVerifier[mItemIdx[0]].charset()) ; mDone = true ; } } if (mRunSampler) Sample(null, 0, true); }
ad7e7a2a-590e-4f66-9962-5af000efcaa0
1
private void evalGetField(int opcode, int index, Frame frame) throws BadBytecode { String desc = constPool.getFieldrefType(index); Type type = zeroExtend(typeFromDesc(desc)); if (opcode == GETFIELD) { Type objectType = resolveClassInfo(constPool.getFieldrefClassName(index)); verifyAssignable(objectType, simplePop(frame)); } simplePush(type, frame); }
cd50a89a-5506-464c-8f87-44fd28f6802d
2
public static String readAll() { if (!scanner.hasNextLine()) return ""; String result = ""; while (scanner.hasNextLine()) { result = result + scanner.nextLine(); result = result + "\n"; } return result; }
1853cd64-8e8f-4690-89cc-87ddc3cf651e
5
public void keyTyped(KeyEvent e) { if (!Character.isDigit(e.getKeyChar())) { e.setKeyChar((char) 0); } else { if ((e.getSource() == tfPort) && !tfPort.getText().isEmpty()) { int port = Integer.valueOf(tfPort.getText() + e.getKeyChar()); if ((port < 1) || (port > 65535)) { e.setKeyChar((char) 0); } } } }
31ab7190-3083-4b3c-ab92-ce30c25fa0cb
4
public int[][] idct(int F[][]) { double tempX[][] = new double[N][N]; double tempY[][] = new double[N][N]; int f[][] = new int[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { tempY[i][j] = (double)F[i][j]; } } idct_direct(tempY, tempX); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { f[i][j] = (int)(Math.floor(tempX[i][j] + 0.5)); } } return f; }
dcb299bc-4016-4177-bc50-8d46e476c47e
6
public void run() { stop = false; double gy = transformY(garbage.getX()); double gx = transformX(garbage.getY()); while (!cancelled) { while(!pos2d.isDataReady()){}; double x = pos2d.getX(); double y = pos2d.getY(); if (getDistance(x, y, gx, gy) <= 0.55) { pos2d.setSpeed(0, 0); while(!pos2d.isDataReady()){}; x = pos2d.getX(); y = pos2d.getY(); // Point bot = RobotData.INSTANCE.getLocation(); // turn to face the target at the same location //double yaw = getAngle(garbage.getY(), garbage.getX(), bot.x, bot.y); double yaw = getAngle(gx, gy, x, y); stop = true; cancelled = true; //pos2d.setPosition(new PlayerPose2d(x, y, yaw), new PlayerPose2d(1, 1, 1), 0); try { Thread.sleep(1000);} catch (Exception e) {} pos2d.setSpeed(0, 0); } try { Thread.sleep(50);} catch (Exception e) {} } }
8dd31c04-b654-4d5f-8a65-f11abccda75d
5
public void start() { if (running) { throw new IllegalStateException("Simulation is already running."); } // the reason we do not inherit from Runnable is that we do not want to // expose the void run() method to the outside world. We want to well // encapsulate the whole idea of a thread. // thread cannot be restarted so we need to always create a new one if (thread != null) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } thread = new Thread() { @Override public void run() { while (running) { try { synchronized (this) { Thread.sleep(executionDelay); } } catch (InterruptedException e) { throw new RuntimeException(e); } simulate(); notifySimulationListeners(); } } }; // set the flag running = true; // start the thread thread.start(); }
56464ee7-bdcd-4f45-a29f-9d016d711f0c
7
public int compareTo(AsciiString str) { if(str == null) return 1; if(chars().hashCode() == str.val.hashCode()) return 0; int len1=val.length; int len2=str.val.length; int lim=Math.min(len1, len2); int k = 0; while (k < lim) { byte c1 =val[k]; byte c2 =str.val[k]; if (c1 != c2) return c1 > c2? 1 : -1; k++; } return len1 > len2? 1 : len1 < len2? -1 : 0; }
181cdac7-dec0-4a3b-b268-36710395d043
3
public void mousePressed(MouseEvent e) { // request page focus // requestFocusInWindow(); if (documentViewModel.getViewToolMode() == DocumentViewModel.DISPLAY_TOOL_TEXT_SELECTION) { textSelectionHandler.mousePressed(e); } else if (documentViewModel.getViewToolMode() == DocumentViewModel.DISPLAY_TOOL_SELECTION || documentViewModel.getViewToolMode() == DocumentViewModel.DISPLAY_TOOL_LINK_ANNOTATION) { annotationHandler.mousePressed(e); } }
3001fac9-3ba8-4341-8cf9-56889b02789d
4
public boolean inArea(Rectangle in, Rectangle area) { if (area.getX() >= in.getX() && area.getX() + area.getWidth() <= in.getX() + in.getWidth() && area.getY() >= in.getY() && area.getY() + area.getHeight() <= in.getY() + in.getHeight()) { return true; } return false; }
d86fe564-c521-4a12-a65f-38dabd79d537
0
public static void main(String[] args) throws ExecutionException, InterruptedException { scheduleAtFixedRateTest(); //scheduleWithFixedDelayTest(); }
d9372be9-72a9-40c1-ac9d-c59aa747518f
2
public void loseHealth(int i){ if(alive){ health -= i; if(health <= 0){ health = 0; die(); } } }
4533f7b7-c6c4-4732-9a52-d441b9cf62d7
0
public String getMessage() { return message; }
8903e58d-ce28-438e-aa78-56357bad8754
7
public void thumbnail(String fromFileStr, String saveToFileStr, int width, int height,String format) throws Exception { BufferedImage srcImage; File saveFile = new File(saveToFileStr); File fromFile = new File(fromFileStr); srcImage = javax.imageio.ImageIO.read(fromFile); // construct image int imageWideth = srcImage.getWidth(null); int imageHeight = srcImage.getHeight(null); if(width==0){ width=imageWideth; } if(height==0){ height=imageHeight; } int changeToWideth = 0; int changeToHeight = 0; if (imageWideth > 0 && imageHeight > 0) { // flag=true; if (imageWideth / imageHeight >= width / height) { if (imageWideth > width) { changeToWideth = width; changeToHeight = (imageHeight * width) / imageWideth; } else { changeToWideth = imageWideth; changeToHeight = imageHeight; } } else { if (imageHeight > height) { changeToHeight = height; changeToWideth = (imageWideth * height) / imageHeight; } else { changeToWideth = imageWideth; changeToHeight = imageHeight; } } } srcImage = imageZoomOut(srcImage, changeToWideth, changeToHeight); ImageIO.write(srcImage, format, saveFile); }
d2a23715-a07c-4023-ad26-10da943cb29a
3
private void loadExampleBN() { File dir = new File(exdir); optionsBN.addItem("None"); for (File file : dir.listFiles()) { if (!file.isDirectory()) { String name = file.getName(); if (name.endsWith(".bn")) { optionsBN.addItem(name.substring(0, name.length())); } } } }
b8e88ffa-ee42-4227-9743-1fb7435cf90b
4
@Override public String downloadSong(final String songUrl, final String destinationFolder, final Mp3Metadata metadata) { String trackString = null; try { final long trackId = getApi().resolve(songUrl); final HttpResponse trackResponse = getApi().get(new Request(String.format(Constants.TRACK_URL, trackId, Constants.CLIENT_ID))); trackString = EntityUtils.toString(trackResponse.getEntity()); } catch (final Exception e) { e.printStackTrace(); } final JSONObject obj = new JSONObject(trackString); final boolean streamable = obj.getBoolean("streamable"); if (streamable) { try { final String streamurl = obj.getString("stream_url"); // Replace all illegal characters with 'space hyphen' final String title = obj.getString("title").replace(":", " -").replace("\\", " -").replace("/", " -").replace("*", " -").replace("?", " -") .replace("\"", " -").replace(">", " -").replace("<", " -").replace("|", " -"); final URL url = new URL(streamurl + "?client_id=" + Constants.CLIENT_ID); final String endFilename = destinationFolder + File.separatorChar + title + ".mp3"; final File mp3 = getDownloadFilename(endFilename, metadata != null); System.out.println("Starting to download track " + title); IOUtils.copyLarge(url.openStream(), new FileOutputStream(mp3)); System.out.println("Finished downloading track " + title); if (metadata != null) { // Copy original so we can change values for each song final Mp3Metadata newMetadata = new Mp3Metadata(metadata); newMetadata.setTitle(title); newMetadata.setUrl(songUrl); Mp3Tagger.tagMp3(mp3.getAbsolutePath(), endFilename, newMetadata); } return title; } catch (final Exception e) { e.printStackTrace(); } } else { System.out.println("Track is not streamable, no way to download song from URL " + songUrl); } return ""; }
b2ddf171-b56a-49e6-9e35-573072efd980
6
private static final String esc(final String str) { StringBuffer sb = new StringBuffer(str.length()); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); switch (ch) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '\"': sb.append("&quot;"); break; default: if (ch > 0x7f) { sb.append("&#").append(Integer.toString(ch)) .append(';'); } else { sb.append(ch); } } } return sb.toString(); }
9a67b334-5bad-46f6-9870-3454636777a0
0
public String getSector() { return Address.getSector(); }
161d6577-caac-4cc1-bc2f-e3983b566d41
0
public BufferedReader getReader() { return reader; }
712ab7b6-3aae-4e1b-880b-9d140679bddc
2
private void open( Handshakedata d ) { if ( DEBUG ) System.out.println( "open using draft: " + draft.getClass().getSimpleName() ); readystate = READYSTATE.OPEN; try { wsl.onWebsocketOpen( this, d ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); } }
8fe84755-e383-4523-95bf-c3d890d78bb4
2
@EventHandler public void onPlayerDeath(final PlayerDeathEvent e) { new BukkitRunnable() { public void run() { try { Object nmsPlayer = e.getEntity().getClass().getMethod("getHandle").invoke(e.getEntity()); Object con = nmsPlayer.getClass().getDeclaredField("playerConnection").get(nmsPlayer); Class< ? > EntityPlayer = Class.forName(nmsPlayer.getClass().getPackage().getName() + ".EntityPlayer"); Field minecraftServer = con.getClass().getDeclaredField("minecraftServer"); minecraftServer.setAccessible(true); Object mcserver = minecraftServer.get(con); Object playerlist = mcserver.getClass().getDeclaredMethod("getPlayerList").invoke(mcserver); Method moveToWorld = playerlist.getClass().getMethod("moveToWorld" , EntityPlayer , int.class , boolean.class); moveToWorld.invoke(playerlist , nmsPlayer , 0 , false); } catch (Exception ex) { ex.printStackTrace(); } } }.runTaskLater(plugin , 2); }
0fb1057a-5570-4d6b-8fea-e92e297e2ca0
3
public void actualizarTurnosDesdeJTable() { for (int i = 0; i < tabla.getRowCount(); i++) { if (tabla.getValueAt(i, 3) != null) { if (tabla.getValueAt(i, 4) != null) { turno.turnos.get(i).setDuración((int) tabla.getValueAt(i, 3)); turno.turnos.get(i).setDescripcion((String) tabla.getValueAt(i, 4)); System.out.println(turno.turnos.get(i).getDuración()); System.out.println(turno.turnos.get(i).getDescripcion()); } } else { // JOptionPane.showMessageDialog(this, "", TOOL_TIP_TEXT_KEY, WIDTH); } } }
e4586e48-74dc-4a0d-90f8-a014789e7ab0
5
private static boolean checkRelative(Board board, SquarePos position, List<SquarePos> blocks, int x, int y) { for (SquarePos pos : blocks) { int relxPos = pos.x + position.x + x; int relyPos = pos.y + position.y + y; if (relyPos > board.getHeight() - 1 || relxPos > board.getWidth() - 1 || relxPos < 0 || board.getSquare(relyPos, relxPos) != null) { return true; } } return false; }
ebdf3f11-ddfc-43a7-8e7b-696486072996
4
private static boolean isValidEvent(String eventNumber) { if (eventNumber == null) return false; try { Integer.parseInt(eventNumber); } catch (NumberFormatException e) { return false; } int index = Integer.parseInt(eventNumber) - 1; if (events.size() > index && index >= 0) return true; else return false; }
003a5d9a-3022-42c9-8db6-1b7b32f7a171
3
public void appendSamples(int channel, float[] f) { int pos = bufferp[channel]; short s; float fs; for (int i=0; i<32;) { fs = f[i++]; fs = (fs>32767.0f ? 32767.0f : (fs < -32767.0f ? -32767.0f : fs)); s = (short)fs; buffer[pos] = s; pos += channels; } bufferp[channel] = pos; }
21db6067-316d-4607-8389-ba3dcdb9df7e
2
private String replace(String message, String playerName, String targetName) { // colors message = message.replace("{BLACK}", "&0"); message = message.replace("{DARKBLUE}", "&1"); message = message.replace("{DARKGREEN}", "&2"); message = message.replace("{DARKTEAL}", "&3"); message = message.replace("{DARKRED}", "&4"); message = message.replace("{PURPLE}", "&5"); message = message.replace("{GOLD}", "&6"); message = message.replace("{GRAY}", "&7"); message = message.replace("{DARKGRAY}", "&8"); message = message.replace("{BLUE}", "&9"); message = message.replace("{BRIGHTGREEN}", "&a"); message = message.replace("{TEAL}", "&b"); message = message.replace("{RED}", "&c"); message = message.replace("{PINK}", "&d"); message = message.replace("{YELLOW}", "&e"); message = message.replace("{WHITE}", "&f"); message = message.replace("&", "\u00a7"); // player if (playerName != null) message = message.replace("{PLAYER}", playerName); // target if (targetName != null) message = message.replace("{TARGET}", targetName); // TODO other replacement vars message = message.replace("{PWMINLENGTH}", String.valueOf(plugin.getConfig().getInt("password.min-length"))); // newline message = message.replace("{NEWLINE}", "\n"); return message; }
eb4bc43b-529b-4b25-bff4-b3d3add6de6b
5
@Override protected Void doInBackground() { final int BUFFER_SIZE = 2048; BufferedInputStream bis = null; ByteArrayOutputStream baos; try { URL url = new URL(addr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "User-Agent: Kubach v" + Constants.VERSION); this.totalProgressValue = connection.getContentLength(); int totalDataRead = 0; bis = new BufferedInputStream(connection.getInputStream()); baos = new ByteArrayOutputStream(); try (BufferedOutputStream bos = new BufferedOutputStream(baos, BUFFER_SIZE)) { byte[] data = new byte[BUFFER_SIZE]; int i = 0; while ((i = bis.read(data)) != -1) { totalDataRead = totalDataRead + i; baos.write(data, 0, i); publish(new SyncTaskState(addr, "Downloading (" + String.format("%.2f", totalDataRead / (float) this.totalProgressValue * 100) + "%)", totalDataRead)); } // Write file to disk File file = new File(this.pathToFile); writeBytesToFile(file, baos.toByteArray()); publish(new SyncTaskState(addr, "Finished", this.totalProgressValue, file)); } } catch (IOException ex) { ex.printStackTrace(); if (--numTries > 0) { publish(new SyncTaskState(addr, "Retrying...", 0)); this.doInBackground(); } else { publish(new SyncTaskState(addr, "FAILED", 0)); } } finally { try { bis.close(); } catch (IOException ex) { ex.printStackTrace(); if (--numTries > 0) { publish(new SyncTaskState(addr, "Retrying...", 0)); this.doInBackground(); } else { publish(new SyncTaskState(addr, "FAILED", 0)); } } } return null; }
1cf28045-f35e-4fcf-9fcb-a944c509b455
1
private static boolean isArray(Object object) { return (object == null ? false : object.getClass().isArray()); }
26df1c3c-3b78-4af0-92ec-ec358f685d3f
6
public static IPCTrackerDataV2 LoadData(String path){ IPCTrackerDataV2 loadedData = new IPCTrackerDataV2(); IPCTrackerData v1LoadedData = new IPCTrackerData(); FileInputStream fis = null; ObjectInputStream in = null; if(path.endsWith(IPCTrackerKeys.FileNames.FileName)){ try { fis = new FileInputStream(path); in = new ObjectInputStream(fis); loadedData = (IPCTrackerDataV2)in.readObject(); in.close(); } catch(IOException ex) { logger.log(CLASS_NAME, "ERROR: " + ex.getMessage()); } catch(ClassNotFoundException ex) { logger.log(CLASS_NAME, "ERROR: " + ex.getMessage()); } }else if (path.endsWith(IPCTrackerKeys.FileNames.Version1FileName)){ try { fis = new FileInputStream(path); in = new ObjectInputStream(fis); v1LoadedData = (IPCTrackerData)in.readObject(); in.close(); } catch(IOException ex) { logger.log(CLASS_NAME, "ERROR: " + ex.getMessage()); } catch(ClassNotFoundException ex) { logger.log(CLASS_NAME, "ERROR: " + ex.getMessage()); } //Here parse v1LoadedData data into the loadedData object. //Fill in the other loadedData with the defaults. loadedData.setSUTotal(v1LoadedData.getSUTotal()); loadedData.setGerTotal(v1LoadedData.getGerTotal()); loadedData.setUKTotal(v1LoadedData.getUKTotal()); loadedData.setJapTotal(v1LoadedData.getJapTotal()); loadedData.setUSTotal(v1LoadedData.getUSTotal()); loadedData.setTransactionHistorySU(v1LoadedData.getTransactionHistorySU()); loadedData.setTransactionHistoryGer(v1LoadedData.getTransactionHistoryGer()); loadedData.setTransactionHistoryUK(v1LoadedData.getTransactionHistoryUK()); loadedData.setTransactionHistoryJap(v1LoadedData.getTransactionHistoryJap()); loadedData.setTransactionHistoryUS(v1LoadedData.getTransactionHistoryUS()); loadedData.setIsVictoryConditionNine(true); loadedData.setIsVictoryCityWashingtonAxis(false); loadedData.setIsVictoryCityLondonAxis(false); loadedData.setIsVictoryCityLeningradAxis(false); loadedData.setIsVictoryCityMoscowAxis(false); loadedData.setIsVictoryCityCalcuttaAxis(false); loadedData.setIsVictoryCityLosAngelesAxis(false); loadedData.setIsVictoryCityBerlinAxis(true); loadedData.setIsVictoryCityParisAxis(true); loadedData.setIsVictoryCityRomeAxis(true); loadedData.setIsVictoryCityShanghaiAxis(true); loadedData.setIsVictoryCityTokyoAxis(true); } else{ logger.log(CLASS_NAME, "ERROR: Unknown fileName returning empty object."); } return loadedData; }
20c866ab-48eb-40a1-9aa9-26870e7c1296
4
public void jump() { main.getCam().removeFocus(); resetIdle(); if(snoozing){ wake(); return; } //can't move if the current action disallows it if(immobileActions.contains(getAction(), true) || frozen) return; if (isOnGround()) { main.playSound(getPosition(), "jump1"); body.applyForceToCenter(0f, 160f, true); setAnimation(Anim.JUMPING, LoopBehavior.ONCE, Vars.ACTION_ANIMATION_RATE*1.5f); } }
a086735f-1478-4ec4-89e4-2c1eaed413c9
6
public static void getArticlesFromName(String name, ArrayList<Article> articles, ArrayList<String> coauthers) { try { if (conn == null || conn.isClosed()) { init(); } if (statement == null || statement.isClosed()) { statement = conn.createStatement(); } String sql = String.format( SQL_Operations.GetArticlesFromOneAuthorName, name); System.out.println(sql); ResultSet rs = statement.executeQuery(sql); while (rs.next()) { Article tmpa = new Article(); tmpa.setBooktitle(rs.getString("booktitle")); tmpa.setDate(rs.getString("mdate")); tmpa.setMkey(rs.getString("mkey")); tmpa.setId(rs.getInt("id")); tmpa.setPages(rs.getString("pages")); tmpa.setTitle(rs.getString("title")); articles.add(tmpa); } } catch (SQLException e) { e.printStackTrace(); } }
42b909a2-2044-4598-9086-d1c999f13684
7
private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed try { /* * Validity check */ if (!valid()) { return; } System.out.println("\"" + comboGemeentes.getSelectedItem() + "\""); model.setFirm(txtFirma.getText()); model.setSortKey(txtFirma.getText()); model.setAddress(txtAdres.getText()); model.setMunicipality(comboGemeentes.getSelectedItem().toString()); model.setZipcode(txtPostcode.getText()); model.setTelephone(txtTel.getText()); model.setTelephone2(txtTel2.getText()); model.setFax(txtFax.getText()); model.setCellphone(txtGSM.getText()); model.setEmail(txtEmail.getText()); model.setContact(txtContact.getText()); model.setNotes(notesOutlet.getText()); model.setTaxnumber(taxnrOutlet.getText()); model.setPricecode(pricecodeOutlet.getSelectedItem().toString()); // if (type == Contact.both) { // model.setType(typeBox.getSelectedItem().toString()); // } else if (type == Contact.supplier) { model.setType("supplier"); // } else if (type == Contact.client) { // model.setType("client"); // } FunctionResult<Contact> result = model.create(); if (result.getCode() == 0 && result.getObj() != null) { // delegate.addAndSelect(result.getObj()); delegate.addContact(result.getObj()); disposeLater(); } else { // switch case the return code String msg; switch (result.getCode()) { case 1: msg = "Controleer of alle velden uniek zijn. Informatie van de databank:\n" + result.getMessage(); break; case 4: case 5: msg = result.getMessage(); break; default: msg = "Het toevoegen van de contactpersoon is foutgelopen (code " + result.getCode() + "). Contacteer de ontwikkelaars met deze informatie."; } JOptionPane.showMessageDialog(null, msg, "Fout!", JOptionPane.ERROR_MESSAGE); System.err.println("\"Het toevoegen van de contactpersoon heeft foutcode " + result.getCode() + " opgeleverd. Contacteer de ontwikkelaars met deze informatie.\""); // disposeLater(); } } catch (Exception ex) { System.err.println("Error caught"); ex.printStackTrace(); JOptionPane.showMessageDialog(null, tools.Utilities.incorrectFormMessage, "Fout!", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_addActionPerformed
a074cb14-badc-419e-ad74-470937258ed6
6
@Override public void keyReleased(KeyEvent e) { //Space bar generates a new generation if (e.getKeyCode() == KeyEvent.VK_SPACE) { generator.generateNewGeneration(); //Clear the selected fractals selectedFractals = new boolean[9]; repaint(); } //Left goes back one generation else if (e.getKeyCode() == KeyEvent.VK_LEFT) { generator.decrementGeneration(); } //Right goes forward a generation else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { generator.incrementGeneration(); } //F toggles full-screen mode else if (e.getKeyCode() == KeyEvent.VK_F) { toggleFullScreen(); } //S saves the state of the program else if (e.getKeyChar() == 's') { save(); } //L loads a previously saved state else if (e.getKeyChar() == 'l') { load(); } }
9d9720d6-31ab-4951-a82a-1f80ac722171
0
public BlogDelegate getBlogDelegate() { return blogDelegate; }
42d32129-1de2-47ef-88e4-292bf23e20dd
3
OptionSet(Options.Prefix prefix, Options.Multiplicity defaultMultiplicity, String setName, int minData, int maxData) { if (setName == null) throw new IllegalArgumentException(CLASS + ": setName may not be null"); if (minData < 0) throw new IllegalArgumentException(CLASS + ": minData must be >= 0"); if (maxData < minData) throw new IllegalArgumentException(CLASS + ": maxData must be >= minData"); this.prefix = prefix; this.defaultMultiplicity = defaultMultiplicity; this.setName = setName; this.minData = minData; this.maxData = maxData; }
f78cfa08-5601-49c7-8944-c9e9d418e52c
6
public void prepareToWrite() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.newDocument(); Element root = document.createElement("staff"); document.appendChild(root); for (Employee employee : staff) { Element emplNode = document.createElement("employee"); root.appendChild(emplNode); Element post = document.createElement("post"); Text postVal = document.createTextNode(employee.getPost().toString()); emplNode.appendChild(post); post.appendChild(postVal); //emplNode.setAttribute("type", post); Element id = document.createElement("id"); Text idValue = document.createTextNode(Integer.toString(employee.getId())); emplNode.appendChild(id); id.appendChild(idValue); Element surname = document.createElement("surname"); Text surnameValue = document.createTextNode(employee.getSurname()); emplNode.appendChild(surname); surname.appendChild(surnameValue); Element name = document.createElement("name"); Text nameValue = document.createTextNode(employee.getName()); emplNode.appendChild(name); name.appendChild(nameValue); Element patronimyc = document.createElement("patronymic"); Text patronimycVal = document.createTextNode(employee.getPatronymic()); emplNode.appendChild(patronimyc); patronimyc.appendChild(patronimycVal); String bd = dateFormat.format(employee.getBirthday()); Element birthday = document.createElement("birthday"); Text birthdayVal = document.createTextNode(bd); emplNode.appendChild(birthday); birthday.appendChild(birthdayVal); String hd = dateFormat.format(employee.getHiringDate()); Element hiringDate = document.createElement("hiringDate"); Text hiringDateVal = document.createTextNode(hd); emplNode.appendChild(hiringDate); hiringDate.appendChild(hiringDateVal); if (employee.getPost().toString().equalsIgnoreCase("other")) { String descr = ((Other) employee.getPost()).getDescription(); Element description = document.createElement("description"); Text descriptionVal = document.createTextNode(descr); emplNode.appendChild(description); description.appendChild(descriptionVal); } if (employee.getPost().toString().equalsIgnoreCase("manager")) { List<Integer> list = ((Manager)employee.getPost()).getWorkers(); Element subordinates = document.createElement("subordinates"); emplNode.appendChild(subordinates); if (!list.isEmpty()) { for (int i = 0;i < list.size(); i ++ ) { Element idNode = document.createElement("worker_id"); subordinates.appendChild(idNode); String subid = Integer.toString(list.get(i)); Text subordinatesVal = document.createTextNode(subid); subordinates.appendChild(idNode); idNode.appendChild(subordinatesVal); } } } } logger.info("Document was created successfully"); writeToXml(document); } catch (ParserConfigurationException e) { e.printStackTrace(); } }
3b49e529-1749-4ea4-8416-88b2ceb9c3ff
1
public void showMeVector(Vector vec) { for(int i=0;i<vec.size();i++) { System.out.println(vec.elementAt(i)); } }
4103f974-6503-409f-9b7e-71ac72d196ca
7
@Override public void trainOnInstanceImpl(Instance inst) { if (this.treeRoot == null) { this.treeRoot = newLearningNode(); this.activeLeafNodeCount = 1; } FoundNode[] foundNodes = this.treeRoot.filterInstanceToLeaves(inst, null, -1, true); for (FoundNode foundNode : foundNodes) { // option leaves will have a parentBranch of -999 // option splits will have an option count of -999 //System.out.println( foundNode.parentBranch ); Node leafNode = foundNode.node; if (leafNode == null) { leafNode = newLearningNode(); foundNode.parent.setChild(foundNode.parentBranch, leafNode); this.activeLeafNodeCount++; } if (leafNode instanceof LearningNode) { LearningNode learningNode = (LearningNode) leafNode; learningNode.learnFromInstance(inst, this); if (learningNode instanceof ActiveLearningNode) { ActiveLearningNode activeLearningNode = (ActiveLearningNode) learningNode; double weightSeen = activeLearningNode.getWeightSeen(); if (weightSeen - activeLearningNode .getWeightSeenAtLastSplitEvaluation() >= this.gracePeriodOption .getValue()) { attemptToSplit(activeLearningNode, foundNode.parent, foundNode.parentBranch); activeLearningNode .setWeightSeenAtLastSplitEvaluation(weightSeen); } } } } if (this.trainingWeightSeenByModel % this.memoryEstimatePeriodOption.getValue() == 0) { estimateModelByteSizes(); } }
10fc02a5-9a8e-49e7-ba33-375db2f16fb5
4
public static String unParse(String in){ String B = in; for (int y = 0; y < CodeList.size(); y++) { String A[] = B.split(CodeList.get(y).get(true)); B = A[0]; for (int x = 1; x < A.length; x++) { B += CodeList.get(y).get(false); B += (CodeList.get(y).get(false).endsWith(">")) ? A[x] : (CodeList.get(y) .get(false).equals("<a href=\"") ? A[x].replaceFirst("\\]", "\">") : A[x].replaceFirst("\\]", ">")); } } return "<font face=\"arial\">" + B + "</font>"; }
aa7e860c-750f-42bb-a642-c70fc8dfcca5
8
public void parse22(String input){ char[] temp = new char[13]; input.trim(); for (String retval : input.split("> ")) { retval.getChars(5, 18, temp, 0); if(Character.isDigit(temp[12])){ if(temp[12]!='0'){ String[] course = String.copyValueOf(temp).split("\\s+"); if (course.length < 3) continue; arrayTakenCourse.add(new Course(course[0], course[1])); } } if(retval.length()>48){ retval.getChars(35, 48, temp, 0); if(Character.isDigit(temp[12])){ if(temp[12]!='0'){ String[] course = String.copyValueOf(temp).split("\\s+"); if (course.length < 3) continue; arrayTakenCourse.add(new Course(course[0], course[1])); } } } } }
cf2343e0-9dcb-44d4-8de4-9dfacccf1b20
6
private ArrayList<Integer> parseAnswer(int multiplier) throws Exception { Thread.sleep(this.MAX_INTERVAL * multiplier); int c; ArrayList<Integer> answer = new ArrayList<Integer>(); while ((c = input.read()) != -1) answer.add(c); if (answer.get(0) == Status.OK) { if (answer.size() > 1) { if (answer.get(1) != Sign.MESSAGE_BEGIN) { this.output.write((char)Status.ERROR); this.output.flush(); throw new Exception("Второй байт ответа не является STX!"); } int length = answer.get(2); String data = ""; for (int i = 5; i < answer.size() - 2; i++) data += (char)(int)answer.get(i); /*if ((length - 3) != data.length()) { System.out.println(length); System.out.println(data.length()); this.output.write((char)Status.ERROR); this.output.flush(); throw new Exception("Длина сообщения не совпадает!"); }*/ } this.output.write((char)Status.OK); this.output.flush(); //Thread.sleep(this.MAX_INTERVAL * 2); } else if (answer.get(0) == Status.ERROR) { System.out.println("Получен NAK"); } else throw new Exception("Первый байт ответа не является ACK млм NAK!"); return answer; }
3e0e8c7b-1bd2-4545-b7f9-ae500dd7ebd5
5
@Override public void addNewPastMeeting(Set<Contact> contacts, Calendar date, String text) { if(contacts.isEmpty() || !contactsExist(contacts)) { throw new IllegalArgumentException(); } else if(contacts != null && date != null && text != null) { PastMeeting newMeeting = new PastMeetingImpl(generateMeetingId(), date, contacts, text); allMeetings.add(newMeeting); } else { throw new NullPointerException(); } }
90266dba-d5c7-4dbe-8a70-ae654bbe5530
3
public ArrayList<ChatChannel> getPlayersChannels(String name) throws SQLException { ArrayList<ChatChannel> channels = new ArrayList<ChatChannel>(); sql.initialise(); ResultSet res = sql.sqlQuery("SELECT ChannelName FROM BungeeMembers WHERE PlayerName = '"+name+"'"); while(res.next()){ channels.add(plugin.getChannel(res.getString("ChannelName"))); } if(plugin.globalToggleable && CommandUtil.hasPermission(name, GlobalCommand.PERMISSION_NODES)){ channels.add(plugin.getChannel("Global")); } sql.closeConnection(); return channels; }
bbb685cc-b19d-4b85-abdd-2f5fe37d132a
9
public int process(int signal) throws MaltChainedException { if (cachedGraph == null) { marking_strategy = OptionManager.instance().getOptionValue(getOptionContainerIndex(), "pproj", "marking_strategy").toString().trim(); covered_root = OptionManager.instance().getOptionValue(getOptionContainerIndex(), "pproj", "covered_root").toString().trim(); lifting_order = OptionManager.instance().getOptionValue(getOptionContainerIndex(), "pproj", "lifting_order").toString().trim(); cachedGraph = (TokenStructure)flowChartinstance.getFlowChartRegistry(org.maltparserx.core.syntaxgraph.TokenStructure.class, sourceName); if (!marking_strategy.equalsIgnoreCase("none") || !covered_root.equalsIgnoreCase("none")) { pprojActive = true; } } if (pprojActive && cachedGraph instanceof DependencyStructure) { if (taskName.equals("proj")) { pproj.projectivize((DependencyStructure)cachedGraph); } else if (taskName.equals("merge")) { pproj.mergeArclabels((DependencyStructure)cachedGraph); } else if (taskName.equals("deproj")) { pproj.deprojectivize((DependencyStructure)cachedGraph); } else if (taskName.equals("split")) { pproj.splitArclabels((DependencyStructure)cachedGraph); } } return signal; }
fc7c2d01-9b18-4d01-b2cd-1377ead7d9bd
1
@Test public void testPostTracking() throws Exception { //test informed all the fields allowed to post Tracking tracking1 = new Tracking(trackingNumberPost); tracking1.setSlug(slugPost); tracking1.setOrderIDPath(orderIDPathPost); tracking1.setCustomerName(customerNamePost); tracking1.setOrderID(orderIDPost); tracking1.setTitle(titlePost); tracking1.setDestinationCountryISO3(countryDestinationPost); tracking1.addEmails(email1Post); tracking1.addEmails(email2Post); tracking1.addCustomFields("product_name",customProductNamePost); tracking1.addCustomFields("product_price",customProductPricePost); tracking1.addSmses(sms1Post); tracking1.addSmses(sms2Post); Tracking trackingPosted = connection.postTracking(tracking1); Assert.assertEquals("Should be equals TrackingNumber", trackingNumberPost, trackingPosted.getTrackingNumber()); Assert.assertEquals("Should be equals slug", slugPost, trackingPosted.getSlug()); Assert.assertEquals("Should be equals orderIDPath", orderIDPathPost, trackingPosted.getOrderIDPath()); Assert.assertEquals("Should be equals orderID", orderIDPost, trackingPosted.getOrderID()); Assert.assertEquals("Should be equals countryOrigin", countryDestinationPost, trackingPosted.getDestinationCountryISO3()); Assert.assertTrue("Should contains email",trackingPosted.getEmails().contains(email1Post)); Assert.assertTrue("Should contains email",trackingPosted.getEmails().contains(email2Post)); Assert.assertEquals("Should be equals size emails", 2, trackingPosted.getEmails().size()); Assert.assertTrue("Should contains smses",trackingPosted.getSmses().contains(sms1Post)); Assert.assertTrue("Should contains smses",trackingPosted.getSmses().contains(sms2Post)); Assert.assertEquals("Should be equals size smses", 2, trackingPosted.getSmses().size()); Assert.assertEquals("Should be equals custom field product_name", customProductNamePost, trackingPosted.getCustomFields().get("product_name")); Assert.assertEquals("Should be equals custom field product_price", customProductPricePost, trackingPosted.getCustomFields().get("product_price")); //test post only informing trackingNumber (the slug can be dpd and fedex) Tracking tracking2 = new Tracking(trackingNumberToDetect); Tracking trackingPosted2 = connection.postTracking(tracking2); Assert.assertEquals("Should be equals TrackingNumber", trackingNumberToDetect, trackingPosted2.getTrackingNumber()); Assert.assertEquals("Should be equals slug", "dpd", trackingPosted2.getSlug());//the system assign dpd (it exist) //test post tracking number doesn't exist Tracking tracking3 = new Tracking(trackingNumberToDetectError); try{ connection.postTracking(tracking3); //always should give an exception before this assertTrue("This never should be executed",false); }catch (Exception e){ assertEquals("It should return a exception if the tracking number doesn't matching any courier you have defined" , "{\"meta\":{\"code\":4005,\"message\":\"The value of `tracking_number` is invalid.\",\"type\":\"BadRequest\"},\"data\":{\"tracking\":{\"tracking_number\":\"asdq\",\"title\":\"asdq\"}}}", e.getMessage()); } }
5a1f248c-cc87-450e-b55f-361029d93b4c
0
@Override public void mousePressed(MouseEvent e) { isMouseDown = true; mouseY = e.getY(); }
0786518c-06fb-4882-affe-019eb794c7f3
2
@Override public void setSelectionPath(TreePath p) { if (p.getPathCount() == 3) { if (!isPathSelected(p)) { super.setSelectionPath(p); gui.imageBrowser.setEvent(p.getLastPathComponent().toString()); } else { super.removeSelectionPath(p); gui.imageBrowser.clearEvent(); } } else { super.clearSelection(); gui.imageBrowser.clearEvent(); } gui.loadImages(); }
fd6b2fee-176e-47df-801a-e4e773bb545d
3
public JSONArray toJSONArray(JSONArray names) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } return ja; }
a1799553-be41-4536-bd8e-d1a8bb79e74a
0
static boolean patroonInterval(String invoer) { return invoer.matches("[0-9]{4}-[0-9]{4}"); }
ea0ac3c0-1ff4-4a39-9dda-f2826544da02
0
@Override public String toString() { return "BOP " + operator; }
df56738a-b164-4518-b857-938b511e86b0
2
public void startHandshake( ClientHandshakeBuilder handshakedata ) throws InvalidHandshakeException { assert ( readystate != READYSTATE.CONNECTING ) : "shall only be called once"; // Store the Handshake Request we are about to send this.handshakerequest = draft.postProcessHandshakeRequestAsClient( handshakedata ); resourceDescriptor = handshakedata.getResourceDescriptor(); assert ( resourceDescriptor != null ); // Notify Listener try { wsl.onWebsocketHandshakeSentAsClient( this, this.handshakerequest ); } catch ( InvalidDataException e ) { // Stop if the client code throws an exception throw new InvalidHandshakeException( "Handshake data rejected by client." ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); throw new InvalidHandshakeException( "rejected because of" + e ); } // Send write( draft.createHandshake( this.handshakerequest, role ) ); }
a05a5fa6-4e94-49bb-81a0-bdc384d0085e
4
public void color(int i, int x, int y) { if(x < texture.getWidth() && y < texture.getHeight() && x >= 0 && y >= 0) { texture.setRGB(x, y, new Color(i).getRGB()); this.repaint(); } }
f159534f-a3a5-4c91-86ba-831e083dd93a
2
public boolean save(String filename) { boolean success = true; PrintWriter writer = null; try { writer = new PrintWriter(new File(filename)); for (Score score : scores) { writer.printf("%s\n", score); } } catch (FileNotFoundException e) { success = false; } finally { writer.close(); } return success; }
744e5bdd-7ac3-4a3a-bbc2-cb9ae4ac082f
4
@Override public void update(GameContainer window) { if (isAnimating()) { float currentAlpha = tile.getAlpha(); if (fadingIn) { if (currentAlpha < 1F) tile.setAlpha(currentAlpha + 0.01F); else animating = false; } else { if (currentAlpha > 0F) tile.setAlpha(currentAlpha - 0.01F); else animating = false; } } }
ab8c8bb7-7e37-4f20-8400-33db8b431db6
2
public void update() { if(Keyboard.isKeyDown(getKey())) { setPressed(true); setReleased(false); } else { if(isPressed()) setReleased(true); else setReleased(false); setPressed(false); setHeld(false); } }
a7c0e1dd-3753-4955-a78b-11cf0cbc2ed8
3
public Espectaculo(String localidad, int cantidadEntradas, String nombre, String[] fecha, List<Zona> zonas) { this.localidad = localidad; this.cantidadEntradas = cantidadEntradas; this.nombre = nombre; this.fecha = fecha; this.zonas = zonas; // this.entradas = new ArrayList<Entrada>(cantidadEntradas); // for (int i = 0; i < cantidadEntradas; i++) { // Entrada entrada = new Entrada(i); // entradas.add(entrada); // } this.entradas = new HashMap<Zona, Entrada[][]>(); for (Zona zona:zonas){ Entrada[][] listaEntradas = new Entrada[zona.getCantFilas()][zona.getLargoFila()]; int numeroAsiento = 1; for (int i = 0; i < zona.getCantFilas(); i++) { for (int j = 0; j < zona.getLargoFila(); j++) { listaEntradas[i][j] = new Entrada(numeroAsiento); numeroAsiento++; } } entradas.put(zona, listaEntradas); } }
c4bac70e-b455-4c3c-b9db-bf0084ea0685
8
private void setDayCells(){ Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, 1); // Calendar.DAY_OF_WEEK uses base 1. That's why one is subtracted. int firstDayOfMonth = calendar.get(Calendar.DAY_OF_WEEK) - 1; // Check whether Sunday is the first day of the week. If not, shift the first day if(!isSundayFirstDay){ firstDayOfMonth += 6; if (firstDayOfMonth > 7) firstDayOfMonth -= 7; } int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); calendar.set(Calendar.MONTH, month - 1); int daysInPreviousMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // Set the cells for the days of previous month for (int i = 0; i < firstDayOfMonth; i++) { int m = month - 1; int y = year; if (m < 0) { m = Calendar.DECEMBER; y--; } DayCell cell = dayCells[i]; cell.setDate(daysInPreviousMonth - (firstDayOfMonth) + i + 1, m, y); cell.getStyleClass().removeAll(cellStyleList); cell.getStyleClass().add(DATEPICKER_OTHERMONTH); } // Set the cells for the days of month to be presented int day = 1; for (int i = firstDayOfMonth; i < daysInMonth + firstDayOfMonth; i++) { DayCell cell = dayCells[i]; cell.setDate(day++, month, year); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, cell.getDay()); cell.getStyleClass().removeAll(cellStyleList); if (isToday(calendar)) cell.getStyleClass().add(DATEPICKER_TODAY); else cell.getStyleClass().add(DATEPICKER_MONTH); } // Set the cells for the days of next month day = 1; for (int i = firstDayOfMonth + daysInMonth; i < COLUMN_NUMBER * ROW_NUMBER; i++) { int m = month + 1; int y = year; if (m > Calendar.DECEMBER) { m = Calendar.JANUARY; y++; } DayCell cell = dayCells[i]; cell.setDate(day++, m, y); cell.getStyleClass().removeAll(cellStyleList); cell.getStyleClass().add(DATEPICKER_OTHERMONTH); } }
e247e442-6701-43a0-b472-d9816ae35baa
8
private void EtudiantsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EtudiantsActionPerformed // TODO add your handling code here: switch(etat){ case Debut: //interdit break; case Debut1: this.donner1.frame_Etudiant(this.id_promo); this.donner1.setVisible(true); this.donner1.setEtat("Etudiant"); this.donner1.desactive_sup_modif(); etat = Etat.Etudiant; activeBouton(); break; case UE: this.donner1.frame_Etudiant(this.id_promo); this.donner1.setVisible(true); this.donner1.setEtat("Etudiant"); this.donner1.desactive_sup_modif(); etat = Etat.Etudiant; activeBouton(); break; case Intervenant: this.donner1.frame_Etudiant(this.id_promo); this.donner1.setVisible(true); this.donner1.setEtat("Etudiant"); this.donner1.desactive_sup_modif(); etat = Etat.Etudiant; activeBouton(); break; case Salle: this.donner1.frame_Etudiant(this.id_promo); this.donner1.setVisible(true); this.donner1.setEtat("Etudiant"); this.donner1.desactive_sup_modif(); etat = Etat.Etudiant; activeBouton(); break; case Etudiant: this.donner1.frame_Etudiant(this.id_promo); this.donner1.setVisible(true); this.donner1.setEtat("Etudiant"); this.donner1.desactive_sup_modif(); etat = Etat.Etudiant; activeBouton(); break; case Creneau: this.donner1.frame_Etudiant(this.id_promo); this.donner1.setVisible(true); this.donner1.setEtat("Etudiant"); this.donner1.desactive_sup_modif(); etat = Etat.Etudiant; activeBouton(); break; case Batiment: this.donner1.frame_Etudiant(this.id_promo); this.donner1.setVisible(true); this.donner1.setEtat("Etudiant"); this.donner1.desactive_sup_modif(); etat = Etat.Etudiant; activeBouton(); break; } }//GEN-LAST:event_EtudiantsActionPerformed
2d08018b-f512-4380-b2dd-37a37e4c909d
3
public void _updateNodeCollection(Node n) { if(!n.holdInNodeCollection) { return; // the node is not yet hold by this node collection } //sensitiveInformationChanged = true; SquarePos newPosition = getPosOfNode(n); SquarePos oldPosition = (SquarePos) n.nodeCollectionInfo; if((oldPosition.x != newPosition.x)|| oldPosition.y != newPosition.y){ //do not call this.remove. Already calculated the new position and thus we can //save time to directly call the remove on the list and on the localNodes. NodeListInterface list = lists[oldPosition.x][oldPosition.y]; list.removeNode(n); oldPosition.x = newPosition.x; oldPosition.y = newPosition.y; lists[newPosition.x][newPosition.y].addNode(n); } }
f6b0ac30-a475-40d2-84b1-640ec40ce334
1
public static void main(final String args[]) { Type.truncatedName(Type.getType("(D)V")); // Print the truncated name of each argument for (int i = 0; i < args.length; i++) { System.out.println("Truncated name of " + args[i] + ": " + Type.truncatedName(Type.getType(args[i]))); } }
3a94f958-82a7-4f1d-abf9-6efe4018c550
6
private void handleCreateReservation(Sim_event ev) { int src = -1; // the sender id boolean success = false; int tag = -1; try { // get the data ARObject obj = (ARObject) ev.get_data(); src = obj.getUserID(); // get the unique tag to send back to recepient int returnTag = GridSimTags.RETURN_AR_CREATE; tag = returnTag + obj.getTransactionID(); // check whether this resource can support AR or not success = checkResourceType(src, returnTag, obj.getTransactionID(), GridSimTags.AR_CREATE_FAIL_RESOURCE_CANT_SUPPORT, "can't create a new reservation"); // if this resource can't support AR then exit if (!success) { return; } // if it is AR if (ev.get_tag() == GridSimTags.SEND_AR_CREATE) { ( (ARPolicy) policy_).handleCreateReservation(obj, src, tag); } else { // if it is an immediate reservation ( (ARPolicy) policy_).handleImmediateReservation(obj, src, tag); } } catch (ClassCastException c) { success = false; } catch (Exception e) { success = false; } // if there is an exception, then send back an error msg if (!success && tag != -1) { System.out.println(super.get_name() + " : Error - can't create a"+ " new reservation."); super.send(src, 0.0, GridSimTags.RETURN_AR_CREATE, new IO_data(new Integer(GridSimTags.AR_CREATE_ERROR),SIZE,src)); } }
5775e392-7080-4ffc-a790-376c7578fb6d
9
public final NiklausParser.arithmeticexpression_return arithmeticexpression() throws RecognitionException { NiklausParser.arithmeticexpression_return retval = new NiklausParser.arithmeticexpression_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token ADDITION109=null; Token SUBTRACTION110=null; NiklausParser.multiplicationexpression_return multiplicationexpression108 =null; NiklausParser.multiplicationexpression_return multiplicationexpression111 =null; CommonTree ADDITION109_tree=null; CommonTree SUBTRACTION110_tree=null; try { // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:143:21: ( multiplicationexpression ( ( ADDITION ^| SUBTRACTION ^) multiplicationexpression )* ) // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:144:3: multiplicationexpression ( ( ADDITION ^| SUBTRACTION ^) multiplicationexpression )* { root_0 = (CommonTree)adaptor.nil(); pushFollow(FOLLOW_multiplicationexpression_in_arithmeticexpression807); multiplicationexpression108=multiplicationexpression(); state._fsp--; adaptor.addChild(root_0, multiplicationexpression108.getTree()); // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:145:3: ( ( ADDITION ^| SUBTRACTION ^) multiplicationexpression )* loop28: do { int alt28=2; int LA28_0 = input.LA(1); if ( (LA28_0==ADDITION||LA28_0==SUBTRACTION) ) { alt28=1; } switch (alt28) { case 1 : // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:145:4: ( ADDITION ^| SUBTRACTION ^) multiplicationexpression { // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:145:4: ( ADDITION ^| SUBTRACTION ^) int alt27=2; int LA27_0 = input.LA(1); if ( (LA27_0==ADDITION) ) { alt27=1; } else if ( (LA27_0==SUBTRACTION) ) { alt27=2; } else { NoViableAltException nvae = new NoViableAltException("", 27, 0, input); throw nvae; } switch (alt27) { case 1 : // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:145:5: ADDITION ^ { ADDITION109=(Token)match(input,ADDITION,FOLLOW_ADDITION_in_arithmeticexpression814); ADDITION109_tree = (CommonTree)adaptor.create(ADDITION109) ; root_0 = (CommonTree)adaptor.becomeRoot(ADDITION109_tree, root_0); } break; case 2 : // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:145:17: SUBTRACTION ^ { SUBTRACTION110=(Token)match(input,SUBTRACTION,FOLLOW_SUBTRACTION_in_arithmeticexpression819); SUBTRACTION110_tree = (CommonTree)adaptor.create(SUBTRACTION110) ; root_0 = (CommonTree)adaptor.becomeRoot(SUBTRACTION110_tree, root_0); } break; } pushFollow(FOLLOW_multiplicationexpression_in_arithmeticexpression823); multiplicationexpression111=multiplicationexpression(); state._fsp--; adaptor.addChild(root_0, multiplicationexpression111.getTree()); } break; default : break loop28; } } while (true); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { // do for sure before leaving } return retval; }
7d235445-c773-4219-a29f-b49a4aea34df
4
public void writeDouble(double v) throws IOException { if (trace == API_TRACE_DETAILED) { Log.current.println("writeDouble = " + v); } if (Double.isNaN(v)) { throw new RuntimeException("Tried to send a NaN floating-point"); } else if (Double.isInfinite(v)) { throw new RuntimeException("Tried to send an infinite floating-point"); } else { if (v < 0.0) { write(CFASL_N_FLOAT); v = -v; // Log.current.print("writeDouble sign=-1"); } else { write(CFASL_P_FLOAT); // Log.current.print("writeDouble sign=+1"); } DecodedDouble decoded = new DecodedDouble(v); int exp = decoded.exponent; double sig = decoded.mantissa; // Log.current.println(" signif=" + (long)Math.floor(sig) + " exp=" + exp); writeInt((long) Math.floor(sig)); writeInt(exp); } }
34747812-abe7-4b15-85a6-31556bcc09e5
8
public ControlloreFasiGioco(int numGiocatori, Mazziere mazziere, ControlloreUtenti controlloreUtenti) { this.mazziere = mazziere; this.controlloreUtenti = controlloreUtenti; int segnaliniScommesse; switch (numGiocatori){ case 2: {numTurniTotali=6; segnaliniScommesse=1;break;} case 3: {numTurniTotali=6; segnaliniScommesse=2;break;} case 4: {numTurniTotali=4; segnaliniScommesse=3;break;} case 5: {numTurniTotali=5; segnaliniScommesse=4;break;} case 6: {numTurniTotali=6; segnaliniScommesse=4;break;} default : {throw new NumErratoGiocatoriException();} } statoDelGioco=new StatoDelGioco(numTurniTotali, mazziere); statoDelGioco.aggiungiCorsia(new Scuderia(Colore.NERO, segnaliniScommesse)); statoDelGioco.aggiungiCorsia(new Scuderia(Colore.BLU, segnaliniScommesse)); statoDelGioco.aggiungiCorsia(new Scuderia(Colore.VERDE, segnaliniScommesse)); statoDelGioco.aggiungiCorsia(new Scuderia(Colore.ROSSO, segnaliniScommesse)); statoDelGioco.aggiungiCorsia(new Scuderia(Colore.GIALLO, segnaliniScommesse)); statoDelGioco.aggiungiCorsia(new Scuderia(Colore.BIANCO, segnaliniScommesse)); List<Scuderia> scuderieTemp; scuderieTemp = statoDelGioco.getCorsie(); mazziere.shuffle(scuderieTemp); for(int i=scuderieTemp.size()-1; i>=0;i--){ scuderieTemp.get(i).assegnaQuotazione(i+2); } statoDelGioco.setCorsie(scuderieTemp); mazziere.mischiaPersonaggi(); for (int i=0; i<numGiocatori;i++){ Personaggio cartaPersonaggio=mazziere.popPersonaggio(); int count=0; while (statoDelGioco.getCorsie().get(count).getQuotazione()!=cartaPersonaggio.getScuderiaAssociata()){ count++; } List<Scuderia> scuderiaDaAssociare=new ArrayList<Scuderia>(); scuderiaDaAssociare.add(statoDelGioco.getCorsie().get(count)); statoDelGioco.aggiungiGiocatore(new Giocatore(cartaPersonaggio.getDanari(),1,scuderiaDaAssociare,cartaPersonaggio)); } }
b27eb51c-7d00-4e44-856d-ba6d8285b23d
4
private void buildBuilding(BuildRequest request) { Unit worker = control.requestUnit(UnitType.Terran_SCV); if (worker == null) { return; } TilePosition requestLocation = request.getBuildLocation(); if (requestLocation == null) { requestLocation = self.getStartLocation(); } TilePosition buildTile = getBuildTile(worker, request.getUnit(), requestLocation); System.out.println("Sending " + worker.getType() + " to build " + request.getUnit() + " at " + buildTile); if (buildTile == null || worker.build(buildTile, request.getUnit())) { System.out.println("Success: " + request.getUnit()); startedMinerals += request.getUnit().mineralPrice(); startedGas += request.getUnit().gasPrice(); startedRequests.add(new StartedBuildRequest(request, worker)); pendingRequests.remove(request); } else { System.out.println("Fail: " + request.getUnit()); control.releaseUnit(worker); buildFailures += 1; } }
9d3a6f37-205d-4c6b-8fd6-77d638efc3ad
7
public synchronized String formalizeLiteralBooleanFunctionString(final String literalVariableStr, Map<LiteralVariable, LiteralVariable> literalVariableMapping, Map<LiteralVariable, String> literalBooleanFunctionAnswers, boolean isSubstituteWithJavaCode) throws ParserException { if (null == literalVariableStr || "".equals(literalVariableStr.trim())) return ""; String originalStr = literalVariableStr.replaceAll("\\s", ""); int l = originalStr.length(); if (originalStr.charAt(0) != DflTheoryConst.LITERAL_BOOLEAN_FUNCTION_PREFIX) throw new ParserException( ErrorMessage.LITERAL_BOOLEAN_FUNCTION_PREFIX_MISMATCH, new Object[] { "" + DflTheoryConst.LITERAL_BOOLEAN_FUNCTION_PREFIX }); if (originalStr.charAt(l - 1) != DflTheoryConst.LITERAL_BOOLEAN_FUNCTION_POSTFIX) throw new ParserException( ErrorMessage.LITERAL_BOOLEAN_FUNCTION_POSTFIX_MISMATCH, new Object[] { "" + DflTheoryConst.LITERAL_BOOLEAN_FUNCTION_POSTFIX }); try { List<String> tokens = tokenizeBooleanFunctionString(originalStr, 0, literalVariableMapping, literalBooleanFunctionAnswers, isSubstituteWithJavaCode, 0); StringBuilder sb = new StringBuilder(); for (String s : tokens) { sb.append(s); } return sb.toString(); } catch (ParserException e) { throw e; } catch (Exception e) { throw new ParserException(ErrorMessage.LITERAL_BOOLEAN_FUNCTION_COMPONENT_MISMATCH, new String[] { originalStr }, e); } }
486abfc9-5f71-415e-b2a8-e5dfbc7c47f5
8
public int[] getAvailableTopRowColumnPairs() { /* Only pairs of columns are valid. */ if(this.getNumberOfColumns() < 2) return new int[0]; /* filter available columns */ int row = 0; ArrayList<Integer> colsList = new ArrayList(this.getNumberOfRows()); for(int col = 0; col < this.getNumberOfColumns() - 1; col++) { if(this.isPositionAvailable(col, row)) { int adjacentCol = col + 1; if(this.isPositionAvailable(adjacentCol, row)) { colsList.add(col); colsList.add(adjacentCol); col = adjacentCol + 1; } } } if(this.getNumberOfColumns() % 2 == 1) { int lastColumn = this.getNumberOfColumns() - 1; if(this.isPositionAvailable(lastColumn, row)) { if(this.isPositionAvailable(lastColumn - 1, row)) colsList.add(lastColumn); } } /* Convert final ArrayList to Array */ int availableColumns[] = new int[colsList.size()]; int i = 0; for(Integer columnNumber : colsList) { availableColumns[i++] = columnNumber; } return availableColumns; }
c2f510d3-1daf-4d20-a9ac-ff011726737c
3
public boolean isGood(){ switch(this){ case LAWFUL_GOOD: case NEUTRAL_GOOD: case CHAOTIC_GOOD: return true; default: return false; } }
eab77e03-8bd9-426f-a1a5-0f2a54ac1907
4
public void mousePressed(MouseEvent me) { if(monitorPress) { Zone activeZone = checkActiveZone(new Point(me.getX(),me.getY())); if(null != activeZone) listener.zoneEventOccurred(activeZone.name, ZoneEvents.PRESS); } //If drag events are to be monitored, the point at which the mouse is //first pressed to start the drag motion must be used to check which //zone the operation started in. If there is no zone defined at this //point, drag functionality is assumed to not be required for this event //since the area is not prepared for event handling. if(monitorMovement) { Zone activeZone = checkActiveZone(new Point(me.getX(),me.getY())); //Set the defined start zone for the potential drag event only if //the relevant zone exists if(null != activeZone) movementMonitor.startZone = activeZone; } }
48c32659-5b35-43f4-9cb9-21b8e1317356
7
@Test public void testToString() { Rarity r = Rarity.BASIC; try { assert(r.toString(r).equalsIgnoreCase("basic")); } catch (IOException io) { fail(io.getMessage()); } r = Rarity.BASIC; try { assert(r.toString(r).equalsIgnoreCase("basic")); } catch (IOException io) { fail(io.getMessage()); } r = Rarity.FINE; try { assert(r.toString(r).equalsIgnoreCase("FINE")); } catch (IOException io) { fail(io.getMessage()); } r = Rarity.MASTERWORK; try { assert(r.toString(r).equalsIgnoreCase("MASTERWORK")); } catch (IOException io) { fail(io.getMessage()); } r = Rarity.EXOTIC; try { assert(r.toString(r).equalsIgnoreCase("EXOTIC")); } catch (IOException io) { fail(io.getMessage()); } r = Rarity.ASCENDED; try { assert(r.toString(r).equalsIgnoreCase("ASCENDED")); } catch (IOException io) { fail(io.getMessage()); } r = Rarity.LEGENDARY; try { assert(r.toString(r).equalsIgnoreCase("legendary")); } catch (IOException io) { fail(io.getMessage()); } }
56b04163-c5e8-4c88-b828-17668254e94f
4
private static boolean validAuctionPublication(Auction au) { return au.getMinPrice() >= 0 && au.getReservePrice() >= au.getMinPrice() && au.getEndDate().after(new Date()) && au.getState().equals(AuctionState.CREATED) && !auctionsContainer.hasItem(au.getItem()); }
767e037a-2b6a-408f-bdf4-9f43a028115a
9
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ContentType that = (ContentType) o; if (charset != null ? !charset.equals(that.charset) : that.charset != null) return false; if (subtype != null ? !subtype.equals(that.subtype) : that.subtype != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; return true; }
957ba2e1-09ff-4e7e-8f72-c596c102a2aa
0
public static boolean isMonospacedFont(Font font) { FontMetrics fm = getFontMetrics(font); return isMonospaced(fm); }
92fab9d4-2bc0-48d8-9ce5-e4c1d4c1eee7
8
public void doRun(int run) throws Exception { if (getRawOutput()) { if (m_ZipDest == null) { m_ZipDest = new OutputZipper(m_OutputFile); } } if (m_Instances == null) { throw new Exception("No Instances set"); } // Randomize on a copy of the original dataset Instances runInstances = new Instances(m_Instances); Random random = new Random(run); runInstances.randomize(random); if (runInstances.classAttribute().isNominal()) { runInstances.stratify(m_NumFolds); } for (int fold = 0; fold < m_NumFolds; fold++) { // Add in some fields to the key like run and fold number, dataset name Object [] seKey = m_SplitEvaluator.getKey(); Object [] key = new Object [seKey.length + 3]; key[0] = Utils.backQuoteChars(m_Instances.relationName()); key[1] = "" + run; key[2] = "" + (fold + 1); System.arraycopy(seKey, 0, key, 3, seKey.length); if (m_ResultListener.isResultRequired(this, key)) { Instances train = runInstances.trainCV(m_NumFolds, fold, random); Instances test = runInstances.testCV(m_NumFolds, fold); try { Object [] seResults = m_SplitEvaluator.getResult(train, test); Object [] results = new Object [seResults.length + 1]; results[0] = getTimestamp(); System.arraycopy(seResults, 0, results, 1, seResults.length); if (m_debugOutput) { String resultName = (""+run+"."+(fold+1)+"." + Utils.backQuoteChars(runInstances.relationName()) +"." +m_SplitEvaluator.toString()).replace(' ','_'); resultName = Utils.removeSubstring(resultName, "weka.classifiers."); resultName = Utils.removeSubstring(resultName, "weka.filters."); resultName = Utils.removeSubstring(resultName, "weka.attributeSelection."); m_ZipDest.zipit(m_SplitEvaluator.getRawResultOutput(), resultName); } m_ResultListener.acceptResult(this, key, results); } catch (Exception ex) { // Save the train and test datasets for debugging purposes? throw ex; } } } }
50bd8828-fdb5-4492-b6c7-2b04472ded56
2
static public void serialize(OutputStream out, Object obj) throws IOException { if (out==null) throw new NullPointerException("out"); if (obj==null) throw new NullPointerException("obj"); ObjectOutputStream objOut = new ObjectOutputStream(out); objOut.writeObject(obj); }
b28fbb87-b436-4354-8cd7-3c686a789b55
0
public boolean getLogin() { return isLogin; }
ec6cab26-968f-4b92-8e2c-a3d7107b90c9
6
private QueryResult gatherResultInfoForSelectQuery(String queryString, int queryNr, boolean sorted, Document doc, String[] rows) { Element root = doc.getRootElement(); //Get head information Element child = root.getChild("head", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#")); //Get result rows (<head>) @SuppressWarnings("unchecked") List<Element> headChildren = child.getChildren("variable", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#")); Iterator<Element> it = headChildren.iterator(); ArrayList<String> headList = new ArrayList<String>(); while(it.hasNext()) { headList.add((it.next()).getAttributeValue("name")); } @SuppressWarnings("unchecked") List<Element> resultChildren = root.getChild("results", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#")) .getChildren("result", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#")); int nrResults = resultChildren.size(); QueryResult queryResult = new QueryResult(queryNr, queryString, nrResults, sorted, headList); it = resultChildren.iterator(); while(it.hasNext()) { Element resultElement = it.next(); StringBuilder result = new StringBuilder(); //get the row values and paste it together to one String for(int i=0;i<rows.length;i++) { @SuppressWarnings("unchecked") List<Element> bindings = resultElement.getChildren("binding", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#")); String rowName = rows[i]; for(int j=0;j<bindings.size();j++) { Element binding = bindings.get(j); if(binding.getAttributeValue("name").equals(rowName)) if(result.length()==0) result.append(rowName + ": " + ((Element)binding.getChildren().get(0)).getTextNormalize()); else result.append("\n" + rowName + ": " + ((Element)binding.getChildren().get(0)).getTextNormalize()); } } queryResult.addResult(result.toString()); } return queryResult; }
00744f9e-9b82-4d16-8588-8f407c5038d1
6
public static String getHtmlString(int heading,String value,String colour,boolean isBold) { String bold=""; if(isBold){ bold="<b>"+value+"</b>"; }else{ bold=value; } String font=""; if(colour!=null){ font="<font color=\""+colour+"\">"+bold+"</font>"; }else{ font="<font color=\"black\">"+bold+"</font>"; } String headingString=""; switch(heading){ case 1: headingString="<h1>"+font+"</h1>"; break; case 2: headingString="<h2>"+font+"</h2>"; break; case 3: headingString="<h3>"+font+"</h3>"; break; case 4: headingString="<h4>"+font+"</h4>"; break; default: headingString=font; break; } return "<html>"+headingString+"</html>"; }
275ce5a3-02fc-4f20-bc82-f327a34a1321
7
public void drawCalendar(int inputMonth, int inputYear) { p2.removeAll(); for (int i = 0; i < weekdays.length; i++) { JLabel label = new JLabel(weekdays[i]); label.setHorizontalAlignment(SwingConstants.RIGHT); p2.add(label); } Calendar today = Calendar.getInstance(); today.setTime(new Date()); Calendar cal = new GregorianCalendar(inputYear, inputMonth, 1); int noOfDaysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH); int day = 1; int i = 1; while (day <= noOfDaysInMonth) { while (day==1 && i < cal.get(Calendar.DAY_OF_WEEK)) { JLabel label = new JLabel(""); p2.add(label); i++; } DateAction dAction = new DateAction(inputYear, inputMonth, day); JButton btnDate = new JButton(dAction); btnDate.setHorizontalAlignment(SwingConstants.RIGHT); btnDate.setText(String.valueOf(day)); if ( inputYear==today.get(Calendar.YEAR) && inputMonth==today.get(Calendar.MONTH) && day==today.get(Calendar.DAY_OF_MONTH)) { Font font = btnDate.getFont(); Font boldFont = new Font(font.getFontName(), Font.BOLD, 14); btnDate.setFont(boldFont); } p2.add(btnDate); day++; } p2.validate(); p2.repaint(); }
3a13e072-f984-4ef4-b1ec-848fa1a749fc
9
private void testBroadcastMode() { System.out.println("BEGIN: BROADCAST TEST"); final int numConnections = 10; final int numMessages = 100; ServerConnection[] connections = new ServerConnection[numConnections]; for (int i = 0; i < numConnections; i++) connections[i] = new ServerConnection(serverLocation, portLocation); try { Thread.sleep(2000); // ensure all the server connections have been established } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < numConnections; i++) for (int j = 0; j < numMessages; j++) { String message = String.format("message %d of %d from connection %d of %d", j + 1, numMessages, i + 1, numConnections); System.out.println(message); connections[i].writeLine(message); } for (int i = 0; i < numConnections; i++) { System.out.printf("%d: STARTING\n", i + 1); int j = 0; while (j < numMessages * numConnections) { String response = connections[i].readLine(); if (response == null) { System.err.printf("%d: null response on connection\n", i + 1); break; } String[] fields = response.split(" "); if (fields.length > 0 && fields[1].equals("message")) { j++; System.out.printf("%d: received %d of %d: %s\n", i + 1, j, numMessages * numConnections, response); } else System.out.printf("%d: IGNORING: %s\n", i + 1, response); } System.out.printf("%d: COMPLETED\n", i + 1); } System.out.println("END: BROADCAST TEST"); }
955439e0-45cf-48c8-9910-250d3e33905a
7
public static void main(String[] args) throws Exception { StaticDynamicUncertaintyULHSolver solver = new StaticDynamicUncertaintyULHSolver(); StaticDynamicUncertaintyWithADIULHSolver solverADI = new StaticDynamicUncertaintyWithADIULHSolver(); PrintStream filePrintStream = new PrintStream(new File("results/SetupPatternExperiment2.csv")); PrintStream[] printStreams = new PrintStream[2]; printStreams[0] = System.out; printStreams[1] = filePrintStream; MultiPrintStreamWrapper out = new MultiPrintStreamWrapper(printStreams); out.println(";CV=0.25;CV=0.25;CV=0.25;CV=0.5;CV=0.5;CV=0.5;CV=0.75;CV=0.75;CV=0.75;CV=1.0;CV=1.0;CV=1.0;CV=1.25;CV=1.25;CV=1.25;CV=1.5;CV=1.25;CV=1.25;;;;;;;"); out.println("s;pattern identical?;more #setups without ADI?;more #setups with ADI?;pattern identical?;more #setups without ADI?;more #setups with ADI?;pattern identical?;more #setups without ADI?;more #setups with ADI?;pattern identical?;more #setups without ADI?;more #setups with ADI?;pattern identical?;more #setups without ADI?;more #setups with ADI?;pattern identical?;more #setups without ADI?;more #setups with ADI?"); AbstractStochasticLotSizingProblem problem; AbstractStochasticLotSizingSolution solution; AbstractStochasticLotSizingSolution solutionADI; DecimalFormat oneDecimal = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.US)); //Fixed problem parameters int T = 20; float alpha = .95f; TriangleDivisionNormalDistributedOrdersGenerator orderGenerator = new TriangleDivisionNormalDistributedOrdersGenerator(8, 0); for(double setupCost = 10; setupCost < 13000; setupCost += 10){ out.print(oneDecimal.format(setupCost)); double marker = 0.5; for (double cv = .25; cv<1.55; cv += .25){ //Constant(100) problem = ConstantNormalDistributedProblemGenerator.generate(T, 100, cv, setupCost, alpha, orderGenerator); solution = solver.solve(problem); solutionADI = solverADI.solve(problem); out.print(";"); boolean equalSetupPattern = ArraysUtils.deepEquals(solution.getSetupPattern(), solutionADI.getSetupPattern()); if (!equalSetupPattern && Math.abs(solverADI.solve(problem, solution.getSetupPattern()).getObjectiveValue() - solutionADI.getObjectiveValue()) < 0.0001) equalSetupPattern = true; if (!equalSetupPattern) out.print(oneDecimal.format(marker)); out.print(";"); if (solution.getNumberOfSetupPeriods() > solutionADI.getNumberOfSetupPeriods()) out.print(oneDecimal.format(marker)); out.print(";"); if (solution.getNumberOfSetupPeriods() < solutionADI.getNumberOfSetupPeriods()) out.print(oneDecimal.format(marker)); marker++; } out.println(); } filePrintStream.flush(); out.close(); }
5e05a927-7b5e-4302-8de9-5b397386e0bd
0
public int getSampleRateHz() { return sampleRateHz; }
57f527d9-f0db-44d2-b9ff-ee6bb6ce753a
6
public boolean equals(IPAddress other) { if ((buffer.length == 4) && (other.buffer.length == 4) && (buffer[0] == other.buffer[0]) && (buffer[1] == other.buffer[1]) && (buffer[2] == other.buffer[2]) && (buffer[3] == other.buffer[3])) return true; return false; }
c8cf145b-bf5a-4b11-baff-d9fa46551f85
3
private static void render(float interpolation) { StretchType stretch = guiList.peek().getOverrideStretchType(); if(stretch == null) stretch = game.getDefaultStretchType(); if(stretch != DisplayHandler.getStretchType()) DisplayHandler.setStretchType(stretch); Renderer.loadIdentity(); int color = guiList.peek().backgroundColor; float r = ((color >> 16) & 0xff)/255f; float g = ((color >> 8) & 0xff)/255f; float b = (color & 0xff)/255f; GL11.glClearColor(0, 0, 0, 1); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); Renderer.drawRect(new Vector2(0,0), DisplayHandler.getDimensions(), r, g, b, 1.0f); if(RESIZING_ENABLED) DisplayHandler.checkDisplayResolution(); guiList.peek().render(interpolation); CursorLoader.render(interpolation); Renderer.clear(); }
26f6f133-4b18-47cb-860a-a08433cb47a2
3
@SuppressWarnings({"deprecation", "static-access"}) @EventHandler(priority = EventPriority.HIGH) public void onMobDeath (EntityDeathEvent event) { Entity entity = event.getEntity(); event.getEntity().getWorld(); if (entity instanceof Pig) { Pig pigc = (Pig) entity; pigc.getLocation(); if (MMPigChest.isPigChest(pigc)) { StorageMinecart chest = (StorageMinecart) pigc.getPassenger(); try { chest.remove(); } catch (Exception ex) { return; } } } }
e9e1ee13-bd32-4736-9120-50d9b62f677e
4
public double standardizedPersonVariance(int index){ if(!this.dataPreprocessed)this.preprocessData(); if(index<1 || index>this.nPersons)throw new IllegalArgumentException("The person index, " + index + ", must lie between 1 and the number of persons," + this.nPersons + ", inclusive"); if(!this.variancesCalculated)this.meansAndVariances(); return this.standardizedPersonVariances[index-1]; }
51f07532-c441-4367-9dad-a05b7b55da2c
4
@Override public void onUpdate(GameContainer window) { if (currentScreen != null) currentScreen.update(window); if (overlayScreen != null) overlayScreen.update(window); if (isLoading()) { IScreenOverlay overlay = getOverlayScreen(); if (!overlay.isAnimating()) { currentScreen = pendingScreen; pendingScreen = null; overlay.fadeOut(); } } }
c1994b78-a8a4-41da-8960-4adec0dca734
6
public int getDiscogID(String artist, String title) { try { URL url = new URL(req.replace("QUERY", URLEncoder.encode(title, "utf-8"))); DiscogHandler handler = new DiscogHandler(); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(new GZIPInputStream(url.openStream()), handler); Map<String, Integer> rMap = handler.getReleaseMap(artist); String[] elems = new String[rMap.keySet().size()]; int pointer = 0; for (String rTitle : rMap.keySet()) elems[pointer++] = rTitle; if (elems.length == 1) return rMap.get(elems[0]); else { int chosen = JOptionPane.showOptionDialog(null, "Select", "Select", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, elems, elems[0]); if (chosen >= 0) return rMap.get(elems[chosen]); } } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return -1; }
6767eaec-eba3-4ce1-85bf-c7febd9ddf4d
9
public Point[] growHull(Point[] hull) { double rad = HULL_GROWTH_RADIUS; double rightRad = endGame ? rad * HULL_GROWTH_ENDGAME_MULT : rad; Point[] newPoints = new Point[hull.length * 6]; for (int i=0; i < hull.length; i++) { // original point newPoints[6 * i + 0] = new Point(hull[i]); // point above newPoints[6 * i + 1] = new Point(hull[i].x, hull[i].y - rad <= FENCE_TOP ? FENCE_TOP + EPSILON : hull[i].y - rad); // point below newPoints[6 * i + 2] = new Point(hull[i].x, hull[i].y + rad >= FENCE_BOTTOM ? FENCE_BOTTOM - EPSILON : hull[i].y + rad); // point on right newPoints[6 * i + 3] = new Point(hull[i].x + rightRad >= FENCE_RIGHT ? FENCE_RIGHT - EPSILON : hull[i].x + rightRad, hull[i].y); // top right newPoints[6 * i + 4] = new Point(hull[i].x + rightRad >= FENCE_RIGHT ? FENCE_RIGHT - EPSILON : hull[i].x + rightRad, hull[i].y - rad <= FENCE_TOP ? FENCE_TOP + EPSILON : hull[i].y - rad); // bottom right newPoints[6 * i + 5] = new Point(hull[i].x + rightRad >= FENCE_RIGHT ? FENCE_RIGHT - EPSILON : hull[i].x + rightRad, hull[i].y + rad >= FENCE_BOTTOM ? FENCE_BOTTOM - EPSILON : hull[i].y + rad); } return computeHull(newPoints); }
75f82432-ae61-4146-89b7-c2d02f812d9c
9
public T put( S query, T value ) { final int queryLength = sequencer.lengthOf( query ); if (value == null || queryLength == 0) { return null; } int queryOffset = 0; TrieNode<S, T> node = root.children.get( sequencer.hashOf( query, 0 ) ); // The root doesn't have a child that starts with the given sequence... if (node == null) { // Add the sequence and value directly to root! return putReturnNull( root, value, query, queryOffset, queryLength ); } while (node != null) { final S nodeSequence = node.sequence; final int nodeLength = node.end - node.start; final int max = Math.min( nodeLength, queryLength - queryOffset ); final int matches = sequencer.matches( nodeSequence, node.start, query, queryOffset, max ); queryOffset += matches; // mismatch in current node if (matches != max) { node.split( matches, null, sequencer ); return putReturnNull( node, value, query, queryOffset, queryLength ); } // partial match to the current node if (max < nodeLength) { node.split( max, value, sequencer ); node.sequence = query; return null; } // Full match to query, replace value and sequence if (queryOffset == queryLength) { node.sequence = query; return node.setValue( value ); } // full match, end of the query or node if (node.children == null) { return putReturnNull( node, value, query, queryOffset, queryLength ); } // full match, end of node TrieNode<S, T> next = node.children.get( sequencer.hashOf( query, queryOffset ) ); if (next == null) { return putReturnNull( node, value, query, queryOffset, queryLength ); } // full match, query or node remaining node = next; } return null; }