text
stringlengths
14
410k
label
int32
0
9
@Override public void run() { BufferedReader is; try { is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String response=is.readLine(); String[] parts=response.split(":"); String action=parts[0]; String[] contents=parts[1].split("/"); PrintWriter os=new PrintWriter(clientSocket.getOutputStream()); switch(action){ case "WRITE": System.out.println("MasterWork:WRITE"); String variable=contents[0]; String value=contents[1]; String clientId=contents[2]; String clientIdPort=contents[3]; master.invalidateVariables(variable,Integer.parseInt(clientIdPort)); master.overwriteOwner(variable, clientIdPort); String serverRes="OK"; os.println(serverRes); os.flush(); break; case "READ": System.out.println("MasterWork:READ"); String variable2=contents[0]; String clientId2=contents[1]; String clientIdPort2=contents[2]; master.forwardRead(variable2, clientIdPort2); //TODO better wait here } } catch (IOException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (InvalidateException e) { e.printStackTrace(); } catch (ReadException e) { e.printStackTrace(); } }
6
@Override public List<Point> startPathfinder(boolean diagonalAllowed) { ArrayList<MazeCell> closedSet = new ArrayList<>(); ArrayList<MazeCell> openSet = new ArrayList<>(); openSet.add(start); ArrayList<MazeCell> pathMap = new ArrayList<>(); while (!openSet.isEmpty()) { MazeCell min = getMinF(openSet); if (min.equals(goal)) { return reconstructPath(start, goal); } openSet.remove(min); closedSet.add(min); List<MazeCell> ngbr = getNeighbourNodes(min, diagonalAllowed); Iterator<MazeCell> iter = ngbr.iterator(); boolean tentativeIsBetter = false; while (iter.hasNext()) { MazeCell cr = iter.next(); if (!closedSet.contains(cr)) { double tentativeGscore = min.getG() + distance(min, cr); if (!openSet.contains(cr)) { openSet.add(cr); tentativeIsBetter = true; } else { if (tentativeGscore < cr.getG()) { tentativeIsBetter = true; } else { tentativeIsBetter = false; } } if (tentativeIsBetter) { cr.setCameFrom(min); cr.setG(tentativeGscore); cr.setH(distance(cr, goal)); cr.setF(cr.getG() + cr.getH()); } } } } return null; }
7
private void writeDoubleArray(Object value, int type) { writeList.clear(); int len = Array.getLength(value); if (len > 0) { if (type == ElementType.TYPE_DOUBLE_ARRAY) { for (int i=0;i<len;i++) { writeList.append(Array.getDouble(value,i)); } } else if (type == ElementType.TYPE_DOUBLE_WRAPPER_ARRAY) { for (int i=0;i<len;i++) { writeList.append(((Double[])value)[i]); } } } valueList.append(writeList); }
5
public static String[] split(String eff) { int idxBr = eff.indexOf('['); int idxParen = eff.indexOf('('); String eff0 = null; if ((idxBr >= 0) && (idxBr < idxParen)) { int idxRbr = eff.indexOf(']'); eff0 = eff.substring(0, idxRbr + 1); eff = eff.substring(idxRbr); } eff = eff.replace('(', '\t'); // Replace all chars by spaces eff = eff.replace('|', '\t'); eff = eff.replace(')', '\t'); String effs[] = eff.split("\t", -1); // Negative number means "use trailing empty as well" if (eff0 != null) effs[0] = eff0; return effs; }
3
public boolean empty() { for (int i = 0; i < tileArray.length; i++) { for (int j = 0; j < tileArray[0].length; j++) { for (int k = 0; k < tileArray[0][0].length; k++) { if (tileArray[i][j][k] != 0) { return false; } } } } return true; }
4
LenDecoder() { }
0
public Character SwapHero(Character willBeSwappedHero) { Character temp = null; try{ temp = hero; hero = null; //hero = CharacterFactory.getCharacter(Constants.CHARACTER_RANDOM); hero = willBeSwappedHero; }catch(Exception e){ hero = temp; temp = null; } return temp; }
1
public String mode_string() { switch (h_mode) { case STEREO: return "Stereo"; case JOINT_STEREO: return "Joint stereo"; case DUAL_CHANNEL: return "Dual channel"; case SINGLE_CHANNEL: return "Single channel"; } return null; }
4
public static void main(String[] args) { prepareMenu(); printMenu(); supplyBeverage(inputCustomerChoice()); }
0
@Override public void buildTopping() { pizza.setTopping("pepperoni+salami"); }
0
public void fireBundleEvent(BundleEvent event) { // Take a snapshot of the listener array. Map<BundleContext, List<ListenerInfo>> listeners = null; Map<BundleContext, List<ListenerInfo>> syncListeners = null; synchronized (this) { listeners = m_bndlListeners; syncListeners = m_syncBndlListeners; } // Create a whitelist of bundle context for bundle listeners, // if we have hooks. Set<BundleContext> whitelist = createWhitelistFromHooks(event, event.getBundle(), listeners, syncListeners, org.osgi.framework.hooks.bundle.EventHook.class); // If we have a whitelist, then create copies of only the whitelisted // listeners. if (whitelist != null) { Map<BundleContext, List<ListenerInfo>> copy = new HashMap<BundleContext, List<ListenerInfo>>(); for (BundleContext bc : whitelist) { List<ListenerInfo> infos = listeners.get(bc); if (infos != null) { copy.put(bc, infos); } } listeners = copy; copy = new HashMap<BundleContext, List<ListenerInfo>>(); for (BundleContext bc : whitelist) { List<ListenerInfo> infos = syncListeners.get(bc); if (infos != null) { copy.put(bc, infos); } } syncListeners = copy; } // Fire synchronous bundle listeners immediately on the calling thread. fireEventImmediately( this, Request.BUNDLE_EVENT, syncListeners, event, null); // The spec says that asynchronous bundle listeners do not get events // of types STARTING, STOPPING, or LAZY_ACTIVATION. if ((event.getType() != BundleEvent.STARTING) && (event.getType() != BundleEvent.STOPPING) && (event.getType() != BundleEvent.LAZY_ACTIVATION)) { // Fire asynchronous bundle listeners on a separate thread. fireEventAsynchronously( this, Request.BUNDLE_EVENT, listeners, event); } }
8
public String getID(double x, double y) { if (nw == null) return this.id; if (nw.canZoom(x, y)) return nw.getID(x, y); if (ne.canZoom(x, y)) return ne.getID(x, y); if (sw.canZoom(x, y)) return sw.getID(x, y); if (se.canZoom(x, y)) return se.getID(x, y); return id; }
5
@Override public Parameter getParameter(final int parameterIndex) { Parameter parameter; switch (parameterIndex) { case 0: case 1: parameter = super.getParameter(parameterIndex); break; case 2: parameter = rate; break; case 3: parameter = pulseWidth; break; case 4: parameter = depth; break; case 5: parameter = resonance; break; case 6: parameter = glide; break; case 7: parameter = blend; break; default: parameter = null; } return parameter; }
8
public String getUsers(){ StringBuffer ret = new StringBuffer(threads.size()*10+12); ret.append("Users in room: ["); for (ChatServerThread thread : threads){ if (thread!=null && thread.isLoggedIn() && thread.isAlive()) ret.append(""+thread.getUserName()+", "); } ret.delete(ret.length()-2, ret.length()); ret.append("]"); return ret.toString(); }
4
public void fireMissiles(){ int checker = rd.nextInt(400); if(checker < 10){ if(!shoudlGenerateExtremeMissiles){ for(int i = 0; i < missiles.length; i++){ if(missiles[i] == null){ missiles[i] = new Missile(this, settings.missileColor, settings.missileSpeed, rd.nextInt(Math.abs(settings.screenWidth)), 0, Math.PI, false, false, settings.missileWidth, settings.missileHeight, this); break; } } }else{ for(int i = 0; i < missiles.length; i++){ if(missiles[i] == null){ missiles[i] = new Missile(this, settings.extremeMissileColor, settings.missileExtremeSpeed, rd.nextInt(Math.abs(settings.screenWidth)), 0, Math.PI, false, false, settings.missileWidth, settings.missileHeight, this); break; } } } } }
6
@EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) public void damageDealt(EntityDamageByEntityEvent event) { if(event.getDamager() instanceof Player) { Player damager = (Player) event.getDamager(); if (event.getEntity() instanceof Player) { plugin.getASPlayer(damager.getName()).curPeriod.damagePlayer(); } else if (event.getEntity() instanceof Monster) { plugin.getASPlayer(damager.getName()).curPeriod.damageMonster(); } else if (event.getEntity() instanceof Creature) { plugin.getASPlayer(damager.getName()).curPeriod.damageAnimal(); } } }
4
private static Boolean checkInterval(int intervalSeconds) { if ((intervalSeconds < MIN_SECONDS) || (intervalSeconds > MAX_SECONDS)) { return false; } return true; }
2
public NondeterminismDetector() { }
0
public Word get(Word word){ int index = base.indexOf(word); if(index == -1) return null; return base.get(index); }
1
public FieldImpl(int width, int height) throws WrongArgumentException { if(width < 1 || height < 1){ throw new WrongArgumentException("Слишком маленькие размеры поля"); } if(width > MAX_ALLOWED_FIELD_SIDE_SIZE || height > MAX_ALLOWED_FIELD_SIDE_SIZE){ throw new WrongArgumentException("Слишком большие размеры поля"); } this.width = width; this.height = height; createCells(); }
4
public void sendAFile( Peer a_recipient, File a_file ) throws UnknownHostException, IOException { Socket l_cliSock = new Socket( a_recipient.addr, this.ctrl_fileTransfertPort); ctrl_uploader.ReSet( l_cliSock, a_file.getAbsolutePath() ); ctrl_uploader.enableProgress( this.ctrl_mainwindow.getFileProgressBar()); Logger.notify("Starting an upload request to " + a_recipient.infos.PI_username + " for file : " + a_file); try { if ( ctrl_uploader.SendHeader() ) // a timeout can occur { Logger.notify("Remote host accepted file transfert."); // Now start transfert of file if ( ctrl_uploader.SendData() ) // a timeout can occur { // SUCCESS UserInteract.info(" Upload was successfully performed !"); Logger.notify("File "+ a_file.getName() +" was successfully sent !"); } else { // ERROR Logger.error("Upload of "+ a_file.getName() +" failed..."); ctrl_uploader.getProgress().interruptProgress(); } } else { // CAN'T CONTACT CLIENT Logger.error("Remote host refused file transfert."); UserInteract.error("Remote host has rejected the file transfert request..."); } } catch ( SocketTimeoutException e) { Logger.exception(e.toString());; // No answer from server ctrl_uploader.getProgress().interruptProgress(); } catch (IOException e) { // TODO Auto-generated catch block Logger.exception(e.toString());; ctrl_uploader.getProgress().interruptProgress(); } finally { l_cliSock.close(); } }
4
public static void disposeImages() { // dispose loaded images { for (Image image : m_imageMap.values()) { image.dispose(); } m_imageMap.clear(); } // dispose decorated images for (int i = 0; i < m_decoratedImageMap.length; i++) { Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i]; if (cornerDecoratedImageMap != null) { for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) { for (Image image : decoratedMap.values()) { image.dispose(); } decoratedMap.clear(); } cornerDecoratedImageMap.clear(); } } }
5
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置上传文件时用于临时存放文件的内存大小,这里是2K.多于的部分将临时存在硬盘 //factory.setSizeThreshold(1024*2); // 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录 //factory.setRepository(new File("c:\\file"));//临时文件 // 以上两项可通过DiskFileItemFactory构参来创建 // DiskFileItemFactory factory = new DiskFileItemFactory(yourMaxMemorySize, yourTempDirectory); // 2. 创建FileUpload对象 ServletFileUpload upload = new ServletFileUpload(factory); // 设置最大上传大小 10M upload.setSizeMax(1024*1024*10); // 3. 判断是否是上传表单 boolean b = upload.isMultipartContent(request); if(!b) { //不是文件上传 request.setAttribute("message","对不起,不是文件上传表单!"); logger.info("对不起,不是文件上传表单!"); request.getRequestDispatcher("/index.jsp").forward(request, response); return; } try { // 是文件上传表单 // 4. 解析request,获得FileItem项 List<FileItem> fileItems = upload.parseRequest(request); // 5. 遍历集合 for(FileItem item : fileItems) { // // 判断是否是表单元素(<input type="text" />单选,多选等) if(item.isFormField()) { //得到文件的名称 String name = item.getFieldName(); String value = item.getString(); //手工的转换 value = new String(value.getBytes("iso-8859-1"),"utf-8"); logger.info(name + "=" + value); }else { // 文件上传字段 // 获得文件名 String filename = item.getName(); logger.info("filename:"+filename); filename = filename.substring(filename.lastIndexOf("\\")+1); logger.info("filename:"+filename); // 创建文件 ServletContext context = getServletContext(); String dir = context.getRealPath("WEB-INF/uploadIMG"); File file = new File(dir,filename); file.createNewFile(); //获得流,读取数据写入文件 InputStream in = item.getInputStream(); FileOutputStream fos = new FileOutputStream(file); int len ; byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) > 0) { fos.write(buffer,0,len); } fos.close(); in.close(); item.delete(); } } } catch (Exception e) { logger.error(e); } }
5
boolean chooseFile() { folderChooser = ModelerUtilities.folderChooser; folderChooser.setDialogType(JFileChooser.SAVE_DIALOG); String s = Modeler.getInternationalText("Download"); folderChooser.setDialogTitle(s != null ? s : "Download"); folderChooser.setApproveButtonText(s); folderChooser.setApproveButtonToolTipText("Download and uncompress to the selected directory"); File dir = null; int i = folderChooser.showDialog(JOptionPane.getFrameForComponent(page), folderChooser.getDialogTitle()); if (i != JFileChooser.APPROVE_OPTION) return false; dir = folderChooser.getSelectedFile(); des = new File(dir, "MW-" + FileUtilities.httpDecode(FileUtilities.removeSuffix(FileUtilities.getFileName(src)))); if (des.exists()) { s = Modeler.getInternationalText("FolderExists"); String s1 = Modeler.getInternationalText("Folder"); String s2 = Modeler.getInternationalText("Overwrite"); String s3 = Modeler.getInternationalText("Exists"); if (JOptionPane.showConfirmDialog(JOptionPane.getFrameForComponent(page), (s1 != null ? s1 : "Folder") + " " + des.getName() + " " + (s3 != null ? s3 : "exists") + ", " + (s2 != null ? s2 : "overwrite") + "?", s != null ? s : "Folder exists", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) { return false; } } else { des.mkdir(); } folderChooser.setCurrentDirectory(dir); return true; }
8
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { ChatColor yellow = ChatColor.YELLOW; ChatColor red = ChatColor.RED; if(args.length < 1) { if(sender instanceof Player) { Player player = (Player) sender; if(player.hasPermission("CrazyFeet.crazysmoke.autosmoke")) { if(p.getASmokePlayers().contains(player.getName())) { p.getASmokePlayers().remove(player); p.getASmokePlayers().saveAutoSmokePlayers(); player.sendMessage(yellow+"You will no longer have "+red+"CrazySmoke "+yellow+"enabled when joining!"); return true; } else { p.getASmokePlayers().add(player); p.getASmokePlayers().saveAutoSmokePlayers(); player.sendMessage(yellow+"You will now have "+red+"CrazySmoke "+yellow+"enabled when joining!"); return true; } } else { player.sendMessage(red+"No permission."); return true; } } else { sender.sendMessage(red+"You must be an ingame player to do this!"); return true; } } else if(args.length == 1) { if(sender.hasPermission("CrazyFeet.crazysmoke.autosmokeother")) { if(Bukkit.getServer().getPlayer(args[0]) != null) { Player targ = Bukkit.getServer().getPlayer(args[0]); if(p.getASmokePlayers().contains(targ.getName())) { p.getASmokePlayers().remove(targ); p.getASmokePlayers().saveAutoSmokePlayers(); targ.sendMessage(red+sender.getName()+yellow+" has enabled automatic "+red+"CrazySmoke"+yellow+" on you when you join!"); sender.sendMessage(red+targ.getDisplayName()+yellow+" now has automatic "+red+"CrazySmoke"+yellow+" when they join."); return true; } else { p.getASmokePlayers().remove(targ); p.getASmokePlayers().saveAutoSmokePlayers(); targ.sendMessage(red+sender.getName()+yellow+" has disabled automatic "+red+"CrazySmoke"+yellow+" on you when you join!"); sender.sendMessage(red+targ.getDisplayName()+yellow+" no longer has automatic "+red+"CrazySmoke"+yellow+" when they join."); return true; } } else { sender.sendMessage(red+"The player "+yellow+args[0]+red+" is either offline or does not exist!"); return true; } } else { sender.sendMessage(red+"No permission"); return true; } } else { sender.sendMessage(red+"Incorrect usage. Use /crazyfeet for help!"); return true; } }
8
private static final boolean isDigit(char ch) { return ch >= '0' && ch <= '9'; }
1
public boolean fieldEmpty() { String met = MetSearch.getText(); String con = ConSearch.getText(); String pop = PopSearch.getText(); return (met.equals("") || con.equals("") || pop.equals("")); }
2
public TurnTest() { }
0
public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
7
@Override public void acceptButtonActionPerformed() { String selectedNames[] = ds.getSelectedData(); if(selectedNames.length == 3 || selectedNames.length == 4){ DataFrame df = mainApplication.getActiveDataFrame(); boolean[] selection = getValidComposition(df, selectedNames); int [] mapping = df.getMapingToData(selectedNames, selection); double[][] data = df.getNumericalData(selectedNames, mapping); double [][]cdata = CoDaStats.centerData(data); cdata = CoDaStats.transformRawCLR(cdata); Matrix Z = (new Matrix(cdata)).transpose(); SingularValueDecomposition svd = new SingularValueDecomposition(Z); double[][] pcomp = new Matrix(CoDaStats.transformCLRRaw(svd.getV().getArray())).transpose().getArray(); int dim = selectedNames.length; String groupedBy = ds.getSelectedGroup(); CoDaPackMain.outputPanel.addOutput( new OutputPlotHeader("Principal components", selectedNames)); double cpExp[] = coda.BasicStats.cumulativeProportionExplained(svd.getSingularValues()); int rank = svd.rank(); String pcnames[] = new String[rank]; String pcheaders[] = new String[dim+1]; double ternarypcomp[][] = new double[rank][dim+1]; pcheaders[dim] = "Cum.Prop.Exp."; for(int j=0;j<dim;j++){ pcheaders[j] = selectedNames[j]; } for(int i=0;i<rank;i++){ pcnames[i] = "PC" + (i+1); ternarypcomp[i][dim] = cpExp[i]; for(int j=0;j<dim;j++) ternarypcomp[i][j] = pcomp[i][j]; } CoDaPackMain.outputPanel.addOutput( new OutputTableTwoEntries("Principal Components", pcheaders, pcnames, ternarypcomp)); CoDaPlotWindow window = null; if(selectedNames.length == 3){ PrincipalComponent2dBuilder builder = new PrincipalComponent2dBuilder( selectedNames, data, pcomp[0], pcomp[1]).mapping(mapping); if(groupedBy != null){ builder.groups(coda.Utils.reduceData( df.getDefinedGroup(groupedBy), selection), coda.Utils.getCategories( df.getCategoricalData(groupedBy),selection)); } window = new TernaryPlot2dWindow( df, builder.build(), "Principal Component Plot"); window.setVisible(true); setVisible(false); } if(dim == 4){ PrincipalComponent3dBuilder builder = new PrincipalComponent3dBuilder( selectedNames, data, pcomp[0], pcomp[1], pcomp[2]).mapping(mapping); if(groupedBy != null){ builder.groups(coda.Utils.reduceData( df.getDefinedGroup(groupedBy), selection), coda.Utils.getCategories( df.getCategoricalData(groupedBy),selection)); } window = new TernaryPlot3dWindow(df, builder.build(), "Principal Component Plot 3d"); window.setVisible(true); setVisible(false); } }else{ JOptionPane.showMessageDialog(this, "<html>Select <b>three</b> or <b>four</b> variables</html>"); } }
9
private JPanel createCanvas() { return new JPanel() { @Override protected void paintComponent( Graphics g ) { super.paintComponent( g ); for( GraphPaintable paintable : paintables ) { Graphics2D g2 = (Graphics2D) g.create(); paintable.paint( g2 ); g2.dispose(); } } }; }
1
public void dispose(){ for (GUI gui:guiLayer){ Input.inputBus.unregister(gui); } }
1
private void handleHttpRequests(ChannelHandlerContext ctx, HttpRequest req) { if (req.getMethod() != HttpMethod.GET){ log.info("Detected POST request - FORBIDDEN"); sendHttpResponse(ctx, req, new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN)); } switch (req.getUri()){ case "/": { log.info("New connection recieved - requesting index.html"); HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); ChannelBuffer content = ServeFile.getContent("index.html"); res.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8"); HttpHeaders.setContentLength(res,content.readableBytes()); res.setContent(content); sendHttpResponse(ctx, req, res); log.info("index.html sent"); return; } case "/favicon.ico": { sendHttpResponse(ctx, req, new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND)); return; } case "/status": { HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); ChannelBuffer content = Status.getInstance().printStatus(); res.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text; charset=UTF-8"); HttpHeaders.setContentLength(res, content.readableBytes()); res.setContent(content); sendHttpResponse(ctx, req, res); return; } } if (req.getUri().contains(".css")){ String filename = req.getUri().replace("/", ""); String type = "text/css; charset=UTF-8"; loadAndSendFile(filename, type, ctx, req); return; } if (req.getUri().contains(".html")){ String filename = req.getUri().replace("/", ""); String type = "text/html; charset=UTF-8"; loadAndSendFile(filename, type, ctx, req); return; } if (req.getUri().contains(".js")){ String filename = req.getUri().replace("/", ""); String type = "text/javascript; charset=UTF-8"; loadAndSendFile(filename, type, ctx, req); return; } log.info("Handshake initiated"); WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory("ws://" + req.getHeader(HttpHeaders.Names.HOST) +"/bableHub", null, false); handshaker = handshakerFactory.newHandshaker(req); if (handshaker == null){ log.info("Handshake failed due to unsupported WebSocket version"); handshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.getChannel()); } else { handshaker.handshake(ctx.getChannel(), req).addListener(WebSocketServerHandshaker.HANDSHAKE_LISTENER); log.info("Handshake succeeded, adding channel to subscriber"); Gson gson = new Gson(); log.debug("Sending buffered chat:" + gson.toJson(buffer.getBuffer())); ctx.getChannel().write(new TextWebSocketFrame(PrepareMessage.createMessage(buffer))); log.info("Adding channel: " + ctx.getChannel().getId()); subscriber.addChannel(ctx.getChannel()); } }
8
public void getAction(GameState gs, int time_limit) { //MAXSIMULATIONTIME = time_limit; PlayerActionGenerator pag; pag = new PlayerActionGenerator(gs); if (pag.choices.size() > 0) { List<PlayerAction> l = new LinkedList<PlayerAction>(); { PlayerAction pa = null; do{ pa = pag.getNextAction(-1); if (pa!=null) l.add(pa); }while(pa!=null); max_actions_so_far = Math.max(l.size(),max_actions_so_far); //if (DEBUG>=1) System.out.println("MontCarloAI for player " + player + " chooses between " + l.size() + " actions [maximum so far " + max_actions_so_far + "] (cycle " + gs.getTime() + ")"); } PlayerAction best = null; float best_score = 0; int SYMS_PER_ACTION = NSIMULATIONS/l.size(); for(PlayerAction pa:l) { float score = 0; for(int i = 0;i<SYMS_PER_ACTION;i++) { Game g2 = new Game(gs, gs.getPlayerID(), time_limit, MAXSIMULATIONTIME); g2.addAgent(randomAI); g2.addAgent(randomAI); g2.play(gs.isFog()); g2.pgs.current_player = gs.getPlayerID(); g2.gs.update(); // Discount factor: score += SimpleEvaluationFunction.evaluate(g2.gs)*Math.pow(0.99,g2.cycle/10.0); } if (best==null || score>best_score) { best = pa; best_score = score; } //if (DEBUG>=2) System.out.println("child " + pa + " explored " + SYMS_PER_ACTION + " Avg evaluation: " + (score/((double)NSIMULATIONS))); } } }
7
public Contents contents() { return new PContents(); }
0
int[][] IteracionesBusquedaSoluciones(int f, int c) { int[][] resp = new int[8][2]; int pos = 0; if(ValidacionSolucion(f-2,c-1)) { resp[pos][0]=f-2; resp[pos++][1]=c-1; } if(ValidacionSolucion(f-2,c+1)) { resp[pos][0]=f-2; resp[pos++][1]=c+1; } if(ValidacionSolucion(f-1,c-2)) { resp[pos][0]=f-1; resp[pos++][1]=c-2; } if(ValidacionSolucion(f-1,c+2)) { resp[pos][0]=f-1; resp[pos++][1]=c+2; } if(ValidacionSolucion(f+2,c-1)) { resp[pos][0]=f+2; resp[pos++][1]=c-1; } if(ValidacionSolucion(f+2,c+1)) { resp[pos][0]=f+2; resp[pos++][1]=c+1; } if(ValidacionSolucion(f+1,c-2)) { resp[pos][0]=f+1; resp[pos++][1]=c-2; } if(ValidacionSolucion(f+1,c+2)) { resp[pos][0]=f+1; resp[pos++][1]=c+2; } int[][] tmp = new int[pos][2]; for(int i=0; i<pos; i++) { tmp[i][0] = resp[i][0]; tmp[i][1]=resp[i][1]; } return tmp; }
9
public void init() { Client.nodeID = Integer.parseInt(getParameter("nodeid")); Client.portOff = Integer.parseInt(getParameter("portoff")); String s = getParameter("lowmem"); if (s != null && s.equals("1")) { Client.setLowMem(); } else { Client.setHighMem(); } String s1 = getParameter("free"); Client.isMembers = !(s1 != null && s1.equals("1")); initGameApplet(503, 765); }
3
public static <GItem extends Comparable<? super GItem>> GItem minItem(final Iterable<? extends GItem> items) { final Iterator<? extends GItem> iterator = Iterators.iterator(items); if (!iterator.hasNext()) return null; GItem result = iterator.next(); while (iterator.hasNext()) { final GItem item = iterator.next(); if (item.compareTo(result) < 0) { result = item; } } return result; }
6
public void initCards(Random gen, boolean playerOne) { isPlayerOne = playerOne; // Generate Player One's deck for (int i = 0; i < 50; i++) { int rand = gen.nextInt(10); if (rand < 4) playerOneCards.addToDeck(new Monster(CardInstance.MONSTER, CardType.ATTACK)); else if (rand >= 4 && rand < 8) playerOneCards.addToDeck(new Potion(CardInstance.POTION, CardType.SINGLE_USE)); else playerOneCards.addToDeck(new BigMonster( CardInstance.BIG_MONSTER, CardType.ATTACK)); } playerOneCards.drawCards(5); // Generate Player Two's deck for (int i = 0; i < 50; i++) { int rand = gen.nextInt(10); if (rand < 4) playerTwoCards.addToDeck(new Monster(CardInstance.MONSTER, CardType.ATTACK)); else if (rand >= 4 && rand < 8) playerTwoCards.addToDeck(new Potion(CardInstance.POTION, CardType.SINGLE_USE)); else playerTwoCards.addToDeck(new BigMonster( CardInstance.BIG_MONSTER, CardType.ATTACK)); } playerTwoCards.drawCards(5); }
8
@Override public String getColumnName(int column) { switch (column) { case 0: return "SUBP"; case 1: return "URL"; case 2: return "Drajver"; case 3: return "Username"; case 4: return "Password"; default: return "Greska"; } }
5
public boolean render(Level level, int x, int y, int z, ShapeRenderer shapeRenderer) { boolean rendered = false; float var7 = 0.5F; float var8 = 0.8F; float var9 = 0.6F; ColorCache colorCache; if (canRenderSide(level, x, y - 1, z, 0)) { colorCache = getBrightness(level, x, y - 1, z); shapeRenderer.color(var7 * colorCache.R, var7 * colorCache.G, var7 * colorCache.B); renderInside(shapeRenderer, x, y, z, 0); rendered = true; } if (canRenderSide(level, x, y + 1, z, 1)) { colorCache = getBrightness(level, x, y + 1, z); shapeRenderer.color(colorCache.R * 1F, colorCache.G * 1F, colorCache.B * 1F); renderInside(shapeRenderer, x, y, z, 1); rendered = true; } if (canRenderSide(level, x, y, z - 1, 2)) { colorCache = getBrightness(level, x, y, z - 1); shapeRenderer.color(var8 * colorCache.R, var8 * colorCache.G, var8 * colorCache.B); renderInside(shapeRenderer, x, y, z, 2); rendered = true; } if (canRenderSide(level, x, y, z + 1, 3)) { colorCache = getBrightness(level, x, y, z + 1); shapeRenderer.color(var8 * colorCache.R, var8 * colorCache.G, var8 * colorCache.B); renderInside(shapeRenderer, x, y, z, 3); rendered = true; } if (canRenderSide(level, x - 1, y, z, 4)) { colorCache = getBrightness(level, x - 1, y, z); shapeRenderer.color(var9 * colorCache.R, var9 * colorCache.G, var9 * colorCache.B); renderInside(shapeRenderer, x, y, z, 4); rendered = true; } if (canRenderSide(level, x + 1, y, z, 5)) { colorCache = getBrightness(level, x + 1, y, z); shapeRenderer.color(var9 * colorCache.R, var9 * colorCache.G, var9 * colorCache.B); renderInside(shapeRenderer, x, y, z, 5); rendered = true; } return rendered; }
6
@Override public Program mutate(Program program) throws InvalidProgramException { if (!(program instanceof ProgramImpl)) { throw new InvalidProgramException(); } Random randomGenerator = new Random(); ProgramImpl program1 = (ProgramImpl) program.clone(); List<Reaction> reactions = program1.getReactions(); int nrOfReactionsToRemove = (reactions.size() / 100) + 1; for (int i=0; i<nrOfReactionsToRemove; i++) { if (!reactions.isEmpty()) { program1.removeReaction(reactions.get(randomGenerator.nextInt(reactions.size()))); } } return program1; }
3
private boolean shortCircuit() { boolean shortCirc = false; Circuit copy = new Circuit(this); for (int i = copy.getComponents().size() - 1; i >= 0; i--) { Component c = copy.getComponents().get(i); { if (c instanceof Resistor) { copy.removeComponent(c); } } } List<Terminal> nodes = new ArrayList<Terminal>(); List<List<Component>> loops = new ArrayList<List<Component>>(); int copyBranches = copy.findNodesAndLoops(nodes, loops); if (copyBranches != 0) // At least one loop found { for (List<Component> loop : loops) { for (Component c : loop) { if (c instanceof Battery) { shortCirc = true; } } } } return shortCirc; }
6
public static void loadDAS4InfoFromConfig() throws IOException{ Properties prop = new Properties(); FileInputStream fis = new FileInputStream("config.txt"); prop.load(fis); if (!prop.containsKey("username")) throw new IOException("Missing username entry for config.txt! (key=username)"); if (!prop.containsKey("password")) throw new IOException("Missing password entry for config.txt! (key=password)"); DAS4_USERNAME = prop.getProperty("username"); DAS4_PASSWORD = prop.getProperty("password"); if (prop.containsKey("comport")) try{ DEFAULT_PORT = Integer.parseInt((String) prop.get("comport")); } catch (NumberFormatException e){} if (prop.containsKey("ftpport")) try{ DEFAULT_FTP_PORT = Integer.parseInt((String) prop.get("ftpport")); } catch (NumberFormatException e){} }
6
/** @return The header panel for this table. */ public OutlineHeader getHeaderPanel() { if (mHeaderPanel == null) { mHeaderPanel = new OutlineHeader(this); } return mHeaderPanel; }
1
public void draw(Graphics g) { for (int i = 0; i < 64; i++) { for (int j = 0; j < 64; j++) { tiles[i][j].setType(Scheme.tiles[i][j]); if (Scheme.labels[i][j]!="") { tiles[i][j].makeTextTile(Scheme.labels[i][j]); } tiles[i][j].draw(g); } } }
3
public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { // Set System L&F UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException e) { // handle exception } catch (ClassNotFoundException e) { // handle exception } catch (InstantiationException e) { // handle exception } catch (IllegalAccessException e) { // handle exception } try { VotingSettings settingsWindow = new VotingSettings(); settingsWindow.getFrame().setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }
5
public void usunOsobe(Osoba osoba) { osoba = em.find(Osoba.class, osoba.getId()); em.remove(osoba); }
0
public void setVerbose(boolean verbose) { this.verbose = verbose; }
0
private int forward(int obj) { // There are three cases that you will need to handle here. // 1) If obj is not a pointer (i.e., if it is greater than // or equal to zero), then you should just return obj // directly. // 2) If obj is a pointer, but the length field of the object // that it points to is negative, then (a) we can conclude // that the object has already been forwarded; and (b) we // can just return the (negative) length value, which is a // pointer to the object's new location in toSpace. // 3) If obj is a pointer and the length field is non negative, // then it points to an object that needs to be forwarded to // toSpace. This requires us to copy the length word and // the associated fields from the heap into the toSpace. // After that, we overwrite the length field with a pointer // to the location of the object in toSpace (because it is // a pointer, this will be a negative number). // The description here is longer than my code! if (obj >= 0) return obj; int addy = size+obj; int retval = hp; if (heap[addy] < 0) return heap[addy]; if (heap[addy] >= 0){ for (int i = 0; i <= heap[addy]; i++){ toSpace[hp++] = heap[addy+i]; } heap[addy] = retval-size; } return retval; }
4
@Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Variable)) return false; Variable other = (Variable)obj; if (this.getValue() == null && other.getValue() == null) return true; if (this.getValue() != null && other.getValue() != null) return this.getValue().equals(other.getValue()); return false; }
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JAgoraNodeID other = (JAgoraNodeID) obj; if (localID == null) { if (other.localID != null) return false; } else if (!localID.equals(other.localID)) return false; if (source == null) { if (other.source != null) return false; } else if (!source.equals(other.source)) return false; return true; }
9
@Override public List<Member> getListOfMembers() { List<Member> member = null; try { member = (List<Member>) deserializeXMLToObject("Member.xml"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return member; }
1
private JPanel createParamLine(int i) { JPanel paramLine = new JPanel(); paramLine.setLayout(new GridLayout(1, 2)); if(i == 0){ JTextArea originXTA = new JTextArea("Origine en X :"); originXTA.setEditable(false); originX = new JTextField("" + currentDrawable.getOriginX()); originXTA.setPreferredSize(originXTA.getPreferredSize()); originX.setPreferredSize(originX.getPreferredSize()); paramLine.add(originXTA); paramLine.add(originX); originX.addKeyListener(ec); }else if(i == 1){ JTextArea originYTA = new JTextArea("Origine en Y :"); originYTA.setEditable(false); originY = new JTextField("" + currentDrawable.getOriginY()); originYTA.setPreferredSize(originYTA.getPreferredSize()); originY.setPreferredSize(originY.getPreferredSize()); paramLine.add(originYTA); paramLine.add(originY); originY.addKeyListener(ec); }else if(i == 2){ JTextArea tailleXTA = new JTextArea("Largeur :"); tailleXTA.setEditable(false); tailleX = new JTextField("" + currentDrawable.getWidth()); tailleXTA.setPreferredSize(tailleXTA.getPreferredSize()); tailleX.setPreferredSize(tailleX.getPreferredSize()); paramLine.add(tailleXTA); paramLine.add(tailleX); tailleX.addKeyListener(ec); }else if(i == 3){ JTextArea tailleYTA = new JTextArea("Hauteur :"); tailleYTA.setEditable(false); tailleY = new JTextField("" + currentDrawable.getHeight()); tailleYTA.setPreferredSize(tailleYTA.getPreferredSize()); tailleY.setPreferredSize(tailleY.getPreferredSize()); paramLine.add(tailleYTA); paramLine.add(tailleY); tailleY.addKeyListener(ec); } return paramLine; }
4
@Override public String getChoix(String p) { if(p.equals(player1)) { return this.choise1; } else if (p.equals(player2)) { return this.choise2; } return "aucun"; }
2
static final void method2383(AbstractToolkit var_ha, int i, Widget class46) { do { try { if (i != -2) method2383(null, -63, null); anInt6385++; boolean bool = ((ToolkitException.itemLoader.method1941 (((Widget) class46).anInt672, (byte) -74, ((Widget) class46).itemId, ((Widget) class46).anInt781, ~0xffffff | ((Widget) class46).anInt809, ((Widget) class46).anInt678, var_ha, (!((Widget) class46).aBoolean720 ? null : (((Player) Class132.localPlayer) .aClass154_10536)))) == null); if (!bool) break; Class5_Sub1_Sub1.aClass262_9931.addToFront (new Class348_Sub7(((Widget) class46).itemId, ((Widget) class46).anInt781, ((Widget) class46).anInt672, (~0xffffff | ((Widget) class46).anInt809), ((Widget) class46).anInt678, ((Widget) class46).aBoolean720), i ^ 0x4ed2); Class251.method1916(-9343, class46); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("ga.QA(" + (var_ha != null ? "{...}" : "null") + ',' + i + ',' + (class46 != null ? "{...}" : "null") + ')')); } break; } while (false); }
7
public boolean sideCollision(ArrayList<Double> xArray, ArrayList<Double> yArray) { for (Block block : blockArray) { for (int i = 0; i < xArray.size(); i++) { if ((xArray.get(i) == block.getXValue()) && (yArray.get(i) == (block.getYValue()))) { return true; } } } return false; }
4
@Override public void onSuccessfulStarted() { System.out.println("onSuccessfulStarted!"); if(!errorsWhileStarting) { setChanged(); notifyObservers(ModelNotification.CONNECTION_ESTABLISHED); } }
1
@Override public void editElection(Date openNominations, Date start, Date end, String electoratelectionID) { if (context.getCurrentUser() != null && context.getCurrentUser().isElectionManager()) { context.getAdminTools().editElection(context.getCurrentUser(), context.getCurrentElectionID(), openNominations, start, end, electoratelectionID); } else throw new RuntimeException( "Illegal action. Current user is not an Election Manager"); }
2
@Override public String execute() throws Exception { try{ Map session =ActionContext.getContext().getSession(); setUser((User) session.get("User")); setSitelist((List<Publish>) getMyDao().getDbsession().createQuery("from Publish").list()); Criteria crit1 = getMyDao().getDbsession().createCriteria(Publish.class); crit1.add(Restrictions.like("user", getUser())); crit1.setMaxResults(20); setSitelist((List<Publish>) crit1.list()); setCamplist((List<Campaign>) getMyDao().getDbsession().createQuery("from Campaign").list()); Criteria crit = getMyDao().getDbsession().createCriteria(Campaign.class); crit.add(Restrictions.like("user", getUser())); crit.setMaxResults(20); setCamplist((List<Campaign>) crit.list()); setUselist((List<UserDetails>) myDao.getDbsession().createQuery("from UserDetails").list()); Criteria ucri=myDao.getDbsession().createCriteria(UserDetails.class); ucri.add(Restrictions.like("user", getUser())); ucri.setMaxResults(1); return "success"; } catch (HibernateException e) { addActionError("Server Error Please Try Again "); e.printStackTrace(); return "error"; } catch (NullPointerException ne) { addActionError("Server Error Please Try Again "); ne.printStackTrace(); return "error"; } catch (Exception e) { addActionError("Server Error Please Try Again "); e.printStackTrace(); return "error"; } }
3
private VariablePrecisionTime getVorbisRecordingDate() { return vorbisDate(true); }
0
public void encrypt(InputStream in, OutputStream out) throws Exception { // Symmetrically Encrypted Data Packet byte version = 4; int block_size = ecipher.getBlockSize(); int len = 0; byte[] buf = new byte[184]; int add = 0; int packet_len; byte[] padded_buf; System.out.println("Encrypted file:: "); while ((len = in.read(buf)) >= 0) { System.out.println(new String(buf)); out.write((byte) SEDP_TAG & 0xff); // pad with 0 for if ((len % block_size) != 0) { add = block_size - (len - block_size * (len / block_size)); padded_buf = new byte[len + add]; Arrays.fill(padded_buf, (byte) 0); for (int i = 0; i < len + add; ++i) padded_buf[i] = buf[i]; } packet_len = len + add + 1 + 1 + 1; // data + padding + version + sym_alg_id + S2K out.write((byte) packet_len & 0xff); out.write(version & 0xff); out.write(TRIPLEDES_ID & 0xff); out.write(S2K_reserved & 0xff); byte[] cipher_text = new byte[len + add]; len = ecipher.update(buf, 0, len + add, cipher_text); out.write(cipher_text, 0, len); Arrays.fill(buf, (byte) 0); } out.flush(); }
3
public List<String> fullJustify(String[] words, int L) { if(words == null || words.length == 0) return new ArrayList<String>(); List<String> result = new ArrayList<String>(); int lineCount = 0; List<String> line = new ArrayList<String>(); for(int i=0; i<words.length; i++){ lineCount += words[i].length(); if(lineCount > L){ result.add(process(line, L, lineCount - words[i].length() - 1)); lineCount = 0; i--; line.clear(); }else{ line.add(words[i]); lineCount++; } } if(line.size() != 0){ String last = ""; int lastCount = 0; for(int i=0; i<line.size(); i++){ last += line.get(i); lastCount += line.get(i).length(); if(lastCount < L){ last += " "; lastCount++; } } result.add(addSpace(last, L-lastCount)); } return result; }
7
public void makeNewBlock(int x, int y, int length){ x = x + 8; Prefab prefab = new Prefab(0, 0, 0, 0); RoadGenerator roadGen = new RoadGenerator(); int xStart = x - 8; int xFar = x + (length * 24) + 8; int yFar = y + ((2 * 8) + (24 * 2)); roadGen.layRoad(xStart, y, xStart, yFar); roadGen.layRoad(xStart, y, xFar, y); roadGen.layRoad(x + (length * 24), y, x + (length * 24), y + ((2 * 8) + (24 * 2))); roadGen.layRoad(xStart, yFar - 8, xFar, yFar - 8); y = y + 8; for (int i = 0; i < length; i++){ for (int j = 0; j < 2; j++){ int xPos = (i * 24) + x; int yPos = (j * 24) + y; try { prefab.randomPrefabFromFile(xPos, yPos); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
3
public Component getComponentAfter(Container container, Component component) { return cycle(component, 1); }
0
private void collectCategoryChanges(CourseModel courseModel, ArrayList<Change> changes) { // TODO: category names are long, and they are mapped to numeric codes // in facets. Something to use in description? for (String c : categories) { String code = makeIdSafe(c); if (courseModel.getCategory(Source.EDX, code) == null) changes.add(DescChange.add(DescChange.CATEGORY, Source.EDX, code, c, null)); } HashSet<String> newIds = new HashSet<String>(); for (String s : this.categories) newIds.add(makeIdSafe(s)); for (DescRec rec : courseModel.getCategories(Source.EDX)) { if (!newIds.contains(rec.getId())) { changes.add(DescChange.delete(DescChange.CATEGORY, rec)); } else { // TODO Once have descriptions, do diff. } newIds.remove(rec.getId()); } }
5
private void afficherInfos(String path, String fichier) { File f = new File(maConf.getRacine() + "\\" +path + "\\" + fichier); Date date = new Date(f.lastModified()); if(!path.equalsIgnoreCase("/") && !path.equalsIgnoreCase("\\") ) { path += "/"; } writer.println("<a href=\""+ path + f.getName() +"\">"); if (!f.isDirectory()) { writer.print(" "); writer.print(" "); writer.print(fichier + "</a> "+ f.length() + " " + getDateRfc822(date)); // Utilise printf vielle méthode du c writer.println(); } else { writer.printf("%-41s %tD %n", " [ ]" + fichier+"</a> " , f.lastModified()); // Utilise printf vielle méthode du c } }
3
@Override public void run() { while(running) { System.out.print("eva < "); if(scanner.hasNextLine()) { String input = scanner.nextLine(); emit(new Event(EventType.INPUT, this, input)); } } }
2
public DoorTile(Sprite sprite, String id){ super(sprite, id); }
0
public boolean SetChartType(int type) { if ((type>=0) && (type<NUMOFCHARTS)) { m_chartType = type; return(true); } else { return(false); } }
2
public int largestRectangleArea(int[] height) { int result = 0; Stack<Integer> s = new Stack<Integer>(); for (int i=0; i<height.length; i++) { if (s.isEmpty() || height[s.peek()] < height[i]) { s.push(i); } else { while (!s.isEmpty() && height[s.peek()] > height[i]) { int h = height[s.pop()]; int width = i - (s.isEmpty() ? -1 : s.peek()) - 1; result = Math.max(result, width * h); } s.push(i); } } while (!s.isEmpty() && height[s.peek()] >= 0) { int h = height[s.pop()]; int width = height.length - (s.isEmpty() ? -1 : s.peek()) - 1; result = Math.max(result, width * h); } return result; }
9
public E remove(Position<E> p) throws IllegalArgumentException { Node<E> node = validate(p); if (numChildren(p) == 2) throw new IllegalArgumentException("p has two children"); Node<E> child = (node.getLeft() != null ? node.getLeft() : node.getRight() ); if (child != null) child.setParent(node.getParent()); // child's grandparent becomes its parent if (node == root) root = child; // child becomes root else { Node<E> parent = node.getParent(); if (node == parent.getLeft()) parent.setLeft(child); else parent.setRight(child); } size--; E temp = node.getElement(); node.setElement(null); // help garbage collection node.setLeft(null); node.setRight(null); node.setParent(node); // our convention for defunct node return temp; }
5
private static EasyPostResponse makeURLConnectionRequest(EasyPostResource.RequestMethod method, String url, String query, String apiKey) throws EasyPostException { javax.net.ssl.HttpsURLConnection conn = null; try { switch (method) { case GET: conn = createGetConnection(url, query, apiKey); break; case POST: conn = createPostConnection(url, query, apiKey); break; case DELETE: conn = createDeleteConnection(url, query, apiKey); break; case PUT: conn = createPutConnection(url, query, apiKey); break; default: throw new EasyPostException( String.format("Unrecognized HTTP method %s. Please contact EasyPost at contact@easypost.com.", method)); } int rCode = conn.getResponseCode(); // sends the request String rBody = null; if (rCode == 204) { rBody = ""; } else if (rCode >= 200 && rCode < 300) { rBody = getResponseBody(conn.getInputStream()); } else { rBody = getResponseBody(conn.getErrorStream()); } return new EasyPostResponse(rCode, rBody); } catch (IOException e) { throw new EasyPostException( String.format( "Could not connect to EasyPost (%s). " + "Please check your internet connection and try again. If this problem persists," + "please contact us at contact@easypost.com.", EasyPost.API_BASE), e); } finally { if (conn != null) { conn.disconnect(); } } }
9
public static void main(String[] args) throws Throwable { ServerSocket serverSocket = null; int port = 10009; try { serverSocket = new ServerSocket(port); } catch (IOException e) { System.err.println("Le serveur ne peut écouter sur le port : " + port); System.exit(1); } Socket clientSocket = null; System.out.println("En attente de connexion..."); try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Acceptation du client à echoué."); System.exit(1); } System.out.println("La connexion est réussie."); System.out.println("En attente de requête client..."); // Mise en place des I/O client-server BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String inputLine; Server server = new Server(); LinkedList<String> res = new LinkedList<String>(); while (!(inputLine = in.readLine()).equals(Application.END_APP)) { res = (LinkedList<String>) server.receiveReq(inputLine, in); System.out.println("fin du reçu"); try { res = (LinkedList<String>) server.lancerMethode(server.getModel(), res, res.pop()); } catch (InvocationTargetException e) { try { throw e.getCause(); } catch(ApplicationException err) { res = Application.appError(err.msg()); } } //LinkedList<String> ret = server.model.listNickNameByName("Julien"); //ret.add(Application.END_APP); while(!res.isEmpty()) out.println(res.pop()); System.out.println("Fin envoie"); } System.out.println("Fin......................."); out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
6
public ArrayList<Ball> getBalls() { return this.balls; }
0
void Translations() { if (lang == "Eng") { file = "File"; help = "Help"; image = "Image"; new1 = "New"; open = "Open"; save = "Save"; exit = "Exit"; about = "About GraphicEditor " + Constants.ver + ""; clear = "Clear"; colourChooser = "ColorChooser"; color = "Color"; fone = "Fone"; oK = "OK"; canCel = "Cancel"; width = "Width:"; height = "Height:"; ch1 = "Coosing size of new image"; ch2 = "Choosing tools size"; aboutText = "<html>About GrpaphicEditor " + Constants.ver + " Program<br>Availible only for russian language.<br><p align=\"right\">&copy;FreeSimpleSoft Team, 2010-2013</p><html>"; // TODO ps = "Pencil size"; es = "Eraser size"; ls = "Line size"; ips = "Input pencil size (in pixels):"; ies = "Input eraser size (in pixels):"; ils = "Input line size (in pixels):"; site = "Our site"; supm = "Support e-mail"; supf = "Support forum"; } else if (lang == "Rus") { file = "Файл"; help = "Помощь"; image = "Изображение"; new1 = "Создать"; open = "Открыть"; save = "Сохранить"; exit = "Выход"; about = "О программе"; clear = "Очистить"; colourChooser = "Палитра"; color = "Осн. цвет"; fone = "Фон"; oK = "OK"; canCel = "Отмена"; width = "Ширина:"; height = "Высота:"; ch1 = "Выбор размера нового изображения"; ch2 = "Выбор размера инструментов"; aboutText = "<html><h1>О программе GrpaphicEditor " + Constants.ver + "</h1><br>" + "<br>&nbsp;Сборка программы GrpaphicEditor " + Constants.ver + " была собрана 22 ноября 2013 года." + "<br>&nbsp;Отличительной чертой этой версии программы является впервые <br>" + " добавленная мультиязычность и добавленная заливка (кнопка \"fil\") которая,<br> активирует инструмент заливки. В финальной версии будет дорабоан алгоритм заливки<br><br> <p align=\"right\">&copy;FreeSimpleSoft Team, 2010-2013</p><html>"; ps = "Размер карандаша"; es = "Размер резинки"; ls = "Толщина линии"; ips = "Введите размер карандаша (в пикселях):"; ies = "Введите размер ластика (в пикселях):"; ils = "Введите толщину линии (в пикселях):"; site = "Наш сайт"; supm = "E-mail поддержки"; supf = "Форум поддержки"; } }
2
public void writeUntil(final int end, final CodedOutputStream output) throws IOException { while (next != null && next.getKey().getNumber() < end) { FieldDescriptor descriptor = next.getKey(); if (messageSetWireFormat && descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE && !descriptor.isRepeated()) { if (next instanceof LazyField.LazyEntry<?>) { output.writeRawMessageSetExtension(descriptor.getNumber(), ((LazyField.LazyEntry<?>) next).getField().toByteString()); } else { output.writeMessageSetExtension(descriptor.getNumber(), (Message) next.getValue()); } } else { // TODO(xiangl): Taken care of following code, it may cause // problem when we use LazyField for normal fields/extensions. // Due to the optional field can be duplicated at the end of // serialized bytes, which will make the serialized size change // after lazy field parsed. So when we use LazyField globally, // we need to change the following writeTCP method to writeTCP cached // bytes directly rather than writeTCP the parsed message. FieldSet.writeField(descriptor, next.getValue(), output); } if (iter.hasNext()) { next = iter.next(); } else { next = null; } } }
9
public void shutdown() { shuttingDown = true; Logger.log("Shutdown was called."); if(ownsSocket) { Logger.log("Closing socket."); socket.close(); } else { Logger.log("Note: not closing socket!"); } runningLock.unlock(); }
1
private void openCoreLocationWindow() { JFileChooser coreFolderSelect = new JFileChooser(); coreFolderSelect.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); coreFolderSelect.setDialogTitle("Select NGECore2 folder"); int success = coreFolderSelect.showOpenDialog(contentPanel); if (success == JFileChooser.APPROVE_OPTION) { File selectedDirectory = coreFolderSelect.getSelectedFile(); String corePath = selectedDirectory.getAbsolutePath(); if (!selectedDirectory.getName().equals("NGECore2")) { File[] childrenFolders = selectedDirectory.listFiles(); String coreFolder = ""; for (File childrenFolder : childrenFolders) { if (childrenFolder.getName().equals("NGECore2")) { coreFolder = childrenFolder.getAbsolutePath(); break; } } if (coreFolder.equals("")) { Helpers.showMessageBox(coreFolderSelect, "Could not find NGECore2 in the directory " + selectedDirectory.getAbsolutePath()); openCoreLocationWindow(); return; } else { corePath = coreFolder; } } tbCore2Location.setText(corePath); if (!dirty) dirty = true; } }
6
private void processMoveToHand(MouseEvent e) { List<Card> hand = game.getHand().getList(); if (hand.size() > 0) { final double handXGap = handXGap(hand.size()); int indexTo = (int) ((e.getX() - handXStart()) / (handXGap + CARD_WIDTH)); activeMove.cardReleased(indexTo, CardMoveImpl.MOVE_TYPE_TO.TO_HAND); String result = activeMove.makeMove(game, this); processMoveResult(result, activeMove); } }
1
@Override public String toString() { StringBuilder string = new StringBuilder(); string.append("Citation type: ").append(this.citationType).append("\n"); if (authors != null) { string.append("Authors: "); for (Author author : this.authors) { string.append(author); if (authors.indexOf(author) != authors.size() - 1) { string.append(" and "); } } string.append("\n"); } if (this.title != null) { string.append("Title: ").append(this.title).append("\n"); } if (this.year != null) { string.append("Year: ").append(this.year).append("\n"); } if (this.publisher != null) { string.append("Publisher: ").append(this.publisher).append("\n"); } if (this.address != null) { string.append("Address: ").append(this.address).append("\n"); } if (tags != null) { string.append("Tags: "); for (String tag : this.tags) { string.append(tag).append(" "); } string.append("\n"); } return string.toString(); }
9
@Override public boolean execute(Player player) { if (!this.hasSecondWord()) { GameEngine.gui.println("Test what?"); return false; } Scanner vScanner; try { vScanner = new Scanner(new File("./" + this.getSecondWord())); while (vScanner.hasNextLine()) { String ligne = vScanner.nextLine(); GameEngine.interpretCommand(ligne); } vScanner.close(); } catch (FileNotFoundException pObjetException) { GameEngine.gui.println("File does not exist."); } return false; }
3
@Override public Token parse() { Token test = first.getNext(); if (!test.isOperator(Operator.BRACKET_LEFT)) throw new RuntimeException("Expected '(' after IF, found: " + test.toString()); testExpression = new BooleanExpression(test.getNext(), scope); test = testExpression.parse(); if (!test.isOperator(Operator.BRACKET_RIGHT)) throw new RuntimeException("Expected ')' after IF condition, found: " + test.toString()); test = test.getNext(); if (!test.isNewline()) throw new RuntimeException("Expected newline, found: " + test.toString()); Keyword[] targets = {Keyword.ELSE,Keyword.END}; trueCondition = new StatementGroup(test.getNext(), targets, scope); test = trueCondition.parse(); if (Keyword.ELSE.equals(test.getKeyword())) { test = test.getNext(); assert(test.isNewline()); targets = new Keyword[1]; targets[0] = Keyword.END; falseCondition = new StatementGroup(test.getNext(), targets, scope); test = falseCondition.parse(); } if (!test.isKeyword(Keyword.END)) throw new RuntimeException("Expected END keyword, found: " + test.toString()); return test.getNext(); }
5
private void register(){ int max = deck.cards; for (int i=0; i<player_count; i++){ Rack r = new Rack(rack_size, this); players[i].register(this, r); } }
1
public PickUp(int state1, int state2) { this.state1 = state1; this.state2 = state2; }
0
protected void fireConnect(ConnectEvent evt) { //.. }
0
public static void main(String[] args) { Map<Integer, Integer> p = new HashMap<>(); TreeMap<Integer, Integer> sorted = new TreeMap<>(new ValueComparator(p)); for (int a = 1; a < 999; a++) { for (int b = 1; b < 999; b++) { for (int c = 1; c <= 1000; c++) { if (Math.pow(a, 2) + Math.pow(b, 2) == Math.pow(c, 2)) { if (a + b + c > 1000) { continue; } if (!p.containsKey(a + b + c)) { p.put(a + b + c, 0); } int t = p.get(a + b + c); p.put(a + b + c, ++t); } } } } sorted.putAll(p); System.out.println(sorted.firstKey()); }
6
private String cipher_digraph(String pl,HashMap<Character,Pair<Integer> > h1, HashMap<Character,Pair<Integer>> h2) { assert(pl.length()==2); StringBuilder sb=new StringBuilder(); char c1=pl.charAt(0); char c2=pl.charAt(1); if(c1=='J') { c1='I'; } if(c2=='J') { c2='I'; } if(!h1.containsKey(Character.valueOf(c1)) || !h2.containsKey(Character.valueOf(c2))) { System.err.println("Error in finding keys in hashmap"); } Pair<Integer> p1=h1.get(Character.valueOf(c1)); Pair<Integer> p2=h2.get(Character.valueOf(c2)); if(p1.get_first()==p2.get_first()) { sb.append(c2); sb.append(c1); return sb.toString(); } else { sb.append(square2[p1.get_first()][p2.get_second()]); sb.append(square1[p2.get_first()][p1.get_second()]); return sb.toString(); } }
5
public Vector<Vector<Object>> notesTable() { try { String[] keys = {"eventID", "cbsEventID", "noteID", "text", "active"}; crs = qb.selectFrom(keys, "notes").all().executeQuery(); data.clear(); while(crs.next()) { Vector<Object> row = new Vector<Object>(); ResultSetMetaData metadata = crs.getMetaData(); int numberOfColumns = metadata.getColumnCount(); for(int i = 1; i <= numberOfColumns; i++) { row.addElement(crs.getObject(i)); } data.addElement(row); } } catch (SQLException e) { e.printStackTrace(); } finally { try { crs.close(); } catch (SQLException e) { e.printStackTrace(); } } return data; }
4
private double[] sort_intervals(double[] unsorted_intervals) { int i, length; double min = unsorted_intervals[0]; double max = unsorted_intervals[0]; double[] sorted_intervals = new double[unsorted_intervals.length]; double[] intervals; for (i=0; i < unsorted_intervals.length; i++) { if (max<unsorted_intervals[i]) { max=unsorted_intervals[i]; } if (min>unsorted_intervals[i]) { min=unsorted_intervals[i]; } } length = 0; sorted_intervals[length] = min; length = 1; while (min != max) { for (i=0; i < unsorted_intervals.length; i++) { //remove all values equal to min by setting them to max if (unsorted_intervals[i] <= min) { unsorted_intervals[i]=max; } } //find the new min min = max; for (i=0; i < unsorted_intervals.length; i++) { if (min>unsorted_intervals[i]) { min=unsorted_intervals[i]; } } sorted_intervals[length] = min; length = length + 1; } //create a new set of intervals with duplicates removed intervals = new double[length]; for (i=0; i < intervals.length; i++) { intervals[i] = sorted_intervals[i]; } return intervals; }
9
public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (!(o instanceof KeyedObjects)) { return false; } KeyedObjects kos = (KeyedObjects) o; int count = getItemCount(); if (count != kos.getItemCount()) { return false; } for (int i = 0; i < count; i++) { Comparable k1 = getKey(i); Comparable k2 = kos.getKey(i); if (!k1.equals(k2)) { return false; } Object o1 = getObject(i); Object o2 = kos.getObject(i); if (o1 == null) { if (o2 != null) { return false; } } else { if (!o1.equals(o2)) { return false; } } } return true; }
9
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Comentario other = (Comentario) obj; if (this.idComentario != other.idComentario) { return false; } if (!Objects.equals(this.timestamp, other.timestamp)) { return false; } if (!Objects.equals(this.usuario, other.usuario)) { return false; } if (this.curso != other.curso) { return false; } if (Double.doubleToLongBits(this.valNum) != Double.doubleToLongBits(other.valNum)) { return false; } if (!Objects.equals(this.texto, other.texto)) { return false; } if (this.votos != other.votos) { return false; } return true; }
9
public Iterable<Work<TI>> iterableWork() { final Master<TI, TO> master = this; return new Iterable<Work<TI>>() { @Override public Iterator<Work<TI>> iterator() { return new Iterator<Work<TI>>() { @Override public boolean hasNext() { return master.hasNext(); } @SuppressWarnings("unchecked") @Override public Work<TI> next() { // Create data array TI data[] = (TI[]) new Object[batchSize]; for (int i = 0; (i < batchSize) && hasNext(); i++) { data[i] = master.next(); if (debug) Gpr.debug("countInputObjects:" + countInputObjects); if (showEvery > 0) Gpr.showMark(countInputObjects++, showEvery); } // Create work return new Work<TI>(data); } @Override public void remove() { throw new RuntimeException("Unimplemented method"); } }; } }; }
4
public void playAnimation(){ for(BufferedImage bi : images) { ActionListener animate = new ActionListener() { private int index = 0; @Override public void actionPerformed(ActionEvent e) { if (index<images.length-1) { index++; } else { index = 0; } animation.setIcon(new ImageIcon(images[index])); } }; final Timer timer = new Timer(frameRate,animate); ActionListener startStop = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (b.isSelected()) { timer.start(); } else { timer.stop(); } } }; b.addActionListener(startStop); }//end for }//end playAnimation
3
public static boolean shouldBuild() { int factories = UnitCounter.getNumberOfUnits(TerranFactory.getBuildingType()); int armories = getNumberOfUnits(); boolean weAreBuilding = Constructing.weAreBuilding(buildingType); if (armories == 0 && (factories >= 2 && !weAreBuilding && !TechnologyManager.isSiegeModeResearchPossible() || TerranFactory.FORCE_GOLIATHS_INSTEAD_VULTURES)) { int numberOfBattleUnits = UnitCounter.getNumberOfBattleUnits(); if (numberOfBattleUnits >= 12 || (TerranFactory.FORCE_GOLIATHS_INSTEAD_VULTURES && numberOfBattleUnits >= 4)) { ShouldBuildCache.cacheShouldBuildInfo(buildingType, true); return true; } } ShouldBuildCache.cacheShouldBuildInfo(buildingType, false); return false; }
8
public static int getNowPage() { String nowPage = getHttpServletRequest().getParameter("nowPage"); if (StringUtils.isNull(nowPage)) { return 0; } else { return Integer.parseInt(nowPage); } }
1
private boolean backupSystem() { new Thread() { @Override public void run() { ProcessBuilder process = null; Process pr = null; BufferedReader reader = null; String line = null; List<String> args = null; try { workingLabel.setText(workingLabel2); File f = new File(backupDir + "/" + backupTitleLabel1.getText() + backupTitleText.getText() + "/system"); f.mkdirs(); process = new ProcessBuilder(); args = new ArrayList<>(); args.add(adbController.getADB().getAbsolutePath()); args.add("-s"); args.add(device.toString()); args.add("pull"); args.add("/system"); process.command(args); process.directory(f); process.redirectErrorStream(true); pr = process.start(); reader = new BufferedReader(new InputStreamReader(pr.getInputStream())); while ((line = reader.readLine()) != null) { if (debug) logger.log(Level.DEBUG, "ADB Output: " + line); if (line.contains("files pulled.")) { workingLabel.setText(line); break; } } pr.destroy(); reader.close(); args.clear(); for (int i = 0; i < 2000; i++) { } // Display result to user before continuing work. } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while backing up /system: " + ex.toString() + "\nThe error stack trace will be printed to the console..."); ex.printStackTrace(System.err); } interrupt(); } }.start(); return true; }
5
public static void main(String [] args) { try { PairedStats ps = new PairedStats(0.05); java.io.LineNumberReader r = new java.io.LineNumberReader( new java.io.InputStreamReader(System.in)); String line; while ((line = r.readLine()) != null) { line = line.trim(); if (line.equals("") || line.startsWith("@") || line.startsWith("%")) { continue; } java.util.StringTokenizer s = new java.util.StringTokenizer(line, " ,\t\n\r\f"); int count = 0; double v1 = 0, v2 = 0; while (s.hasMoreTokens()) { double val = (new Double(s.nextToken())).doubleValue(); if (count == 0) { v1 = val; } else if (count == 1) { v2 = val; } else { System.err.println("MSG: Too many values in line \"" + line + "\", skipped."); break; } count++; } if (count == 2) { ps.add(v1, v2); } } ps.calculateDerived(); System.err.println(ps); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } }
9
public double getStrength() { return strength; }
0
private void phaser() { int count = 4; final Phaser phaser = new Phaser(); phaser.register(); for (int i = 0; i < count; i++) { phaser.register(); final int localCount = i; new Thread(new Runnable() { public void run() { try { Thread.sleep(localCount * 1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(localCount); phaser.arrive(); } }).start(); } }
2