List of usage examples for java.util ArrayList clear
public void clear()
From source file:com.att.nsa.cambria.service.impl.MMServiceImpl.java
private void pushEvents(DMaaPContext ctx, String topic, InputStream msg, String defaultPartition, boolean chunked, String mediaType) throws ConfigDbException, AccessDeniedException, TopicExistsException, CambriaApiException, IOException { final MetricsSet metricsSet = ctx.getConfigReader().getfMetrics(); // setup the event set final CambriaEventSet events = new CambriaEventSet(mediaType, msg, chunked, defaultPartition); // start processing, building a batch to push to the backend final long startMs = System.currentTimeMillis(); long count = 0; long maxEventBatch = 1024 * 16; String batchlen = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, BATCH_LENGTH); if (null != batchlen) maxEventBatch = Long.parseLong(batchlen); // long maxEventBatch = // ctx.getConfigReader().getSettings().getLong(BATCH_LENGTH, 1024 * 16); final LinkedList<Publisher.message> batch = new LinkedList<Publisher.message>(); final ArrayList<KeyedMessage<String, String>> kms = new ArrayList<KeyedMessage<String, String>>(); try {//from w w w . j a v a 2s. c o m // for each message... Publisher.message m = null; while ((m = events.next()) != null) { // add the message to the batch batch.add(m); final KeyedMessage<String, String> data = new KeyedMessage<String, String>(topic, m.getKey(), m.getMessage()); kms.add(data); // check if the batch is full final int sizeNow = batch.size(); if (sizeNow > maxEventBatch) { ctx.getConfigReader().getfPublisher().sendBatchMessage(topic, kms); kms.clear(); batch.clear(); metricsSet.publishTick(sizeNow); count += sizeNow; } } // send the pending batch final int sizeNow = batch.size(); if (sizeNow > 0) { ctx.getConfigReader().getfPublisher().sendBatchMessage(topic, kms); kms.clear(); batch.clear(); metricsSet.publishTick(sizeNow); count += sizeNow; } final long endMs = System.currentTimeMillis(); final long totalMs = endMs - startMs; LOG.info("Published " + count + " msgs in " + totalMs + "ms for topic " + topic); // build a responseP final JSONObject response = new JSONObject(); response.put("count", count); response.put("serverTimeMs", totalMs); // DMaaPResponseBuilder.respondOk(ctx, response); } catch (Exception excp) { int status = HttpStatus.SC_NOT_FOUND; String errorMsg = null; if (excp instanceof CambriaApiException) { status = ((CambriaApiException) excp).getStatus(); JSONTokener jsonTokener = new JSONTokener(((CambriaApiException) excp).getBody()); JSONObject errObject = new JSONObject(jsonTokener); errorMsg = (String) errObject.get("message"); } ErrorResponse errRes = new ErrorResponse(status, DMaaPResponseCode.PARTIAL_PUBLISH_MSGS.getResponseCode(), errorMessages.getPublishMsgError() + ":" + topic + "." + errorMessages.getPublishMsgCount() + count + "." + errorMsg, null, Utils.getFormattedDate(new Date()), topic, null, ctx.getRequest().getRemoteHost(), null, null); LOG.info(errRes.toString()); throw new CambriaApiException(errRes); } }
From source file:mp.teardrop.SongTimeline.java
/** * Run the given query and add the results to the song timeline. * * @param context A context to use./*w w w. ja va2 s . c om*/ * @param query The query to be run. The mode variable must be initialized * to one of SongTimeline.MODE_*. The type and data variables may also need * to be initialized depending on the given mode. * @return The number of songs that were added. */ public int addSongs(Context context, QueryTask query) { Cursor cursor = query.runQuery(context.getContentResolver()); if (cursor == null) { return 0; } int count = cursor.getCount(); if (count == 0) { return 0; } int mode = query.mode; int type = query.type; long data = query.data; ArrayList<Song> timeline = mSongs; synchronized (this) { saveActiveSongs(); switch (mode) { case MODE_ENQUEUE: case MODE_ENQUEUE_POS_FIRST: case MODE_ENQUEUE_ID_FIRST: break; case MODE_PLAY_NEXT: timeline.subList(mCurrentPos + 1, timeline.size()).clear(); break; case MODE_PLAY: case MODE_PLAY_POS_FIRST: case MODE_PLAY_ID_FIRST: timeline.clear(); mCurrentPos = 0; break; default: throw new IllegalArgumentException("Invalid mode: " + mode); } int start = timeline.size(); Song jumpSong = null; for (int j = 0; j != count; ++j) { cursor.moveToPosition(j); Song song = new Song(-1); song.populate(cursor); timeline.add(song); if (jumpSong == null) { if ((mode == MODE_PLAY_POS_FIRST || mode == MODE_ENQUEUE_POS_FIRST) && j == data) { jumpSong = song; } else if (mode == MODE_PLAY_ID_FIRST || mode == MODE_ENQUEUE_ID_FIRST) { long id; switch (type) { /* case MediaUtils.TYPE_ARTIST: id = song.artistId; break; case MediaUtils.TYPE_ALBUM: id = song.albumId; break; case MediaUtils.TYPE_SONG: id = song.id; break; */ default: throw new IllegalArgumentException("Unsupported id type: " + type); } /* if (id == data) jumpSong = song; */ } } } if (mShuffleMode != SHUFFLE_NONE) MediaUtils.shuffle(timeline.subList(start, timeline.size()), mShuffleMode == SHUFFLE_ALBUMS); if (jumpSong != null) { int jumpPos = timeline.indexOf(jumpSong); if (jumpPos != start) { // Get the sublist twice to avoid a ConcurrentModificationException. timeline.addAll(timeline.subList(start, jumpPos)); timeline.subList(start, jumpPos).clear(); } } broadcastChangedSongs(); } changed(); return count; }
From source file:europarl.PhraseTranslation.java
public boolean getFromGz(String fileName, String targetWord, int limit) { String strLine;/*www .ja v a2 s . co m*/ ArrayList<String> line_triple = new ArrayList<String>(); BufferedReader gzipReader; Pattern word_align = Pattern.compile("(\\w+) \\(\\{(.*?)\\}\\) "); Bag<String> words_list = new Bag<String>(); //Set of ALL words: it will be the list of attributes ArrayList<PhraseTranslation> translations = new ArrayList<PhraseTranslation>(); try { gzipReader = new BufferedReader( new InputStreamReader(new GZIPInputStream(new FileInputStream(fileName)))); while ((strLine = gzipReader.readLine()) != null) //read-everything { line_triple.add(strLine); if (line_triple.size() == 3) //triple finished { //TODO: match only complete words //TODO: stem it before doing this Matcher matcher = word_align.matcher(line_triple.get(2)); String[] foreign_words = line_triple.get(1).split(" "); line_triple.clear(); if (!strLine.contains(targetWord)) //skip it continue; ArrayList<String> e_phrase = new ArrayList<String>(); String translation = ""; while (matcher.find()) //each iteration is word +alignment { assert matcher.groupCount() == 2; String e_word = matcher.group(1).trim(); if (e_word.equals("NULL")) e_word = ""; if (stopwordsList.contains(e_word)) continue; if (stemmer != null) e_word = stemmer.stem(e_word); e_phrase.add(e_word); words_list.add(e_word); //we don't care about the alignment of non-target words if (!e_word.equals(targetWord)) continue; //parse the { x y z } alignment part ArrayList<Integer> f_words = new ArrayList<Integer>(); translation = ""; //for each number between curly brackets for (String number : matcher.group(2).split(" ")) { if (!number.isEmpty()) { int n_word = Integer.parseInt(number) - 1; f_words.add(n_word); translation += foreign_words[n_word] + " "; } } // end of curly brackets for } //end of word+alignment while if (!translation.isEmpty()) { PhraseTranslation trans = new PhraseTranslation(e_phrase, translation); translations.add(trans); } line_triple.clear(); } //end of triple-finished if if (translations.size() == limit) break; //stop collecting! } //end of the read-everything while } catch (Exception e) { log.error("Error: " + e); e.printStackTrace(); return false; } //what we NOW have: a set of attributes in HashSet<String>words_list //a ArrayList<PhraseTranslation> translations log.info("Collected " + translations.size() + " phrases and " + words_list.size() + " words"); postProcessData(translations, words_list); //now convert the data we collected to Weka data //we needed to do "double passing" because we need to initialize //the dataset with the complete list of attributes //this will convert word to attributes: they are all "boolean" ArrayList<Attribute> attrs = new ArrayList<Attribute>(); HashMap<String, Attribute> attrs_map = new HashMap<String, Attribute>(); Attribute att; for (String word : words_list) { att = new Attribute(word); attrs.add(att); attrs_map.put(word, att); } //now we need to manage class. //each translation is a class, so we need to get all of them HashMap<String, Integer> class_map = new HashMap<String, Integer>(); ArrayList<String> classes = new ArrayList<String>(); for (PhraseTranslation phraseTranslation : translations) { if (!class_map.containsKey(phraseTranslation.getTranslatedWord())) { class_map.put(phraseTranslation.getTranslatedWord(), classes.size()); classes.add(phraseTranslation.getTranslatedWord()); } } log.info(targetWord + " has " + classes.size() + " translations:"); if (log.isInfoEnabled()) for (String translation : classes) System.out.println(translation); att = new Attribute("%class", classes); attrs.add(att); attrs_map.put("%class", att); dataSet = new Instances("dataset", attrs, 0); for (PhraseTranslation phraseTranslation : translations) { SparseInstance inst = new SparseInstance(attrs.size()); //set everything to 0 for (int i = 0; i < attrs.size(); i++) inst.setValue(i, 0); //set present word to 1 for (String word : phraseTranslation.getPhraseWords()) inst.setValue(attrs_map.get(word), 1); //set class of instance inst.setValue(attrs_map.get("%class"), class_map.get(phraseTranslation.getTranslatedWord())); dataSet.add(inst); } return true; }
From source file:com.yoctopuce.YoctoAPI.YColorLedCluster.java
/** * Returns a list on 24bit RGB color values with the current colors displayed on * the RGB leds. The first number represents the RGB value of the first LED, * the second number represents the RGB value of the second LED, etc. * * @param ledIndex : index of the first LED which should be returned * @param count : number of LEDs which should be returned * * @return a list of 24bit color codes with RGB components of selected LEDs, as 0xRRGGBB. * * @throws YAPI_Exception on error/* w ww . j a v a2 s.c o m*/ */ public ArrayList<Integer> get_rgbColorArray(int ledIndex, int count) throws YAPI_Exception { byte[] buff; ArrayList<Integer> res = new ArrayList<Integer>(); int idx; int r; int g; int b; // may throw an exception buff = _download(String.format("rgb.bin?typ=0&pos=%d&len=%d", 3 * ledIndex, 3 * count)); res.clear(); idx = 0; while (idx < count) { r = buff[3 * idx]; g = buff[3 * idx + 1]; b = buff[3 * idx + 2]; res.add(r * 65536 + g * 256 + b); idx = idx + 1; } return res; }
From source file:com.yoctopuce.YoctoAPI.YColorLedCluster.java
/** * Returns a list on 24bit RGB color values with the RGB LEDs startup colors. * The first number represents the startup RGB value of the first LED, * the second number represents the RGB value of the second LED, etc. * * @param ledIndex : index of the first LED which should be returned * @param count : number of LEDs which should be returned * * @return a list of 24bit color codes with RGB components of selected LEDs, as 0xRRGGBB. * * @throws YAPI_Exception on error/*from w w w . j a v a2s.c o m*/ */ public ArrayList<Integer> get_rgbColorArrayAtPowerOn(int ledIndex, int count) throws YAPI_Exception { byte[] buff; ArrayList<Integer> res = new ArrayList<Integer>(); int idx; int r; int g; int b; // may throw an exception buff = _download(String.format("rgb.bin?typ=4&pos=%d&len=%d", 3 * ledIndex, 3 * count)); res.clear(); idx = 0; while (idx < count) { r = buff[3 * idx]; g = buff[3 * idx + 1]; b = buff[3 * idx + 2]; res.add(r * 65536 + g * 256 + b); idx = idx + 1; } return res; }
From source file:edu.harvard.i2b2.adminTool.dataModel.ConceptTableModel.java
public void fillDataFromTable(ArrayList<ArrayList<ConceptTableRow>> list) { list.clear(); ConceptTableRow row = null;/*from w ww.java 2s. co m*/ ArrayList<ConceptTableRow> group = null; Integer curRow = null; LinkedHashMap<Integer, ArrayList<ConceptTableRow>> rowMap = new LinkedHashMap<Integer, ArrayList<ConceptTableRow>>(); for (int i = 1; i < rowCount; i++) { row = new ConceptTableRow(); curRow = new Integer((String) content.get("0/" + i)); row.rowNumber = curRow.intValue(); if (!rowMap.containsKey(curRow)) { group = new ArrayList<ConceptTableRow>(); list.add(group); rowMap.put(curRow, group); } else { group = rowMap.get(curRow); } row.conceptName = (String) content.get("1/" + i); row.dateText = (String) content.get("2/" + i); row.valueText = (String) content.get("3/" + i); row.modifierText = (String) content.get("4/" + i); row.height = (String) content.get("5/" + i); row.color = (RGB) content.get("6/" + i); row.conceptXml = (String) content.get("7/" + i); row.data = (QueryModel) content.get("8/" + i); row.rowId = i; group.add(row); } }
From source file:com.yoctopuce.YoctoAPI.YColorLedCluster.java
/** * Returns a list on 32 bit signatures for specified blinking sequences. * Since blinking sequences cannot be read from the device, this can be used * to detect if a specific blinking sequence is already programmed. * * @param seqIndex : index of the first blinking sequence which should be returned * @param count : number of blinking sequences which should be returned * * @return a list of 32 bit integer signatures * * @throws YAPI_Exception on error//from w w w .j a v a 2 s . co m */ public ArrayList<Integer> get_blinkSeqSignatures(int seqIndex, int count) throws YAPI_Exception { byte[] buff; ArrayList<Integer> res = new ArrayList<Integer>(); int idx; int hh; int hl; int lh; int ll; // may throw an exception buff = _download(String.format("rgb.bin?typ=2&pos=%d&len=%d", 4 * seqIndex, 4 * count)); res.clear(); idx = 0; while (idx < count) { hh = buff[4 * idx]; hl = buff[4 * idx + 1]; lh = buff[4 * idx + 2]; ll = buff[4 * idx + 3]; res.add(((hh) << (24)) + ((hl) << (16)) + ((lh) << (8)) + ll); idx = idx + 1; } return res; }
From source file:com.mwang.irregulargridview.DynamicItemAnimator.java
@Override public void runPendingAnimations() { boolean removalsPending = !mPendingRemovals.isEmpty(); boolean movesPending = !mPendingMoves.isEmpty(); boolean changesPending = !mPendingChanges.isEmpty(); boolean additionsPending = !mPendingAdditions.isEmpty(); if (!removalsPending && !movesPending && !additionsPending && !changesPending) { // nothing to animate return;/*ww w. jav a 2 s . c om*/ } // First, remove stuff for (RecyclerView.ViewHolder holder : mPendingRemovals) { animateRemoveImpl(holder); } mPendingRemovals.clear(); // Next, move stuff if (movesPending) { final ArrayList<MoveInfo> moves = new ArrayList<>(); moves.addAll(mPendingMoves); mMovesList.add(moves); mPendingMoves.clear(); Runnable mover = new Runnable() { @Override public void run() { for (MoveInfo moveInfo : moves) { animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, moveInfo.toX, moveInfo.toY, moveInfo.fromWidth, moveInfo.fromHeight, moveInfo.toWidth, moveInfo.toHeight); } moves.clear(); mMovesList.remove(moves); } }; if (removalsPending) { View view = moves.get(0).holder.itemView; ViewCompat.postOnAnimationDelayed(view, mover, getRemoveDuration()); } else { mover.run(); } } // Next, change stuff, to run in parallel with move animations if (changesPending) { final ArrayList<ChangeInfo> changes = new ArrayList<>(); changes.addAll(mPendingChanges); mChangesList.add(changes); mPendingChanges.clear(); Runnable changer = new Runnable() { @Override public void run() { for (ChangeInfo change : changes) { animateChangeImpl(change); } changes.clear(); mChangesList.remove(changes); } }; if (removalsPending) { RecyclerView.ViewHolder holder = changes.get(0).oldHolder; ViewCompat.postOnAnimationDelayed(holder.itemView, changer, getRemoveDuration()); } else { changer.run(); } } // Next, add stuff if (additionsPending) { final ArrayList<RecyclerView.ViewHolder> additions = new ArrayList<>(); additions.addAll(mPendingAdditions); mAdditionsList.add(additions); mPendingAdditions.clear(); Runnable adder = new Runnable() { public void run() { for (RecyclerView.ViewHolder holder : additions) { animateAddImpl(holder); } additions.clear(); mAdditionsList.remove(additions); } }; if (removalsPending || movesPending || changesPending) { long removeDuration = removalsPending ? getRemoveDuration() : 0; long moveDuration = movesPending ? getMoveDuration() : 0; long changeDuration = changesPending ? getChangeDuration() : 0; long totalDelay = removeDuration + Math.max(moveDuration, changeDuration); View view = additions.get(0).itemView; ViewCompat.postOnAnimationDelayed(view, adder, totalDelay); } else { adder.run(); } } }
From source file:com.pdftron.pdf.controls.OutlineDialogFragment.java
private ArrayList<Bookmark> getBookmarkList(Bookmark firstSibling) { ArrayList<Bookmark> bookmarkList = new ArrayList<Bookmark>(); if (mPDFViewCtrl != null) { try {//from ww w . ja va2 s . c om Bookmark current; if (firstSibling == null) { current = mPDFViewCtrl.getDoc().getFirstBookmark(); } else { current = firstSibling; } int numBookmarks = 0; while (current.isValid()) { bookmarkList.add(current); current = current.getNext(); numBookmarks++; } if (firstSibling == null && numBookmarks == 1) { ArrayList<Bookmark> bookmarkListNextLevel = new ArrayList<Bookmark>(); bookmarkListNextLevel .addAll(getBookmarkList(mPDFViewCtrl.getDoc().getFirstBookmark().getFirstChild())); if (bookmarkListNextLevel.size() > 0) { return bookmarkListNextLevel; } } } catch (PDFNetException e) { bookmarkList.clear(); } } return bookmarkList; }
From source file:de.ovgu.featureide.featurehouse.FeatureHouseComposer.java
@Override public void buildFSTModel() { if (featureProject == null) { return;// w w w . j a v a 2 s . c om } final String configPath; IFile currentConfiguration = featureProject.getCurrentConfiguration(); if (currentConfiguration != null) { configPath = currentConfiguration.getRawLocation().toOSString(); } else { configPath = featureProject.getProject().getFile(".project").getRawLocation().toOSString(); } final String basePath = featureProject.getSourcePath(); final String outputPath = featureProject.getBuildPath(); if (configPath == null || basePath == null || outputPath == null) return; composer = new FSTGenComposerExtension(); composer.addParseErrorListener(listener); List<String> featureOrderList = featureProject.getFeatureModel().getConcreteFeatureNames(); String[] features = new String[featureOrderList.size()]; int i = 0; for (String f : featureOrderList) { features[i++] = f; } try { ((FSTGenComposerExtension) composer) .buildFullFST(getArguments(configPath, basePath, outputPath, getContractParameter()), features); } catch (TokenMgrError e) { createBuilderProblemMarker(getTokenMgrErrorLine(e.getMessage()), getTokenMgrErrorMessage(e.getMessage())); } catch (Error e) { LOGGER.logError(e); } ArrayList<FSTNode> fstnodes = composer.getFstnodes(); if (fstnodes != null) { fhModelBuilder.buildModel(fstnodes, false); fstnodes.clear(); } }