javatips.net counter

Java Examples for java.util.Arrays

The following java examples will help you to understand the usage of java.util.Arrays. These source code samples are taken from different open source projects.

Example 1
Project: Strata-master  File: LaguerrePolynomialRealRootFinderTest.java View source code
@Test
public void test() {
    Double[] result = ROOT_FINDER.getRoots(TWO_REAL_ROOTS);
    Arrays.sort(result);
    assertEquals(result.length, 2);
    assertEquals(result[0], -4, EPS);
    assertEquals(result[1], -3, EPS);
    result = ROOT_FINDER.getRoots(ONE_REAL_ROOT);
    assertEquals(result.length, 2);
    assertEquals(result[0], 3, EPS);
    assertEquals(result[1], 3, EPS);
    result = ROOT_FINDER.getRoots(CLOSE_ROOTS);
    Arrays.sort(result);
    assertEquals(result.length, 2);
    assertEquals(result[1] - result[0], 1e-6, 1e-8);
}
Example 2
Project: framework-master  File: ComboBoxTextFieldEventOrder.java View source code
@Override
protected void setup() {
    TextField textField = new TextField("text field");
    textField.setImmediate(true);
    final Select select = new Select("select", Arrays.asList("1", "2", "3", "4"));
    textField.addListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            // or
            select.addItem(Long.valueOf(select.size() + 1).toString());
        // just
        // select.requestRepaint();
        }
    });
    addComponent(textField);
    addComponent(select);
}
Example 3
Project: yarn-comment-master  File: TestTextNonUTF8.java View source code
public void testNonUTF8() throws Exception {
    // this is a non UTF8 byte array
    byte b[] = { -0x01, -0x01, -0x01, -0x01, -0x01, -0x01, -0x01 };
    boolean nonUTF8 = false;
    Text t = new Text(b);
    try {
        Text.validateUTF8(b);
    } catch (MalformedInputException me) {
        nonUTF8 = false;
    }
    // asserting that the byte array is non utf8
    assertFalse(nonUTF8);
    byte ret[] = t.getBytes();
    // asseting that the byte array are the same when the Text
    // object is created.
    assertTrue(Arrays.equals(b, ret));
}
Example 4
Project: flink-master  File: ExecutionConfigTest.java View source code
@Test
public void testDoubleTypeRegistration() {
    ExecutionConfig config = new ExecutionConfig();
    List<Class<?>> types = Arrays.<Class<?>>asList(Double.class, Integer.class, Double.class);
    List<Class<?>> expectedTypes = Arrays.<Class<?>>asList(Double.class, Integer.class);
    for (Class<?> tpe : types) {
        config.registerKryoType(tpe);
    }
    int counter = 0;
    for (Class<?> tpe : config.getRegisteredKryoTypes()) {
        assertEquals(tpe, expectedTypes.get(counter++));
    }
    assertTrue(counter == expectedTypes.size());
}
Example 5
Project: quickml-master  File: PenalizedMSEScorerTest.java View source code
@Test
public void simpleTest() {
    ClassificationCounter a = new ClassificationCounter();
    a.addClassification("a", 4);
    a.addClassification("b", 9);
    a.addClassification("c", 1);
    ClassificationCounter b = new ClassificationCounter();
    b.addClassification("a", 5);
    b.addClassification("b", 9);
    b.addClassification("c", 6);
    PenalizedMSEScorer mseScorer = new PenalizedMSEScorer(0, 0.0, new AttributeStats<>(Arrays.asList(a, b), a.add(b), "a"));
    Assert.assertTrue(Math.abs(mseScorer.scoreSplit(a, b) - 0.021776929) < 0.000000001);
}
Example 6
Project: google-web-toolkit-svnmirror-master  File: ExtractClassNamesVisitorTest.java View source code
public void testImportedClasses() throws UnableToCompleteException {
    ExtractClassNamesVisitor v = new ExtractClassNamesVisitor(new TreeSet<String>(Arrays.asList("blah-selector-", "prefixed-", "postfixed-")));
    test(TreeLogger.NULL, "extractClassNames", false, v);
    Set<String> expected = new TreeSet<String>(Arrays.asList("selector1", "selector2", "selector3", "external1", "external2", "external3", "selector_with_underscores", "-selector-with-hyphen"));
    Set<String> actual = new TreeSet<String>(v.getFoundClasses());
    assertEquals(expected, actual);
}
Example 7
Project: tmdm-studio-se-master  File: ProcessAllCallJobVariableCandidatesHolder.java View source code
@Override
public String[] getExternalInfo() {
    if (service == null) {
        return new String[0];
    }
    Set<String> inputVariables = new HashSet<String>();
    for (WSTransformerProcessStep step : service.getProcessSteps()) {
        for (WSTransformerVariablesMapping mapping : step.getInputMappings()) {
            inputVariables.add(mapping.getPipelineVariable() == null ? TransformerMainPage.DEFAULT_VAR : mapping.getPipelineVariable());
        }
    }
    String[] results = inputVariables.toArray(new String[0]);
    Arrays.sort(results);
    return results;
}
Example 8
Project: sitebricks-master  File: FlatTemplateCompiler.java View source code
public Renderable compile(Class<?> page, Template template) {
    try {
        return registry.textWidget(template.getText(), new MvelEvaluatorCompiler(page));
    } catch (ExpressionCompileException e) {
        final List<CompileError> errors = Arrays.asList(CompileError.in(template.getText()).near(e.getError().getError().getLineNumber()).causedBy(e));
        final List<CompileError> warnings = Collections.emptyList();
        metrics.logErrorsAndWarnings(page, errors, warnings);
        throw new TemplateCompileException(page, template.getText(), errors, warnings);
    }
}
Example 9
Project: lettuce-master  File: ConnectToMasterSlaveUsingElastiCacheCluster.java View source code
public static void main(String[] args) {
    // Syntax: redis://[password@]host[:port][/databaseNumber]
    RedisClient redisClient = RedisClient.create();
    List<RedisURI> nodes = Arrays.asList(RedisURI.create("redis://host1"), RedisURI.create("redis://host2"), RedisURI.create("redis://host3"));
    StatefulRedisMasterSlaveConnection<String, String> connection = MasterSlave.connect(redisClient, new Utf8StringCodec(), nodes);
    connection.setReadFrom(ReadFrom.MASTER_PREFERRED);
    System.out.println("Connected to Redis");
    connection.close();
    redisClient.shutdown();
}
Example 10
Project: JPaxos-master  File: CatchUpQueryTest.java View source code
protected void compare(CatchUpQuery expected, CatchUpQuery actual) {
    assertEquals(expected.getView(), actual.getView());
    assertEquals(expected.getSentTime(), actual.getSentTime());
    assertEquals(expected.getType(), actual.getType());
    assertTrue(Arrays.equals(expected.getInstanceIdArray(), actual.getInstanceIdArray()));
    assertTrue(Arrays.equals(expected.getInstanceIdRangeArray(), actual.getInstanceIdRangeArray()));
    assertEquals(expected.isPeriodicQuery(), actual.isPeriodicQuery());
    assertEquals(expected.isSnapshotRequest(), actual.isSnapshotRequest());
}
Example 11
Project: jena-master  File: TestDatasetWithLowerCaseKeywordAnalyzer.java View source code
@Test
public void testLowerCaseKeywordAnalyzerIsCaseInsensitive() {
    final String testName = "testLowerCaseKeywordAnalyzerIsCaseInsensitive";
    final String turtle = StrUtils.strjoinNL(TURTLE_PROLOG, "<" + RESOURCE_BASE + testName + ">", "  rdfs:label 'F;riM at&/ped9'", ".");
    String queryString = StrUtils.strjoinNL(QUERY_PROLOG, "SELECT ?s", "WHERE {", "    ?s text:query ( rdfs:label 'f;ri*' 10 ) .", "}");
    Set<String> expectedURIs = new HashSet<>();
    expectedURIs.addAll(Arrays.asList(RESOURCE_BASE + testName));
    doTestSearch(turtle, queryString, expectedURIs);
}
Example 12
Project: eclipselink.runtime-master  File: XSDTypesHolder.java View source code
public boolean equals(Object obj) {
    if (obj instanceof XSDTypesHolder) {
        for (int i = 0; i < things.size(); i++) {
            Object next = things.get(i);
            Object nextCompare = ((XSDTypesHolder) obj).things.get(i);
            if (next instanceof byte[] && nextCompare instanceof byte[]) {
                if (!(Arrays.equals((byte[]) next, (byte[]) nextCompare))) {
                    return false;
                }
            } else if (!next.equals(nextCompare)) {
                return false;
            }
        }
        return true;
    }
    return false;
}
Example 13
Project: ilarkesto-master  File: GwtServiceInterfaceGenerator.java View source code
@Override
protected void printCode(JavaPrinter out) {
    out.package_(getPackageName());
    out.beginInterface(module.getValue() + "Service", Arrays.asList(com.google.gwt.user.client.rpc.RemoteService.class.getName()));
    List<Node> calls = module.getChildrenByTypeRecursive(ServiceCall);
    for (Node call : calls) {
        List<String> params = getParameterTypesAndNames(call, "String");
        params.add(0, "int conversationNumber");
        out.interfaceMethod(getPackageName() + ".DataTransferObject", Str.lowercaseFirstLetter(call.getValue()), params);
    }
    out.endInterface();
}
Example 14
Project: ehour-master  File: AssignmentAdminBackingBeanTest.java View source code
@Test
public void should_update_customer_when_single_projects_is_selected_in_add_mode() {
    ProjectAssignment assignment = ProjectAssignmentObjectMother.createProjectAssignment(1);
    assignment.setAssignmentId(null);
    should_update_customer_when_single_project_is_selected_in_edit_mode();
    AssignmentAdminBackingBean bean = new AssignmentAdminBackingBean(assignment);
    Project project = ProjectObjectMother.createProject(10);
    bean.setSelectedProjects(Arrays.asList(project));
    bean.updateCustomerBasedOnSelectedProject();
    assertEquals(project.getCustomer(), bean.getCustomer());
}
Example 15
Project: windowtester-master  File: OpenEditorCondition.java View source code
// TODO[pq]: move to utility class
private List<IEditorReference> getEditors() {
    final List<IEditorReference> editors = new ArrayList<IEditorReference>();
    Display.getDefault().syncExec(new Runnable() {

        public void run() {
            IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
            if (window != null) {
                IWorkbenchPage page = window.getActivePage();
                if (page != null) {
                    editors.addAll(Arrays.asList(page.getEditorReferences()));
                }
            }
        }
    });
    return editors;
}
Example 16
Project: expenditures-master  File: FenixJasperCompiler.java View source code
@Override
public String compileClasses(File[] sourceFiles, String classpath) throws JRException {
    // Retrieve files from the standard location
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> sources = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFiles));
    CompilationTask task = compiler.getTask(new StringWriter(), fileManager, null, Arrays.asList("-classpath", classpath), null, sources);
    if (!task.call()) {
        throw new JRException("Error compiling report java source files");
    }
    return null;
}
Example 17
Project: deb-kitkat-storage-access-framework-master  File: TestUtils.java View source code
public static LiveConnectSession newMockLiveConnectSession() {
    LiveAuthClient authClient = TestUtils.newMockLiveAuthClient();
    LiveConnectSession session = new LiveConnectSession(authClient);
    session.setAccessToken("access_token");
    session.setAuthenticationToken("authentication_token");
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, 3600);
    session.setExpiresIn(calendar.getTime());
    String[] scopes = { "scope" };
    session.setScopes(Arrays.asList(scopes));
    session.setRefreshToken("refresh_token");
    session.setTokenType("token_type");
    return session;
}
Example 18
Project: databus-master  File: RemovePaths.java View source code
/**
   * main
   */
public static void main(String[] args) {
    String pathsToDeleteStr = ExampleUtils.getRequiredStringProperty("paths", LOG);
    String[] pathsToDelete = pathsToDeleteStr.split(",");
    LOG.info("Deleting paths: " + Arrays.toString(pathsToDelete));
    ZkClient zkClient = new ZkClient(ExampleUtils.getRequiredStringProperty("zkServerList", LOG), ExampleUtils.getRequiredIntProperty("sessionTimeoutMillis", LOG), ExampleUtils.getRequiredIntProperty("connectTimeoutMillis", LOG));
    for (String pathToDelete : pathsToDelete) {
        zkClient.deleteRecursive(pathToDelete);
    }
    zkClient.close();
}
Example 19
Project: keycloak-master  File: DummyConfigurableUserFederationProviderFactory.java View source code
@Override
public List<ProviderConfigProperty> getConfigProperties() {
    ProviderConfigProperty prop1 = new ProviderConfigProperty();
    prop1.setName("prop1");
    prop1.setLabel("Prop1");
    prop1.setDefaultValue("prop1Default");
    prop1.setHelpText("Prop1 HelpText");
    prop1.setType(ProviderConfigProperty.STRING_TYPE);
    ProviderConfigProperty prop2 = new ProviderConfigProperty();
    prop2.setName("prop2");
    prop2.setLabel("Prop2");
    prop2.setDefaultValue("true");
    prop2.setHelpText("Prop2 HelpText");
    prop2.setType(ProviderConfigProperty.BOOLEAN_TYPE);
    return Arrays.asList(prop1, prop2);
}
Example 20
Project: molgenis-master  File: TokenAuthenticationProviderTest.java View source code
@Test
public void authenticate() {
    RestAuthenticationToken authToken = new RestAuthenticationToken("token");
    assertFalse(authToken.isAuthenticated());
    when(tokenService.findUserByToken("token")).thenReturn(new User("username", "password", Arrays.asList(new SimpleGrantedAuthority("admin"))));
    Authentication auth = tokenAuthenticationProvider.authenticate(authToken);
    assertNotNull(auth);
    assertTrue(auth.isAuthenticated());
    assertEquals(auth.getName(), "username");
    assertEquals(auth.getAuthorities().size(), 1);
    assertEquals(auth.getAuthorities().iterator().next().getAuthority(), "admin");
}
Example 21
Project: cdo-master  File: SignalStreamWrappingTest.java View source code
public void testXORStreamWrappingWithMultipleSignals() throws Exception {
    TestSignalProtocol protocol = null;
    try {
        startTransport();
        protocol = new TestSignalProtocol(getConnector());
        protocol.setStreamWrapper(new XORStreamWrapper(KEY));
        protocol.setTimeout(1000000L);
        for (int i = 0; i < 20; i++) {
            byte[] data = TinyData.getBytes();
            byte[] result = new ArrayRequest(protocol, data).send();
            assertEquals(true, Arrays.equals(data, result));
        }
    } finally {
        if (protocol != null) {
            protocol.close();
        }
    }
}
Example 22
Project: checkstyle-master  File: InputMethodReferences.java View source code
public void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
    numbers.forEach(String.CASE_INSENSITIVE_ORDER::equals);
    InputMethodReferences tl = new InputMethodReferences();
    String roster = new String();
    Supplier<InputMethodReferences> supplier = InputMethodReferences<String>::new;
    numbers.forEach(this::println);
    numbers.forEach(super::println);
    Supplier<InputMethodReferences2> supplier2 = InputMethodReferences2::new;
    Supplier<InputMethodReferences2> suppl = InputMethodReferences2::<Integer>new;
    Function<Integer, String[]> messageArrayFactory = String[]::new;
}
Example 23
Project: JBound-master  File: Exercises.java View source code
protected Restriction forClasses(final Class<?> exercisedClass, final Class<?>... otherExercisedClasses) {
    if (exercisedClass == null) {
        throw new NullPointerException("exercisedClass can not be null");
    }
    if (otherExercisedClasses == null) {
        throw new NullPointerException("otherExercisedClasses can not be null");
    }
    final List<Class<?>> exercisedClasses = new ArrayList<Class<?>>();
    exercisedClasses.add(exercisedClass);
    exercisedClasses.addAll(Arrays.asList(otherExercisedClasses));
    final Builder builder = new Builder(exercisedClasses);
    exercisesBuilders.add(builder);
    return builder;
}
Example 24
Project: raven-aws-emr-kissmetrics-mapreduce-parser-redshift-master  File: KissmetricsJsonToSchemaReducer.java View source code
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
    int total = 0;
    int maxLen = 0;
    int currentLen = 0;
    List<String> valueList = null;
    for (Text value : values) {
        valueList = Arrays.asList(value.toString().split("\t"));
        total += Integer.valueOf(valueList.get(0));
        if (valueList.size() > 1) {
            currentLen = Integer.valueOf(valueList.get(1));
            if (maxLen < currentLen) {
                maxLen = currentLen;
            }
        }
    }
    context.write(key, new Text(String.valueOf(total) + "\t" + String.valueOf(maxLen)));
}
Example 25
Project: teiid-designer-master  File: EntryResult.java View source code
@Override
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if ((anObject != null) && (anObject instanceof EntryResult)) {
        EntryResult anEntryResult = (EntryResult) anObject;
        if (!Arrays.equals(this.word, anEntryResult.word))
            return false;
        int length;
        int[] refs, otherRefs;
        if ((length = (refs = this.fileRefs).length) != (otherRefs = anEntryResult.fileRefs).length)
            return false;
        for (int i = 0; i < length; i++) {
            if (refs[i] != otherRefs[i])
                return false;
        }
        return true;
    }
    return false;
}
Example 26
Project: incubator-hivemall-master  File: MinHashUDFTest.java View source code
@Test
public void testEvaluate() throws HiveException {
    MinHashesUDF minhash = new MinHashesUDF();
    Assert.assertEquals(5, minhash.evaluate(Arrays.asList(1, 2, 3, 4)).size());
    Assert.assertEquals(9, minhash.evaluate(Arrays.asList(1, 2, 3, 4), 9, 2).size());
    Assert.assertEquals(minhash.evaluate(Arrays.asList(1, 2, 3, 4)), minhash.evaluate(Arrays.asList(1, 2, 3, 4), 5, 2));
    Assert.assertEquals(minhash.evaluate(Arrays.asList(1, 2, 3, 4)), minhash.evaluate(Arrays.asList("1", "2", "3", "4"), true));
    Assert.assertEquals(minhash.evaluate(Arrays.asList(1, 2, 3, 4)), minhash.evaluate(Arrays.asList("1:1.0", "2:1.0", "3:1.0", "4:1.0"), false));
}
Example 27
Project: MyFramework-master  File: DateHelper.java View source code
public static Date parseDate(String value, Class targetType, String... formats) {
    for (String format : formats) {
        try {
            long v = new SimpleDateFormat(format).parse(value).getTime();
            return (Date) targetType.getConstructor(long.class).newInstance(v);
        } catch (ParseException e) {
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            return (Date) targetType.getConstructor(String.class).newInstance(value);
        } catch (Exception e) {
        }
    }
    throw new IllegalArgumentException("cannot parse:" + value + " for date by formats:" + Arrays.asList(formats));
}
Example 28
Project: raylew_algorithm-master  File: 组合问题.java View source code
public static void dfs(int cur) {
    int sum = 0;
    for (int i = 0; i < cur; i++) {
        sum += res[i];
    }
    if (sum >= goal) {
        if (sum == goal) {
            total++;
            for (int i = 0; i < cur; i++) {
                System.out.print(res[i] + ",");
            }
            System.out.println();
        }
        return;
    }
    int index = Arrays.binarySearch(arr, 2);
    for (int i = index; i < N; i++) {
        if (cur == 0) {
            res[cur] = arr[i];
            dfs(cur + 1);
        } else {
            if (arr[i] >= res[cur - 1]) {
                res[cur] = arr[i];
                dfs(cur + 1);
            }
        }
    }
}
Example 29
Project: dimple-master  File: TestNonNullListIndices.java View source code
@Test
public void test() {
    List<String> list = Arrays.asList("foo", null, "bar", null, null, "baz");
    NonNullListIndices indices = new NonNullListIndices(list);
    assertSame(list, indices.getList());
    assertArrayEquals(new Object[] { 0, 2, 5 }, Iterators.toArray(indices.iterator(), Integer.class));
    PrimitiveIterator.OfInt iter = indices.iterator();
    assertTrue(iter.hasNext());
    assertEquals(0, iter.nextInt());
    assertEquals(2, iter.nextInt());
    assertEquals(5, iter.nextInt());
    assertFalse(iter.hasNext());
    expectThrow(NoSuchElementException.class, iter, "nextInt");
    expectThrow(UnsupportedOperationException.class, iter, "remove");
}
Example 30
Project: lucene-solr-master  File: SystemInfoHandlerTest.java View source code
public void testMagickGetter() throws Exception {
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    // make one directly
    SimpleOrderedMap<Object> info = new SimpleOrderedMap<>();
    info.add("name", os.getName());
    info.add("version", os.getVersion());
    info.add("arch", os.getArch());
    // make another using addMXBeanProperties() 
    SimpleOrderedMap<Object> info2 = new SimpleOrderedMap<>();
    SystemInfoHandler.addMXBeanProperties(os, OperatingSystemMXBean.class, info2);
    // make sure they got the same thing
    for (String p : Arrays.asList("name", "version", "arch")) {
        assertEquals(info.get(p), info2.get(p));
    }
}
Example 31
Project: android-platform-tools-base-master  File: SdkManagerTest7.java View source code
public void testSdkManager_getBuildTools() {
    // There is no build-tools folder in this repository.
    SdkManager sdkman = getSdkManager();
    Set<FullRevision> v = sdkman.getBuildTools();
    // Make sure we get a stable set -- hashmap order isn't stable and can't be used in tests.
    if (!(v instanceof TreeSet<?>)) {
        v = Sets.newTreeSet(v);
    }
    // no errors in the logger
    assertEquals("", getLog().toString());
    assertEquals("[]", Arrays.toString(v.toArray()));
    assertNull(sdkman.getBuildTool(new FullRevision(1)));
    assertNull(sdkman.getBuildTool(new FullRevision(3, 0, 0)));
    assertNull(sdkman.getBuildTool(new FullRevision(12, 3, 4, 5)));
}
Example 32
Project: freemind-mmx-master  File: RemoveMapToNodeAction.java View source code
/* (non-Javadoc)
	 * @see freemind.extensions.NodeHookAdapter#invoke(freemind.modes.MindMapNode)
	 */
public void invoke(MindMapNode pNode) {
    super.invoke(pNode);
    List selecteds = getMindMapController().getSelecteds();
    for (Iterator it = selecteds.iterator(); it.hasNext(); ) {
        MindMapNode node = (MindMapNode) it.next();
        MapNodePositionHolderBase hook = MapNodePositionHolder.getHook(node);
        if (hook != null) {
            List nodeSelected = Arrays.asList(new MindMapNode[] { node });
            // double add = remove
            getMindMapController().addHook(node, nodeSelected, MapNodePositionHolderBase.NODE_MAP_HOOK_NAME, null);
        }
    }
}
Example 33
Project: aws-sdk-android-master  File: Base16CodecTest.java View source code
@Test
public void testVectorsPerRfc4648() throws NoSuchAlgorithmException, UnsupportedEncodingException {
    String[] testVectors = { "", "f", "fo", "foo", "foob", "fooba", "foobar" };
    String[] expected = { "", "66", "666F", "666F6F", "666F6F62", "666F6F6261", "666F6F626172" };
    for (int i = 0; i < testVectors.length; i++) {
        String data = testVectors[i];
        byte[] source = data.getBytes("UTF-8");
        String b16encoded = Base16.encodeAsString(data.getBytes("UTF-8"));
        Assert.assertEquals(expected[i], b16encoded);
        byte[] b16 = b16encoded.getBytes("UTF-8");
        byte[] decoded = Base16.decode(b16);
        Assert.assertTrue(Arrays.equals(source, decoded));
    }
}
Example 34
Project: org.eclipse.ecr-master  File: SerializableInputStreamTest.java View source code
public void testFileBlobSerialization() throws Exception {
    URL url = getResource("org.eclipse.ecr.core.api.test", "resources/test.blob");
    assertNotNull(url);
    InputStream sin = new SerializableInputStream(url.openStream());
    File tmp = File.createTempFile("SerializableISTest-", ".tmp");
    tmp.deleteOnExit();
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmp));
    out.writeObject(sin);
    out.close();
    ObjectInputStream oin = new ObjectInputStream(new FileInputStream(tmp));
    sin = (InputStream) oin.readObject();
    byte[] bytes1 = FileUtils.readBytes(url.openStream());
    byte[] bytes2 = FileUtils.readBytes(sin);
    assertTrue(Arrays.equals(bytes1, bytes2));
}
Example 35
Project: codemap-master  File: DijkstrasAlgorithm.java View source code
public static int[] apply(Graph g, int source) {
    int[] dist = new int[g.nodes.length];
    boolean[] done = new boolean[g.nodes.length];
    Node[] todo = new Node[g.nodes.length];
    Arrays.fill(dist, Integer.MAX_VALUE);
    int index = 0;
    todo[index++] = g.nodes[source];
    done[source] = true;
    dist[source] = 0;
    for (int n = 0; n < todo.length; n++) {
        Node node = todo[n];
        if (node == null)
            break;
        int d = dist[node.index] + 1;
        for (Node each : node.edges) {
            if (done[each.index])
                continue;
            todo[index++] = each;
            dist[each.index] = d;
            done[each.index] = true;
        }
    }
    return dist;
}
Example 36
Project: McMMOPlus-master  File: AlchemyBrewCheckTask.java View source code
@Override
public void run() {
    Location location = brewingStand.getLocation();
    ItemStack[] newInventory = Arrays.copyOfRange(brewingStand.getInventory().getContents(), 0, 4);
    boolean validBrew = AlchemyPotionBrewer.isValidBrew(player, newInventory);
    if (Alchemy.brewingStandMap.containsKey(location)) {
        if (oldInventory[Alchemy.INGREDIENT_SLOT] == null || newInventory[Alchemy.INGREDIENT_SLOT] == null || !oldInventory[Alchemy.INGREDIENT_SLOT].isSimilar(newInventory[Alchemy.INGREDIENT_SLOT]) || !validBrew) {
            Alchemy.brewingStandMap.get(location).cancelBrew();
        }
    } else if (validBrew) {
        Alchemy.brewingStandMap.put(location, new AlchemyBrewTask(brewingStand, player));
    }
}
Example 37
Project: androiddevice.info-master  File: PackageSigProperty.java View source code
@Override
public Object getProperty() {
    try {
        JSONArray result = new JSONArray();
        PackageInfo packageInfo = Application.getContext().getPackageManager().getPackageInfo("android", PackageManager.GET_SIGNATURES);
        for (Signature item : Arrays.asList(packageInfo.signatures)) {
            MessageDigest digest = null;
            try {
                digest = MessageDigest.getInstance("SHA-256");
                digest.update(item.toCharsString().getBytes());
                result.put(byteToHexString(digest.digest()));
            } catch (NoSuchAlgorithmException e) {
            }
        }
        return result;
    } catch (PackageManager.NameNotFoundException e) {
        return JSONObject.NULL;
    }
}
Example 38
Project: cms-ce-master  File: PreferenceXmlCreatorTest.java View source code
@Test
public void testCreatePreferencesDocumentMultiple() throws Exception {
    final String expectedXml = getXml("/com/enonic/cms/core/preference/MultiplePreferencesDocument-result.xml");
    final PreferenceEntity pref1 = new PreferenceEntity();
    final PreferenceKey key1 = new PreferenceKey("user:ABC1234.GLOBAL.key1");
    pref1.setKey(key1);
    pref1.setValue("value1");
    final PreferenceEntity pref2 = new PreferenceEntity();
    final PreferenceKey key2 = new PreferenceKey("user:ABC1234.GLOBAL.key2");
    pref2.setKey(key2);
    pref2.setValue("value2");
    final XMLDocument xmlDoc = PreferenceXmlCreator.createPreferencesDocument(Arrays.asList(pref1, pref2));
    assertEquals(expectedXml, getFormattedXmlString(xmlDoc));
}
Example 39
Project: csrf-jhipster-master  File: LoggingAspect.java View source code
@Around("loggingPoincut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    try {
        Object result = joinPoint.proceed();
        log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), result);
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        throw e;
    }
}
Example 40
Project: android_packages_apps-master  File: IntArrayTest.java View source code
public void testIntArray() {
    IntArray a = new IntArray();
    assertEquals(0, a.size());
    assertTrue(Arrays.equals(new int[] {}, a.toArray(null)));
    a.add(0);
    assertEquals(1, a.size());
    assertTrue(Arrays.equals(new int[] { 0 }, a.toArray(null)));
    a.add(1);
    assertEquals(2, a.size());
    assertTrue(Arrays.equals(new int[] { 0, 1 }, a.toArray(null)));
    int[] buf = new int[2];
    int[] result = a.toArray(buf);
    assertSame(buf, result);
    IntArray b = new IntArray();
    for (int i = 0; i < 100; i++) {
        b.add(i * i);
    }
    assertEquals(100, b.size());
    result = b.toArray(buf);
    assertEquals(100, result.length);
    for (int i = 0; i < 100; i++) {
        assertEquals(i * i, result[i]);
    }
}
Example 41
Project: MUtils-master  File: ThreadUtil.java View source code
/**
     * Get threads for group
     */
public static Thread[] getGroup(String name) {
    Thread[] activeThreads = new Thread[Thread.activeCount()];
    int enumCount = Thread.enumerate(activeThreads);
    LinkedList<Thread> group = new LinkedList<Thread>();
    for (int i = 0; i < enumCount; i++) {
        Thread t = activeThreads[i];
        ThreadGroup tGroup = t.getThreadGroup();
        if (tGroup == null) {
            continue;
        }
        String gName = tGroup.getName();
        if (gName != null && gName.equals(name)) {
            group.add(t);
        }
    }
    Arrays.fill(activeThreads, null);
    Thread[] groupThreads = new Thread[group.size()];
    group.toArray(groupThreads);
    group.clear();
    return groupThreads;
}
Example 42
Project: ocr-tools-master  File: ResultXmlMergerTest.java View source code
@Test
public void shouldMergeTwoWellFormed() throws XpathException, SAXException, IOException {
    InputStream stream1 = new ByteArrayInputStream(input1.getBytes());
    InputStream stream2 = new ByteArrayInputStream(input2.getBytes());
    List<InputStream> inputs = Arrays.asList(stream1, stream2);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    Merger mergerSut = new ResultXmlMerger();
    mergerSut.mergeBuffered(inputs, output);
    String result = output.toString();
    System.out.println(result);
    assertXpathEvaluatesTo("2", "count(//Statistics)", result);
    assertXpathEvaluatesTo("1500", "sum([email protected])", result);
    assertXpathEvaluatesTo("150", "sum([email protected])", result);
}
Example 43
Project: hank-master  File: TestFooter.java View source code
@Test
public void testValid() throws Exception {
    final FileOutputStream out = new FileOutputStream(filePath);
    out.write(new byte[] { // not going to have any actual data section
    5, 0, 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 125, 0, 0, 0, 0, 0, 0, 0, (byte) 0xff, 0, 0, 0, 0, 0, 0, 0, (byte) 130, 0, 0, 0, (byte) 250, 0, 0, 0 });
    out.flush();
    out.close();
    final Footer footer = new Footer(new FileInputStream(filePath).getChannel(), 2);
    assertEquals(0, footer.getDataLength());
    assertEquals(40, footer.getFileSize());
    assertEquals(250, footer.getMaxCompressedBufferSize());
    assertEquals(130, footer.getMaxUncompressedBufferSize());
    assertTrue(Arrays.equals(new long[] { 5, 25, 125, 255 }, footer.getHashIndex()));
}
Example 44
Project: OSM2World-master  File: CAGUtilTest.java View source code
@Test
public void testOverlap() {
    List<VectorXZ> outline = asList(new VectorXZ(1, -2), new VectorXZ(1, 2), new VectorXZ(-1, 2), new VectorXZ(-1, -2), new VectorXZ(1, -2));
    List<VectorXZ> subOutline = asList(new VectorXZ(2, -1), new VectorXZ(0, -1), new VectorXZ(0, 1), new VectorXZ(2, 1), new VectorXZ(2, -1));
    List<PolygonWithHolesXZ> results = new ArrayList<PolygonWithHolesXZ>(CAGUtil.subtractPolygons(new SimplePolygonXZ(outline), Arrays.asList(new SimplePolygonXZ(subOutline))));
    assertSame(1, results.size());
    assertSameCyclicOrder(results.get(0).getOuter().getVertices(), new VectorXZ(1, -2), new VectorXZ(1, -1), new VectorXZ(0, -1), new VectorXZ(0, 1), new VectorXZ(1, 1), new VectorXZ(1, 2), new VectorXZ(-1, 2), new VectorXZ(-1, -2));
}
Example 45
Project: dtangler-master  File: GenericDependencyEngineTest.java View source code
@Test
public void testDependencies() {
    String corePath = ClassPathEntryFinder.getPathContaining("core");
    String dtPath = corePath + "/org/dtangler/genericengine/dependencyengine/testdata/test.dt";
    Arguments args = new Arguments();
    args.setInput(Arrays.asList(dtPath));
    GenericDependencyEngine engine = new GenericDependencyEngine();
    Dependencies dependencies = engine.getDependencies(args);
    DependencyGraph deps = dependencies.getDependencyGraph(dependencies.getDefaultScope());
    assertEquals("scope2", dependencies.getDefaultScope().getDisplayName());
    List<String> items = getItemNames(deps.getAllItems());
    assertEquals(2, items.size());
    assertTrue(items.containsAll(new HashSet<String>(Arrays.asList("item1", "item2"))));
}
Example 46
Project: picard-tools-master  File: RelativeIso8601DateTest.java View source code
@Test
public void testNonLazyInstance() {
    // ISO strips off milliseconds
    final long time = new Iso8601Date(new Date(System.currentTimeMillis())).getTime();
    // Test both constructor methods
    final List<RelativeIso8601Date> testDates = Arrays.<RelativeIso8601Date>asList(new RelativeIso8601Date(new Date(time)), new RelativeIso8601Date(new Iso8601Date(new Date(time)).toString()));
    for (final RelativeIso8601Date nonLazy : testDates) {
        Assert.assertFalse(nonLazy.toString().equals(RelativeIso8601Date.LAZY_NOW_LABEL));
        Assert.assertEquals((double) nonLazy.getTime(), (double) time);
        // Assert no exception thrown; this should be valid, because toString return an iso-looking date.
        new RelativeIso8601Date(nonLazy.toString());
    }
}
Example 47
Project: castor-master  File: MapOfArrays.java View source code
public boolean equals(Object obj) {
    if (!(obj instanceof MapOfArrays)) {
        return false;
    }
    final MapOfArrays other = (MapOfArrays) obj;
    if (other.getMap().size() != this.getMap().size()) {
        return false;
    }
    final Set myKeys = this.getMap().keySet();
    final Set otherKeys = other.getMap().keySet();
    if (!myKeys.containsAll(otherKeys) && otherKeys.containsAll(myKeys)) {
        return false;
    }
    for (Iterator i = myKeys.iterator(); i.hasNext(); ) {
        final Object key = i.next();
        final String[] myValue = (String[]) this.getMap().get(key);
        final String[] otherValue = (String[]) other.getMap().get(key);
        if (!Arrays.equals(myValue, otherValue)) {
            return false;
        }
    }
    return true;
}
Example 48
Project: rapaio-master  File: OLSRFit.java View source code
@Override
public void printSummary() {
    StringBuilder sb = new StringBuilder();
    sb.append("OLS regression fit printSummary\n");
    sb.append("======================\n");
    sb.append("\n");
    sb.append("Model type: ").append(regressor.name()).append("\n");
    sb.append("Model instance: ").append(regressor.fullName()).append("\n");
    sb.append("\n");
    sb.append("Predicted frame printSummary:\n");
    sb.append(" - rows: ").append(getFrame().rowCount()).append("\n");
    sb.append(" - cols: ").append(getFrame().varCount()).append("\n");
    sb.append(" - inputs: ").append(Arrays.toString(regressor.inputNames())).append("\n");
    sb.append(" - targets: ").append(Arrays.toString(regressor.targetNames())).append("\n");
    sb.append("\n");
    WS.code(sb.toString());
}
Example 49
Project: sonar-java-master  File: ReplaceLambdaByMethodRefCheck_no_version.java View source code
void fun() {
    IntStream.range(1, 5).map(( x) -> x * x).map(// Noncompliant {{Replace this lambda with a method reference. (sonar.java.source not set. Assuming 8 or greater.)}}
     x -> square(x)).map(// Noncompliant
     x -> {
        return square(x);
    }).map(//Compliant
    this::square).forEach(System.out::println);
    // Noncompliant
    IntStream.range(1, 5).forEach( x -> System.out.println(x));
    // Noncompliant
    IntStream.range(1, 5).forEach(// Noncompliant
     x -> {
        System.out.println(x);
    });
    // Compliant
    IntStream.range(1, 5).forEach( x -> {
        return;
    });
    // Compliant
    Arrays.asList("bar").stream().filter( string -> string.startsWith("b"));
    // Compliant
    Arrays.asList(new A()).stream().filter( a -> a.coolerThan(0, a));
}
Example 50
Project: eclipse.jdt.core-master  File: A_out.java View source code
public void function1(Object param1, Object param2, Object param3, Object param4) throws Exc1, Ex2, Ex3 {
    List<String> strings = Arrays.asList("aaa", "bbb", "ccc", "ddd");
    int aa = 11111, bb = 22222, cc = 33333, dd = 44444;
    param1.field1.field2.field3.function();
    param2.function1().function2().function3().function4();
    String sss1 = this.array.length > 3 ? "yes" : "no";
    String sss2 = this.array.length > 3 ? "yes" : "no";
    try (InputStream in = new IStream();
        OutputStream out = new OStream();
        Object o = null) {
        System.out.println(aa * (aa + bb) * cc * (cc + aa));
    } catch (Exception1Exception2 | Exception3 |  e) {
        System.out.println(param3.function1(aa, bb));
    }
    this.getWriter().println("aaaaa" + //
    "bbbbbb" + "ccc");
}
Example 51
Project: keywhiz-master  File: UtilitiesTest.java View source code
@Test
public void validateNameReturnsFalseOnInvalidNames() throws Exception {
    assertThat(validName("hello!")).isFalse();
    assertThat(validName("hello world")).isFalse();
    assertThat(validName("$$ bill yall")).isFalse();
    assertThat(validName("blah/../../../etc/passwd")).isFalse();
    assertThat(validName("bad/I-am-secret.yml")).isFalse();
    assertThat(validName(".almostvalid")).isFalse();
    assertThat(validName("bad\tI-am-secret.yml")).isFalse();
    List<String> specialCharacters = Arrays.asList("&", "|", "(", ")", "[", "]", "{", "}", "^", ";", ",", "\\", "/", "<", ">", "\t", "\n", "\r", "`", "'", "\"", "?", "#", "%", "*", "+", "=", "\0", "", "\000");
    for (String name : specialCharacters) {
        assertFalse("Failed character: \"" + name + "\"", validName(name));
    }
}
Example 52
Project: breakout-master  File: LineLineIntersection2fTest.java View source code
public static void main(String[] args) {
    System.out.println(Math.floor(Math.log10(20.35)));
    System.out.println(Math.floor(Math.log10(0.0053)));
    float[] m = { 1, -1, -5, -.5f, 0, 5, 0, 1 };
    // float[ ] m = { -1 , 1 , -.5f , -5f , 5 , 0 , 1 , 0 };
    System.out.println(Vecmath.prettyPrint(m, 4));
    int[] row_perms = new int[2];
    Vecmath.gauss(m, 2, 4, row_perms);
    System.out.println(Arrays.toString(row_perms));
    System.out.println(Vecmath.prettyPrint(m, 4, row_perms));
    LineLineIntersection2f llx = new LineLineIntersection2f();
    llx.setUp(new float[] { 0, 5 }, new float[] { 1, -1 }, new float[] { 0, -1 }, new float[] { 5, .5f });
    llx.findIntersection();
    System.out.println(llx.t0);
    System.out.println(llx.t1);
    System.out.println(Arrays.toString(llx.x));
}
Example 53
Project: adc-wildner-master  File: MainTestDefMe_saveToMemory.java View source code
public static void main(String[] arg) throws IOException {
    // Loading the binary context
    // the database
    String input = fileToPath("contextZart.txt");
    // means a minsup of 2 transaction (we used a relative support)
    double minsup = 0.4;
    TransactionDatabase database = new TransactionDatabase();
    try {
        database.loadFile(input);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Applying the DefMe algorithm
    AlgoDefMe algo = new AlgoDefMe();
    Itemsets generators = algo.runAlgorithm(null, database, minsup);
    algo.printStats();
    for (List<Itemset> genSizeK : generators.getLevels()) {
        for (Itemset itemset : genSizeK) {
            System.out.println(Arrays.toString(itemset.getItems()) + " #SUP: " + itemset.getAbsoluteSupport());
        }
    }
}
Example 54
Project: devcoin-android-master  File: Base58Test.java View source code
public void testDecode() throws Exception {
    byte[] testbytes = "Hello World".getBytes();
    byte[] actualbytes = Base58.decode("JxF12TrwUP45BMd");
    assertTrue(new String(actualbytes), Arrays.equals(testbytes, actualbytes));
    assertTrue("1", Arrays.equals(Base58.decode("1"), new byte[1]));
    assertTrue("1111", Arrays.equals(Base58.decode("1111"), new byte[4]));
    try {
        Base58.decode("This isn't valid base58");
        fail();
    } catch (AddressFormatException e) {
    }
    Base58.decodeChecked("4stwEBjT6FYyVV");
    // Now check we can correctly decode the case where the high bit of the first byte is not zero, so BigInteger
    // sign extends. Fix for a bug that stopped us parsing keys exported using sipas patch.
    Base58.decodeChecked("93VYUMzRG9DdbRP72uQXjaWibbQwygnvaCu9DumcqDjGybD864T");
}
Example 55
Project: mldht-master  File: EncoderTest.java View source code
@Test
public void testSorting() {
    Map<String, Object> root = new LinkedHashMap<>();
    String[] keys = new String[256];
    Arrays.setAll(keys, ( i) -> buf2str(ByteBuffer.wrap(new byte[] { (byte) i })));
    // clone to shuffle independently of original order
    List<String> keyList = Arrays.asList(keys);
    List<String> shuffledKeys = Arrays.asList(keys.clone());
    Collections.shuffle(shuffledKeys);
    shuffledKeys.forEach( s -> root.put(s, 1L));
    BEncoder enc = new BEncoder();
    ByteBuffer out = enc.encode(root, 2048);
    StringBuilder reference = new StringBuilder();
    reference.append("d");
    keyList.forEach( str -> {
        reference.append("1:");
        reference.append(str);
        reference.append("i1e");
    });
    reference.append("e");
    assertEquals(str2buf(reference.toString()), out);
}
Example 56
Project: usercenter-master  File: SimpleCredentialsMatcher.java View source code
protected boolean equals(Object tokenCredentials, Object accountCredentials) {
    if (log.isDebugEnabled()) {
        log.debug("Performing credentials equality check for tokenCredentials of type [" + tokenCredentials.getClass().getName() + " and accountCredentials of type [" + accountCredentials.getClass().getName() + "]");
    }
    if (isByteSource(tokenCredentials) && isByteSource(accountCredentials)) {
        if (log.isDebugEnabled()) {
            log.debug("Both credentials arguments can be easily converted to byte arrays.  Performing " + "array equals comparison");
        }
        byte[] tokenBytes = toBytes(tokenCredentials);
        byte[] accountBytes = toBytes(accountCredentials);
        return Arrays.equals(tokenBytes, accountBytes);
    } else {
        return accountCredentials.equals(tokenCredentials);
    }
}
Example 57
Project: cdt-tests-runner-master  File: MIRegistersTest_7_2.java View source code
// GDB's list of registers is different with GDB 7.2
@Override
protected List<String> get_X86_REGS() {
    List<String> list = new LinkedList<String>(Arrays.asList("eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", "eflags", "cs", "ss", "ds", "es", "fs", "gs", "st0", "st1", "st2", "st3", "st4", "st5", "st6", "st7", "fctrl", "fstat", "ftag", "fiseg", "fioff", "foseg", "fooff", "fop", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", /*"","","","","","","","",*/
    "mxcsr", "orig_eax", "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "ax", "cx", /*"",*/
    "dx", "bx", "bp", "si", "di", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7"));
    // On Windows, gdb doesn't report "orig_eax" as a register. Apparently it does on Linux
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        list.remove("orig_eax");
    }
    return list;
}
Example 58
Project: GlowstonePlusPlus-master  File: MushroomDecorator.java View source code
@Override
public void decorate(World world, Random random, Chunk source) {
    int sourceX = (source.getX() << 4) + random.nextInt(16);
    int sourceZ = (source.getZ() << 4) + random.nextInt(16);
    int sourceY = random.nextInt(128);
    for (int i = 0; i < 64; i++) {
        int x = sourceX + random.nextInt(8) - random.nextInt(8);
        int z = sourceZ + random.nextInt(8) - random.nextInt(8);
        int y = sourceY + random.nextInt(4) - random.nextInt(4);
        final Block block = world.getBlockAt(x, y, z);
        final Block blockBelow = world.getBlockAt(x, y - 1, z);
        if (y < 128 && block.getType() == Material.AIR && Arrays.asList(MATERIALS).contains(blockBelow.getType())) {
            final BlockState state = block.getState();
            state.setType(type);
            state.setData(new MaterialData(type));
            state.update(true);
        }
    }
}
Example 59
Project: GATECH-master  File: DataSetLabelBinarySeperator.java View source code
public static void seperateLabels(DataSet set) {
    int numberOfLabels = 0;
    ArrayList<Integer> labels = new ArrayList<Integer>();
    //count up the number of distinct labels
    for (int i = 0; i < set.size(); i++) {
        if (!labels.contains(new Integer(set.getInstances()[i].getLabel().getDiscrete()))) {
            numberOfLabels++;
            labels.add(new Integer(set.getInstances()[i].getLabel().getDiscrete()));
        }
    }
    double[] values = new double[numberOfLabels];
    for (int i = 0; i < values.length; i++) {
        values[i] = 0;
    }
    for (int i = 0; i < set.size(); i++) {
        int labelValue = set.getInstances()[i].getLabel().getDiscrete() % values.length;
        values[labelValue] = 1;
        Instance instance = new Instance(Arrays.copyOf(values, values.length));
        set.get(i).setLabel(instance);
        values[labelValue] = 0;
    }
}
Example 60
Project: LambdaDojo-master  File: S206LambdaForCompositeFunction.java View source code
private void sortPerson() {
    List<Person> persons = Arrays.asList(new Person("James", "Brown"), new Person("David", "Crosby"), new Person("James", "Taylor"), new Person("Jackson", "Brown"), new Person("Neil", "Young"), new Person("Coco", "Taylor"));
    Comparator<Person> comparator = new Comparator<Person>() {

        @Override
        public int compare(Person p1, Person p2) {
            // 姓で比較
            String last1 = p1.getLast();
            String last2 = p2.getLast();
            int result = last1.compareTo(last2);
            if (result != 0) {
                return result;
            } else {
                // 姓が同じ場合、名で比較
                String first1 = p1.getFirst();
                String first2 = p2.getFirst();
                return first1.compareTo(first2);
            }
        }
    };
    Collections.sort(persons, comparator);
    System.out.println(persons);
}
Example 61
Project: TinyProtocolAPI-master  File: TestTPAPI.java View source code
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    TabAPI.refresh(this.getClass(), (Player) sender,  api -> {
        api.setTexture("MHF_Cow");
        api.setSignal(99999);
        api.setMessage(0, 0, "test1");
        api.setSignal(1, 0, 0);
        api.setTexture(2, 0, "MHF_Slime");
        Collection<String> list = Arrays.asList("eldo", "eldo", "eldo");
        api.set(Arrays.asList("elo", "elo", "elo"), list);
        ArrayList<String> foot = api.getFooter();
        System.out.println(foot);
        api.set(0, 1, "test2", 13);
        api.set(1, 1, "test3", "MHF_Pig");
        api.set(2, 1, "test4", "MHF_Zombie", 0);
        System.out.println(api.getMessage(0, 0));
        System.out.println(api.getTexture(2, 1));
        System.out.println(api.getSignal(0, 1));
    });
    return super.onCommand(sender, command, label, args);
}
Example 62
Project: GdxStudio-master  File: ImageBinaryGreyFeature.java View source code
public void init(BufferedImage img) {
    image = new RGBImage();
    grey = new ImageBinaryChannelFeature();
    list = Arrays.asList(new ImageBinaryChannelFeature[] { grey });
    this.image.init(img);
    this.grey.initBase(this.image.r);
    for (int x = 0; x < this.image.cx; x++) {
        for (int y = 0; y < this.image.cy; y++) {
            this.image.step(x, y);
            this.grey.step(x, y);
        }
    }
    grey.zeroMean = new ImageZeroMean();
    grey.zeroMean.init(grey.integral);
    for (int x = 0; x < this.image.cx; x++) {
        for (int y = 0; y < this.image.cy; y++) {
            grey.zeroMean.step(x, y);
        }
    }
    grey.zeroMeanIntegral = new IntegralImage();
    grey.zeroMeanIntegral.initBase(grey.zeroMean);
    for (int x = 0; x < this.image.cx; x++) {
        for (int y = 0; y < this.image.cy; y++) {
            grey.zeroMeanIntegral.step(x, y);
        }
    }
}
Example 63
Project: Eclipse-Postfix-Code-Completion-master  File: ConfigureWorkingSetAction.java View source code
/**
	 * [email protected]}
	 */
@Override
public void run() {
    List<IWorkingSet> workingSets = new ArrayList<IWorkingSet>(Arrays.asList(fWorkingSetModel.getAllWorkingSets()));
    IWorkingSet[] activeWorkingSets;
    if (fWorkingSetModel.needsConfiguration()) {
        activeWorkingSets = fWorkingSetModel.getAllWorkingSets();
    } else {
        activeWorkingSets = fWorkingSetModel.getActiveWorkingSets();
    }
    boolean isSortingEnabled = fWorkingSetModel.isSortingEnabled();
    WorkingSetConfigurationDialog dialog = new WorkingSetConfigurationDialog(fSite.getShell(), workingSets.toArray(new IWorkingSet[workingSets.size()]), isSortingEnabled);
    dialog.setSelection(activeWorkingSets);
    if (dialog.open() == IDialogConstants.OK_ID) {
        isSortingEnabled = dialog.isSortingEnabled();
        fWorkingSetModel.setWorkingSets(dialog.getAllWorkingSets(), isSortingEnabled, dialog.getSelection());
    }
}
Example 64
Project: neo4j-jdbc-master  File: ResultSetTest.java View source code
@SuppressWarnings("unchecked")
@Parameterized.Parameters
public static Collection<ResultSet[]> data() {
    row = Arrays.<Object>asList("0", 1, (short) 2, 3L, (byte) 4, 5f, 6d, BigDecimal.valueOf(7L), null, new String[] { "array" }, Collections.singletonMap("a", 1), Collections.singletonList("list"));
    List<Neo4jColumnMetaData> columns = asList(col("String", Types.VARCHAR), col("int", Types.INTEGER), col("short", Types.SMALLINT), col("long", Types.BIGINT), col("byte", Types.TINYINT), col("float", Types.FLOAT), col("double", Types.DOUBLE), col("BigDecimal", Types.NUMERIC), col("Null", Types.NULL), col("Array", Types.ARRAY), col("Map", Types.STRUCT), col("List", Types.ARRAY));
    return Arrays.<ResultSet[]>asList(new ResultSet[] { new ListResultSet(columns, Arrays.<List<Object>>asList(row), null) }, new ResultSet[] { new IteratorResultSet(columns, Arrays.<Object[]>asList(row.toArray()).iterator(), null) });
}
Example 65
Project: open-mika-master  File: PKIXCertPathValidatorSpiTest.java View source code
public void testTrustAndRemoteCertificatesWithDifferentEncodings() throws IOException, CertificateException, KeyStoreException, InvalidAlgorithmParameterException, CertPathValidatorException {
    X509CertPathImpl certPath = new X509CertPathImpl(Arrays.asList(new X509CertImpl(serviceSprintComCertChain[0]), new X509CertImpl(serviceSprintComCertChain[1]), new X509CertImpl(serviceSprintComCertChain[2])));
    Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
    trustAnchors.add(new TrustAnchor(new X509CertificateObject(new X509CertificateStructure((ASN1Sequence) new ASN1InputStream(trustedCert).readObject())), null));
    IndexedPKIXParameters indexedPKIXParameters = new IndexedPKIXParameters(trustAnchors);
    indexedPKIXParameters.setRevocationEnabled(false);
    new PKIXCertPathValidatorSpi().engineValidate(certPath, indexedPKIXParameters);
// completing normally indicates that the certificate was valid
}
Example 66
Project: eclipse-license-management-tools-master  File: SignLicense.java View source code
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println("Usage: SignLicense licenseFile privateKey");
        System.exit(1);
    }
    Properties license = new Properties();
    license.load(new FileInputStream(args[0]));
    PrivateKey privateKey = Utils.readPrivateKeyFromFile(args[1]);
    Signature signature = Signature.getInstance("SHA1withDSA", "SUN");
    signature.initSign(privateKey);
    String[] propKeys = license.keySet().toArray(new String[0]);
    Arrays.sort(propKeys);
    for (String propKey : propKeys) {
        if (!"Signature".equals(propKey)) {
            String propValue = license.getProperty(propKey);
            signature.update(propValue.getBytes("UTF-8"));
        }
    }
    byte[] sig = signature.sign();
    license.setProperty("Signature", new String(Base64.encodeBase64(sig)));
    license.store(new FileOutputStream(args[0]), null);
}
Example 67
Project: java8-tutorial-master  File: Lambda1.java View source code
public static void main(String[] args) {
    List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
    Collections.sort(names, new Comparator<String>() {

        @Override
        public int compare(String a, String b) {
            return b.compareTo(a);
        }
    });
    Collections.sort(names, (String a, String b) -> {
        return b.compareTo(a);
    });
    Collections.sort(names, (String a, String b) -> b.compareTo(a));
    Collections.sort(names, ( a,  b) -> b.compareTo(a));
    System.out.println(names);
    names.sort(Collections.reverseOrder());
    System.out.println(names);
    List<String> names2 = Arrays.asList("peter", null, "anna", "mike", "xenia");
    names2.sort(Comparator.nullsLast(String::compareTo));
    System.out.println(names2);
    List<String> names3 = null;
    Optional.ofNullable(names3).ifPresent( list -> list.sort(Comparator.naturalOrder()));
    System.out.println(names3);
}
Example 68
Project: violetumleditor-master  File: MenuUtils.java View source code
public static void alterMenuBar(JMenuBar menuBar) {
    MenuElement[] subMenuElements = menuBar.getSubElements();
    List<MenuElement> menuEntryStack = new ArrayList<MenuElement>();
    if (subMenuElements.length > 0) {
        menuEntryStack.addAll(Arrays.asList(subMenuElements));
    }
    while (!menuEntryStack.isEmpty()) {
        MenuElement menuElement = menuEntryStack.get(0);
        if (menuElement instanceof JMenuItem) {
            final JMenuItem menuItem = (JMenuItem) menuElement;
            menuItem.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    System.out.println(menuItem.getName());
                }
            });
        }
        MenuElement[] subElements = menuElement.getSubElements();
        if (subElements.length > 0) {
            menuEntryStack.addAll(Arrays.asList(subElements));
        }
        menuEntryStack.remove(0);
    }
}
Example 69
Project: richfaces-master  File: AbstractOrderingComponent.java View source code
protected boolean compareValues(Object previous, Object value) {
    if (previous == null && value != null) {
        return true;
    } else if (previous != null && value == null) {
        return true;
    } else if (previous == null) {
        return false;
    }
    List oldList;
    List newList;
    if (previous instanceof List) {
        oldList = (List) previous;
    } else {
        if (previous instanceof Object[]) {
            oldList = Arrays.asList(previous);
        } else {
            throw new IllegalArgumentException("Ordered List Components must be backed by a List or Array");
        }
    }
    if (value instanceof List) {
        newList = (List) value;
    } else {
        if (value instanceof Object[]) {
            newList = Arrays.asList(value);
        } else {
            throw new IllegalArgumentException("Ordered List Components must be backed by a List or Array");
        }
    }
    return !oldList.equals(newList);
}
Example 70
Project: android_platform_libcore-master  File: CertificateCertificateRepTest.java View source code
/**
     * Test for
     * <code>Certificate.CertificateRep(String type, byte[] data)</code>
     * method<br>
     */
public final void testCertificateCertificateRep() {
    MyCertificate c1 = new MyCertificate("TEST_TYPE", testEncoding);
    MyCertificateRep rep = c1.new MyCertificateRep("TEST_TYPE", new byte[] { (byte) 1, (byte) 2, (byte) 3 });
    assertTrue(Arrays.equals(new byte[] { (byte) 1, (byte) 2, (byte) 3 }, rep.getData()));
    assertEquals("TEST_TYPE", rep.getType());
    try {
        c1.new MyCertificateRep(null, null);
    } catch (Exception e) {
        fail("Unexpected exeption " + e.getMessage());
    }
    try {
        MyCertificate.MyCertificateRep rep1 = c1.new MyCertificateRep("X509", TestUtils.getX509Certificate_v3());
        assertEquals("X509", rep1.getType());
        assertTrue(Arrays.equals(TestUtils.getX509Certificate_v3(), rep1.getData()));
    } catch (Exception e) {
        fail("Unexpected exeption " + e.getMessage());
    }
}
Example 71
Project: abmash-master  File: TypablePredicate.java View source code
@Override
public void buildCommands() {
    List<String> inputSelectors = Arrays.asList("input[type=password]", "input[type=text]", "input[type=email]", "input[type=url]", "input[type=number]", "input[type=search]", "textarea");
    JQuery typableQuery = JQueryFactory.select("'" + StringUtils.join(inputSelectors, ',') + "'", 0).not("':attrMatch(CONTAINS, *, \"datepicker\")'");
    if (text != null) {
        // tinymce support
        // TODO add closeness (close to iframe and selection of inner #tinymce element)
        add(JQueryFactory.select("'.mceIframeContainer > iframe'", 150).containsAttribute(StringMatcher.CONTAINS, "*", text).contents().find("'#tinymce'"));
        // close to label
        closeTo(typableQuery.setWeight(100), new DirectionOptions(DirectionType.CLOSETOLABEL).setLimitPerTarget(1).setMaxDistance(500), QueryFactory.text(text));
        containsText(typableQuery, text);
        containsAttribute(typableQuery, "*", text);
    } else {
        add(typableQuery);
    }
}
Example 72
Project: geotoolkit-master  File: DisjointSetTest.java View source code
/**
      * Tests the set.
      */
@Test
public void testDisjointSet() {
    DisjointSet<String> t1 = new DisjointSet<>(true);
    DisjointSet<String> t2 = new DisjointSet<>(t1);
    DisjointSet<String> t3 = new DisjointSet<>(t2);
    assertNotNull(t1.getTrash());
    assertSame(t1.getTrash(), t2.getTrash());
    assertSame(t2.getTrash(), t3.getTrash());
    assertTrue(t1.add("alpha"));
    assertTrue(t2.add("bêta"));
    assertTrue(t3.add("gamma"));
    assertTrue(t2.add("delta"));
    assertTrue(t1.add("epsilon"));
    assertTrue(t2.add("alpha"));
    assertTrue(t2.remove("bêta"));
    assertEquals(Collections.singleton("epsilon"), t1);
    assertEquals(new HashSet<>(Arrays.asList(new String[] { "alpha", "delta" })), t2);
    assertEquals(Collections.singleton("gamma"), t3);
    assertEquals(Collections.singleton("bêta"), t1.getTrash());
    assertNotSame(t1, assertSerializedEquals(t1));
    assertNotSame(t2, assertSerializedEquals(t2));
    assertNotSame(t3, assertSerializedEquals(t3));
}
Example 73
Project: mkgmap-master  File: MultiPolygonFinishHook.java View source code
public void end() {
    long t1 = System.currentTimeMillis();
    log.info("Finishing multipolygons");
    for (Way way : saver.getWays().values()) {
        String removeTag = way.getTag(ElementSaver.MKGMAP_REMOVE_TAG);
        if (removeTag == null) {
            continue;
        }
        if (ElementSaver.MKGMAP_REMOVE_TAG_ALL_KEY.equals(removeTag)) {
            if (log.isDebugEnabled())
                log.debug("Remove all tags from way", way.getId(), way.toTagString());
            way.removeAllTags();
        } else {
            String[] tagsToRemove = removeTag.split(";");
            if (log.isDebugEnabled())
                log.debug("Remove tags", Arrays.toString(tagsToRemove), "from way", way.getId(), way.toTagString());
            for (String rTag : tagsToRemove) {
                way.deleteTag(rTag);
            }
            way.deleteTag(ElementSaver.MKGMAP_REMOVE_TAG);
        }
    }
    log.info("Multipolygon hook finished in " + (System.currentTimeMillis() - t1) + " ms");
}
Example 74
Project: liferay-ide-master  File: PortalFilterNamesPossibleValuesService.java View source code
@Override
protected void compute(Set<String> values) {
    if (this.servletFilterNames == null) {
        final IFile hookFile = this.context().find(Element.class).adapt(IFile.class);
        if (hookFile != null) {
            try {
                final ILiferayProject liferayProject = LiferayCore.create(hookFile.getProject());
                if (liferayProject != null) {
                    final ILiferayPortal portal = liferayProject.adapt(ILiferayPortal.class);
                    if (portal != null) {
                        final IPath appServerPortalDir = portal.getAppServerPortalDir();
                        if (appServerPortalDir != null) {
                            this.servletFilterNames = ServerUtil.getServletFilterNames(appServerPortalDir);
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
    }
    if (this.servletFilterNames != null) {
        values.addAll(Arrays.asList(this.servletFilterNames));
    }
}
Example 75
Project: dataverse-master  File: DatasetVersionTest.java View source code
@Test
public void testComparator() {
    DatasetVersion ds1_0 = new DatasetVersion();
    ds1_0.setId(0l);
    ds1_0.setVersionNumber(1l);
    ds1_0.setMinorVersionNumber(0l);
    ds1_0.setVersionState(DatasetVersion.VersionState.RELEASED);
    DatasetVersion ds1_1 = new DatasetVersion();
    ds1_1.setId(1l);
    ds1_1.setVersionNumber(1l);
    ds1_1.setMinorVersionNumber(1l);
    ds1_1.setVersionState(DatasetVersion.VersionState.RELEASED);
    DatasetVersion ds2_0 = new DatasetVersion();
    ds2_0.setId(2l);
    ds2_0.setVersionNumber(2l);
    ds2_0.setMinorVersionNumber(0l);
    ds2_0.setVersionState(DatasetVersion.VersionState.RELEASED);
    DatasetVersion ds_draft = new DatasetVersion();
    ds_draft.setId(3l);
    ds_draft.setVersionState(DatasetVersion.VersionState.DRAFT);
    List<DatasetVersion> expected = Arrays.asList(ds1_0, ds1_1, ds2_0, ds_draft);
    List<DatasetVersion> actual = Arrays.asList(ds2_0, ds1_0, ds_draft, ds1_1);
    Collections.sort(actual, DatasetVersion.compareByVersion);
    assertEquals(expected, actual);
}
Example 76
Project: jnlp-master  File: TestNLP.java View source code
public static void main(String[] args) throws Exception {
    NLP nlp = new NLP("这个东西真心很赞");
    System.out.println(nlp.words());
    System.out.println(nlp.tags());
    System.out.println(nlp.sentiments());
    System.out.println(nlp.pinyin());
    nlp = new NLP("「繁體字」「繁體中文」的叫法在臺灣亦很常見。");
    System.out.println(nlp.han());
    String text = "自然语言处理是计算机科学领域与人工智能领域中的一个重要方向。\r\n它研究能实现人与计算机之间用自然语言进行有效通信的各种理论和方法。\r\n自然语言处理是一门融语言学、计算机科学、数学于一体的科学。\r\n因此,这一领域的研究将涉及自然语言,即人们日常使用的语言,\r\n所以它与语言学的研究有着密切的联系,但又有重要的区别。\r\n自然语言处理并不是一般地研究自然语言,\r\n而在于研制能有效地实现自然语言通信的计算机系统,\r\n特别是其中的软件系统。因而它是计算机科学的一部分。";
    nlp = new NLP(text);
    System.out.println(nlp.keywords(5));
    System.out.println(nlp.summary(3));
    System.out.println(nlp.sentences());
    List<List<String>> test = new ArrayList<List<String>>();
    test.add(Arrays.asList("这篇", "文章"));
    test.add(Arrays.asList("那篇", "论文"));
    test.add(Arrays.asList("这个"));
    nlp = new NLP(test);
    System.out.println(nlp.tf());
    System.out.println(nlp.idf());
    System.out.println(nlp.sim(Arrays.asList("文章")));
}
Example 77
Project: cassandra-dev-master  File: CommitLogTest.java View source code
@Test
public void testMain() throws IOException {
// TODO this is useless, since it assumes we have a working set of commit logs to parse
/*
        File logDir = new File(DatabaseDescriptor.getLogFileLocation());
        File[] files = logDir.listFiles();
        Arrays.sort( files, new FileUtils.FileComparator() );

        byte[] bytes = new byte[CommitLogHeader.size(Integer.parseInt(args[0]))];
        for ( File file : files )
        {
            CommitLog clog = new CommitLog( file );
            clog.readCommitLogHeader(file.getAbsolutePath(), bytes);
            DataInputBuffer bufIn = new DataInputBuffer();
            bufIn.reset(bytes, 0, bytes.length);
            CommitLogHeader clHeader = CommitLogHeader.serializer().deserialize(bufIn);

            StringBuilder sb = new StringBuilder("");
            for ( byte b : bytes )
            {
                sb.append(b);
                sb.append(" ");
            }

            System.out.println("FILE:" + file);
            System.out.println(clHeader.toString());
        }
        */
}
Example 78
Project: Time4J-master  File: RomanNumberTestForModernUsage.java View source code
@Parameters(name = "{index}: [value={0} / numeral={1}")
public static Iterable<Object[]> data() {
    return Arrays.asList(new Object[][] { { 1, "I" }, { 2, "II" }, { 3, "III" }, { 4, "IV" }, { 5, "V" }, { 6, "VI" }, { 7, "VII" }, { 8, "VIII" }, { 9, "IX" }, { 10, "X" }, { 11, "XI" }, { 12, "XII" }, { 13, "XIII" }, { 14, "XIV" }, { 15, "XV" }, { 16, "XVI" }, { 17, "XVII" }, { 18, "XVIII" }, { 19, "XIX" }, { 20, "XX" }, { 21, "XXI" }, { 22, "XXII" }, { 23, "XXIII" }, { 24, "XXIV" }, { 25, "XXV" }, { 26, "XXVI" }, { 27, "XXVII" }, { 28, "XXVIII" }, { 29, "XXIX" }, { 30, "XXX" }, { 38, "XXXVIII" }, { 39, "XXXIX" }, { 40, "XL" }, { 41, "XLI" }, { 42, "XLII" }, { 43, "XLIII" }, { 44, "XLIV" }, { 45, "XLV" }, { 49, "XLIX" }, { 50, "L" }, { 51, "LI" }, { 60, "LX" }, { 87, "LXXXVII" }, { 89, "LXXXIX" }, { 90, "XC" }, { 91, "XCI" }, { 98, "XCVIII" }, { 99, "XCIX" }, { 100, "C" }, { 499, "CDXCIX" }, { 500, "D" }, { 672, "DCLXXII" }, { 989, "CMLXXXIX" }, { 990, "CMXC" }, { 1000, "M" }, { 1903, "MCMIII" }, { 1904, "MCMIV" }, { 1910, "MCMX" }, { 1954, "MCMLIV" }, { 1990, "MCMXC" }, { 2014, "MMXIV" } });
}
Example 79
Project: cloudtm-data-platform-master  File: ConverterClassAwareDmlCompiler.java View source code
public static void main(String[] args) throws Exception {
    final int c = args.length;
    final int offset = c - 3;
    final File dir = new File(args[offset]);
    final String[] baseArgs;
    if (dir.exists() && dir.isDirectory()) {
        final List<String> dmlFilenames = new ArrayList<String>();
        for (final File file : dir.listFiles()) {
            if (file.isFile() && file.getName().endsWith(".dml")) {
                dmlFilenames.add(file.getCanonicalPath());
            }
        }
        Collections.sort(dmlFilenames);
        List<URL> pluginDmlUrlList = PluginDmlUrlLoader.getPluginDmlUrlList();
        baseArgs = new String[c - 3 + dmlFilenames.size() + pluginDmlUrlList.size()];
        System.arraycopy(args, 0, baseArgs, 0, offset);
        int i = offset;
        for (URL pluginDmlUrl : pluginDmlUrlList) {
            baseArgs[i++] = pluginDmlUrl.toExternalForm();
        }
        for (final String dmlFilename : dmlFilenames) {
            baseArgs[i++] = dmlFilename;
        }
    } else {
        baseArgs = Arrays.copyOfRange(args, 0, c - 2);
    }
    DmlCompiler.main(baseArgs);
}
Example 80
Project: ARTPart-master  File: NarrowingTest.java View source code
public static void main(String[] args) {
    I2 proxy = (I2) Proxy.newProxyInstance(NarrowingTest.class.getClassLoader(), new Class<?>[] { I2.class }, new InvocationHandler() {

        int count = 0;

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("Invocation of " + method);
            if (count == 0) {
                count++;
                return "hello";
            } else {
                return Integer.valueOf(1);
            }
        }
    });
    Method[] methods = proxy.getClass().getDeclaredMethods();
    System.out.println("Proxy methods: " + Arrays.deepToString(methods));
    System.out.println("Invoking foo using I2 type: " + proxy.foo());
    I1 proxyAsParent = proxy;
    System.out.println("Invoking foo using I1 type: " + proxyAsParent.foo());
    try {
        proxy.foo();
        System.out.println("Didn't get expected exception");
    } catch (ClassCastException e) {
        System.out.println("Got expected exception");
    }
    System.out.println("Proxy narrowed invocation return type passed");
}
Example 81
Project: rsimulator-master  File: SimulatorCacheInterceptor.java View source code
public Object invoke(MethodInvocation invocation) throws Throwable {
    log.debug("SimulatorCache is {}", props.isSimulatorCache());
    Object response = null;
    if (props.isSimulatorCache()) {
        if (invocation.getMethod().getName().equals("service")) {
            Object[] arguments = invocation.getArguments();
            String key = Arrays.stream(arguments).map( arg -> arg.toString()).collect(Collectors.joining());
            Element cacheElement = cache.get(key);
            if (cacheElement != null) {
                response = cacheElement.getObjectValue();
                if (response != null) {
                    log.debug("{} returns from cache: {}", new Object[] { invocation.getMethod(), response });
                    return response;
                }
            }
            response = invocation.proceed();
            cacheElement = new Element(key, response);
            cache.put(cacheElement);
        }
    } else {
        response = invocation.proceed();
    }
    log.debug("{} returns not from cache: {}", new Object[] { invocation.getMethod(), response });
    return response;
}
Example 82
Project: CodingSpectator-master  File: RemoveFilterDialog.java View source code
public void prompt(Shell shell) {
    ListDialog dialog = new ListDialog(shell) {

        @Override
        protected int getTableStyle() {
            return super.getTableStyle() - SWT.SINGLE + SWT.MULTI;
        }
    };
    dialog.setTitle(Messages.RemoveFilterDialog_0);
    dialog.setMessage(Messages.RemoveFilterDialog_1);
    dialog.setAddCancelButton(true);
    dialog.setLabelProvider(new LabelProvider() {

        @Override
        public String getText(Object element) {
            return (String) element;
        }
    });
    dialog.setContentProvider(new IStructuredContentProvider() {

        public Object[] getElements(Object inputElement) {
            return (Object[]) inputElement;
        }

        public void dispose() {
        }

        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }
    });
    String[] filterPatterns = filter.getFilterPatterns();
    Arrays.sort(filterPatterns);
    dialog.setInput(filterPatterns);
    dialog.open();
    Object[] selected = dialog.getResult();
    if (selected == null)
        return;
    filter.removeFilterPatterns(selected);
}
Example 83
Project: android-15-master  File: CursorWindowTest.java View source code
private void doTestValues(CursorWindow window) {
    assertTrue(window.setNumColumns(7));
    assertTrue(window.allocRow());
    double db1 = 1.26;
    assertTrue(window.putDouble(db1, 0, 0));
    double db2 = window.getDouble(0, 0);
    assertEquals(db1, db2);
    long int1 = Long.MAX_VALUE;
    assertTrue(window.putLong(int1, 0, 1));
    long int2 = window.getLong(0, 1);
    assertEquals(int1, int2);
    assertTrue(window.putString("1198032740000", 0, 3));
    assertEquals("1198032740000", window.getString(0, 3));
    assertEquals(1198032740000L, window.getLong(0, 3));
    assertTrue(window.putString(Long.toString(1198032740000L), 0, 3));
    assertEquals(Long.toString(1198032740000L), window.getString(0, 3));
    assertEquals(1198032740000L, window.getLong(0, 3));
    assertTrue(window.putString(Double.toString(42.0), 0, 4));
    assertEquals(Double.toString(42.0), window.getString(0, 4));
    assertEquals(42.0, window.getDouble(0, 4));
    // put blob
    byte[] blob = new byte[1000];
    byte value = 99;
    Arrays.fill(blob, value);
    assertTrue(window.putBlob(blob, 0, 6));
    assertTrue(Arrays.equals(blob, window.getBlob(0, 6)));
}
Example 84
Project: many-ql-master  File: TestComputedQuestion.java View source code
@Parameters
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] { { createComputedQuestion("boolean", "true"), true }, { createComputedQuestion("integer", "5"), true }, { createComputedQuestion("integer", "5.0"), true }, { createComputedQuestion("float", "5"), true }, { createComputedQuestion("float", "5.0"), true }, { createComputedQuestion("money", "5"), true }, { createComputedQuestion("money", "5.0"), true }, { createComputedQuestion("string", "\"String\""), true }, { createComputedQuestion("boolean", "5"), false }, { createComputedQuestion("boolean", "5.0"), false }, { createComputedQuestion("boolean", "\"String\""), false }, { createComputedQuestion("integer", "true"), false }, { createComputedQuestion("integer", "\"String\""), false }, { createComputedQuestion("float", "true"), false }, { createComputedQuestion("float", "\"String\""), false }, { createComputedQuestion("money", "true"), false }, { createComputedQuestion("money", "\"String\""), false }, { createComputedQuestion("string", "true"), false }, { createComputedQuestion("string", "5"), false }, { createComputedQuestion("string", "5.0"), false } });
}
Example 85
Project: openmap-master  File: SimpleBeanContainerBeanInfo.java View source code
public PropertyDescriptor[] getPropertyDescriptors() {
    ArrayList<PropertyDescriptor> list = new ArrayList<PropertyDescriptor>(8);
    PropertyDescriptor[] pds = super.getPropertyDescriptors();
    list.addAll(Arrays.asList(pds));
    try {
        list.add(new PropertyDescriptor("widthInNM", SimpleBeanContainer.class));
        list.add(new PropertyDescriptor("heightInNM", SimpleBeanContainer.class));
        PropertyDescriptor pd = new PropertyDescriptor("layoutClass", SimpleBeanContainer.class);
        pd.setPropertyEditorClass(LayoutClassEditor.class);
        list.add(pd);
        pd = new PropertyDescriptor("layoutManager", SimpleBeanContainer.class, "getLayout", "setLayout");
        // since layoutManager property is itself a bean
        // (of type BeanLayoutManager), use the
        // general purpose BeanLayoutEditor class provided in the
        // tools.beanbox
        // package as the editor class of this bean property.
        pd.setPropertyEditorClass(BeanLayoutEditor.class);
        list.add(pd);
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }
    return list.toArray(new PropertyDescriptor[list.size()]);
}
Example 86
Project: openjdk-master  File: T8050993.java View source code
public static void main(String[] args) throws IOException, ConstantPoolException {
    ClassFile someTestIn = ClassFile.read(T8050993.class.getResourceAsStream("T8050993.class"));
    Set<Integer> expectedLineNumbers = new HashSet<>(Arrays.asList(49, 50, 47, 48));
    for (Method m : someTestIn.methods) {
        if ("method".equals(m.getName(someTestIn.constant_pool))) {
            Code_attribute code_attribute = (Code_attribute) m.attributes.get(Attribute.Code);
            for (Attribute at : code_attribute.attributes) {
                if (Attribute.LineNumberTable.equals(at.getName(someTestIn.constant_pool))) {
                    LineNumberTable_attribute att = (LineNumberTable_attribute) at;
                    Set<Integer> actualLinesNumbers = Arrays.stream(att.line_number_table).map( e -> e.line_number).collect(Collectors.toSet());
                    if (!Objects.equals(expectedLineNumbers, actualLinesNumbers)) {
                        throw new AssertionError("Expected LineNumber entries not found;" + "actual=" + actualLinesNumbers + ";" + "expected=" + expectedLineNumbers);
                    }
                }
            }
        }
    }
}
Example 87
Project: netlib-java-master  File: Dgetri.java View source code
@Override
public long benchmark(int size) {
    int m = (int) Math.sqrt(size);
    // random matrices are full rank (and can always be inverted if square)
    // http://www.sciencedirect.com/science/article/pii/S0096300306009040
    double[] a = Benchmarks.randomArray(m * m);
    double[] aOrig = Arrays.copyOf(a, a.length);
    double[] b = new double[1];
    int[] p = new int[m];
    intW info = new intW(0);
    Stopwatch watch = new Stopwatch();
    LAPACK.getInstance().dgetri(m, a, m, p, b, -1, info);
    //log.info(m + " supposedly has optimal work of " + b[0]);
    b = new double[(int) b[0]];
    watch.start();
    LAPACK.getInstance().dgetrf(m, m, a, m, p, info);
    if (info.val != 0)
        throw new IllegalArgumentException();
    LAPACK.getInstance().dgetri(m, a, m, p, b, b.length, info);
    if (info.val != 0)
        throw new IllegalArgumentException();
    watch.stop();
    // quick check
    double[] c = new double[m * m];
    BLAS.getInstance().dgemm("N", "N", m, m, m, 1, aOrig, m, a, m, 0, c, m);
    if (!Benchmarks.isUnit(c, m, 0.000001)) {
        Dgetri.log.warning("failed to invert matrix");
    }
    return watch.elapsed(TimeUnit.NANOSECONDS);
}
Example 88
Project: hibernate-core-ogm-master  File: QueryingWithProxyObjectTest.java View source code
@Test
@TestForIssue(jiraKey = "HHH-4760")
@SuppressWarnings("unchecked")
public void testQueryingWithProxyObject() {
    StrTestEntity originalSte = new StrTestEntity("data", id);
    // Load the proxy instance
    StrTestEntity proxySte = (StrTestEntity) getSession().load(StrTestEntity.class, id);
    Assert.assertTrue(getAuditReader().isEntityClassAudited(proxySte.getClass()));
    StrTestEntity ste = getAuditReader().find(proxySte.getClass(), proxySte.getId(), 1);
    Assert.assertEquals(originalSte, ste);
    List<Number> revisions = getAuditReader().getRevisions(proxySte.getClass(), proxySte.getId());
    Assert.assertEquals(Arrays.asList(1), revisions);
    List<StrTestEntity> entities = getAuditReader().createQuery().forEntitiesAtRevision(proxySte.getClass(), 1).getResultList();
    Assert.assertEquals(Arrays.asList(originalSte), entities);
    ste = (StrTestEntity) getAuditReader().createQuery().forRevisionsOfEntity(proxySte.getClass(), true, false).getSingleResult();
    Assert.assertEquals(originalSte, ste);
    ste = (StrTestEntity) getAuditReader().createQuery().forEntitiesModifiedAtRevision(proxySte.getClass(), 1).getSingleResult();
    Assert.assertEquals(originalSte, ste);
}
Example 89
Project: dove-master  File: SHA1.java View source code
/**
     * 用SHA1算法生成安全签名
     * 
     * @param token 票据
     * @param timestamp 时间戳
     * @param nonce 随机字符串
     * @param encrypt 密文
     * @return 安全签名
     * @throws AesException 
     */
public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException {
    try {
        String[] array = new String[] { token, timestamp, nonce, encrypt };
        StringBuffer sb = new StringBuffer();
        // 字符串排序
        Arrays.sort(array);
        for (int i = 0; i < 4; i++) {
            sb.append(array[i]);
        }
        String str = sb.toString();
        // SHA1签名生成
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(str.getBytes());
        byte[] digest = md.digest();
        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";
        for (int i = 0; i < digest.length; i++) {
            shaHex = Integer.toHexString(digest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return hexstr.toString();
    } catch (Exception e) {
        throw new AesException(AesException.COMPUTE_SIGNATURE_ERROR);
    }
}
Example 90
Project: btpka3.github.com-master  File: TestCasRESTfulApi.java View source code
@SuppressWarnings("unchecked")
public static void test() {
    String casUrlPrefix = "http://login-test.his.com/tcgroup-sso-web";
    String username = "15372712873";
    String password = "123456";
    // GET TGT
    RestTemplate rest = new RestTemplate();
    rest.setMessageConverters(Arrays.asList(new StringHttpMessageConverter(), new FormHttpMessageConverter()));
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.set("username", username);
    params.set("password", password);
    URI tgtUrl = rest.postForLocation(casUrlPrefix + "/v1/tickets", params, Collections.emptyMap());
    System.out.println("[" + tgtUrl + "]");
    // GET ST
    String service = "http://login-test.his.com/tcgroup-his-web/client/nop.do";
    params.clear();
    params.set("service", service);
    ResponseEntity<String> st = rest.postForEntity(tgtUrl, params, String.class);
    System.out.println("[" + st.getBody() + "]");
    // Using ST get data from SSO app(tcgroup-his-web).
    Map<String, Object> urlParams = new HashMap<String, Object>();
    urlParams.put("ticket", st.getBody());
    ResponseEntity<String> html = rest.getForEntity(service + "?ticket=" + st.getBody(), String.class, urlParams);
    System.out.println("[" + html.getBody() + "]");
}
Example 91
Project: alien4cloud-master  File: SetNodePropertyAsInputProcessor.java View source code
@Override
protected void processNodeOperation(SetNodePropertyAsInputOperation operation, NodeTemplate nodeTemplate) {
    Topology topology = EditionContextManager.getTopology();
    PropertyDefinition inputPropertyDefinition = getOrFail(topology.getInputs(), operation.getInputName(), "Input {} not found in topology", operation.getInputName());
    NodeType indexedNodeType = ToscaContext.get(NodeType.class, nodeTemplate.getType());
    PropertyDefinition nodePropertyDefinition = getOrFail(indexedNodeType.getProperties(), operation.getPropertyName(), "Property {} do not exist for node {}", operation.getPropertyName(), operation.getNodeName());
    // Check that the property definition of the input is indeed compatible with the property definition of the capability.
    inputPropertyDefinition.checkIfCompatibleOrFail(nodePropertyDefinition);
    FunctionPropertyValue getInput = new FunctionPropertyValue();
    getInput.setFunction(ToscaFunctionConstants.GET_INPUT);
    getInput.setParameters(Arrays.asList(operation.getInputName()));
    nodeTemplate.getProperties().put(operation.getPropertyName(), getInput);
    log.debug("Associate the property <{}> of the node template <{}> to input <{}> of the topology <{}>.", operation.getPropertyName(), operation.getNodeName(), operation.getInputName(), topology.getId());
}
Example 92
Project: RoboBuggy-master  File: ComparisonFailureTest.java View source code
@Parameters(name = "compact-msg-{index}, exp=\"{1}\"")
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] { // simple base case
    { "a", "b", "expected:<[a]> but was:<[b]>" }, // common prefix
    { "ba", "bc", "expected:<b[a]> but was:<b[c]>" }, // common suffix
    { "ab", "cb", "expected:<[a]b> but was:<[c]b>" }, // common pre and suffix
    { "abc", "adc", "expected:<a[b]c> but was:<a[d]c>" }, // expected is subset of actual
    { "ab", "abc", "expected:<ab[]> but was:<ab[c]>" }, // expected is superset of actual
    { "abc", "ab", "expected:<ab[c]> but was:<ab[]>" }, // overlapping matches.
    { "abc", "abbc", "expected:<ab[]c> but was:<ab[b]c>" }, // long prefix yielding "..."
    { "01234567890123456789PRE:hello:POST", "01234567890123456789PRE:world:POST", "expected:<...4567890123456789PRE:[hello]:POST> but was:<...4567890123456789PRE:[world]:POST>" }, // long suffix	yielding "..."
    { "PRE:hello:01234567890123456789POST", "PRE:world:01234567890123456789POST", "expected:<PRE:[hello]:0123456789012345678...> but was:<PRE:[world]:0123456789012345678...>" }, // bug609972
    { "S&P500", "0", "expected:<[S&P50]0> but was:<[]0>" }, // empty expected string
    { "", "a", "expected:<[]> but was:<[a]>" }, // empty actual string
    { "a", "", "expected:<[a]> but was:<[]>" } });
}
Example 93
Project: cloudbees-api-client-master  File: TrustAllSocketFactory.java View source code
public static SSLSocketFactory create() {
    try {
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException {
                if (LOGGER.isLoggable(FINE)) {
                    LOGGER.fine("Got the certificate: " + Arrays.asList(x509Certificates));
                }
            // TODO: define a mechanism for users to accept a certificate from UI
            //                    try {
            //                        CertificateUtil.validatePath(Arrays.asList(x509Certificates));
            //                    } catch (GeneralSecurityException e) {
            //                        e.printStackTrace();
            //                    }
            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, new SecureRandom());
        return context.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        throw new Error(e);
    } catch (KeyManagementException e) {
        throw new Error(e);
    }
}
Example 94
Project: sosies-generator-master  File: AbstractLinkedListTest.java View source code
@SuppressWarnings(value = "unchecked")
@Test(timeout = 1000)
public void testRemoveFirst_add625() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testRemoveFirst_add625");
    resetEmpty();
    resetEmpty();
    final AbstractLinkedList<E> list = getCollection();
    if (!(isRemoveSupported())) {
        try {
            list.removeFirst();
        } catch (final UnsupportedOperationException ex) {
        }
    }
    list.addAll(java.util.Arrays.asList(((E[]) (new String[] { "value1", "value2" }))));
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2026, list, 2025, list.removeFirst());
    checkNodes();
    list.addLast(((E) ("value3")));
    checkNodes();
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2028, list, 2027, list.removeFirst());
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2030, list, 2029, list.removeFirst());
    checkNodes();
    list.addLast(((E) ("value4")));
    checkNodes();
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2032, list, 2031, list.removeFirst());
    checkNodes();
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 95
Project: DrakkarKeel-master  File: _ConfigurationDisp.java View source code
public Ice.DispatchStatus __dispatch(IceInternal.Incoming in, Ice.Current __current) {
    int pos = java.util.Arrays.binarySearch(__all, __current.operation);
    if (pos < 0) {
        throw new Ice.OperationNotExistException(__current.id, __current.facet, __current.operation);
    }
    switch(pos) {
        case 0:
            {
                return drakkar.oar.slice.action.twoway._GetDisp.___getAMID(this, in, __current);
            }
        case 1:
            {
                return drakkar.oar.slice.action.twoway._GetDisp.___getSAMI(this, in, __current);
            }
        case 2:
            {
                return ___ice_id(this, in, __current);
            }
        case 3:
            {
                return ___ice_ids(this, in, __current);
            }
        case 4:
            {
                return ___ice_isA(this, in, __current);
            }
        case 5:
            {
                return ___ice_ping(this, in, __current);
            }
        case 6:
            {
                return drakkar.oar.slice.action.oneway._SendDisp.___sendAMID(this, in, __current);
            }
        case 7:
            {
                return drakkar.oar.slice.action.oneway._SendDisp.___sendSAMI(this, in, __current);
            }
    }
    assert (false);
    throw new Ice.OperationNotExistException(__current.id, __current.facet, __current.operation);
}
Example 96
Project: xbnjava-master  File: CrashIfCollection_Unit.java View source code
@Test
public void test_bad() {
    CrashIfCollection.bad(null, null, NullContainer.OK, 1, null, NullElement.BAD, 1, null);
    CrashIfCollection.bad(Arrays.asList(new String[] {}), null, NullContainer.BAD, 0, null, NullElement.BAD, 1, null);
    CrashIfCollection.bad(Arrays.asList(new String[] { null }), null, NullContainer.BAD, 1, null, NullElement.OK, 1, null);
    CrashIfCollection.bad(Arrays.asList(new String[] { "" }), null, NullContainer.BAD, 1, null, NullElement.BAD, 0, null);
    try {
        CrashIfCollection.bad(null, null, NullContainer.BAD, 1, null, NullElement.BAD, 1, null);
        fail("null array");
    } catch (NullPointerException x) {
        assertTrue(true);
    }
    try {
        CrashIfCollection.bad(Arrays.asList(new String[] {}), null, NullContainer.BAD, 1, null, NullElement.BAD, 1, null);
        fail("array empty");
    } catch (LengthLessThanRequiredException x) {
        assertTrue(true);
    }
    try {
        CrashIfCollection.bad(Arrays.asList(new Object[] { null }), null, NullContainer.BAD, 1, null, NullElement.BAD, 1, null);
        fail("null element");
    } catch (NullPointerException x) {
        assertTrue(true);
    }
    try {
        CrashIfCollection.bad(Arrays.asList(new Object[] { "" }), null, NullContainer.BAD, 1, null, NullElement.BAD, 1, null);
        fail("empty element");
    } catch (LengthLessThanRequiredException x) {
        assertTrue(true);
    }
}
Example 97
Project: SRE-RoboCode-master  File: AlphanumericComparatorTest.java View source code
@Test
public void correctSorting() {
    // Our unsorted strings that must be sorted
    final String[] unsortedStrings = { null, "", " ", "alpha2", "alpha1", "bEtA", "BeTa", "alpha", "Alpha2", "Alpha1", "Alpha", "1.2", "1.22", "1.22A", "1.3", "2.10a.1", "2.1.1", "2.10", "2.1a", "2.10.2", "1c", "1h", "1p", "alpha", "beta", "alPHA", "beTA", "ALpha", "BEta", "ALPHA", "BETA" };
    // The expected result, when the unsorted strings have been sorted correctly
    final String[] correctlySortedStrings = { "1.2", "1.3", "1.22A", "1.22", "1c", "1h", "1p", "2.1.1", "2.1a", "2.10.2", "2.10a.1", "2.10", " ", "ALPHA", "ALpha", "Alpha1", "Alpha2", "Alpha", "alPHA", "alpha1", "alpha2", "alpha", "alpha", "BETA", "BEta", "BeTa", "bEtA", "beTA", "beta", "", null };
    // Make sure the input and expected output string arrays have the same length 
    Assert.assertEquals(unsortedStrings.length, correctlySortedStrings.length);
    // Sort the unsorted strings
    Arrays.sort(unsortedStrings, new AlphanumericComparator());
    // Check the result against our expected result
    boolean sortedCorrectly = true;
    for (int i = 0; i < unsortedStrings.length; i++) {
        String str1 = unsortedStrings[i];
        String str2 = correctlySortedStrings[i];
        if (!(str1 == null && str2 == null) && !str1.equals(str2)) {
            sortedCorrectly = false;
            break;
        }
    }
    Assert.assertTrue(sortedCorrectly);
}
Example 98
Project: geotools-old-master  File: CrsCreationDeadlockTest.java View source code
@Test
public void testForDeadlock() throws InterruptedException {
    // prepare the loaders
    final AtomicInteger ai = new AtomicInteger(NUMBER_OF_THREADS);
    final Runnable runnable = new Runnable() {

        public void run() {
            try {
                final CRSAuthorityFactory authorityFactory = ReferencingFactoryFinder.getCRSAuthorityFactory("EPSG", null);
                authorityFactory.createCoordinateReferenceSystem("4326");
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                ai.decrementAndGet();
            }
        }
    };
    // start them
    final List<Thread> threads = new ArrayList<Thread>();
    for (int index = 0; index < NUMBER_OF_THREADS; index++) {
        final Thread thread = new Thread(runnable);
        thread.start();
        threads.add(thread);
    }
    // use jmx to do deadlock detection
    try {
        final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
        while (ai.get() > 0) {
            long[] deadlockedThreads = mbean.findMonitorDeadlockedThreads();
            if (deadlockedThreads != null && deadlockedThreads.length > 0) {
                fail("Deadlock detected between the following threads: " + Arrays.toString(deadlockedThreads));
            }
            // sleep for a bit
            Thread.currentThread().sleep(10);
        }
    } finally {
        // kill all the 
        for (final Thread thread : threads) {
            if (thread.isAlive()) {
                thread.interrupt();
            }
        }
    }
}
Example 99
Project: j2objc-master  File: VarargsRewriterTest.java View source code
// Verify that a single object array argument to an object varargs method is passed unchanged.
// Covers all kinds of invocation.
public void testObjectArrayVarargs() throws IOException {
    String translation = translateSourceFile("import java.util.Arrays;" + "interface Baz { void baz(Object[] o); } class Foo<T> { Foo(T... t) {} } class Bar {" + "<T> Bar(T... t) {} Bar(int i, Object[] array) { this(array); } <T> void bar(T... t) {} }" + "enum E { A(new Object[] { }); <T> E(T... t) {} }" + "class Test extends Bar { Test(Object[] array) { super(array); }" + "void test(Object[] array) { " + "Arrays.asList(array); super.bar(array); new Foo(array); Baz b = Arrays::asList;}}", "Test", "Test.m");
    assertTranslation(translation, "E_initWithNSObjectArray_withNSString_withInt_(e, [IOSObjectArray arrayWithObjects:" + "(id[]){  } count:0 type:NSObject_class_()], @\"A\", 0);");
    assertTranslatedLines(translation, "void Bar_initWithInt_withNSObjectArray_(Bar *self, jint i, IOSObjectArray *array) {", "  Bar_initWithNSObjectArray_(self, array);", "}");
    assertTranslatedLines(translation, "void Test_initWithNSObjectArray_(Test *self, IOSObjectArray *array) {", "  Bar_initWithNSObjectArray_(self, array);", "}");
    assertTranslatedLines(translation, "JavaUtilArrays_asListWithNSObjectArray_(array);", "[super barWithNSObjectArray:array];", "create_Foo_initWithNSObjectArray_(array);");
    // Lambda implementation for Arrays::asList.
    assertTranslatedLines(translation, "- (void)bazWithNSObjectArray:(IOSObjectArray *)a {", "  JavaUtilArrays_asListWithNSObjectArray_(a);", "}");
}
Example 100
Project: seasar2-master  File: MessageResourceBundleFactoryTest.java View source code
/**
     * @throws Exception
     */
public void testCalcurateBundleNames() throws Exception {
    // 言語のみ
    String[] bundleNames = MessageResourceBundleFactory.calcurateBundleNames(BASE_NAME, Locale.JAPANESE);
    List expected = java.util.Arrays.asList(new String[] { BASE_NAME, BASE_NAME + "_ja" });
    assertEquals(expected, java.util.Arrays.asList(bundleNames));
    // 言語と国
    bundleNames = MessageResourceBundleFactory.calcurateBundleNames(BASE_NAME, new Locale("ja", "JP"));
    expected = java.util.Arrays.asList(new String[] { BASE_NAME, BASE_NAME + "_ja", BASE_NAME + "_ja_JP" });
    assertEquals(expected, java.util.Arrays.asList(bundleNames));
    // 言語と国とバリアント
    bundleNames = MessageResourceBundleFactory.calcurateBundleNames(BASE_NAME, new Locale("ja", "JP", "WIN"));
    expected = java.util.Arrays.asList(new String[] { BASE_NAME, BASE_NAME + "_ja", BASE_NAME + "_ja_JP", BASE_NAME + "_ja_JP_WIN" });
    assertEquals(expected, java.util.Arrays.asList(bundleNames));
    // 言語とバリアント
    bundleNames = MessageResourceBundleFactory.calcurateBundleNames(BASE_NAME, new Locale("ja", "", "WIN"));
    expected = java.util.Arrays.asList(new String[] { BASE_NAME, BASE_NAME + "_ja", BASE_NAME + "_ja__WIN" });
    assertEquals(expected, java.util.Arrays.asList(bundleNames));
    // 国とバリアント
    bundleNames = MessageResourceBundleFactory.calcurateBundleNames(BASE_NAME, new Locale("", "JP", "WIN"));
    expected = java.util.Arrays.asList(new String[] { BASE_NAME, BASE_NAME + "__JP", BASE_NAME + "__JP_WIN" });
    assertEquals(expected, java.util.Arrays.asList(bundleNames));
    // 国のみ
    bundleNames = MessageResourceBundleFactory.calcurateBundleNames(BASE_NAME, new Locale("", "JP"));
    expected = java.util.Arrays.asList(new String[] { BASE_NAME, BASE_NAME + "__JP" });
    assertEquals(expected, java.util.Arrays.asList(bundleNames));
    // バリアントのみ
    bundleNames = MessageResourceBundleFactory.calcurateBundleNames(BASE_NAME, new Locale("", "", "WIN"));
    expected = java.util.Arrays.asList(new String[] { BASE_NAME, BASE_NAME + "___WIN" });
    assertEquals(expected, java.util.Arrays.asList(bundleNames));
}
Example 101
Project: openjdk8-jdk-master  File: PBKDF2KeyImpl.java View source code
private static byte[] deriveKey(final Mac prf, final byte[] password, byte[] salt, int iterCount, int keyLengthInBit) {
    int keyLength = keyLengthInBit / 8;
    byte[] key = new byte[keyLength];
    try {
        int hlen = prf.getMacLength();
        // ceiling
        int intL = (keyLength + hlen - 1) / hlen;
        // residue
        int intR = keyLength - (intL - 1) * hlen;
        byte[] ui = new byte[hlen];
        byte[] ti = new byte[hlen];
        // SecretKeySpec cannot be used, since password can be empty here.
        SecretKey macKey = new SecretKey() {

            private static final long serialVersionUID = 7874493593505141603L;

            @Override
            public String getAlgorithm() {
                return prf.getAlgorithm();
            }

            @Override
            public String getFormat() {
                return "RAW";
            }

            @Override
            public byte[] getEncoded() {
                return password;
            }

            @Override
            public int hashCode() {
                return Arrays.hashCode(password) * 41 + prf.getAlgorithm().toLowerCase().hashCode();
            }

            @Override
            public boolean equals(Object obj) {
                if (this == obj)
                    return true;
                if (this.getClass() != obj.getClass())
                    return false;
                SecretKey sk = (SecretKey) obj;
                return prf.getAlgorithm().equalsIgnoreCase(sk.getAlgorithm()) && Arrays.equals(password, sk.getEncoded());
            }
        };
        prf.init(macKey);
        byte[] ibytes = new byte[4];
        for (int i = 1; i <= intL; i++) {
            prf.update(salt);
            ibytes[3] = (byte) i;
            ibytes[2] = (byte) ((i >> 8) & 0xff);
            ibytes[1] = (byte) ((i >> 16) & 0xff);
            ibytes[0] = (byte) ((i >> 24) & 0xff);
            prf.update(ibytes);
            prf.doFinal(ui, 0);
            System.arraycopy(ui, 0, ti, 0, ui.length);
            for (int j = 2; j <= iterCount; j++) {
                prf.update(ui);
                prf.doFinal(ui, 0);
                // XOR the intermediate Ui's together.
                for (int k = 0; k < ui.length; k++) {
                    ti[k] ^= ui[k];
                }
            }
            if (i == intL) {
                System.arraycopy(ti, 0, key, (i - 1) * hlen, intR);
            } else {
                System.arraycopy(ti, 0, key, (i - 1) * hlen, hlen);
            }
        }
    } catch (GeneralSecurityException gse) {
        throw new RuntimeException("Error deriving PBKDF2 keys");
    }
    return key;
}