Java 类org.apache.commons.lang3.ArrayUtils 实例源码

项目:Backmemed    文件:Property.java   
public boolean setPropertyValue(String propVal)
{
    if (propVal == null)
    {
        this.value = this.defaultValue;
        return false;
    }
    else
    {
        this.value = ArrayUtils.indexOf(this.propertyValues, propVal);

        if (this.value >= 0 && this.value < this.propertyValues.length)
        {
            return true;
        }
        else
        {
            this.value = this.defaultValue;
            return false;
        }
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:JtableUtils.java   
/**
 * deletes all selected columns if it is not present in the <code>exp</code>
 * List
 *
 * @param table the table to DELETE columns
 * @param exp columns to avoid deleting
 * @see #deletecol(javax.swing.JTable, int)
 */
static void deletecols(JTable table, int[] exp) {
    Integer[] selcols;
    try {
        TableColumnModel tcm = table.getColumnModel();
        selcols = ArrayUtils.toObject(table.getSelectedColumns());
        Arrays.sort(selcols, Collections.reverseOrder());
        List<Integer> explist = Ints.asList(exp);
        for (int i : selcols) {
            if (!explist.contains(i)) {
                tcm.removeColumn(tcm.getColumn(i));
            }
        }

    } catch (Exception e) {
        Logger.getLogger(JtableUtils.class.getName()).log(Level.SEVERE, null, e);
    }

}
项目:java-debug    文件:SetExceptionBreakpointsRequestHandler.java   
@Override
public CompletableFuture<Response> handle(Command command, Arguments arguments, Response response, IDebugAdapterContext context) {
    if (context.getDebugSession() == null) {
        return AdapterUtils.createAsyncErrorResponse(response, ErrorCode.EMPTY_DEBUG_SESSION, "Empty debug session.");
    }

    String[] filters = ((SetExceptionBreakpointsArguments) arguments).filters;
    try {
        boolean notifyCaught = ArrayUtils.contains(filters, Types.ExceptionBreakpointFilter.CAUGHT_EXCEPTION_FILTER_NAME);
        boolean notifyUncaught = ArrayUtils.contains(filters, Types.ExceptionBreakpointFilter.UNCAUGHT_EXCEPTION_FILTER_NAME);

        context.getDebugSession().setExceptionBreakpoints(notifyCaught, notifyUncaught);
        return CompletableFuture.completedFuture(response);
    } catch (Exception ex) {
        return AdapterUtils.createAsyncErrorResponse(response, ErrorCode.SET_EXCEPTIONBREAKPOINT_FAILURE,
                String.format("Failed to setExceptionBreakpoints. Reason: '%s'", ex.toString()));
    }
}
项目:Proyecto-DASI    文件:KeyManager.java   
/** Call this to finalise any additional key bindings we want to create in the mod.
 * @param settings Minecraft's original GameSettings object which we are appending to.
 */
private void fixAdditionalKeyBindings(GameSettings settings)
{
    if (this.additionalKeys == null)
    {
        return; // No extra keybindings to add.
    }

    // The keybindings are stored in GameSettings as a java built-in array.
    // There is no way to append to such arrays, so instead we create a new
    // array of the correct
    // length, copy across the current keybindings, add our own ones, and
    // set the new array back
    // into the GameSettings:
    KeyBinding[] bindings = (KeyBinding[]) ArrayUtils.addAll(settings.keyBindings, this.additionalKeys.toArray());
    settings.keyBindings = bindings;
}
项目:javadoc2swagger    文件:DefinitionParser.java   
private Definition getDefinitionByClass(Class<?> cls, String className, Definition rootDefinition)
        throws ParserException {

    Field[] fields = cls.getDeclaredFields();

    // if cls is enum, remove the values field
    if (cls.isEnum()) {
        for (int i = fields.length - 1; i >= 0; i--) {
            if (!fields[i].isEnumConstant()) {
                fields = ArrayUtils.removeElement(fields, fields[i]);
                break;
            }
        }
    }

    Definition definition = new Definition();
    definition.setClassName(className);
    if (rootDefinition == null) {
        rootDefinition = definition;
    }
    List<Property> properties = processFields(fields, definition, rootDefinition);
    definition.setProperties(properties);
    return definition;
}
项目:BaseClient    文件:GameSettings.java   
public GameSettings(Minecraft mcIn, File p_i46326_2_)
{
    this.keyBindings = (KeyBinding[])((KeyBinding[])ArrayUtils.addAll(new KeyBinding[] {this.keyBindAttack, this.keyBindUseItem, this.keyBindForward, this.keyBindLeft, this.keyBindBack, this.keyBindRight, this.keyBindJump, this.keyBindSneak, this.keyBindSprint, this.keyBindDrop, this.keyBindInventory, this.keyBindChat, this.keyBindPlayerList, this.keyBindPickBlock, this.keyBindCommand, this.keyBindScreenshot, this.keyBindTogglePerspective, this.keyBindSmoothCamera, this.keyBindStreamStartStop, this.keyBindStreamPauseUnpause, this.keyBindStreamCommercials, this.keyBindStreamToggleMic, this.keyBindFullscreen, this.keyBindSpectatorOutlines}, this.keyBindsHotbar));
    this.difficulty = EnumDifficulty.NORMAL;
    this.lastServer = "";
    this.fovSetting = 70.0F;
    this.language = "en_US";
    this.forceUnicodeFont = false;
    this.mc = mcIn;
    this.optionsFile = new File(p_i46326_2_, "options.txt");
    this.optionsFileOF = new File(p_i46326_2_, "optionsof.txt");
    this.limitFramerate = (int)GameSettings.Options.FRAMERATE_LIMIT.getValueMax();
    this.ofKeyBindZoom = new KeyBinding("of.key.zoom", 46, "key.categories.misc");
    this.keyBindings = (KeyBinding[])((KeyBinding[])ArrayUtils.add(this.keyBindings, this.ofKeyBindZoom));
    GameSettings.Options.RENDER_DISTANCE.setValueMax(32.0F);
    this.renderDistanceChunks = 8;
    this.loadOptions();
    Config.initGameSettings(this);
}
项目:spring-cloud-samples    文件:ErrorHolder.java   
public static String getMessage(CodeTemp templ, String... params) {
    String regContent = templ.getTemp();
    int index = 0;
    while (regContent.indexOf("{}") >= 0) {
        if (ArrayUtils.isEmpty(params) || params.length <= index) {
            if (regContent.indexOf("{}") >= 0) {
                regContent = regContent.replaceAll("\\{\\}", "");
            }
            break;
        }
        regContent = StringUtils.replaceOnce(regContent, "{}", params[index]);
        index++;
    }

    return regContent;
}
项目:MCBot    文件:MappingDatabase.java   
public void reload() throws IOException {
    mappings.clear();
    ZipFile zipfile = new ZipFile(zip);

    try {
        for (MappingType type : MappingType.values()) {
            if (type.getCsvName() != null) {
                List<String> lines;
                lines = IOUtils.readLines(zipfile.getInputStream(zipfile.getEntry(type.getCsvName() + ".csv")), Charsets.UTF_8);

                lines.remove(0); // Remove header line

                for (String line : lines) {
                    String[] info = line.split(",", -1);
                    String comment = info.length > 3 ? Joiner.on(',').join(ArrayUtils.subarray(info, 3, info.length)) : "";
                    IMapping mapping = new IMapping.Impl(type, info[0], info[1], comment, Side.values()[Integer.valueOf(info[2])]);
                    mappings.put(type, mapping);
                }
            }
        }
    } finally {
        zipfile.close();
    }
}
项目:xm-commons    文件:AopAnnotationUtilUnitTest.java   
@Test
public void testIncludeOnClassLevel() throws NoSuchMethodException {

    Class<?> aClass = TestServiceIncludeOnClass.class;

    when(signature.getMethod()).thenReturn(aClass.getMethod("method1",
                                                            Object.class,
                                                            String.class,
                                                            int.class));
    when(signature.getDeclaringType()).thenReturn(aClass);

    Optional<LoggingAspectConfig> conf = AopAnnotationUtils.getConfigAnnotation(joinPoint);
    assertTrue(conf.isPresent());
    assertArrayEquals(ArrayUtils.toArray("param1", "param3"), conf.get().inputIncludeParams());
    assertArrayEquals(new String[]{}, conf.get().inputExcludeParams());

}
项目:BaseClient    文件:Property.java   
public boolean setPropertyValue(String propVal)
{
    if (propVal == null)
    {
        this.value = this.defaultValue;
        return false;
    }
    else
    {
        this.value = ArrayUtils.indexOf(this.propertyValues, propVal);

        if (this.value >= 0 && this.value < this.propertyValues.length)
        {
            return true;
        }
        else
        {
            this.value = this.defaultValue;
            return false;
        }
    }
}
项目:URTorrent    文件:BencodeReader.java   
/**
 * Reads a bencoded <code>Map</code> (dict in the specification) from the
 * <code>InputStream</code>. The <code>Map</code> may contain lists and maps
 * itself.
 *
 * @since 0.1.0
 * @exception IOException if an IO exception occurs when reading
 * @exception EOFException if the stream ended unexpectedly
 * @exception BencodeReadException if the value read is not a properly bencoded Map
 */
public Map<String, Object> readDict() throws IOException, BencodeReadException {
    int initial = forceRead();
    if (initial != 'd') {
        throw new BencodeReadException("Bencoded dict must start with 'd', not '%c'",
                                       initial);
    }
    LinkedHashMap<String, Object> hm = new LinkedHashMap<String, Object>();
    while (peek() != 'e') {
        String key =  new String(ArrayUtils.toPrimitive(readString()), StandardCharsets.UTF_8);
        Object val = read();
        if (val == null) {
            throw new EOFException();
        }
        hm.put(key, val);
    }
    forceRead(); // read 'e' that we peeked
    return hm;
}
项目:Backmemed    文件:LootPool.java   
public JsonElement serialize(LootPool p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_)
{
    JsonObject jsonobject = new JsonObject();
    jsonobject.add("entries", p_serialize_3_.serialize(p_serialize_1_.lootEntries));
    jsonobject.add("rolls", p_serialize_3_.serialize(p_serialize_1_.rolls));

    if (p_serialize_1_.bonusRolls.getMin() != 0.0F && p_serialize_1_.bonusRolls.getMax() != 0.0F)
    {
        jsonobject.add("bonus_rolls", p_serialize_3_.serialize(p_serialize_1_.bonusRolls));
    }

    if (!ArrayUtils.isEmpty((Object[])p_serialize_1_.poolConditions))
    {
        jsonobject.add("conditions", p_serialize_3_.serialize(p_serialize_1_.poolConditions));
    }

    return jsonobject;
}
项目:elastic-db-tools-for-java    文件:ReplaceMappingsOperation.java   
/**
 * Performs the undo of LSM operation on the source shard.
 *
 * @param ts
 *            Transaction scope.
 * @return Result of the operation.
 */
@Override
public StoreResults undoLocalSourceExecute(IStoreTransactionScope ts) {
    StoreMapping sourceLeft = mappingsSource.get(0).getLeft();
    StoreMapping targetLeft = mappingsTarget.get(0).getLeft();

    StoreShard dssOriginal = new StoreShard(sourceLeft.getStoreShard().getId(), this.getOriginalShardVersionAdds(), sourceLeft.getShardMapId(),
            sourceLeft.getStoreShard().getLocation(), sourceLeft.getStoreShard().getStatus());

    StoreMapping dsmSource = new StoreMapping(sourceLeft.getId(), sourceLeft.getShardMapId(), sourceLeft.getMinValue(), sourceLeft.getMaxValue(),
            sourceLeft.getStatus(), mappingsSource.get(0).getRight(), dssOriginal);

    StoreMapping dsmTarget = new StoreMapping(targetLeft.getId(), targetLeft.getShardMapId(), targetLeft.getMinValue(), targetLeft.getMaxValue(),
            targetLeft.getStatus(), mappingsTarget.get(0).getRight(), dssOriginal);

    StoreMapping[] ms = new StoreMapping[] {dsmSource};
    StoreMapping[] mt = new StoreMapping[] {dsmTarget};

    return ts.executeOperation(StoreOperationRequestBuilder.SP_BULK_OPERATION_SHARD_MAPPINGS_LOCAL,
            StoreOperationRequestBuilder.replaceShardMappingsLocal(this.getId(), true, shardMap,
                    (StoreMapping[]) ArrayUtils.addAll(mt, mappingsTarget.stream().skip(1).map(Pair::getLeft).toArray()),
                    (StoreMapping[]) ArrayUtils.addAll(ms, mappingsSource.stream().skip(1).map(Pair::getLeft).toArray())));
}
项目:ECFileCache    文件:RedisAccessBase.java   
/**
 * Convert chunks get from Redis.
 * Make a zero-filled array if failed to read chunk from Redis.
 *
 * @param redisDataArray chunks get from all Redis nodes
 * @param chunkSize length of chunk data
 * @return pair of chunks and erasures array
 */
static Pair<byte[][], int[]> convertChunk(byte[][] redisDataArray, int chunkSize) {
  Validate.isTrue(ArrayUtils.isNotEmpty(redisDataArray));

  List<Integer> erasures = new ArrayList<Integer>();

  int i = 0;
  for (byte[] chunk : redisDataArray) {
    // can not read chunk data from redis
    // make a zero-filled array for ec decode
    if (ArrayUtils.isEmpty(chunk) || chunk.length != chunkSize) {
      chunk = new byte[chunkSize];
      erasures.add(i);
    }
    redisDataArray[i++] = chunk;
  }
  return Pair.create(redisDataArray, adjustErasures(erasures, redisDataArray.length));
}
项目:PoiExcelExport2.0    文件:PoiExportFacade.java   
/**
 * export excel with year and quarter
 * @param baseSearchDto
 * @param excelPath
 * @param exportName
 * @param data
 * @param dataCls
 * @param templateCls
 * @param pictureArea
 * @param hasYear
 * @param hasQuarter
 * @return {@code Optional<InputStream>}
 * @throws IOException
 */
public static <T> Optional<InputStream> export(final BaseSearchDto baseSearchDto,final String excelPath,final String exportName,final List<T> data,final Class<T> dataCls,final Class<?> templateCls,final int[] pictureArea,boolean hasYear,boolean hasQuarter) throws IOException{
    Objects.requireNonNull(baseSearchDto, "baseSearchDto must not be null!");
    Builder<T> builder=new ExcelExportService.Builder<T>(excelPath,exportName,data,dataCls);
    String svg=Objects.requireNonNull(baseSearchDto.getSvgString(), "baseSearchDto svg string must not be null!");
    builder.setSvg(svg);
    List<String> _titles=baseSearchDto.getTitles();
    if(!CollectionUtils.isEmpty(_titles)){
        builder.setTitles(_titles);
    }
    if(hasYear){
        Integer _year=Objects.requireNonNull(baseSearchDto.getYear(), "baseSearchDto year must not be null!");
        builder.setYear(_year.toString());
    }
    if(hasQuarter){
        Integer _quarter=Objects.requireNonNull(baseSearchDto.getQuarter(), "baseSearchDto quarter must not be null!");
        builder.setQuarter(_quarter.toString());
    }
    org.springframework.util.Assert.isTrue(!ArrayUtils.isEmpty(pictureArea),"picture area have not been specified!");
    builder.setPictureStartCol(pictureArea[0]);
    builder.setPictureEndCol(pictureArea[1]);
    builder.setPictureStartRow(pictureArea[2]);
    builder.setPictureEndRow(pictureArea[3]);
    ExportBuilder exportBuilder=builder.build();
    return Optional.of(exportBuilder.writeStreamFromTemplate(templateCls));
}
项目:ytk-learn    文件:GBDTFeatureParams.java   
private int[] parseCol(String colConf, Set<Integer> existCols, Map<String, Integer> fName2IndexMap) {
    if (colConf.equalsIgnoreCase("default")) {
        CheckUtils.check(!existCols.contains(-1), "[GBDT] feature approximate config error! default has been set twice");
        existCols.add(-1);
        return new int[]{-1};
    }

    List<Integer> colList = new ArrayList<>(16);
    String[] allCols = colConf.split(COL_SPLIT);

    for (String colField : allCols) {
        colField = colField.trim();
        CheckUtils.check(fName2IndexMap.containsKey(colField), "[GBDT] feature approximate config error! feature(%s) does not exist", colField);
        int col = fName2IndexMap.get(colField);
        CheckUtils.check(!existCols.contains(col), "[GBDT] feature approximate config error!, feature(%s) has been set twice", colField);
        colList.add(col);
        existCols.add(col);
    }
    return ArrayUtils.toPrimitive(colList.toArray(new Integer[colList.size()]));
}
项目:BaseClient    文件:SoundHandler.java   
/**
 * Returns a random sound from one or more categories
 */
public SoundEventAccessorComposite getRandomSoundFromCategories(SoundCategory... categories)
{
    List<SoundEventAccessorComposite> list = Lists.<SoundEventAccessorComposite>newArrayList();

    for (ResourceLocation resourcelocation : this.sndRegistry.getKeys())
    {
        SoundEventAccessorComposite soundeventaccessorcomposite = (SoundEventAccessorComposite)this.sndRegistry.getObject(resourcelocation);

        if (ArrayUtils.contains(categories, soundeventaccessorcomposite.getSoundCategory()))
        {
            list.add(soundeventaccessorcomposite);
        }
    }

    if (list.isEmpty())
    {
        return null;
    }
    else
    {
        return (SoundEventAccessorComposite)list.get((new Random()).nextInt(list.size()));
    }
}
项目:DecompiledMinecraft    文件:NetworkManager.java   
public void sendPacket(Packet packetIn, GenericFutureListener <? extends Future <? super Void >> listener, GenericFutureListener <? extends Future <? super Void >> ... listeners)
{
    if (this.isChannelOpen())
    {
        this.flushOutboundQueue();
        this.dispatchPacket(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener));
    }
    else
    {
        this.field_181680_j.writeLock().lock();

        try
        {
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener)));
        }
        finally
        {
            this.field_181680_j.writeLock().unlock();
        }
    }
}
项目:DecompiledMinecraft    文件:NetworkManager.java   
public void sendPacket(Packet packetIn, GenericFutureListener <? extends Future <? super Void >> listener, GenericFutureListener <? extends Future <? super Void >> ... listeners)
{
    if (this.isChannelOpen())
    {
        this.flushOutboundQueue();
        this.dispatchPacket(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener));
    }
    else
    {
        this.field_181680_j.writeLock().lock();

        try
        {
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener)));
        }
        finally
        {
            this.field_181680_j.writeLock().unlock();
        }
    }
}
项目:plugin-bt-jira    文件:JiraDao.java   
/**
 * Return all custom fields matching to the given names
 * 
 * @param dataSource
 *            The data source of JIRA database.
 * @param customFields
 *            the expected custom fields names.
 * @param project
 *            Jira project identifier. Required to filter custom field against contexts.
 * @return all custom field configurations referenced in the given project and matching the required names.
 */
public Map<String, CustomFieldEditor> getCustomFields(final DataSource dataSource, final Set<String> customFields, final int project) {
    if (customFields.isEmpty()) {
        // No custom field, we save useless queries
        return new HashMap<>();
    }

    // Get map as list
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    final RowMapper<CustomFieldEditor> rowMapper = new BeanPropertyRowMapper<>(CustomFieldEditor.class);
    final List<CustomFieldEditor> resultList = jdbcTemplate
            .query("SELECT cf.ID AS id, TRIM(cf.cfname) AS name, cf.DESCRIPTION AS description, cf.CUSTOMFIELDTYPEKEY AS fieldType FROM customfield AS cf WHERE TRIM(cf.cfname) IN ("
                    + newIn(customFields) + ")", rowMapper, customFields.toArray());

    // Also add the translated items
    final List<CustomFieldEditor> resultListTranslated = jdbcTemplate.query(
            "SELECT cf.ID AS id, TRIM(cf.cfname) AS originalName, TRIM(ps.propertyvalue) AS name, cf.cfname AS originalName, cf.DESCRIPTION AS description, "
                    + "cf.CUSTOMFIELDTYPEKEY AS fieldType "
                    + "FROM customfield AS cf INNER JOIN propertyentry AS pe ON pe.ENTITY_ID = cf.ID INNER JOIN propertystring AS ps ON pe.ID = ps.ID "
                    + "WHERE pe.ENTITY_NAME=? AND PROPERTY_KEY LIKE ? AND TRIM(ps.propertyvalue) IN (" + newIn(customFields) + ")",
            rowMapper, ArrayUtils.addAll(new String[] { "CustomField", "%FR" }, customFields.toArray()));

    // Make a Map of valid values for single/multi select values field
    final Map<String, CustomFieldEditor> result = new HashMap<>();
    addListToMap(dataSource, resultList, result, project);
    addListToMap(dataSource, resultListTranslated, result, project);
    return result;
}
项目:VillagerTrades    文件:TradeLoader.java   
private static boolean containsCurrencyItems(List<ItemStack> stacks)
{
    for (ItemStack stack : stacks)
    {
        String resourceName = Item.REGISTRY.getNameForObject(stack.getItem()).toString();
        if (stack.getItemDamage() > 0) resourceName += "," + Integer.toString(stack.getItemDamage());

        if (ArrayUtils.contains(ModConfiguration.currencyItems, resourceName)) return true;
    }
    return false;
}
项目:BaseClient    文件:GuiKeyBindingList.java   
public GuiKeyBindingList(GuiControls controls, Minecraft mcIn)
{
    super(mcIn, controls.width, controls.height, 63, controls.height - 32, 20);
    this.field_148191_k = controls;
    this.mc = mcIn;
    KeyBinding[] akeybinding = (KeyBinding[])ArrayUtils.clone(mcIn.gameSettings.keyBindings);
    this.listEntries = new GuiListExtended.IGuiListEntry[akeybinding.length + KeyBinding.getKeybinds().size()];
    Arrays.sort((Object[])akeybinding);
    int i = 0;
    String s = null;

    for (KeyBinding keybinding : akeybinding)
    {
        String s1 = keybinding.getKeyCategory();

        if (!s1.equals(s))
        {
            s = s1;
            this.listEntries[i++] = new GuiKeyBindingList.CategoryEntry(s1);
        }

        int j = mcIn.fontRendererObj.getStringWidth(I18n.format(keybinding.getKeyDescription(), new Object[0]));

        if (j > this.maxListLabelWidth)
        {
            this.maxListLabelWidth = j;
        }

        this.listEntries[i++] = new GuiKeyBindingList.KeyEntry(keybinding);
    }
}
项目:otf2ttf    文件:CTQ.java   
public double[][] splitAtTs(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4,
        double[] ts) {
    if (ts.length == 0)
        return new double[][] { new double[] { x1, y1, x2, y2, x3, y3, x4, y4 } };
    double[][] s = splitAt(x1, y1, x2, y2, x3, y3, x4, y4, ts[0]);
    if (ts.length == 1) {
        return s;
    } else {
        return ArrayUtils.addAll(new double[][] { s[0] }, splitAtTs(s[1][0], s[1][1], s[1][2], s[1][3], s[1][4],
                s[1][5], s[1][6], s[1][7], ArrayUtils.subarray(ts, 1, ts.length)));
    }
}
项目:elasticsearch-aem    文件:AbstractElasticSearchContentBuilder.java   
/**
 * @param primaryType
 * @return List with all properties to index
 */
protected String[] getIndexRules(String primaryType) {
  ElasticSearchIndexConfiguration config = getIndexConfig(primaryType);
  if (config != null) {
    return ArrayUtils.addAll(config.getIndexRules(), getFixedRules());
  }
  return getFixedRules();
}
项目:ClientAPI    文件:MultiType.java   
/**
 * Sets value to the next one in the set
 */
public final void next() {
    int index = ArrayUtils.indexOf(values, getValue());
    if (++index >= values.length)
        index = 0;
    this.setValue(values[index]);
}
项目:froog    文件:Feedforward.java   
/**
 *
 * @return B1, B2, ...,Bm
 */
public SimpleMatrix getParamsB() {
    if (layers.isEmpty()) {
        System.err.println("Inicialice los pesos primero");
        return null;
    }
    double[] aux = new double[0];
    for (int i = 0; i < layers.size(); i++) {
        aux = ArrayUtils.addAll(aux, layers.get(i).getB().getMatrix().getData());
    }
    return new SimpleMatrix(1, aux.length, true, aux);
}
项目:java-restclient    文件:HTTPCAsyncSpec.java   
@Test
public void shouldHead() throws RestException, ExecutionException, InterruptedException {
    HTTPCMockHandler.INSTANCE.addMock("HEAD", 200, Collections.singletonMap("X-Test","1"));

    Request request = makeRequest(HEAD, "/test");
    Response response = TestClients.getAsyncClient().asyncHead(request, getCallback(request)).get();

    assertEquals(200, response.getStatus());
    assertEquals("1", response.getHeader("X-Test").getValue());
    assertTrue(ArrayUtils.isEmpty(response.getBytes()));
}
项目:CombinedPotions    文件:RecipeCombinedPotions2.java   
@Override
public boolean matches(InventoryCrafting inv, World worldIn)
{
    ItemStack tempStack = ItemStack.EMPTY;
    if (VALID_ITEMS == null) buildValidItemsArray();

    int potionEffects = 0;
    for (int i = 0; i < inv.getSizeInventory(); i++)
    {
        ItemStack stack = inv.getStackInSlot(i);
        if (!stack.isEmpty())
        {
            Item item = stack.getItem();
            if (!ArrayUtils.contains(VALID_ITEMS, item)) return false;

            if (tempStack.isEmpty())
            {
                tempStack = stack.copy();
            }
            else
            {
                if (!canCombineItems(tempStack, stack)) return false;
            }

            if (ModConfiguration.maxPotionEffects >= 0)
            {
                potionEffects += getEffectsFromStack(stack).size();
                if (potionEffects > ModConfiguration.maxPotionEffects) return false;
            }
        }
    }

    return true;
}
项目:otf2ttf    文件:CTQ.java   
public Contour[][] c2qContours(Contour[][] contours, Double splitAtX, Double splitAtY, Double err) {
    Contour[][] ans = new Contour[][] {};
    for (Contour[] c : contours) {
        Contour[] c1 = toquad(c, splitAtX, splitAtY, err == null ? 1 : err);
        if (haspt(c1)) {
            ans = ArrayUtils.add(ans, c1);
        }
    }
    return ans;
}
项目:plugin-bt-jira    文件:JiraDao.java   
/**
 * Query JIRA database to collect activities of given users. For now, only the last success connection is
 * registered.
 * 
 * @param dataSource The JIRA datasource to query the user activities.
 * @param users
 *            the users to query.
 * @return activities.
 */
public Map<String, Activity> getActivities(final DataSource dataSource, final Collection<String> users) {
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    final Map<String, Activity> result = new HashMap<>();
    if (!users.isEmpty()) {
        jdbcTemplate.query("SELECT u.lower_user_name AS login, attribute_value AS value FROM cwd_user AS u"
                + " INNER JOIN cwd_user_attributes AS ua ON ua.user_id = u.ID WHERE u.lower_user_name IN (" + newIn(users)
                + ") AND attribute_name=?;", rs -> {
                    final Activity activity = new Activity();
                    activity.setLastConnection(new Date(Long.valueOf(rs.getString("value"))));
                    result.put(rs.getString("login"), activity);
                }, ArrayUtils.add(users.toArray(), "lastAuthenticated"));
    }
    return result;
}
项目:ShotgunWSD    文件:WindowConfiguration.java   
public static WindowConfiguration merge(WindowConfiguration window1, WindowConfiguration window2, int offset){
    if(window2.getLastGlobalSense() < window1.getLastGlobalSense())
        return null;

    int startAt = window1.getLength() - offset;

    int[] synsets = ArrayUtils.addAll(Arrays.copyOf(window1.getSynsetsIndex(), window1.getLength()), Arrays.copyOfRange(window2.getSynsetsIndex(), startAt, window2.getLength()));
    String[] globalSenses = ArrayUtils.addAll(Arrays.copyOf(window1.getGlobalSynsets(), window1.getLength()), Arrays.copyOfRange(window2.getGlobalSynsets(), startAt, window2.getLength()));
    String[] windowWords  = ArrayUtils.addAll(Arrays.copyOf(window1.getWindowWords(), window1.getLength()), Arrays.copyOfRange(window2.getWindowWords(), startAt, window2.getLength()));
    String[] windowWordsPOS  = ArrayUtils.addAll(Arrays.copyOf(window1.getWindowWordsPOS(), window1.getLength()), Arrays.copyOfRange(window2.getWindowWordsPOS(), startAt, window2.getLength()));
    Synset[] configurationSynsets = ArrayUtils.addAll(Arrays.copyOf(window1.getConfigurationSynsets(), window1.getLength()), Arrays.copyOfRange(window2.getConfigurationSynsets(), startAt, window2.getLength()));

    return new WindowConfiguration(synsets, windowWords, windowWordsPOS, configurationSynsets, globalSenses);
}
项目:neo-java    文件:ModelUtil.java   
/**
 * converts a byte array to a hex string in reverse byte order.
 *
 * @param bytes
 *            the array of bytes.
 * @return the string.
 */
public static String toReverseHexString(final byte... bytes) {
    final byte[] ba = new byte[bytes.length];
    System.arraycopy(bytes, 0, ba, 0, bytes.length);
    ArrayUtils.reverse(ba);
    final BigInteger bi = new BigInteger(1, ba);
    return bi.toString(16);
}
项目:mumu    文件:DataUtil.java   
/**
 * 分别去空格
 * 
 * @param paramArray
 * @return
 */
public static final String[] trim(String[] paramArray) {
    if (ArrayUtils.isEmpty(paramArray)) {
        return paramArray;
    }
    String[] resultArray = new String[paramArray.length];
    for (int i = 0; i < paramArray.length; i++) {
        String param = paramArray[i];
        resultArray[i] = StringUtils.trim(param);
    }
    return resultArray;
}
项目:j1st-mqtt    文件:MqttUnsubscribePayload.java   
@Override
public String toString() {
    return StringUtil.simpleClassName(this)
            + '['
            + "topics=" + ArrayUtils.toString(topics)
            + ']';
}
项目:SerenityCE    文件:ModuleConfigurationPanel.java   
private void addValues(Value<?>[] values, List<BaseComponent> components) {
    for (Value<?> value : values) {
        if (value instanceof BooleanValue) {
            components.add(new BooleanValueCheckbox((BooleanValue) value));
        } else if (value instanceof EnumValue) {
            EnumValue enumValue = (EnumValue) value;

            Object[] objects = Arrays.stream(enumValue.getConstants()).map(Enum::toString).toArray();
            String[] strings = new String[objects.length];
            for (int i = 0; i < objects.length; i++) {
                strings[i] = (String) objects[i];
            }

            Dropdown dropdown = new Dropdown(enumValue.getName(), strings) {
                @Override
                protected void onSelectionChanged(String selection) {
                    enumValue.setValueFromString(selection);
                }
            };

            dropdown.setSelectedIndex(ArrayUtils.indexOf(enumValue.getConstants(), enumValue.getValue()));

            components.add(dropdown);
        } else if (value instanceof BlockListValue) {
            components.add(new BlockListSelector(value.getName(), (BlockListValue) value));
        } else {
            components.add(new ValueTextbox(value));
        }
    }
}
项目:springboot-shiro-cas-mybatis    文件:EhcacheBackedMapTests.java   
@Test
public void verifyKeysValues() {
    final String[][] arrayItems = {{"key0", "Item0"}, {"key1", "Item1"}, {"key2", "Item2"}};
    final Map mapItems = ArrayUtils.toMap(arrayItems);

    this.map.putAll(mapItems);
    assertEquals(map.keySet().size(), 3);
    assertEquals(map.values().size(), 3);
}
项目:jblockchain    文件:Block.java   
/**
 * Calculates the Hash of all transactions as hash tree.
 * https://en.wikipedia.org/wiki/Merkle_tree
 * @return SHA256-hash as raw bytes
 */
public byte[] calculateMerkleRoot() {
    Queue<byte[]> hashQueue = new LinkedList<>(transactions.stream().map(Transaction::getHash).collect(Collectors.toList()));
    while (hashQueue.size() > 1) {
        // take 2 hashes from queue
        byte[] hashableData = ArrayUtils.addAll(hashQueue.poll(), hashQueue.poll());
        // put new hash at end of queue
        hashQueue.add(DigestUtils.sha256(hashableData));
    }
    return hashQueue.poll();
}
项目:plugin-prov    文件:TerraformResource.java   
/**
 * Execute the given Terraform commands. Note there is no concurrency check for
 * now.
 */
private void executeTerraform(final Subscription subscription, final Writer out, final String[][] commands,
        final String... additionalParameters) throws InterruptedException, IOException {
    final AtomicInteger step = new AtomicInteger(0);
    // Reset the current step
    for (final String[] command : commands) {
        // Next step, another transaction
        runner.nextStep("service:prov:test:account", t -> t.setStep(TerraformStep.values()[step.get()]));

        final int code = executeTerraform(subscription, out, ArrayUtils.addAll(command, additionalParameters));
        if (code == 0) {
            // Nothing wrong, no change, only useless to go further
            log.info("Terraform paused for {} ({}) : {}", subscription.getId(), subscription, code);
            out.write("Terraform exit code " + code + " -> no need to continue");
            break;
        }
        if (code != 2) {
            // Something goes wrong
            log.error("Terraform failed for {} ({}) : {}", subscription.getId(), subscription, code);
            out.write("Terraform exit code " + code + " -> aborted");
            throw new BusinessException("aborted");
        }
        out.flush();

        // Code is correct, proceed the next command
        step.incrementAndGet();
    }
}
项目:Wechat-Group    文件:WxMpPayServiceImpl.java   
private void checkParameters(WxPayUnifiedOrderRequest request) throws WxErrorException {
  BeanUtils.checkRequiredFields(request);

  if (!ArrayUtils.contains(TRADE_TYPES, request.getTradeType())) {
    throw new IllegalArgumentException("trade_type目前必须为" + Arrays.toString(TRADE_TYPES) + "其中之一,实际值:" + request.getTradeType());
  }

  if ("JSAPI".equals(request.getTradeType()) && request.getOpenid() == null) {
    throw new IllegalArgumentException("当 trade_type是'JSAPI'时未指定openid");
  }

  if ("NATIVE".equals(request.getTradeType()) && request.getProductId() == null) {
    throw new IllegalArgumentException("当 trade_type是'NATIVE'时未指定product_id");
  }
}
项目:AppCoins-ethereumj    文件:OlympicConfig.java   
@Override
public long getTransactionCost(Transaction tx) {
    long nonZeroes = tx.nonZeroDataBytes();
    long zeroVals  = ArrayUtils.getLength(tx.getData()) - nonZeroes;

    return getGasCost().getTRANSACTION() + zeroVals * getGasCost().getTX_ZERO_DATA() +
            nonZeroes * getGasCost().getTX_NO_ZERO_DATA();
}