Java Code Examples for java.util.List.get()

The following are Jave code examples for showing how to use get() of the java.util.List class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Tribe   File: ChooseCountryFragment.java   View Source Code Vote up 8 votes
private void clickCountry(List<String> countryNames,int i){
    String northName = countryNames.get(i);

    for (int j = 0; j < mOpenCountries.size(); j++) {
        ChooseCountryBean countryBean = mOpenCountries.get(j);
        String name = countryBean.getName();
        String country_id = countryBean.getCountry_id();
        if(northName.equals(name)){
            isContains = true;
            Intent north = new Intent();
            north.putExtra("countryName",northName);
            north.putExtra("countryId",country_id);
            getActivity().setResult(Activity.RESULT_OK,north);
            getActivity().finish();
        }
    }

    if (!isContains){
        Toast.makeText(getContext(),"该国家暂时没有开放",Toast.LENGTH_SHORT).show();
    }
}
 
Example 2
Project: okwallet   File: BloomFilter.java   View Source Code Vote up 7 votes
/**
 * Creates a new FilteredBlock from the given Block, using this filter to select transactions. Matches can cause the
 * filter to be updated with the matched element, this ensures that when a filter is applied to a block, spends of
 * matched transactions are also matched. However it means this filter can be mutated by the operation. The returned
 * filtered block already has the matched transactions associated with it.
 */
public synchronized FilteredBlock applyAndUpdate(Block block) {
    List<Transaction> txns = block.getTransactions();
    List<Sha256Hash> txHashes = new ArrayList<>(txns.size());
    List<Transaction> matched = Lists.newArrayList();
    byte[] bits = new byte[(int) Math.ceil(txns.size() / 8.0)];
    for (int i = 0; i < txns.size(); i++) {
        Transaction tx = txns.get(i);
        txHashes.add(tx.getHash());
        if (applyAndUpdate(tx)) {
            Utils.setBitLE(bits, i);
            matched.add(tx);
        }
    }
    PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(block.getParams(), bits, txHashes);
    FilteredBlock filteredBlock = new FilteredBlock(block.getParams(), block.cloneAsHeader(), pmt);
    for (Transaction transaction : matched)
        filteredBlock.provideTransaction(transaction);
    return filteredBlock;
}
 
Example 3
Project: BachelorPraktikum   File: VaultDao.java   View Source Code Vote up 7 votes
/**
 * This is used to query a single Event ({@link VaultEntry} before a given point in time.
 * This is useful to determine why certain events might have happened (correlation of events).
 *
 * @param timestamp The point in time to get the preceding event from.
 * @param type The Type of {@link VaultEntry} to query for.
 * @return The event of the {@link VaultEntryType} preceding the specified point in time.
 */
public VaultEntry queryLatestEventBefore(final Date timestamp, final VaultEntryType type) {
    VaultEntry returnValue = null;
    try {

        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", false)
                .limit(1L)
                .where()
                .eq(VaultEntry.TYPE_FIELD_NAME, type)
                .and()
                .le(VaultEntry.TIMESTAMP_FIELD_NAME, timestamp)
                .prepare();
        List<VaultEntry> tmpList = vaultDao.query(query);
        if (tmpList.size() > 0) {
            returnValue = tmpList.get(0);
        }
    } catch (SQLException exception) {
        LOG.log(Level.SEVERE, "Error while db query", exception);
    }
    return returnValue;
}
 
Example 4
Project: Android-UtilCode   File: FragmentUtils.java   View Source Code Vote up 7 votes
/**
 * 处理fragment回退键
 * <p>如果fragment实现了OnBackClickListener接口,返回{@code true}: 表示已消费回退键事件,反之则没消费</p>
 * <p>具体示例见FragmentActivity</p>
 *
 * @param fragmentManager fragment管理器
 * @return 是否消费回退事件
 */
public static boolean dispatchBackPress(@NonNull FragmentManager fragmentManager) {
    List<Fragment> fragments = fragmentManager.getFragments();
    if (fragments == null || fragments.isEmpty()) return false;
    for (int i = fragments.size() - 1; i >= 0; --i) {
        Fragment fragment = fragments.get(i);
        if (fragment != null
                && fragment.isResumed()
                && fragment.isVisible()
                && fragment.getUserVisibleHint()
                && fragment instanceof OnBackClickListener
                && ((OnBackClickListener) fragment).onBackClick()) {
            return true;
        }
    }
    return false;
}
 
Example 5
Project: QLExpress   File: NodeType.java   View Source Code Vote up 7 votes
public static String[][] splitProperties(String str) {
	Pattern p = Pattern.compile("(,|:)\\s*(([A-Z]|-|_)*)\\s*=");
	Matcher matcher = p.matcher(str);
	List<String[]> list = new ArrayList<String[]>();
	int endIndex = 0;
	while (matcher.find()) {
		if (list.size() > 0) {
			list.get(list.size() - 1)[1] = str.substring(endIndex,
					matcher.start()).trim();
		}
		list.add(new String[2]);
		list.get(list.size() - 1)[0] = str.substring(matcher.start() + 1,
				matcher.end() - 1).trim();
		endIndex = matcher.end();
	}
	if (list.size() > 0) {
		list.get(list.size() - 1)[1] = str.substring(endIndex).trim();
	}
	return (String[][]) list.toArray(new String[0][2]);
}
 
Example 6
Project: exam   File: EnrolmentControllerTest.java   View Source Code Vote up 7 votes
@Test
@RunAsStudent
public void testCreateEnrolmentFutureReservationExists() throws Exception {
    // Setup
    reservation.setMachine(room.getExamMachines().get(0));
    reservation.setStartAt(DateTime.now().plusDays(1));
    reservation.setEndAt(DateTime.now().plusDays(2));
    reservation.save();

    DateTime enrolledOn = DateTime.now();
    enrolment.setEnrolledOn(enrolledOn);
    enrolment.setReservation(reservation);
    enrolment.save();

    // Execute
    Result result = request(Helpers.POST,
            String.format("/app/enroll/%s/exam/%d", exam.getCourse().getCode(), exam.getId()), null);
    assertThat(result.status()).isEqualTo(200);

    // Verify
    List<ExamEnrolment> enrolments = Ebean.find(ExamEnrolment.class).findList();
    assertThat(enrolments).hasSize(1);
    ExamEnrolment e = enrolments.get(0);
    assertThat(e.getEnrolledOn().isAfter(enrolledOn));
    assertThat(e.getReservation()).isNull();
}
 
Example 7
Project: scanning   File: ScanClusterProcessingChecker.java   View Source Code Vote up 6 votes
public void checkSubmittedBean(boolean allowEmpty) throws Exception {

		List<StatusBean> statusSet = consumer.getStatusSet();
		if (allowEmpty && statusSet.isEmpty()) return;

		assertThat(statusSet.get(0), is(instanceOf(DummyOperationBean.class)));
		DummyOperationBean operationBean = (DummyOperationBean) statusSet.get(0);

		assertThat(operationBean.getDataKey(), is(equalTo(DEFAULT_ENTRY_PATH + GROUP_NAME_SOLSTICE_SCAN)));
		assertTrue(operationBean.getFilePath().contains("test_nexus"));
		assertTrue(operationBean.getFilePath().endsWith(NEXUS_FILE_EXTENSION));
		assertTrue(operationBean.getOutputFilePath().contains("processed"));
		assertTrue(operationBean.getOutputFilePath(),
				   operationBean.getOutputFilePath().endsWith("-"+processingName+NEXUS_FILE_EXTENSION));
		assertThat(operationBean.getDatasetPath(), is(equalTo(DEFAULT_ENTRY_PATH + detectorName)));
		assertThat(operationBean.getSlicing(), is(nullValue()));
		assertThat(operationBean.getProcessingPath(), is(equalTo("/tmp/sum.nxs")));
		assertThat(operationBean.isDeleteProcessingFile(), is(false));
		assertThat(operationBean.getAxesNames(), is(nullValue()));
		assertThat(operationBean.getXmx(), is(equalTo("1024m")));
		assertThat(operationBean.getDataDimensions(), is(nullValue()));
		assertThat(operationBean.getScanRank(), is(2));
		assertThat(operationBean.isReadable(), is(true));

		assertThat(System.getProperty("java.io.tmpdir"), startsWith(operationBean.getRunDirectory()));
		assertThat(operationBean.getNumberOfCores(), is(1));
	}
 
Example 8
Project: s-store   File: TaxRateGenerator.java   View Source Code Vote up 6 votes
@Override
public Object[] next() {
    Object tuple[] = new Object[columnsNum];
    List<String[]> tuples;
    
    if (countryCnt < countrySize) {
        tuples = tr_country_file.getTuplesByIndex(countryCnt);
    }
    else {
        tuples = tr_div_file.getTuplesByIndex(divCnt);
    }
    
    String[] tr_record = tuples.get(tuplesCnt++);
    int col = 0;

    tuple[col++] = tr_record[0]; // tr_id
    tuple[col++] = tr_record[1]; // tr_name
    tuple[col++] = Double.valueOf(tr_record[2]); // tr_rate
    
    if (tuplesCnt == tuples.size()) {
        tuplesCnt = 0;
        if (countryCnt < countrySize) {
            countryCnt++;
        }
        else {
            divCnt++;
        }
    }
    
    return tuple;
}
 
Example 9
Project: dremio-oss   File: FormatPluginOptionsDescriptor.java   View Source Code Vote up 6 votes
/**
 * @return a readable String of the parameters and their names
 */
String presentParams() {
  StringBuilder sb = new StringBuilder("(");
  List<TableParamDef> params = params();
  for (int i = 0; i < params.size(); i++) {
    TableParamDef paramDef = params.get(i);
    if (i != 0) {
      sb.append(", ");
    }
    sb.append(paramDef.getName()).append(": ").append(paramDef.getType().getSimpleName());
  }
  sb.append(")");
  return sb.toString();
}
 
Example 10
Project: lams   File: ChatMessageDAO.java   View Source Code Vote up 6 votes
@Override
   public ChatMessage getByUID(Long uid) {
// TODO Auto-generated method stub
List list = doFind(ChatMessageDAO.SQL_QUERY_FIND_MESSAGE_BY_UID, new Object[] { uid });

if ((list != null) && (list.size() > 0)) {
    return (ChatMessage) list.get(0);
} else {
    return null;
}

   }
 
Example 11
Project: rapidminer   File: RainflowMatrixOperator.java   View Source Code Vote up 6 votes
private double[][] createRainflowCounts(List<String> values, Map<String, Integer> indexMap) {
	double[][] counts = new double[indexMap.size()][indexMap.size()];

	int currentIndex = 4;
	while (currentIndex < values.size()) {
		String value1 = values.get(currentIndex - 4);
		String value2 = values.get(currentIndex - 3);
		String value3 = values.get(currentIndex - 2);
		String value4 = values.get(currentIndex - 1);

		boolean betweenIncreasing = value2.compareTo(value1) >= 0 && value2.compareTo(value4) <= 0
				&& value3.compareTo(value1) >= 0 && value3.compareTo(value4) <= 0;
				boolean betweenDecreasing = value2.compareTo(value1) <= 0 && value2.compareTo(value4) >= 0
						&& value3.compareTo(value1) <= 0 && value3.compareTo(value4) >= 0;
						if (betweenIncreasing || betweenDecreasing) {
							int fromIndex = indexMap.get(value2);
							int toIndex = indexMap.get(value3);
							counts[fromIndex][toIndex] = counts[fromIndex][toIndex] + 1;
							values.remove(currentIndex - 2);
							values.remove(currentIndex - 3);
							currentIndex = 4;
						} else { // nothing found
							currentIndex++;
						}
	}

	return counts;
}
 
Example 12
Project: parabuild-ci   File: SSTestConfigurationManager.java   View Source Code Vote up 6 votes
/**
 * Makes test that configuration configuations are not null
 */
public void test_getExistingBuildConfigs() throws Exception {
  final List configurations = configManager.getExistingBuildConfigs();
  assertNotNull(configurations);
  assertTrue(!configurations.isEmpty()); // this relays on test data populated by DBUnit
  final BuildConfig config = (BuildConfig) configurations.get(0);
  assertTrue(config.getBuildID() != BuildConfig.UNSAVED_ID);
  assertNotNull(config.getBuildName());
}
 
Example 13
Project: dremio-oss   File: DatasetBuilder.java   View Source Code Vote up 6 votes
/**
 * @return null if datasetPath is not canonical and couldn't find a corresponding table in the source
 */
static DatasetBuilder getDatasetBuilder(
    HiveClient client,
    String user,
    NamespaceKey datasetPath,
    boolean isCanonicalDatasetPath,
    boolean ignoreAuthzErrors,
    HiveConf hiveConf,
    DatasetConfig oldConfig) throws TException {
  final List<String> noSourceSchemaPath =
    datasetPath.getPathComponents().subList(1, datasetPath.getPathComponents().size());

  // extract database and table names from dataset path
  final String dbName;
  final String tableName;
  switch (noSourceSchemaPath.size()) {
  case 1:
    dbName = "default";
    tableName = noSourceSchemaPath.get(0);
    break;
  case 2:
    dbName = noSourceSchemaPath.get(0);
    tableName = noSourceSchemaPath.get(1);
    break;
  default:
    //invalid.
    return null;
  }

  // if the dataset path is not canonized we need to get it from the source
  final Table table;
  final String canonicalTableName;
  final String canonicalDbName;
  if (isCanonicalDatasetPath) {
    canonicalDbName = dbName;
    canonicalTableName = tableName;
    table = null;
  } else {
    // passed datasetPath is not canonical, we need to get it from the source
    table = client.getTable(dbName, tableName, ignoreAuthzErrors);
    if(table == null){
      return null;
    }
    canonicalTableName = table.getTableName();
    canonicalDbName = table.getDbName();
  }

  final List<String> canonicalDatasetPath = Lists.newArrayList(datasetPath.getRoot(), canonicalDbName, canonicalTableName);
  return new DatasetBuilder(client, user, new NamespaceKey(canonicalDatasetPath), ignoreAuthzErrors, hiveConf, canonicalDbName, canonicalTableName, table, oldConfig);
}
 
Example 14
Project: monarch   File: AbstractIndex.java   View Source Code Vote up 6 votes
void applyProjection(List projAttrib, ExecutionContext context, Collection result,
    Object iterValue, SelectResults intermediateResults, boolean isIntersection)
    throws FunctionDomainException, TypeMismatchException, NameResolutionException,
    QueryInvocationTargetException {
  if (projAttrib == null) {
    iterValue = deserializePdxForLocalDistinctQuery(context, iterValue);
    this.addToResultsWithUnionOrIntersection(result, intermediateResults, isIntersection,
        iterValue);
  } else {
    // TODO : Asif : Optimize this . This condition looks ugly.
    /*
     * if (result instanceof StructBag || result instanceof LinkedStructSet || result instanceof
     * LinkedStructBag) {
     */
    boolean isStruct = result instanceof SelectResults
        && ((SelectResults) result).getCollectionType().getElementType() != null
        && ((SelectResults) result).getCollectionType().getElementType().isStructType();
    if (isStruct) {
      int projCount = projAttrib.size();
      Object[] values = new Object[projCount];
      Iterator projIter = projAttrib.iterator();
      int i = 0;
      while (projIter.hasNext()) {
        Object projDef[] = (Object[]) projIter.next();
        values[i] = deserializePdxForLocalDistinctQuery(context,
            ((CompiledValue) projDef[1]).evaluate(context));
        i++;
      }
      this.addToStructsWithUnionOrIntersection(result, intermediateResults, isIntersection,
          values);
    } else {
      Object[] temp = (Object[]) projAttrib.get(0);
      Object val = deserializePdxForLocalDistinctQuery(context,
          ((CompiledValue) temp[1]).evaluate(context));
      this.addToResultsWithUnionOrIntersection(result, intermediateResults, isIntersection, val);
    }
  }
}
 
Example 15
Project: YuiHatano   File: AfinalTest.java   View Source Code Vote up 6 votes
@Test
public void testDelete() {
    saveBean("kk");

    List<Bean> beanRS = finalDb.findAll(Bean.class);
    Bean       b      = beanRS.get(0);

    finalDb.delete(b);

    Assert.assertEquals(0, finalDb.findAll(Bean.class).size());
}
 
Example 16
Project: JavaGraph   File: LayoutIO.java   View Source Code Vote up 6 votes
/**
 * Creates an edge vector from a list of points. The edge vector is the
 * vector from the first to the last point, if they are distinct; otherwise,
 * it is the average of the edge points; if that yields <code>(0,0)</code>,
 * the edge vector is given by {@link #DEFAULT_EDGE_VECTOR}.
 *
 * @param points the list of points; should not be empty
 * @param isLoop flag indicating that the underlying edge is a loop
 * @see EdgeView#getLabelVector()
 */
private static Point2D version2LabelVector(List<Point2D> points, boolean isLoop) {
    Point2D result = null;
    // first try a vector from the first to the last point
    Point2D begin = points.get(0);
    Point2D end = points.get(points.size() - 1);
    if (!(isLoop || begin.equals(end))) {
        double dx = end.getX() - begin.getX();
        double dy = end.getY() - begin.getY();
        result = new Point2D.Double(dx, dy);
    } else if (points.size() > 0) {
        // the first and last point coincide; try taking the max of all
        // points
        double sumX = 0;
        double sumY = 0;
        for (Point2D point : points) {
            sumX += point.getX() - begin.getX();
            sumY += point.getY() - begin.getY();
        }
        // double the average (why? don't know; see
        // EdgeView#getLabelVector())
        int n = points.size() / 2;
        result = new Point2D.Double(sumX / n, sumY / n);
    }
    if (result == null || result.getX() == 0 && result.getY() == 0) {
        // nothing worked
        result = DEFAULT_EDGE_VECTOR;
    }
    return result;
}
 
Example 17
Project: kafka-0.11.0.0-src-with-comment   File: JaasContextTest.java   View Source Code Vote up 6 votes
private AppConfigurationEntry configurationEntry(JaasContext.Type contextType, String jaasConfigProp) {
    Map<String, Object> configs = new HashMap<>();
    if (jaasConfigProp != null)
        configs.put(SaslConfigs.SASL_JAAS_CONFIG, new Password(jaasConfigProp));
    JaasContext context = JaasContext.load(contextType, null, contextType.name(), configs);
    List<AppConfigurationEntry> entries = context.configurationEntries();
    assertEquals(1, entries.size());
    return entries.get(0);
}
 
Example 18
Project: GitHub   File: SerializeWriter.java   View Source Code Vote up 5 votes
public void write(List<String> list) {
    if (list.isEmpty()) {
        write("[]");
        return;
    }

    int offset = count;
    final int initOffset = offset;
    for (int i = 0, list_size = list.size(); i < list_size; ++i) {
        String text = list.get(i);

        boolean hasSpecial = false;
        if (text == null) {
            hasSpecial = true;
        } else {
            for (int j = 0, len = text.length(); j < len; ++j) {
                char ch = text.charAt(j);
                if (hasSpecial = (ch < ' ' //
                                  || ch > '~' //
                                  || ch == '"' //
                                  || ch == '\\')) {
                    break;
                }
            }
        }

        if (hasSpecial) {
            count = initOffset;
            write('[');
            for (int j = 0; j < list.size(); ++j) {
                text = list.get(j);
                if (j != 0) {
                    write(',');
                }

                if (text == null) {
                    write("null");
                } else {
                    writeStringWithDoubleQuote(text, (char) 0);
                }
            }
            write(']');
            return;
        }

        int newcount = offset + text.length() + 3;
        if (i == list.size() - 1) {
            newcount++;
        }
        if (newcount > buf.length) {
            count = offset;
            expandCapacity(newcount);
        }

        if (i == 0) {
            buf[offset++] = '[';
        } else {
            buf[offset++] = ',';
        }
        buf[offset++] = '"';
        text.getChars(0, text.length(), buf, offset);
        offset += text.length();
        buf[offset++] = '"';
    }
    buf[offset++] = ']';
    count = offset;
}
 
Example 19
Project: monarch   File: ADataReader.java   View Source Code Vote up 5 votes
@Override
public OrcIndex readRowIndex(StripeInformation stripe, OrcProto.StripeFooter footer,
    boolean[] included, OrcProto.RowIndex[] indexes, boolean[] sargColumns,
    OrcProto.BloomFilterIndex[] bloomFilterIndices) throws IOException {
  if (file == null) {
    open();
  }
  if (footer == null) {
    footer = readStripeFooter(stripe);
  }
  if (indexes == null) {
    indexes = new OrcProto.RowIndex[typeCount];
  }
  if (bloomFilterIndices == null) {
    bloomFilterIndices = new OrcProto.BloomFilterIndex[typeCount];
  }
  long offset = stripe.getOffset();
  List<OrcProto.Stream> streams = footer.getStreamsList();
  for (int i = 0; i < streams.size(); i++) {
    OrcProto.Stream stream = streams.get(i);
    OrcProto.Stream nextStream = null;
    if (i < streams.size() - 1) {
      nextStream = streams.get(i + 1);
    }
    int col = stream.getColumn();
    int len = (int) stream.getLength();
    // row index stream and bloom filter are interlaced, check if the sarg column contains bloom
    // filter and combine the io to read row index and bloom filters for that column together
    if (stream.hasKind() && (stream.getKind() == OrcProto.Stream.Kind.ROW_INDEX)) {
      boolean readBloomFilter = false;
      if (sargColumns != null && sargColumns[col]
          && nextStream.getKind() == OrcProto.Stream.Kind.BLOOM_FILTER) {
        len += nextStream.getLength();
        i += 1;
        readBloomFilter = true;
      }
      if ((included == null || included[col]) && indexes[col] == null) {
        // byte[] buffer = new byte[len];
        // file.readFully(offset, buffer, 0, buffer.length);
        ByteBuffer bb = ByteBuffer.wrap(this.bytes, (int) offset, len);
        indexes[col] = OrcProto.RowIndex.parseFrom(
            InStream.create("index", Lists.<DiskRange>newArrayList(new BufferChunk(bb, 0)),
                stream.getLength(), codec, bufferSize));
        if (readBloomFilter) {
          bb.position((int) stream.getLength());
          bloomFilterIndices[col] =
              OrcProto.BloomFilterIndex.parseFrom(InStream.create("bloom_filter",
                  Lists.<DiskRange>newArrayList(new BufferChunk(bb, 0)), nextStream.getLength(),
                  codec, bufferSize));
        }
      }
    }
    offset += len;
  }

  OrcIndex index = new OrcIndex(indexes, bloomFilterIndices);
  return index;
}
 
Example 20
Project: manifold   File: ExtCodeGen.java   View Source Code Vote up 5 votes
private AbstractSrcMethod findMethod( AbstractSrcMethod method, SrcClass extendedType, JavacTaskImpl[] javacTask )
{
  AbstractSrcMethod duplicate = null;
  outer:
  for( AbstractSrcMethod m: extendedType.getMethods() )
  {
    if( m.getSimpleName().equals( method.getSimpleName() ) && m.getParameters().size() == method.getParameters().size()-1 )
    {
      List parameters = method.getParameters();
      List params = m.getParameters();
      for( int i = 1; i < parameters.size(); i++ )
      {
        SrcParameter param = (SrcParameter)parameters.get( i );
        SrcParameter p = (SrcParameter)params.get( i-1 );
        if( !param.getType().equals( p.getType() ) )
        {
          continue outer;
        }
      }
      duplicate = m;
      break;
    }
  }
  if( duplicate == null )
  {
    if( !extendedType.isInterface() )
    {
      SrcType superClass = extendedType.getSuperClass();
      if( superClass != null && superClass.getName().equals( Object.class.getName() ) )
      {
        SrcClass superSrcClass = ClassSymbols.instance( getModule() ).makeSrcClassStub( superClass.getName(), javacTask, null );
        duplicate = findMethod( method, superSrcClass, javacTask );
      }
    }
    if( duplicate == null )
    {
      //## note: we are checking interfaces even for a non-abstract class because it could be
      //## inheriting default interface methods, which must not be shadowed by an extension.
      for( SrcType iface: extendedType.getInterfaces() )
      {
        SrcClass superIface = ClassSymbols.instance( getModule() ).makeSrcClassStub( iface.getName(), javacTask, null );
        duplicate = findMethod( method, superIface, javacTask );
        if( duplicate != null )
        {
          break;
        }
      }
    }
  }
  return duplicate;
}