text
stringlengths
14
410k
label
int32
0
9
protected void readImage() { ix = readShort(); // (sub)image position & size iy = readShort(); iw = readShort(); ih = readShort(); int packed = read(); lctFlag = (packed & 0x80) != 0; // 1 - local color table flag interlace = (packed & 0x40) != 0; // 2 - interlace flag // 3 - sort flag // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color table size if (lctFlag) { lct = readColorTable(lctSize); // read table act = lct; // make local table active } else { act = gct; // make global table active if (bgIndex == transIndex) bgColor = 0; } int save = 0; if (transparency) { save = act[transIndex]; act[transIndex] = 0; // set transparent color if specified } if (act == null) { status = STATUS_FORMAT_ERROR; // no color table defined } if (err()) return; decodeImageData(); // decode pixel data skip(); if (err()) return; frameCount++; // create new image to receive frame data image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); setPixels(); // transfer pixel data to image frames.add(new GifFrame(image, delay)); // add image to frame list if (transparency) { act[transIndex] = save; } resetFrame(); }
7
private static int method503(char ac[], char ac1[], int j) { if (j == 0) return 2; for (int k = j - 1; k >= 0; k--) { if (!method517(ac[k])) break; if (ac[k] == '@') return 3; } int l = 0; for (int i1 = j - 1; i1 >= 0; i1--) { if (!method517(ac1[i1])) break; if (ac1[i1] == '*') l++; } if (l >= 3) return 4; return !method517(ac[j - 1]) ? 0 : 1; }
9
public void draw() { GL11.glPushMatrix(); GL11.glTranslatef((float)(container.getX() - Theater.get().getScreen().camera.getX()), (float)(container.getY() - Theater.get().getScreen().camera.getY()), 0); GL11.glColor3f(0.75f, 0.5f, 1.0f); GL11.glLineWidth(1.0f); GL11.glBegin(GL11.GL_LINE_LOOP); { GL11.glVertex2d(0, 0); GL11.glVertex2d(container.getWidth(), 0); GL11.glVertex2d(container.getWidth(), container.getHeight()); GL11.glVertex2d(0, container.getHeight()); } GL11.glEnd(); GL11.glPopMatrix(); if(!noChildren()) { for(int x = 0; x<propChildren.length; x++) { propChildren[x].draw(); } } }
2
public static void main(String [] args) { long limit = ((long)1e8)-1L; long palindromicSum = 0; for (int i=1; i<=Math.sqrt(limit); i++) { long sqSum = 0; for (int j=i; sqSum < limit; j++) { sqSum += j*j; if (i != j) { // don't want a single square like 3*3 = 9 (per hint that 11 palindromics below 1000) if (sqSum <= limit) { if (isPalindromic(sqSum)) { palindromicSum += sqSum; System.out.println("i: " + i + ", j: " + j + ", sqSum: " + sqSum + ", palSum: " + palindromicSum); // hmmm... are some Palindromics repeated?? Sort output | uniq to find out // YEP 2 are repeated! // System.out.println(sqSum); } } } } } }
5
@Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof DHCPPacket)) { return false; } DHCPPacket p = (DHCPPacket) o; boolean b; b = (this.comment.equals(p.comment)); b &= (this.op == p.op); b &= (this.htype == p.htype); b &= (this.hlen == p.hlen); b &= (this.hops == p.hops); b &= (this.xid == p.xid); b &= (this.secs == p.secs); b &= (this.flags == p.flags); b &= (Arrays.equals(this.ciaddr, p.ciaddr)); b &= (Arrays.equals(this.yiaddr, p.yiaddr)); b &= (Arrays.equals(this.siaddr, p.siaddr)); b &= (Arrays.equals(this.giaddr, p.giaddr)); b &= (Arrays.equals(this.chaddr, p.chaddr)); b &= (Arrays.equals(this.sname, p.sname)); b &= (Arrays.equals(this.file, p.file)); b &= (this.options.equals(p.options)); b &= (this.isDhcp == p.isDhcp); // we deliberately ignore "truncated" since it is reset when cloning b &= (Arrays.equals(this.padding, p.padding)); b &= (equalsStatic (this.address, p.address)); b &= (this.port == p.port); return b; }
2
public void delete(Integer id){ Vector<String> usr = fileToVector(); FileWriter usersFile = null; PrintWriter pw = null; String key = id.toString(); try{ usersFile = new FileWriter("users.txt"); pw = new PrintWriter(usersFile); int i=0; while(i<usr.size()){ if(!usr.get(i).equals(key)){ pw.print(usr.get(i)+" "); pw.print(usr.get(i+1)+" "); pw.println(usr.get(i+2)); } i=i+3; } usersFile.close(); }catch (IOException e){ e.getStackTrace(); } } // end delete
3
private void processRequest(Packet packet) throws IOException { Packet out = null; if(packet == null) { out = Packet.getIncorrectCommandPacket(); } else { String code = packet.getCode(); if(code.equals(Packet.PACKET_CODES.REGISTRATION_CMD)) { out = register(packet); } else if(code.equals(Packet.PACKET_CODES.LOGIN_CMD)) { out = login(packet); } else if(code.equals(Packet.PACKET_CODES.LOGOUT_CMD)) { out = logout(packet); } else if(code.equals(Packet.PACKET_CODES.GET_USER_STATISTIC_CMD)) { out = getStatistic(packet); } else if(code.equals(Packet.PACKET_CODES.GET_GAME_LIST_CMD)) { out = getGameList(packet); } else if(code.equals(Packet.PACKET_CODES.NEW_GAME_CMD)) { out = createNewGame(packet); } else if(code.equals(Packet.PACKET_CODES.JOIN_TO_GAME_CMD)) { out = joinToGame(packet); } else { out = Packet.getIncorrectCommandPacket(); } } sendToClient(out); }
8
private void btnSubmit() { Factory f = new Factory(); try { String username = this.txtUsername.getText(); Authentication a = Factory.createAuthentication(); ArrayList<User> u = f.getUsers(); System.out.println(username); //System.out.println(this.txtPassword.getPassword()); if(a.authenticateUser(username, String.valueOf(this.txtPassword.getPassword()))){ for(int i = 0; i < u.size(); i++){ if(username.equals(u.get(i).getUsername())){ loggedIn = u.get(i); if(u.get(i).isClient()){ privilege = 0; log = true; break; } if(u.get(i).isTrainer()){ privilege = 1; log=true; break; } if(u.get(i).isOwner()){ privilege = 2; log=true; break; } } if(log == false){ mainUI.logOut(this); } } } if(log == false){ mainUI.logOut(this); loginError = new LoginErrorDialog(this); loginError.setVisible(true); } else{ mainUI.switchUI(this); } } catch (SQLException e) { e.printStackTrace(); connectionError = new ConnectionErrorDialog(this); connectionError.setVisible(true); } /* switch (this.txtUsername.getText()) { case "user": privilege = 0; break; case "trainer": privilege = 1; break; case "owner": privilege = 2; break; default: break; }*/ }
9
protected static void createDescriptor() { try { InputStream descriptorStream = TTC13ParseControllerGenerated.class.getResourceAsStream(DESCRIPTOR); InputStream table = TTC13ParseControllerGenerated.class.getResourceAsStream(TABLE); boolean filesystem = false; if(descriptorStream == null && new File("./" + DESCRIPTOR).exists()) { descriptorStream = new FileInputStream("./" + DESCRIPTOR); filesystem = true; } if(table == null && new File("./" + TABLE).exists()) { table = new FileInputStream("./" + TABLE); filesystem = true; } if(descriptorStream == null) throw new BadDescriptorException("Could not load descriptor file from " + DESCRIPTOR + " (not found in plugin: " + getPluginLocation() + ")"); if(table == null) throw new BadDescriptorException("Could not load parse table from " + TABLE + " (not found in plugin: " + getPluginLocation() + ")"); descriptor = DescriptorFactory.load(descriptorStream, table, filesystem ? Path.fromPortableString("./") : null); descriptor.setAttachmentProvider(TTC13ParseControllerGenerated.class); } catch(BadDescriptorException exc) { notLoadingCause = exc; Environment.logException("Bad descriptor for " + LANGUAGE + " plugin", exc); throw new RuntimeException("Bad descriptor for " + LANGUAGE + " plugin", exc); } catch(IOException exc) { notLoadingCause = exc; Environment.logException("I/O problem loading descriptor for " + LANGUAGE + " plugin", exc); throw new RuntimeException("I/O problem loading descriptor for " + LANGUAGE + " plugin", exc); } }
9
public void showProfileToFile(FileWriter f) throws IOException, ProfileNotSetException { if (this.getEmail() == "" || this.getPhone() == "" || this.getDescription() == "") { f.write("User " + this.getName() + " does not have any info set.\n"); } else { f.write("User " + this.getName() + " has the following info:\n"); f.write(" -Email: " + this.getEmail()); f.write("\n -Telephone nr: " + this.getPhone()); f.write("\n -Description: " + this.getDescription()); f.write("\n"); } }
3
@Override public Value evaluate(Value... arguments) throws Exception { // Check the number of argument if (arguments.length == 1) { // get Value Value value = arguments[0]; // If numerical if (value.getType().isNumeric()) { return new Value(new Double(Math.cos(value.getDouble()))); } if (value.getType() == ValueType.ARRAY) { Value[] vector = value.getValues(); Value result[] = new Value[vector.length]; for (int i = 0; i < vector.length; i++) { result[i] = evaluate(vector[i]); } return new Value(result); } // the type is incorrect throw new EvalException(this.name() + " function does not handle " + value.getType().toString() + " type"); } // number of argument is incorrect throw new EvalException(this.name() + " function only allows one numerical parameter"); }
4
public static String getCMDKey(final MetaData columnMD, final String line) { if (!columnMD.isAnyRecordFormatSpecified()) { // no <RECORD> elements were specified for this parse, just return the // detail id return FPConstants.DETAIL_ID; } final Iterator<Entry<String, XMLRecordElement>> mapEntries = columnMD.xmlRecordIterator(); // loop through the XMLRecordElement objects and see if we need a // different MD object while (mapEntries.hasNext()) { final Entry<String, XMLRecordElement> entry = mapEntries.next(); final XMLRecordElement recordXMLElement = entry.getValue(); if (recordXMLElement.getEndPositition() > line.length()) { // make sure our substring is not going to fail continue; } final int subfrm = recordXMLElement.getStartPosition() - 1; // convert // to 0 // based final int subto = recordXMLElement.getEndPositition(); if (line.substring(subfrm, subto).equals(recordXMLElement.getIndicator())) { // we found the MD object we want to return return entry.getKey(); } } // must be a detail line return FPConstants.DETAIL_ID; }
4
@Override public void visit(Page page) { if (!(page.getParseData() instanceof HtmlParseData)) { return; } HtmlParseData htmlParseData = (HtmlParseData)page.getParseData(); Document doc = Jsoup.parse(htmlParseData.getHtml()); Elements links = doc.select("a[href^=magnet]"); if (links.size() > 0) { for (Element link : links) { String magnetLink = link.attr("href"); MagnetURI magnet = new MagnetURI(magnetLink, "bitsnoop.com"); Element seeders = doc.select("[title^=seed]").first(); Element leechers = doc.select("[title^=leech]").first(); try { if (seeders != null) { magnet.setSeeders(DataWorker.getNumberFormat().parse(seeders.text()).intValue()); } if (leechers != null) { magnet.setLeechers(DataWorker.getNumberFormat().parse(leechers.text()).intValue()); } } catch (ParseException e) { e.printStackTrace(); } MagnetURI oldMagnet = m_parent.getMagnetLinks().putIfAbsent(magnet.getBtih(), magnet); if (oldMagnet != null) { if (oldMagnet.getSeeders() > magnet.getSeeders()) { m_parent.getMagnetLinks().put(magnet.getBtih(), magnet); } } else { m_currentSize++; } } if (m_currentSize >= m_numOfMagnetsToRead) { getMyController().shutdown(); } } }
9
public boolean is_legal_bilevel() { final DjVuInfo info = getInfo(); if(info == null) { return false; } final int width = info.width; final int height = info.height; if((width <= 0) || (height <= 0)) { return false; } final JB2Image fgJb2 = getFgJb2(); if((fgJb2 == null) || (fgJb2.width != width) || (fgJb2.height != height)) { return false; } return !(hasCodec(bgIWPixmapLock) || hasCodec(fgIWPixmapLock) || hasCodec(fgPaletteLock)); }
8
@Override public void probeEquivalence(final Node other, final Notification result) { try { final SyntaxNode syntax = (SyntaxNode) other; if (!getAttribute(Attributes.TITLE).equals(syntax.getAttribute(Attributes.TITLE))) { result.error("Titles of syntx differs: '%s' != '%s'!", getAttribute(Attributes.TITLE), syntax.getAttribute(Attributes.TITLE)); } if (!getAttribute(Attributes.META).equals(syntax.getAttribute(Attributes.META))) { result.error("Meta of syntx differs: '%s' != '%s'!", getAttribute(Attributes.META), syntax.getAttribute(Attributes.META)); } if (countChildren() != syntax.countChildren()) { result.error( "Node %s has different child count than other: %d != %d!", getNodeName(), countChildren(), syntax.countChildren() ); } final List<Node> subnodes = getChildren(); final List<Node> otherSubnodes = syntax.getChildren(); int i = 0; // NOPMD for (Node subnode : subnodes) { try { subnode.probeEquivalence(otherSubnodes.get(i), result); } catch (IndexOutOfBoundsException ex) { result.error("Other node has not the expected subnode!"); } i++; } } catch (ClassCastException ex) { result.error( "Probed node types mismatch: '%s' != '%s'!", getClass(), other.getClass() ); } }
6
private ResultSet executeQueryRS(String sql, Object[] params) { try { con = this.getConnection(); ps = con.prepareStatement(sql); for (int i = 0; i < params.length; i++) { ps.setObject(i + 1, params[i]); } rs = ps.executeQuery(); } catch (SQLException e) { System.out.println(e.getMessage()); } return rs; }
2
public final static String replaceAlls(String str, final String pairs[][]) { if((str==null) ||(pairs==null) ||(str.length()==0) ||(pairs.length==0)) return str; final StringBuilder newStr=new StringBuilder(""); boolean changed=false; for(int i=0;i<str.length();i++) { changed=false; for (final String[] pair : pairs) { if((str.charAt(i)==pair[0].charAt(0)) &&(str.substring(i).startsWith(pair[0]))) { newStr.append(pair[1]); changed=true; i=i+pair[0].length()-1; break; } } if(!changed) newStr.append(str.charAt(i)); } return newStr.toString(); }
9
public final WaiprParser.stat_return stat() throws RecognitionException { WaiprParser.stat_return retval = new WaiprParser.stat_return(); retval.start = input.LT(1); CommonTree root_0 = null; ParserRuleReturnScope globalstat54 =null; ParserRuleReturnScope localstat55 =null; try { dbg.enterRule(getGrammarFileName(), "stat"); if ( getRuleLevel()==0 ) {dbg.commence();} incRuleLevel(); dbg.location(46, 0); try { // C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:46:6: ( globalstat | localstat ) int alt15=2; try { dbg.enterDecision(15, decisionCanBacktrack[15]); int LA15_0 = input.LA(1); if ( (LA15_0==14) ) { alt15=1; } else if ( (LA15_0==ID) ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); dbg.recognitionException(nvae); throw nvae; } } finally {dbg.exitDecision(15);} switch (alt15) { case 1 : dbg.enterAlt(1); // C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:46:8: globalstat { root_0 = (CommonTree)adaptor.nil(); dbg.location(46,8); pushFollow(FOLLOW_globalstat_in_stat358); globalstat54=globalstat(); state._fsp--; adaptor.addChild(root_0, globalstat54.getTree()); } break; case 2 : dbg.enterAlt(2); // C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:47:4: localstat { root_0 = (CommonTree)adaptor.nil(); dbg.location(47,4); pushFollow(FOLLOW_localstat_in_stat363); localstat55=localstat(); state._fsp--; adaptor.addChild(root_0, localstat55.getTree()); } break; } 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 } dbg.location(47, 12); } finally { dbg.exitRule(getGrammarFileName(), "stat"); decRuleLevel(); if ( getRuleLevel()==0 ) {dbg.terminate();} } return retval; }
7
private int partition(final int p, final int r) { final int x = values[p]; int i = p - 1; int j = r + 1; while (true) { do { j--; } while (values[j] > x); do { i++; } while (values[i] < x); if (i < j) { final int v = values[i]; values[i] = values[j]; values[j] = v; final Label t = targets[i]; targets[i] = targets[j]; targets[j] = t; } else { return j; } } }
4
private ETrainerType trainerTypeMenu(){ ETrainerType trainerType = ETrainerType.NONE; do{ System.out.println("Select the energy type :"); System.out.println("1 - Item"); System.out.println("2 - Supporter"); System.out.println("3 - Stadium"); this.typedChoice = sc.nextLine(); switch(this.typedChoice){ case "1": trainerType = ETrainerType.ITEM; break; case "2": trainerType = ETrainerType.SUPPORTER; break; case "3": trainerType = ETrainerType.STADIUM; break; } }while(trainerType == ETrainerType.NONE); return trainerType; }
4
private void unloadNatives(String nativePath) { if (!natives_loaded) return; try { Field field = ClassLoader.class.getDeclaredField("loadedLibraryNames"); field.setAccessible(true); @SuppressWarnings("rawtypes") Vector libs = (Vector)field.get(getClass().getClassLoader()); String path = new File(nativePath).getCanonicalPath(); for (int i = 0; i < libs.size(); i++) { String s = (String)libs.get(i); if (s.startsWith(path)) { libs.remove(i); i--; } } } catch (Exception e) { e.printStackTrace(); } }
4
static public void main(String[] argv) throws Exception { // if (argv.length != 2) { // System.err.println("usage: java HTMLLinkExtractor [url] [file-to-process]"); // System.exit(1); // } // argv[0] should be in the form of proto://host.domain/dir/file URL aUrl = new URL("http://index.html"); File aFile = new File("D:/2013-spring/index.html"); InputStream in = new FileInputStream(aFile); String page = ""; int c = in.read(); while (c >= 0) { page += (char)c; c = in.read(); } HTMLLinkExtractor htmlExtractor = new HTMLLinkExtractor(page, aUrl); System.out.println("count of urls : " + htmlExtractor.urls.size()); htmlExtractor.printAllUrls(); }
1
private void genTajnA() { if (klientA == null || klientA.kluczPrywatny == null) { JOptionPane.showMessageDialog(null, "Naley wygenerowa klucz prywatny uytkownika A.", "Bd", JOptionPane.ERROR_MESSAGE); } else if (klientA.kluczPublicznyB == null) { JOptionPane.showMessageDialog(null, "Naley obliczy klucz publiczny uytkownika B.", "Bd", JOptionPane.ERROR_MESSAGE); } else { klientA.oblKluczaTajnego(); textField_9.setText(klientA.kluczTajny.X.b.toString()); textField_10.setText(klientA.kluczTajny.Y.b.toString()); listModel.addElement("Obliczono klucz tajny uytkownika A"); } if (klientB.kluczTajny != null) { if (klientB.kluczTajny.X.b.compareTo(klientA.kluczTajny.X.b) == 0 && klientB.kluczTajny.Y.b.compareTo(klientA.kluczTajny.Y.b) == 0) { JOptionPane.showMessageDialog(null, "Obliczone klucze tajne uytkownikw A i B s rwne!", "", JOptionPane.INFORMATION_MESSAGE); listModel.addElement("Obliczone klucze tajne uytkownikw A i B s rwne!"); } else { listModel.addElement("Obliczone klucze tajne uytkownikw A i B nie s rwne :-("); } } }
6
public void interval(int symbol, int[] result, ByteSet exclusions) { if (symbol == ArithCodeModel.EOF) symbol = EOF_INDEX; int sum = 0; for (int i = 0; i < symbol; ++i) if (!exclusions.contains(i)) sum += _count[i]; result[0] = sum; sum += _count[symbol]; result[1] = sum; for (int i = symbol+1; i < _count.length-1; ++i) if (!exclusions.contains(i)) sum += _count[i]; if (symbol != EOF_INDEX) sum += _count[EOF_INDEX]; result[2] = sum; increment(symbol); }
6
public ArrayList<Interval> merge(ArrayList<Interval> intervals) { ArrayList<Interval> result = new ArrayList<Interval>(); Collections.sort(intervals, new Comparator<Interval>(){ public int compare(Interval obj1, Interval obj2) { if (obj1.start>obj2.start) return 1; if (obj1.start<obj2.start) return -1; return 0; }}); int index = 0; while (index<intervals.size()){ int start = intervals.get(index).start; int end = intervals.get(index).end; int j = index+1; while (j<intervals.size()&&intervals.get(j).start<=end){ end = Math.max(end,intervals.get(j).end); j++; } result.add(new Interval(start,end)); index = j; } return result; }
5
public WeaponSlots getWeaponSlot(){ return weaponSlot; }
0
public void setLineGain(float gain) { if (source != null) { if (source.isControlSupported(FloatControl.Type.MASTER_GAIN)) { FloatControl volControl = (FloatControl) source.getControl(FloatControl.Type.MASTER_GAIN); float newGain = Math.min(Math.max(gain, volControl.getMinimum()), volControl.getMaximum()); volControl.setValue(newGain); } } }
2
private void readFromFile(File file){ // fieldNameFile.setText(file.getName().split(".java")[0]); fieldNameFile.setText(file.getName()); ArrayList<String> buffer =(ArrayList<String>)PreparingNewAlgos.readSourceFromFile(file); for(int i = buffer.size()-1; i>=0; i--) textArea.insert(buffer.get(i)+"\n",textArea.getRows()); }
1
@Override public void readValue(NBTInputStream input) throws IOException { while (true) { final NamedBinaryTag nbt = input.readNBT(); if (nbt == null) { return; } this.addTag(nbt); } }
2
public void computeEditKeyFr(float value) { currentTrack().setKeyFr(value); currentTrack().setRefFr(refFr); float frPerBpm = 0; currentTrack().setTempoForRef(currentTrack().getBpm()*currentTrack().getRefFr()/currentTrack().getKeyFr()); if (currentTrack().getTempoForRef() > 0) frPerBpm = currentTrack().getRefFr() / currentTrack().getTempoForRef(); if (frPerBpm > 0) { while (frPerBpm >= 2) frPerBpm /= 2; while (frPerBpm < 1) frPerBpm *= 2; } currentTrack().setFrPerBpm(frPerBpm); }
4
public void testSePeriodAfterStart_RI2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setPeriodAfterStart(new Period(-1L)); fail(); } catch (IllegalArgumentException ex) {} }
1
final public void WhileStatement() throws ParseException { /*@bgen(jjtree) WhileStatement */ BSHWhileStatement jjtn000 = new BSHWhileStatement(JJTWHILESTATEMENT); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtreeOpenNodeScope(jjtn000); try { jj_consume_token(WHILE); jj_consume_token(LPAREN); Expression(); jj_consume_token(RPAREN); Statement(); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtreeCloseNodeScope(jjtn000); } } }
8
protected void turnRight() { if (moveDirection == UP) { moveDirection = RIGHT; checkDirection = UP; } else if (moveDirection == RIGHT) { moveDirection = DOWN; checkDirection = RIGHT; } else if (moveDirection == DOWN) { moveDirection = LEFT; checkDirection = DOWN; } else if (moveDirection == LEFT) { moveDirection = UP; checkDirection = LEFT; } //PApplet.println("turnRight"); //printDirection(); }
4
public static void w(ActionCharacter x) { x.fight(); }
0
private void merge(int left, int middle, int right){ for(int printCount=left; printCount<=middle; printCount++) System.out.println("MergeSort_Adv: Elements in LeftArray == > "+inputArray[printCount]); for(int printCount=middle+1; printCount<=right; printCount++) System.out.println("MergeSort_Adv: Elements in RightArray == > "+inputArray[printCount]); int leftIndex = left; int rightIndex = middle+1; int helperIndex = left; //Important while(leftIndex<=middle && rightIndex<=right){ if(inputArray[leftIndex]<inputArray[rightIndex]){ helperArray[helperIndex++] = inputArray[leftIndex++]; }else{ helperArray[helperIndex++] = inputArray[rightIndex++]; } } while(leftIndex<=middle){ helperArray[helperIndex++] = inputArray[leftIndex++]; } while(rightIndex<=right){ helperArray[helperIndex++] = inputArray[rightIndex++]; } System.out.println("Merge STEP COMPLETED MERGED Array == > "); int i=left; while(i<helperIndex){ System.out.println(helperArray[i]); inputArray[i] = helperArray[i]; i++; } }
8
@SuppressWarnings("unchecked") private static <T extends Number> T parseNumber(String text, Class<T> targetClass) { if (text == null) { throw new IllegalArgumentException("Text must not be null"); } else if (targetClass == null) { throw new IllegalArgumentException("Target class must not be null"); } String trimmed = text.replaceAll("\\p{javaWhitespace}+", ""); if (targetClass.equals(Byte.class)) { return (T) (Byte.valueOf(trimmed)); } else if (targetClass.equals(Short.class)) { return (T) (Short.valueOf(trimmed)); } else if (targetClass.equals(Integer.class)) { return (T) (Integer.valueOf(trimmed)); } else if (targetClass.equals(Long.class)) { return (T) (Long.valueOf(trimmed)); } else if (targetClass.equals(Float.class)) { return (T) Float.valueOf(trimmed); } else if (targetClass.equals(Double.class)) { return (T) Double.valueOf(trimmed); } else { throw new IllegalArgumentException( "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]"); } }
8
public int synthesis(Packet op) { Info vi = vd.vi; // first things first. Make sure decode is ready opb.readinit(op.packet_base, op.packet, op.bytes); // Check the packet type if (opb.read(1) != 0) { // Oops. This is not an audio data packet return (-1); } // read our mode and pre/post windowsize int _mode = opb.read(vd.modebits); if (_mode == -1) { return (-1); } mode = _mode; W = vi.mode_param[mode].blockflag; if (W != 0) { lW = opb.read(1); nW = opb.read(1); if (nW == -1) { return (-1); } } else { lW = 0; nW = 0; } // more setup granulepos = op.granulepos; sequence = op.packetno - 3; // first block is third packet eofflag = op.e_o_s; // alloc pcm passback storage pcmend = vi.blocksizes[W]; if (pcm.length < vi.channels) { pcm = new float[vi.channels][]; } for (int i = 0; i < vi.channels; i++) { if (pcm[i] == null || pcm[i].length < pcmend) { pcm[i] = new float[pcmend]; } else { for (int j = 0; j < pcmend; j++) { pcm[i][j] = 0; } } } // unpack_header enforces range checking int type = vi.map_type[vi.mode_param[mode].mapping]; return (FuncMapping.mapping_P[type].inverse(this, vd.mode[mode])); }
9
public static boolean demoPauseP(boolean pauseP, Object [] MV_returnarray) { { boolean exitP = false; String input = null; if (pauseP) { System.out.print("------ pause ------"); input = InputStream.readLine(Stella.STANDARD_INPUT); System.out.println(); if (input.length() > 0) { switch (Stella.$CHARACTER_UPCASE_TABLE$.charAt(((int) (input.charAt(0))))) { case 'C': pauseP = false; break; case 'Q': if (Stella.yOrNP("Really exit demo? (y or n) ")) { pauseP = false; exitP = true; } break; case 'H': case '?': { System.out.println("Type `c' to continue without pausing,"); System.out.println(" `q' to quit from this demo,"); System.out.println(" `?' or `h' to get this message,"); System.out.println(" or any other key to continue."); } ; return (Logic.demoPauseP(pauseP, MV_returnarray)); default: break; } } } else { System.out.println(); } { boolean _return_temp = pauseP; MV_returnarray[0] = BooleanWrapper.wrapBoolean(exitP); return (_return_temp); } } }
7
public void tick() { up = keys[KeyEvent.VK_UP]; down = keys[KeyEvent.VK_DOWN]; left = keys[KeyEvent.VK_LEFT]; right = keys[KeyEvent.VK_RIGHT]; enter = keys[KeyEvent.VK_ENTER] || keys[KeyEvent.VK_E]; use = keys[KeyEvent.VK_X]; attack = keys[KeyEvent.VK_C]; escape = keys[KeyEvent.VK_ESCAPE]; for(int i = 0; i < keys.length; i++){ if(clickedBuffer[i] && !clicked[i]){ clicked[i] = true; clickedBuffer[i] = false; }else if(clicked[i]){ clicked[i] = false; } } }
5
public boolean match(PathInput input) { input.rewind(); if ((httpMethods & input.getHttpMethod()) == 0) { return false; } for (Element element : elements) { if (element == null) { continue; } if (!element.match(input)) { return false; } } return input.end(); }
4
protected static boolean fixedTimeEqual(String lhs, String rhs) { boolean equal = (lhs.length() == rhs.length() ? true : false); // If not equal, work on a single operand to have same length. if (!equal) { rhs = lhs; } int len = lhs.length(); for (int i = 0; i < len; i++) { if (lhs.charAt(i) == rhs.charAt(i)) { equal = equal && true; } else { equal = equal && false; } } return equal; }
6
public CheckResultMessage checkF05(int day) { return checkReport.checkF05(day); }
0
public static void addBlock(Block b) { if (custom.contains(b)) return; custom.add(b); }
1
@Override public int compare(Object o1, Object o2) { Aula aula1 = (Aula) o1; Periodo p1 = aula1.getPeriodo(); Aula aula2 = (Aula) o2; Periodo p2 = aula2.getPeriodo(); int flag = 0; if(aula1.getDiaDaSemana() > aula2.getDiaDaSemana() ){ flag = -1; }else if(aula1.getDiaDaSemana() < aula2.getDiaDaSemana()){ flag = 1; } else{ if(p1.getLimiteInferior().before(p2.getLimiteInferior())){ flag = -1; } else { if(p1.getLimiteInferior().after(p2.getLimiteInferior())){ flag = 1; } } } return flag; }
4
public static int ZipFiles(File[] srcfile, String zipFile) { try { // Create the ZIP file OutputStream os = new FileOutputStream(zipFile); BufferedOutputStream bs = new BufferedOutputStream(os); ZipOutputStream out = new ZipOutputStream(bs); // Compress the files for (int i = 0; i < srcfile.length; i++) { zip(srcfile[i], new File(zipFile), out, true, true); } out.closeEntry(); // Complete the ZIP file out.close(); // System.out.println("压缩完成."); return 1; } catch (IOException e) { e.printStackTrace(); return -1; } }
2
public void data( String sentence ) { String identifier = sentence.substring( 1, 6 ).replaceAll( "-", "" ); NMEASentence s; Class c; //create class object and sentence try { //get class object c = Class.forName( "com.anthonyontheweb.nmea.sentence." + identifier + "Sentence" ); //create the sentence s = (NMEASentence) c .getDeclaredConstructor( String.class ) .newInstance( sentence ); } catch (SecurityException | ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) { return; } //not null? add to our map if( s != null ) { //add the object to our map data.put( c, s ); //call event if it exists if( events.containsKey( c ) ) { events.get( c ).event( s ); } } }
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Moto other = (Moto) obj; if (!Objects.equals(this.tipo, other.tipo)) { return false; } if (!Objects.equals(this.matricula, other.matricula)) { return false; } if (!Objects.equals(this.nroMotor, other.nroMotor)) { return false; } if (!Objects.equals(this.nroChasis, other.nroChasis)) { return false; } if (!Objects.equals(this.marca, other.marca)) { return false; } if (!Objects.equals(this.modelo, other.modelo)) { return false; } return true; }
8
public static void allTests() throws IOException{ int error = 0; if(testEmptyString() == false){ error += 1; } if(testRightBraces() == false){ error += 1; } if(test1() == false){ error += 1; } /* if(testPlus() == false){ error += 1; } if(testMinus() == false){ error += 1; } if(testBrackets() == false){ error += 1; } if(testIs() == false){ error += 1; } */ if(testExtraLines() == false){ error += 1; } if(testExtraSpaces() == false){ error += 1; } System.out.print("Error: "+error+"\n"); }
5
public void run( int pageCount, boolean outputContent ) throws Exception { String seedFile = createSeedFile(pageCount); Path seedFilePath = new Path(seedFile); Configuration conf = new Configuration(); String input = Constants.SEED_INPUT; String output = Constants.POST_OUTPUT_DIR; FileSystem fileSystem = FileSystem.get(conf); Path inputPath = new Path(input); fileSystem.delete(inputPath, true); fileSystem.mkdirs(inputPath); fileSystem.copyFromLocalFile(false, true, seedFilePath, inputPath); Path outputPath = new Path(output); fileSystem.delete(outputPath, true); Job job = new Job(conf); job.setJobName("analysisjob"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setJarByClass(Crawler.class); job.setMapperClass(MapClass.class); //job.setCombinerClass(ReduceClass.class); job.setReducerClass(ReduceClass.class); //job.setPartitionerClass(PartitionerClass.class); //job.setNumReduceTasks(2); FileInputFormat.setInputPaths(job, inputPath); FileOutputFormat.setOutputPath(job, outputPath); Date startTime = new Date(); System.out.println("Job started: " + startTime); job.waitForCompletion(true); if (outputContent) { Path outputFile = new Path(output + "/" + Constants.OUTPUT_FILE); Path copyDest = new Path(ClassLoader.getSystemResource("").getFile() + Constants.POST_OUTPUT_DEST_FILE); fileSystem.copyToLocalFile(outputFile, copyDest); } Date end_time = new Date(); System.out.println("Job ended: " + end_time); System.out.println("The job took " + (end_time.getTime() - startTime.getTime()) / 1000 + " seconds."); }
1
public ComboViewer(Setting s) throws Exception { super(s); box_ = new JComboBox<>(); if (s.getType() == ValueType.ENUM) { @SuppressWarnings("unchecked") EnumSet<?> set = EnumSet.allOf(s.getValue().getEnum().getClass()); for (Object obj : set.toArray()) { box_.addItem(obj.toString()); } } else if (s.getValue().getDescriptor().hasPossbilities()) { for (Value v : s.getValue().getDescriptor().getPossibilities()) { box_.addItem(v.getString()); } } else { throw new Exception( "Setting is not an Enum and has no possibilities"); } box_.setSelectedItem(s.getValue().getString()); this.addMainComponent(box_); box_.addActionListener(this); }
5
public static void main(String[] args) throws Exception { SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(new File("jdom.xml")); Element element = doc.getRootElement(); System.out.println(element.getName()); Element student = element.getChild("学生"); System.out.println(student.getText()); @SuppressWarnings("rawtypes") List list = student.getAttributes(); for(Object a:list) { System.out.print(((Attribute)a).getName() + "="); System.out.println(((Attribute)a).getValue()); } student.removeChild("地址"); XMLOutputter out = new XMLOutputter(); out.setFormat(Format.getPrettyFormat()); out.output(element, new FileOutputStream("jdom1.xml")); }
1
private boolean diagonalIncrementingAttack(int[][] grid, LinkedList<Square> squareStore, boolean pickOne) { //Attack - Diagonal Inc if ((grid[2][0] == 2 && grid[1][1] == 2) && grid[0][2] != 1) { BuildAndAddSquareZeroTwo(squareStore); pickOne = updateGridZeroTwo(grid); } else if ((grid[1][1] == 2 && grid[0][2] == 2) && grid[2][0] != 1) { BuildAndAddSquareTwoZero(squareStore); pickOne = updateGridTwoZero(grid); } else if ((grid[2][0] == 2 && grid[0][2] == 2) && grid[1][1] != 1) { BuildAndAddSquareOneOne(squareStore); pickOne = updateGridOneOne(grid); } return pickOne; }
9
public int lancerDe(int bonusDe) { showTemp("Lancement du dé..."); int value = (int) Math.round(Math.random() * (3.0 - 1.0)) + 1; if (bonusDe == 0) { showTemp("Résultat: " + value); } else if (bonusDe > 0) { showTemp("Résultat: " + value + " (+ " + bonusDe + ")"); } else { showTemp("Résultat: " + value + " (- " + bonusDe + ")"); } return value + bonusDe; }
2
private boolean promptForNew(boolean brandNew) { // SO NOW ASK THE USER FOR A WORLD NAME String worldName = JOptionPane.showInputDialog( app.getWindow(), WORLD_NAME_REQUEST_TEXT, WORLD_NAME_REQUEST_TITLE_TEXT, JOptionPane.QUESTION_MESSAGE); // GET THE WORLD DATA WorldDataManager dataManager = app.getWorldDataManager(); // IF THE USER CANCELLED, THEN WE'LL GET A fileName // OF NULL, SO LET'S MAKE SURE THE USER REALLY // WANTS TO DO THIS ACTION BEFORE MOVING ON if ((worldName != null) && (worldName.length() > 0)) { // WE ARE STILL IN DANGER OF AN ERROR DURING THE WRITING // OF THE INITIAL FILE, SO WE'LL NOT FINALIZE ANYTHING // UNTIL WE KNOW WE CAN WRITE TO THE FILE String fileNameToTry = worldName + WORLD_FILE_EXTENSION; File fileToTry = new File(WORLDS_PATH + fileNameToTry); if (fileToTry.isDirectory()) { return false; } int selection = JOptionPane.OK_OPTION; if (fileToTry.exists()) { selection = JOptionPane.showConfirmDialog(app.getWindow(), OVERWRITE_FILE_REQUEST_TEXT_A + fileNameToTry + OVERWRITE_FILE_REQUEST_TEXT_B, OVERWRITE_FILE_REQUEST_TITLE_TEXT, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); } if (selection == JOptionPane.OK_OPTION) { // MAKE OUR NEW WORLD if (brandNew) { dataManager.reset(worldName); } // INITIALIZE THE GUI CONTROLS IF THIS IS // THE FIRST WORLD THIS SESSION app.initRegionControls(); // NOW FOR THE DATA. THIS RELOADS ALL REGIONS INTO THE TREE app.initWorldTree(); // NOW SAVE OUR NEW WORLD dataManager.save(fileToTry); // NO ERROR, SO WE'RE HAPPY saved = true; // UPDATE THE FILE NAMES AND FILE currentFileName = fileNameToTry; currentFile = fileToTry; // SELECT THE ROOT NODE, WHICH SHOULD FORCE A // TRANSITION INTO THE REGION VIEWING STATE // AND PUT THE FILE NAME IN THE TITLE BAR app.getWindow().setTitle(APP_NAME + APP_NAME_FILE_NAME_SEPARATOR + currentFileName); // WE DID IT! return true; } } // USER DECIDED AGAINST IT return false; }
6
public static void deleteFile(String realpath) { File file = new File(realpath); if (file.exists()) file.delete(); }
1
public CheckResultMessage checkL7(int day){ int r1 = get(17,5); int c1 = get(18,5); int r2 = get(30,5); int c2 = get(31,5); if(checkVersion(file).equals("2003")){ try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); if(0!=getValue(r2+7, c2+day, 10).compareTo(getValue(r1+2+day, c1+2, 6))){ return error("支付机构汇总报表<" + fileName + ">本期向备付金存管银行办理预付卡先行赎回资金结转业务金额 L7 = I03:" + day + "日错误"); } in.close(); } catch (Exception e) { } }else{ try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); if(0!=getValue(r2+7, c2+day, 10).compareTo(getValue(r1+2+day, c1+2, 6))){ return error("支付机构汇总报表<" + fileName + ">本期向备付金存管银行办理预付卡先行赎回资金结转业务金额 L7 = I03:" + day + "日错误"); } in.close(); } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">本期向备付金存管银行办理预付卡先行赎回资金结转业务金额 L7 = I03:" + day + "日错误"); }
5
@Override public boolean equals(Object object) { if (object == null) { return false; } if (object == this) { return true; } if (object instanceof Instructor) { Instructor other = (Instructor) object; return name.equals(other.getName()) && phoneNumber.equals(other.getPhoneNumber()); } return false; }
4
public void parseVariable() { String var = nameField.getText() + ";"; if(stringField.isEnabled()) { var += "S;" + stringField.getText(); } else if(intSpinner.isEnabled()) { var += "I;" + intSpinner.getValue(); } else if(booleanBox.isEnabled()) { var += "B;" + booleanBox.isSelected(); } else if(floatSpinner.isEnabled()) { var += "F;" + floatSpinner.getValue(); } listModel.add(list.getSelectedIndex(), var); listModel.remove(list.getSelectedIndex()); disableEdit(); }
4
public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PitStopMan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { PitStopMan dialog = new PitStopMan(new javax.swing.JFrame(), true, new ArrayList(), new String(), new String()); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
3
public Object retrieve(String key) { if(key == null) { return null; } totalAccess++; if(entryMap.containsKey(key)) { RREntry entry = entryMap.get(key); hitCount++; if(debug) System.out.println("Hit cache entry: " + key); return entry.value; } else if(refresherMap.containsKey(key)) { RREntry newEntry = new RREntry(key, refresherMap.get(key)); if(size > 0) { int idx = -1; if(entryMap.size() < size) { idx = entryMap.size(); } else { Random random = new Random(); idx = random.nextInt(size); entryMap.remove(keyArr[idx]); } keyArr[idx] = key; entryMap.put(key, newEntry); } if(debug) System.out.println("New cache entry: " + key); return newEntry.value; } else { if(debug) System.out.println("Please provide according refresher to initilize key!"); return null; } }
8
@Override public void executeTask() { try { m_SendingSocket = new ServerSocket(LISTEN_PORT); } catch (IOException e2) { LISTEN_PORT += 1; executeTask(); } /* Responding the client to tell them which port to connect to */ try { Server selfServer = new Server(); selfServer .setCurrentIP(InetAddress.getLocalHost().getHostAddress()); selfServer.setHostname(InetAddress.getLocalHost().getHostName()); selfServer.setReceivingPort(ReceiveRemoteMessagesTask.LISTEN_PORT); selfServer.setUsername("Server " + DCServer.getLocalHostname()); selfServer.addStringMessage("TASK_OKAY"); buffer = selfServer.toBytes(); dataGram = new DatagramPacket(buffer, buffer.length); dataGram.setPort(clientNode.getReceivingPort()); dataGram.setAddress(InetAddress.getByName(clientNode.getCurrentIP())); System.out.println("Datagram: PORT: " + clientNode.getReceivingPort() + " IP: " + clientNode.getReceivingIP()); System.out.println("Sending datagram"); SocketManager.getInstance().sendDatagram(dataGram); } catch (UnknownHostException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Listening for remote messages..."); try { m_RecievingSocket = m_SendingSocket.accept(); System.out.println("Received socket"); send = new DataOutputStream(m_RecievingSocket.getOutputStream()); // network input stream // receive = new BufferedReader(new InputStreamReader( // m_RecievingSocket.getInputStream())); inDataStream = new DataInputStream( m_RecievingSocket.getInputStream()); do { // receivedMessage = receive.readLine(); receivedMessage = inDataStream.readUTF(); System.out.println("Received: " + receivedMessage); String returnMessage = receivedMessage.toUpperCase(Locale .getDefault()); System.out.println("Sending message: " + returnMessage); send.writeUTF(returnMessage); if (receivedMessage.equalsIgnoreCase("q")) { System.out.println("Recieved QUIT command. Closing."); break; } } while (!receivedMessage.equalsIgnoreCase("q")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { send.flush(); send.close(); inDataStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } stopTask(); }
7
synchronized void backward(float[] in, float[] out){ if(_x.length<n/2){ _x=new float[n/2]; } if(_w.length<n/2){ _w=new float[n/2]; } float[] x=_x; float[] w=_w; int n2=n>>>1; int n4=n>>>2; int n8=n>>>3; // rotate + step 1 { int inO=1; int xO=0; int A=n2; int i; for(i=0; i<n8; i++){ A-=2; x[xO++]=-in[inO+2]*trig[A+1]-in[inO]*trig[A]; x[xO++]=in[inO]*trig[A+1]-in[inO+2]*trig[A]; inO+=4; } inO=n2-4; for(i=0; i<n8; i++){ A-=2; x[xO++]=in[inO]*trig[A+1]+in[inO+2]*trig[A]; x[xO++]=in[inO]*trig[A]-in[inO+2]*trig[A+1]; inO-=4; } } float[] xxx=mdct_kernel(x, w, n, n2, n4, n8); int xx=0; // step 8 { int B=n2; int o1=n4, o2=o1-1; int o3=n4+n2, o4=o3-1; for(int i=0; i<n4; i++){ float temp1=(xxx[xx]*trig[B+1]-xxx[xx+1]*trig[B]); float temp2=-(xxx[xx]*trig[B]+xxx[xx+1]*trig[B+1]); out[o1]=-temp1; out[o2]=temp1; out[o3]=temp2; out[o4]=temp2; o1++; o2--; o3++; o4--; xx+=2; B+=2; } } }
5
@Override public int getRowCount() { return size(); }
0
private int getDirection(Pair<Integer, Integer> init, Pair<Integer, Integer> target) { if (target.second - 1 == init.second) { return Mouse.UP; } else if (target.second + 1 == init.second) { return Mouse.DOWN; } else if (target.first - 1 == init.first) { return Mouse.RIGHT; } else { return Mouse.LEFT; } }
3
private void removeParentSelectionPath(TreePath p) { if (p.getPathCount() == 3 || p.getPathCount() == 4) { removeParentSelectionPath(p.getParentPath()); } super.removeSelectionPath(p); }
2
public void run(){ try{ in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream())); String inputLine; StringBuilder input = new StringBuilder(); Message msg = null; while ((inputLine = in.readLine()) != null) { if (inputLine.equalsIgnoreCase("EOM")){ msg = MessageBus.process(new Message(input.toString())); this.producer.produce(msg, true); input = new StringBuilder(); }else if(inputLine.equalsIgnoreCase("BYE")){ msg = MessageBus.process(new Message(input.toString())); this.producer.produce(msg, false); break; }else{ input.append(inputLine); } } }catch(IOException ioe){ ioe.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); }finally{ try{ in.close(); clientSocket.close(); this.producer.close(); }catch(Exception e){ e.printStackTrace(); } } }
6
private void notifyStatChange(int eventType) { try { Object[] curListeners = listeners.getListenerList(); CycWorkerEvent cwe = null; for (int i = curListeners.length-2; i>=0; i-=2) { if (curListeners[i]==CycWorkerListener.class) { if (cwe == null) { cwe = new CycWorkerEvent(this); } switch(eventType) { case CYC_WORKER_START: ((CycWorkerListener)curListeners[i+1]). notifyWorkerStarted(cwe); break; case CYC_WORKER_INTERRUPT: ((CycWorkerListener)curListeners[i+1]). notifyWorkerInterrupted(cwe); break; case CYC_WORKER_FINISHED: ((CycWorkerListener)curListeners[i+1]). notifyWorkerFinished(cwe); break; } } } } catch (Exception e) { e.printStackTrace(); } }
7
@Override public Object getValueAt(int rowIndex, int columnIndex) { if (row == null) { return ""; } switch(columnIndex) { case 0: return row.getId(); case 1: return row.getVal(); case 2: return row.getExtra(); } return null; }
4
public void sendContentProviderMail(Screen s, String data) { //System.out.println("Send mail to CP: " + data); JSONObject form = (JSONObject) JSONValue.parse(data); String email = (String) form.get("email"); String id = (String) form.get("identifier"); String provider = (String) form.get("provider"); String subject = (String) form.get("subject"); String title = (String) form.get("title"); String message = (String) form.get("message"); message = message.replaceAll("(\r\n|\n)", "<br />"); //Form validation JSONObject mailResponse = new JSONObject(); Set<String> keys = form.keySet(); boolean errors = false; for(String key : keys) { String value = (String) form.get(key); if(value==null || value.isEmpty()) { errors = true; break; } } if(errors) { mailResponse.put("status", "false"); mailResponse.put("message", "Please fill in all the fields."); s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")"); return; } String toemail = null; //Find the provider email FsNode providerNode = Fs.getNode("/domain/euscreenxl/user/" + provider + "/account/default"); if(providerNode != null){ toemail = providerNode.getProperty("email"); }else { toemail = "euscreen-portal@noterik.nl"; } String body = "Identifier: " + id + "<br/>"; body += "Title: " + title + "<br/>"; body += "Link to item on EUScreen:<br/>"; body += "<a href=\"http://euscreen.eu/item.html?id=" +id+ "\">http://euscreen.eu/item.html?id="+id+"</a><br/>"; body += "-------------------------------------------<br/><br/>"; body += "Subject: " + subject + "<br/>"; body += "Message:<br/>"; body += message + "<br/><br/>"; body += "-------------------------------------------<br/>"; body += "You can contact the sender of this message on: <a href=\"mailto:"+email+"\">"+email+"</a><br/>"; if(this.inDevelMode()){ //In devel mode always send the email to the one filled in the form toemail = email; } //!!! Hack to send the email to the one filled in the form (for testing purposes). When on production it should be removed //toemail = email; boolean success = true; if(toemail!=null) { try { mailer.sendMessage(new EuscreenCopyrightEmail(toemail, body)); } catch(Exception e) { System.out.println("Failed sending email: " + e); success = false; } } else { success = false; } String response = "Your message has been successfuly sent."; if(!success) response = "There was a problem sending your mail.<br/>Please try again later."; mailResponse.put("status", Boolean.toString(success)); mailResponse.put("message", response); s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")"); }
9
@Override public void mouseReleased(MouseEvent e) { }
0
private boolean canDoOpToChunk(int x, int z, int op) { if (x < 0 || x >= xSize) return false; if (z < 0 || z >= zSize) return false; if (chunks[x][z] == null) return false; if (chunks[x][z].opsDone[op]) return false; for (int xx = x - 2; xx <= x + 2; xx++) for (int zz = z - 2; zz <= z + 2; zz++) if (!isChunkOpDone(xx, zz, op - 1)) return false; return true; }
9
@Override public void writeTo(Movie movie, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { JsonGenerator gen = Json.createGenerator(entityStream); gen.writeStartObject() .write("id", movie.getId()) .write("name", movie.getName()) .write("actors", movie.getActors()) .writeEnd(); gen.flush(); }
1
public ArrayList<BEPlaylist> getAllPlaylists() throws Exception { try { if (m_songs == null) { m_songs = ds.getAllPlaylists(); } return m_songs; } catch (SQLException ex) { throw new Exception("Could not get songs..."); } }
2
public void afficherDecoder(ArrayList<Integer> decoding) { System.out.print("["); for (Integer tab : decoding) { System.out.print(tab + " "); } System.out.print("]"); }
1
@Override public void setCountry(String c) { super.setCountry(c); }
0
public Sprite getSpriteCollision(Sprite sprite) { // run through the list of Sprites Iterator i = map.getBullets(); while (i.hasNext()) { Sprite otherSprite = (Sprite)i.next(); if (isCollision(sprite, otherSprite)) { // collision found, return the Sprite return otherSprite; } } i = map.getSprites(); while (i.hasNext()) { Sprite otherSprite = (Sprite)i.next(); if (isCollision(sprite, otherSprite)) { // collision found, return the Sprite return otherSprite; } } i = map.getEnBul(); while (i.hasNext()) { Sprite otherSprite = (Sprite)i.next(); if (isCollision(sprite, otherSprite)) { // collision found, return the Sprite return otherSprite; } } if(map.getBoss()!=null){ if (isCollision(sprite, map.getBoss())) { // collision found, return the Sprite return map.getBoss(); } } // no collision found return null; }
8
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY); if(target==null) return false; if(!(target instanceof Weapon)) { mob.tell(L("That's not a weapon!")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),null); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); target.unWear(); if(mob.isMine(target)) mob.location().show(mob,target,CMMsg.MSG_DROP,L("<T-NAME> flies out of <S-YOUPOSS> hands!")); else mob.location().show(mob,target,CMMsg.MSG_OK_ACTION,L("<T-NAME> starts flying around!")); if(mob.location().isContent(target)) beneficialAffect(mob,target,asLevel,0); } } else mob.location().show(mob,target,CMMsg.MSG_OK_ACTION,L("<T-NAME> twitch(es) oddly, but does nothing more.")); // return whether it worked return success; }
7
public String getRegisseur() { return regisseur; }
0
public BasicFileHandler() {}
0
public String patch_addPadding(LinkedList<Patch> patches) { short paddingLength = this.Patch_Margin; String nullPadding = ""; for(short x = 1; x <= paddingLength; x++) { nullPadding += String.valueOf((char) x); } // Bump all the patches forward. for(Patch aPatch : patches) { aPatch.start1 += paddingLength; aPatch.start2 += paddingLength; } // Add some padding on start of first diff. Patch patch = patches.getFirst(); LinkedList<Diff> diffs = patch.diffs; if(diffs.isEmpty() || diffs.getFirst().operation != Operation.EQUAL) { // Add nullPadding equality. diffs.addFirst(new Diff(Operation.EQUAL, nullPadding)); patch.start1 -= paddingLength; // Should be 0. patch.start2 -= paddingLength; // Should be 0. patch.length1 += paddingLength; patch.length2 += paddingLength; } else if(paddingLength > diffs.getFirst().text.length()) { // Grow first equality. Diff firstDiff = diffs.getFirst(); int extraLength = paddingLength - firstDiff.text.length(); firstDiff.text = nullPadding.substring(firstDiff.text.length()) + firstDiff.text; patch.start1 -= extraLength; patch.start2 -= extraLength; patch.length1 += extraLength; patch.length2 += extraLength; } // Add some padding on end of last diff. patch = patches.getLast(); diffs = patch.diffs; if(diffs.isEmpty() || diffs.getLast().operation != Operation.EQUAL) { // Add nullPadding equality. diffs.addLast(new Diff(Operation.EQUAL, nullPadding)); patch.length1 += paddingLength; patch.length2 += paddingLength; } else if(paddingLength > diffs.getLast().text.length()) { // Grow last equality. Diff lastDiff = diffs.getLast(); int extraLength = paddingLength - lastDiff.text.length(); lastDiff.text += nullPadding.substring(0, extraLength); patch.length1 += extraLength; patch.length2 += extraLength; } return nullPadding; }
8
@Override public void keyTyped(KeyEvent event) { if (event.getKeyChar() == 'q') { hasQuit = true; } }
1
private double[] sampleFlows() { double[] sample = new double[flows.length]; for (int i = 0; i < flows.length; i++) { sample[i] = flows[i].sample(); } return sample; }
1
public boolean matches( Class<?> clazz ) { Annotation fromElement = clazz.getAnnotation( this.annotation.annotationType() ); return this.annotation.equals( fromElement ); }
1
private static X509Certificate[] getX509CertsFromStringList( String[] paramArrayOfString1, String[] paramArrayOfString2) throws CertificateException { CertificateFactory localCertificateFactory = CertificateFactory .getInstance("X.509"); ArrayList localArrayList = new ArrayList(paramArrayOfString1.length); for (int i = 0; i < paramArrayOfString1.length; i++) { int j = -1; String str = paramArrayOfString1[i]; if (str != null) { j = str.indexOf("-----BEGIN CERTIFICATE-----"); } if (j >= 0) { str = str.substring(j); // Read String and remove white spaces Scanner scanner = new Scanner(str); StringBuilder stringBuilder = new StringBuilder(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); stringBuilder.append(line.trim()); stringBuilder.append("\n"); } scanner.close(); ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream( stringBuilder.toString().getBytes()); try { X509Certificate localX509Certificate = (X509Certificate) localCertificateFactory .generateCertificate(localByteArrayInputStream); localArrayList.add(localX509Certificate); } catch (Exception localException) { if (paramArrayOfString2 != null) { logger.warning(paramArrayOfString2[i] + " can not be parsed as an X509Certificate."); } else { logger.warning("failed to parse an X509Certificate"); } } } } if (localArrayList.isEmpty()) { return null; } return (X509Certificate[]) localArrayList .toArray(new X509Certificate[0]); }
7
public MapData createBasicMap(){ for(int y=0;y<mapData.HEIGHT;y++){ for(int x=0;x<mapData.WIDTH;x++){ mapData.map[y][x] = dict.getTile('.'); if(x == 0 || x == mapData.WIDTH-1 || y == 0 || y == mapData.HEIGHT-1){ mapData.map[y][x] = dict.getTile('#'); } } } return mapData; }
6
public static String numberToWords(int number) { // Zero Rule if (number == 0) { return smallNumbers[0]; } // Array to hold four three digits group int[] digitGroups = new int[4]; // Ensure the number is positive to extract from int positiveNumber = Math.abs(number); // Extract the three-digits group for (int i = 0; i < digitGroups.length; i++) { digitGroups[i] = positiveNumber % 1000; positiveNumber /= 1000; } // Convert each three-digit group to words String[] groupText = new String[4]; for (int i = 0; i < groupText.length; i++) { groupText[i] = Main.threeDigitsGroupToWords(digitGroups[i]); } // Recombine the three digits groups String combined = groupText[0]; boolean appendAnd; // Determine whether an 'and' is needed appendAnd = (digitGroups[0] > 0) && (digitGroups[0] < 100); // Process the remaining groups in turn, smallest to largest for (int i = 1; i < groupText.length; i++) { if (digitGroups[i] != 0) { // Only add non-zero items String prefix = groupText[i] + " " + scale[i]; if (combined.length() != 0) { prefix += appendAnd ? " and " : ", "; } // Opportunity to add 'and' is ended appendAnd = false; // And the three-digit group to the combined string combined = prefix + combined; } } // Negative Rule if (number < 0) { combined = "Negative " + combined; } return combined; }
9
public void setAlgorithm(String value) { this.algorithm = value; }
0
public void analyseData(String path, int skipf) throws IOException { int amount = new File(path).listFiles().length; for (int i = 1; i <= amount; i += skipf) { DecimalFormat format = new DecimalFormat("0000000"); BufferedImage img = ImageIO.read(new File(path + "image-" + format.format(i) + ".png")); // if ((i - 1) % (skipf * 10) == 0) // System.out.println("image-" + format.format(i) + ".png"); // Progress line (debug) if ((i - 1) % 50 == 0) System.out.print("."); for (int x = 0; x < img.getWidth(); x++) for (int y = 0; y < img.getHeight(); y++) { Color c = new Color(img.getRGB(x, y)); float[] d = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), null); // HSB colors int curIndex = Math.round(d[0] * colors); if (curIndex == colors) curIndex--; if (d[2] <= COLORS_BRIGHTNESS[INDEX_DARK]) hsbColors[INDEX_DARK][curIndex].count = hsbColors[INDEX_DARK][curIndex].count.add(BigInteger.ONE); else if (d[2] > COLORS_BRIGHTNESS[INDEX_DARK] && d[1] > COLORS_BRIGHTNESS[INDEX_DARK]) hsbColors[INDEX_MEDIUM][curIndex].count = hsbColors[INDEX_MEDIUM][curIndex].count.add(BigInteger.ONE); else if (d[2] >= COLORS_BRIGHTNESS[INDEX_BRIGHT]) hsbColors[INDEX_BRIGHT][curIndex].count = hsbColors[INDEX_BRIGHT][curIndex].count.add(BigInteger.ONE); hsbColors[INDEX_AVERAGE][curIndex].count = hsbColors[INDEX_AVERAGE][curIndex].count.add(BigInteger.ONE); } } System.out.println(); }
9
public boolean generate(World var1, Random var2, int var3, int var4, int var5) { for(int var6 = 0; var6 < 64; ++var6) { int var7 = var3 + var2.nextInt(8) - var2.nextInt(8); int var8 = var4 + var2.nextInt(4) - var2.nextInt(4); int var9 = var5 + var2.nextInt(8) - var2.nextInt(8); if(var1.isAirBlock(var7, var8, var9) && ((BlockFlower)Block.blocksList[this.plantBlockId]).canBlockStay(var1, var7, var8, var9)) { var1.setBlock(var7, var8, var9, this.plantBlockId); } } return true; }
3
public boolean isOptOut() { synchronized(optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
4
public String nextString() { String returnedString = null; if(length == 0){ returnedString = ""; } else{ for (int idx = 0; idx < buf.length; ++idx){ buf[idx] = symbols[random.nextInt(symbols.length)]; returnedString = new String(buf); } } return returnedString; }
2
private String getUpdatedLogPropertiesFileContent() { final File propertiesFile = new File(logPropertiesFile); final String logRegex = ".*<file>(.*?)</file>.*"; final String logBackupRegex = ".*<fileNamePattern>(.*?)</fileNamePattern>.*"; final String logPath = (new File(logFilePath, logFileName)).getPath(); final String logBackupPath = (new File(logFilePath, logBackupFileName)).getPath(); String fileContent = ""; try { fileContent = new Scanner(propertiesFile, "UTF-8").useDelimiter("\\A").next(); } catch (FileNotFoundException ex) { log.error("Unable to open the logging configuration of the application.\nError: {}", ex.getLocalizedMessage()); } String changedContent = fileContent; changedContent = replaceInString(logRegex, changedContent, logPath); changedContent = replaceInString(logBackupRegex, changedContent, logBackupPath); // If changedContent equals fileContent, the file doesn't need to be overwritten, so we // return null. if (changedContent != null && !changedContent.equals(fileContent)) { return changedContent; } else { return null; } }
3
private void display() { blitNumber((int) totalFps, 5, 2); blitNumber((int) lastPps, 5, 12); plantMan.drawRadar(buffer, car); if (!openGL) { if (!fullscreen) { buffer.display(gFrame, leftBorderWidth, titleBarHeight); } else { Graphics g=bufferStrategy.getDrawGraphics(); g.drawImage(buffer.getOutputBuffer(), 0, 0, null); bufferStrategy.show(); g.dispose(); } } else { buffer.displayGLOnly(); } }
2
public static void main(String[] args) { try { String input = null; boolean outTime = false; for(int i = 0; i<args.length; i++) { switch(args[i]) { case "-time": outTime = true; break; default: // default is intput file name, will only execute // a single file, so last one read will win. input = args[i]; break; } } if(input == null) { System.out.println("No input file provided"); System.exit(1); } int[] code = DLXutil.readCode(input); DLX.load(code); int time = DLX.execute(); if(outTime) { System.err.print(time); } System.exit(0); } catch (Exception e) { System.out.println("An error occured"); System.exit(-1); } }
5
public void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CustomerAccount_SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CustomerAccount_SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CustomerAccount_SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CustomerAccount_SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CustomerAccount_SignUp(db).setVisible(true); } }); }
6
public void mousePressed(MouseEvent e){ int loop; if (!holdingTurret && !sellOrUndo.contains(mX, mY)){ for (loop = 0; loop < turretBuilder.size(); loop++){ if (turretBuilder.get(loop).turretArea().contains(mX, mY)){ turretBuilder.get(loop).changeFocus(true); } else{ turretBuilder.get(loop).changeFocus(false); } } } repaint(); }
4
public static HolidayTypeEnumerationx fromValue(DayTypeEnumeration v) { for (HolidayTypeEnumerationx c: HolidayTypeEnumerationx.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v.toString()); }
2
protected void invoke() { // Reads the memory address register int address = Integer.parseInt(registerStore.readFrom(Register.MAR)); try { // Finds what memory operation should be performed switch(Integer.parseInt(registerStore.readFrom(Register.MRW))) { case 0 : //read String value = get(address); // Informs listeners for(MemoryListener listener : getMemoryListeners()) { listener.memoryReadFrom(this, address, value); } // Writes the value to the Memory data register registerStore.writeTo(Register.MDR, value); break; case 1 : //write String data = registerStore.readFrom(Register.MDR); // Writes the vaue from the Memory data register to memory put(address, data); // Informs listeners for(MemoryListener listener : getMemoryListeners()) { listener.memoryWroteTo(this, address, data); } break; } }catch (Exception e) { // Inform listeners of error for(MemoryListener listener : getMemoryListeners()) { listener.memoryError(this, new Exception("Invalid memory address " + address)); } } }
6
private boolean isFinished(Algebra algebra, SolveFor solveFor) { switch(solveFor) { case SOLVE: return algebra instanceof Equation && isSolved((Equation) algebra); case SIMPLIFY: return algebra instanceof AlgebraicParticle && isSimplified((AlgebraicParticle)algebra) || algebra instanceof Expression && (isFirstDegreeExpression((Expression) algebra)); case FACTOR: return algebra instanceof Term; default: return false; } }
7
public void update() { for(int i = 0; i < collidable.size(); i++) { if(collidable.get(i).getAttachedEntity().isDead()) { collidable.remove(i); } } }
2