java.util.AbstractMap.SimpleEntry Java Examples

The following examples show how to use java.util.AbstractMap.SimpleEntry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SchemeTerm.java    From XHAIL with GNU General Public License v3.0 6 votes vote down vote up
public static Map.Entry<Collection<Atom>, Collection<Term>> matchAndOutput(Scheme scheme, Collection<Atom> atoms, Collection<Term> substitutes) {
	if (null == scheme)
		throw new IllegalArgumentException("Illegal 'scheme' argument in SchemeTerm.matchAndOutput(Scheme, Collection<Atom>, Collection<Term>): " + scheme);
	if (null == atoms)
		throw new IllegalArgumentException("Illegal 'atoms' argument in SchemeTerm.matchAndOutput(Scheme, Collection<Atom>, Collection<Term>): " + atoms);
	if (null == substitutes)
		throw new IllegalArgumentException("Illegal 'substitutes' argument in SchemeTerm.matchAndOutput(Scheme, Collection<Atom>, Collection<Term>): "
				+ substitutes);
	Set<Atom> matches = new HashSet<>();
	Set<Term> outputs = new HashSet<>();
	for (Atom atom : atoms) {
		Collection<Term> output = matchAndOutput(scheme, atom, substitutes);
		if (null != output) {
			matches.add(atom);
			outputs.addAll(output);
		}
	}
	return new SimpleEntry<Collection<Atom>, Collection<Term>>(matches, outputs);
}
 
Example #2
Source File: StreamingContainer.java    From Bats with Apache License 2.0 6 votes vote down vote up
private HashMap.SimpleEntry<String, ComponentContextPair<Stream, StreamContext>> deployBufferServerPublisher(
    String connIdentifier, StreamCodec<?> streamCodec, long finishedWindowId, int queueCapacity,
    OperatorDeployInfo.OutputDeployInfo nodi)
    throws UnknownHostException
{
  String sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(connIdentifier);

  StreamContext bssc = new StreamContext(nodi.declaredStreamId);
  bssc.setPortId(nodi.portName);
  bssc.setSourceId(connIdentifier);
  bssc.setSinkId(sinkIdentifier);
  bssc.setFinishedWindowId(finishedWindowId);
  bssc.put(StreamContext.CODEC, streamCodec);
  bssc.put(StreamContext.EVENT_LOOP, eventloop);
  bssc.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
  bssc.put(StreamContext.BUFFER_SERVER_TOKEN, nodi.bufferServerToken);
  InetAddress inetAddress = bssc.getBufferServerAddress().getAddress();
  if (inetAddress != null && NetUtils.isLocalAddress(inetAddress)) {
    bssc.setBufferServerAddress(new InetSocketAddress(InetAddress.getByName(null), nodi.bufferServerPort));
  }

  Stream publisher = fastPublisherSubscriber ? new FastPublisher(connIdentifier, queueCapacity * 256) : new BufferServerPublisher(connIdentifier, queueCapacity);
  return new HashMap.SimpleEntry<>(sinkIdentifier, new ComponentContextPair<>(publisher, bssc));
}
 
Example #3
Source File: CrySLParser.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
private List<CrySLForbiddenMethod> getForbiddenMethods(final EList<ForbMethod> methods) {
	final List<CrySLForbiddenMethod> methodSignatures = new ArrayList<>();
	for (final ForbMethod fm : methods) {
		final JvmExecutable meth = fm.getJavaMeth();
		final List<Entry<String, String>> pars = new ArrayList<>();
		for (final JvmFormalParameter par : meth.getParameters()) {
			pars.add(new SimpleEntry<>(par.getSimpleName(), par.getParameterType().getSimpleName()));
		}
		final List<CrySLMethod> crysl = new ArrayList<>();

		final Event alternative = fm.getRep();
		if (alternative != null) {
			crysl.addAll(CrySLParserUtils.resolveAggregateToMethodeNames(alternative));
		}
		methodSignatures.add(new CrySLForbiddenMethod(
				new CrySLMethod(meth.getDeclaringType().getIdentifier() + "." + meth.getSimpleName(), pars, null, new SimpleEntry<>(UNDERSCORE, ANY_TYPE)), false, crysl));
	}
	return methodSignatures;
}
 
Example #4
Source File: TokenClientPromiseHolder.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
public static <T> boolean completePromise(int xid, ClusterResponse<T> response) {
    if (!PROMISE_MAP.containsKey(xid)) {
        return false;
    }
    SimpleEntry<ChannelPromise, ClusterResponse> entry = PROMISE_MAP.get(xid);
    if (entry != null) {
        ChannelPromise promise = entry.getKey();
        if (promise.isDone() || promise.isCancelled()) {
            return false;
        }
        entry.setValue(response);
        promise.setSuccess();
        return true;
    }
    return false;
}
 
Example #5
Source File: LobstackNode.java    From jelectrum with MIT License 6 votes vote down vote up
public void getAll(Lobstack stack, BlockingQueue<Map.Entry<String, ByteBuffer> > consumer)
  throws IOException, InterruptedException
{
  for(String key : children.keySet())
  {
    NodeEntry ne = children.get(key);
    if (ne.node)
    {
      stack.loadNodeAt(ne.location).getAll(stack, consumer);
    }
    else
    {
      String data_key = key.substring(0, key.length()-1);
      consumer.put(new SimpleEntry<String,ByteBuffer>(data_key, stack.loadAtLocation(ne.location)));
    }
  }
 
}
 
Example #6
Source File: MusicBrainzTransforms.java    From bigquery-etl-dataflow-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Given a PCollection of String's each representing an MusicBrainzDataObject transform those strings into
 * MusicBrainzDataObject's where the name space for the MusicBrainzDataObject is 'name'
 *
 * @param text    the json string representing the MusicBrainzDataObject
 * @param name    the namespace for hte MusicBrainzDataObject
 * @param mappers variable number of lookup descriptions - lookup descriptions can be created using the
 *                factory method lookup();
 * @return PCollection of MusicBrainzDataObjects
 */

public static PCollection<KV<Long, MusicBrainzDataObject>> loadTableFromText(PCollection<String> text, String name,
                                                                             String keyName,
                                                                             LookupDescription... mappers) {
  //[START lookupTableWithSideInputs2]
  List<SimpleEntry<ArrayList<String>, PCollectionView<Map<Long, String>>>> mapSideInputs = new ArrayList<SimpleEntry<ArrayList<String>, PCollectionView<Map<Long, String>>>>();

  for (LookupDescription mapper : mappers) {
    PCollectionView<Map<Long, String>> mapView = loadMap(text.getPipeline(), mapper.objectName, mapper.keyKey, mapper.valueKey);
    List<String> destKeyList = 
        mapper.destinationKeys.stream()
                              .map( destinationKey -> name + "_" + destinationKey )
                              .collect(Collectors.toList());

      mapSideInputs.add(new SimpleEntry(destKeyList, mapView));

  }
  //[END lookupTableWithSideInputs2]
  return loadTableFromText(text, name, keyName, mapSideInputs);
}
 
Example #7
Source File: ADStateManager.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
private ActionListener<GetResponse> onGetResponse(String adID, ActionListener<Optional<AnomalyDetector>> listener) {
    return ActionListener.wrap(response -> {
        if (response == null || !response.isExists()) {
            listener.onResponse(Optional.empty());
            return;
        }

        String xc = response.getSourceAsString();
        LOG.info("Fetched anomaly detector: {}", xc);

        try (
            XContentParser parser = XContentType.JSON.xContent().createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, xc)
        ) {
            ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
            AnomalyDetector detector = AnomalyDetector.parse(parser, response.getId());
            currentDetectors.put(adID, new SimpleEntry<>(detector, clock.instant()));
            listener.onResponse(Optional.of(detector));
        } catch (Exception t) {
            LOG.error("Fail to parse detector {}", adID);
            LOG.error("Stack trace:", t);
            listener.onResponse(Optional.empty());
        }
    }, listener::onFailure);
}
 
Example #8
Source File: RunRuleModuleTest.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
private Rule createOuterRule() {
    final Configuration outerRuleTriggerConfig = new Configuration(Collections.unmodifiableMap(Stream
            .of(new SimpleEntry<>("eventSource", "ruleTrigger"), new SimpleEntry<>("eventTopic", "smarthome/*"),
                    new SimpleEntry<>("eventTypes", "ItemStateEvent"))
            .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))));

    final List<String> ruleUIDs = new ArrayList<>();
    ruleUIDs.add("exampleSceneRule");

    final Configuration outerRuleActionConfig = new Configuration(
            Collections.unmodifiableMap(Stream.of(new SimpleEntry<>("ruleUIDs", ruleUIDs))
                    .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))));

    final Rule outerRule = RuleBuilder.create("sceneActivationRule")
            .withTriggers(ModuleBuilder.createTrigger().withId("ItemStateChangeTrigger2")
                    .withTypeUID("core.GenericEventTrigger").withConfiguration(outerRuleTriggerConfig).build())
            .withActions(ModuleBuilder.createAction().withId("RunRuleAction1").withTypeUID("core.RunRuleAction")
                    .withConfiguration(outerRuleActionConfig).build())
            .withName("scene activator").build();

    return outerRule;
}
 
Example #9
Source File: SnippetsTests.java    From 30-seconds-of-java with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
@Test
public void reducedFilter_Test() throws Exception {
    Map<String, Object> item1 = new HashMap<>();
    item1.put("id", 1);
    item1.put("name", "john");
    item1.put("age", 24);

    Map<String, Object> item2 = new HashMap<>();
    item2.put("id", 2);
    item2.put("name", "mike");
    item2.put("age", 50);

    Map<String, Object>[] filtered = Snippets.reducedFilter((Map<String, Object>[]) new Map[]{item1, item2}, new String[]{"id", "name"}, item -> (Integer) item.get("age") > 24);
    assertThat(filtered).hasSize(1);
    assertThat(filtered[0])
            .containsOnly(
                    new SimpleEntry<String, Object>("id", 2),
                    new SimpleEntry<String, Object>("name", "mike"));
}
 
Example #10
Source File: EntryStreamTest.java    From streamex with Apache License 2.0 6 votes vote down vote up
@Test
public void testSelect() {
    Map<Object, Object> map = new LinkedHashMap<>();
    map.put("a", 1);
    map.put("b", "2");
    map.put(3, "c");
    assertEquals(Collections.singletonMap("a", 1), EntryStream.of(map).selectValues(Integer.class).toMap());
    assertEquals(Collections.singletonMap(3, "c"), EntryStream.of(map).selectKeys(Integer.class).toMap());

    // Weird way to create a map from the array. Don't do this in production
    // code!
    Object[] interleavingArray = { "a", 1, "bb", 22, "ccc", 33 };
    Map<String, Integer> result = EntryStream.of(
        StreamEx.of(interleavingArray).pairMap(SimpleEntry::new)).selectKeys(String.class)
            .selectValues(Integer.class).toMap();
    assertEquals(createMap(), result);
}
 
Example #11
Source File: HueConfigProviderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void getServiceConfigsWhenKnoxConfiguredToExternalDomain() {
    BlueprintView blueprintView = getMockBlueprintView("7.0.2", "7.0.2");

    GeneralClusterConfigs generalClusterConfigs = new GeneralClusterConfigs();
    generalClusterConfigs.setExternalFQDN("myaddress.cloudera.site");
    generalClusterConfigs.setKnoxUserFacingCertConfigured(true);
    generalClusterConfigs.setPrimaryGatewayInstanceDiscoveryFQDN(Optional.of("private-gateway.cloudera.site"));
    TemplatePreparationObject tpo = new Builder()
            .withGeneralClusterConfigs(generalClusterConfigs)
            .withBlueprintView(blueprintView)
            .withGateway(new Gateway(), "", new HashSet<>())
            .build();
    List<ApiClusterTemplateConfig> result = underTest.getServiceConfigs(null, tpo);
    Map<String, String> paramToVariable =
            result.stream().collect(Collectors.toMap(ApiClusterTemplateConfig::getName, ApiClusterTemplateConfig::getVariable));
    assertThat(paramToVariable).containsOnly(
            new SimpleEntry<>("database_host", "hue-hue_database_host"),
            new SimpleEntry<>("database_port", "hue-hue_database_port"),
            new SimpleEntry<>("database_name", "hue-hue_database_name"),
            new SimpleEntry<>("database_type", "hue-hue_database_type"),
            new SimpleEntry<>("database_user", "hue-hue_database_user"),
            new SimpleEntry<>("database_password", "hue-hue_database_password"),
            new SimpleEntry<>("hue_service_safety_valve", "hue-hue_service_safety_valve")
    );
}
 
Example #12
Source File: CustomTraceDefinition.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Extract the tag and name from an XML element
 *
 * @param element
 *            the XML element
 * @param tagAttribute
 *            the tag attribute
 * @param nameAttribute
 *            the name attribute
 * @return an entry where the key is the tag and the value is the name
 * @since 2.1
 */
protected static Entry<@NonNull Tag, @NonNull String> extractTagAndName(Element element, String tagAttribute, String nameAttribute) {
    Tag tag = Tag.fromName(element.getAttribute(tagAttribute));
    String name = element.getAttribute(nameAttribute);
    if (tag == null) {
        // Backward compatibility
        if (name.equals(Messages.CustomTraceDefinition_timestampTag)) {
            tag = Tag.TIMESTAMP;
            name = checkNotNull(Tag.TIMESTAMP.toString());
        } else if (name.equals(Messages.CustomTraceDefinition_messageTag)) {
            tag = Tag.MESSAGE;
            name = checkNotNull(Tag.MESSAGE.toString());
        } else if (name.equals(Messages.CustomXmlTraceDefinition_ignoreTag)) {
            tag = Tag.IGNORE;
            name = checkNotNull(Tag.IGNORE.toString());
        } else {
            tag = Tag.OTHER;
        }
    } else if (name.isEmpty()) {
        name = checkNotNull(tag.toString());
    }
    return new SimpleEntry<>(tag, name);
}
 
Example #13
Source File: Query.java    From yuvi with Apache License 2.0 6 votes vote down vote up
public Query(final String metricName, final List<TagMatcher> tagMatchers) {
  if (metricName == null || metricName.isEmpty() || tagMatchers == null) {
    throw new IllegalArgumentException("metric name or tag matcher can't be null.");
  }

  final Map<String, List<TagMatcher>> tagNameMap = tagMatchers.stream()
      .map(t -> new SimpleEntry<>(t.tag.key, t))
      .collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toList())));

  tagNameMap.entrySet().forEach(tagKeyEntry -> {
    if (tagKeyEntry.getValue().size() != 1) {
      throw new IllegalArgumentException("Only one tagFilter is allowed per tagKey: "
          + tagKeyEntry.getKey() + " .But we found " + tagKeyEntry.getValue().toString());
    }
  });

  this.metricName = metricName;
  this.tagMatchers = tagMatchers;
}
 
Example #14
Source File: Acquirer.java    From XHAIL with GNU General Public License v3.0 6 votes vote down vote up
public Map.Entry<Values, Collection<Collection<String>>> parse() {
	this.answers = new HashSet<>();
	try {
		if (UNKNOWN.equals(token))
			parseUNKNOWN();
		else if (UNSATISFIABLE.equals(token))
			parseUNSATISFIABLE();
		else
			parseAnswer();
		parseEOF();
	} catch (ParserErrorException e) {
		Logger.error(e.getMessage());
		// return null;
	}
	return new SimpleEntry<Values, Collection<Collection<String>>>(this.values, this.answers);
}
 
Example #15
Source File: TestPrintXML.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    elements.push(new SimpleEntry<>(attrs.getValue("name"), attrs.getValue("index")));
    String nil = attrs.getValue("xsi:nil");
    if ("true".equals(nil)) {
        objects.push(null);
        return;
    }

    switch (qName) {
    case "event":
        objects.push(new XMLEvent(attrs.getValue("type")));
        break;
    case "struct":
        objects.push(new HashMap<String, Object>());
        break;
    case "array":
        objects.push(new Object[Integer.parseInt(attrs.getValue("size"))]);
        break;
    case "value":
        objects.push(new StringBuilder());
        break;
    }
}
 
Example #16
Source File: CommandParser.java    From Chimera with MIT License 6 votes vote down vote up
protected void check(T type, Command command, String name, Label label) {
    if (matcher.reset(name).matches()) {
        environment.error(type, format(name, "is not a valid command " + label, "should not contain whitespaces"));
        return;
        
    } else if (name.isEmpty()) {
        environment.error(type, "Command " + label + " should not be empty");
        return;
    }
    
    var entry = names.get(name);
    if (entry == null) {
        names.put(name, new SimpleEntry<>(command, label));
        
    } else {
        environment.error(type, format(name, "already exists", "commands should not have the same aliases and names"));
    }
}
 
Example #17
Source File: Relationships.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
/**
 * The value for a relationship can be a scalar object (1:1), a collection (1:n), a map (1:n, but with dynamic
 * relationship types) or a map (1:n) with properties for each relationship.
 * This method unifies the type into something iterable, depending on the given inverse type.
 *
 * @param rawValue The raw value to unify
 * @return A unified collection (Either a collection of Map.Entry for dynamic and relationships with properties
 * or a list of related values)
 */
@Nullable
public static Collection<?> unifyRelationshipValue(Neo4jPersistentProperty property, Object rawValue) {
	Collection<?> unifiedValue;
	if (property.isDynamicAssociation()) {
		if (property.isDynamicOneToManyAssociation()) {
			unifiedValue = ((Map<String, Collection<?>>) rawValue)
				.entrySet()
				.stream()
				.flatMap(e -> e.getValue().stream().map(v -> new SimpleEntry(e.getKey(), v)))
				.collect(toList());
		} else {
			unifiedValue = ((Map<String, Object>) rawValue).entrySet();
		}
	} else if (property.isRelationshipWithProperties()) {
		unifiedValue = ((Map<Object, Object>) rawValue).entrySet();
	} else if (property.isCollectionLike()) {
		unifiedValue = (Collection<Object>) rawValue;
	} else {
		unifiedValue = Collections.singleton(rawValue);
	}
	return unifiedValue;
}
 
Example #18
Source File: ProcessUnitState.java    From SPADE with GNU General Public License v3.0 5 votes vote down vote up
protected boolean hasTheNamespaceEverBeenSeenForProcess(NamespaceIdentifier namespace){
	for(SimpleEntry<AgentIdentifier, NamespaceIdentifier> value : timeToAgentAndNamespace.getValues()){
		if(namespace.equals(value.getValue())){
			return true;
		}
	}
	return false;
}
 
Example #19
Source File: TestPrintXML.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void endElement(String uri, String localName, String qName) {
    SimpleEntry<String, String> element = elements.pop();
    switch (qName) {
    case "event":
    case "struct":
    case "array":
    case "value":
        String name = element.getKey();
        Object value = objects.pop();
        if (objects.isEmpty()) {
            events.add((XMLEvent) value);
            return;
        }
        if (value instanceof StringBuilder) {
            value = ((StringBuilder) value).toString();
        }
        Object parent = objects.peek();
        if (parent instanceof XMLEvent) {
            ((XMLEvent) parent).values.put(name, value);
        }
        if (parent instanceof Map) {
            ((Map<String, Object>) parent).put(name, value);
        }
        if (parent != null && parent.getClass().isArray()) {
            int index = Integer.parseInt(element.getValue());
            ((Object[]) parent)[index] = value;
        }
    }
}
 
Example #20
Source File: ConfigurationBuilderTest.java    From chassis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void applicationConfigurationsWithEnvironmentConfiguration() {
    TestUtils.writePropertiesToFile(TEST_APP_CONFIG_PROPERTIES, filesCreated, new SimpleEntry(MODULE_1_KEY_2, MODULE_1_VALUE_2 + "-override"), new SimpleEntry(MODULE_1_KEY_3, MODULE_1_VALUE_3 + "-override"));
    TestUtils.writePropertiesToFile(TEST_APP_CONFIG_PROPERTIES.replace(".properties", "." + ENVIRONMENT + ".properties"), filesCreated, new SimpleEntry(MODULE_1_KEY_2, MODULE_1_VALUE_2 + "-override"));

    configurationBuilder.withApplicationProperties("file://" + TEST_APP_CONFIG_PROPERTIES);
    Configuration configuration = configurationBuilder.build();

    Assert.assertEquals(MODULE_1_VALUE_1, configuration.getString(MODULE_1_KEY_1));
    Assert.assertEquals(MODULE_1_VALUE_2 + "-override", configuration.getString(MODULE_1_KEY_2));
    Assert.assertEquals(MODULE_1_VALUE_3 + "-override", configuration.getString(MODULE_1_KEY_3));
}
 
Example #21
Source File: RecursiveObjectLeaker.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
public static void beforeConstructor(final Object key) {
    Deque<Entry<?, Object>> stack = STACK.get();
    if (stack == null) {
        // Biased: this class is expected to be rarely and shallowly used
        stack = new ArrayDeque<>(1);
        STACK.set(stack);
    }

    LOG.debug("Resolving key {}", key);
    stack.push(new SimpleEntry<>(key, null));
}
 
Example #22
Source File: JavaSqueezer.java    From AndroTickler with Apache License 2.0 5 votes vote down vote up
private ArrayList<String> returnValues(ArrayList<SimpleEntry> hits){
	ArrayList<String> files = new ArrayList<>();
	for (SimpleEntry e:hits)
		files.add(e.getValue().toString());
	
	Collections.sort(files);
 
	ArrayList<String> ret= new ArrayList<String>(new LinkedHashSet<String>(files));
	return ret;
}
 
Example #23
Source File: ComBindingEntryDaoImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void lockBindings(int companyId, List<SimpleEntry<Integer, Integer>> cmPairs) {
	StringBuffer selForUpd = new StringBuffer("select * from customer_" + companyId + "_binding_tbl where (customer_id,mailinglist_id) in (");
	boolean first = true;
	for (SimpleEntry<Integer, Integer> entry : cmPairs) {
		if (!first) {
			selForUpd.append(",");
		}
		selForUpd.append("("+entry.getKey()+","+entry.getValue()+")");
		first = false;
	}
	selForUpd.append(") for update");
	select(logger, selForUpd.toString());
}
 
Example #24
Source File: ModelHelper.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Return list of key ranges available.
 *
 * @param keyRanges List of Key Value pairs.
 * @return Collection of key ranges available.
 */
public static final List<Map.Entry<Double, Double>> encode(final Map<Double, Double> keyRanges) {
    Preconditions.checkNotNull(keyRanges, "keyRanges");

    return keyRanges
            .entrySet()
            .stream()
            .map(x -> new AbstractMap.SimpleEntry<>(x.getKey(), x.getValue()))
            .collect(Collectors.toList());
}
 
Example #25
Source File: ProcessWithAgentState.java    From SPADE with GNU General Public License v3.0 5 votes vote down vote up
protected void setAgentAndNamespace(Double time, AgentIdentifier agent, NamespaceIdentifier namespace){
	super.setAgentAndNamespace(time, agent, namespace);
	previousProcessAgentsAndNamespaces.add(new SimpleEntry<AgentIdentifier, NamespaceIdentifier>(agent, namespace));
	if(isUnitActive()){
		previousUnitAgentsAndNamespaces.add(new SimpleEntry<AgentIdentifier, NamespaceIdentifier>(agent, namespace));
	}
}
 
Example #26
Source File: CountryMenuItemFactoryImpl.java    From cia with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the topic indicator map.
 *
 * @return the topic indicator map
 */
private Map<String, List<ViewWorldbankIndicatorDataCountrySummary>> getTopicIndicatorMap() {
	final DataContainer<ViewWorldbankIndicatorDataCountrySummary, WorldbankIndicatorDataCountrySummaryEmbeddedId> indicatorDataCountrSummaryDailyDataContainer = applicationManager
			.getDataContainer(ViewWorldbankIndicatorDataCountrySummary.class);

	return indicatorDataCountrSummaryDailyDataContainer
			.findListByEmbeddedProperty(ViewWorldbankIndicatorDataCountrySummary.class,ViewWorldbankIndicatorDataCountrySummary_.embeddedId,WorldbankIndicatorDataCountrySummaryEmbeddedId.class,WorldbankIndicatorDataCountrySummaryEmbeddedId_.countryId,"SE").parallelStream()
			.filter(t -> t != null && t.getSourceValue() != null && t.getEndYear() > DATA_POINTS_FOR_YEAR_ABOVE && t.getDataPoint() > MINIMUM_NUMBER_DATA_POINTS)
			.flatMap(t -> Arrays.asList(t.getTopics().split(";")).stream()
					.map(topic -> new AbstractMap.SimpleEntry<>(topic, t)))

			.collect(Collectors.groupingBy(SimpleEntry::getKey,
					Collectors.mapping(SimpleEntry::getValue, Collectors.toList())));
}
 
Example #27
Source File: VariableReplacementAnalysis.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private void findParametersWrappedInLocalVariables() {
	for(StatementObject statement : nonMappedLeavesT2) {
		for(VariableDeclaration declaration : statement.getVariableDeclarations()) {
			AbstractExpression initializer = declaration.getInitializer();
			if(initializer != null) {
				for(String key : initializer.getCreationMap().keySet()) {
					List<ObjectCreation> creations = initializer.getCreationMap().get(key);
					for(ObjectCreation creation : creations) {
						for(String argument : creation.arguments) {
							SimpleEntry<VariableDeclaration, UMLOperation> v2 = getVariableDeclaration2(new Replacement("", argument, ReplacementType.VARIABLE_NAME));
							SimpleEntry<VariableDeclaration, UMLOperation> v1 = getVariableDeclaration1(new Replacement(declaration.getVariableName(), "", ReplacementType.VARIABLE_NAME));
							if(v2 != null && v1 != null) {
								Set<AbstractCodeMapping> references = VariableReferenceExtractor.findReferences(v1.getKey(), v2.getKey(), mappings);
								RenameVariableRefactoring ref = new RenameVariableRefactoring(v1.getKey(), v2.getKey(), v1.getValue(), v2.getValue(), references);
								if(!existsConflictingExtractVariableRefactoring(ref) && !existsConflictingMergeVariableRefactoring(ref) && !existsConflictingSplitVariableRefactoring(ref)) {
									variableRenames.add(ref);
									if(!v1.getKey().getType().equals(v2.getKey().getType()) || !v1.getKey().getType().equalsQualified(v2.getKey().getType())) {
										ChangeVariableTypeRefactoring refactoring = new ChangeVariableTypeRefactoring(v1.getKey(), v2.getKey(), v1.getValue(), v2.getValue(), references);
										refactoring.addRelatedRefactoring(ref);
										refactorings.add(refactoring);
									}
								}
							}
						}
					}
				}
			}
		}
	}
}
 
Example #28
Source File: Snippets.java    From 30-seconds-of-java with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
public static List<String> anagrams(String input) {
    if (input.length() <= 2) {
        return input.length() == 2
                ? Arrays.asList(input, input.substring(1) + input.substring(0, 1))
                : Collections.singletonList(input);
    }
    return IntStream.range(0, input.length())
            .mapToObj(i -> new SimpleEntry<>(i, input.substring(i, i + 1)))
            .flatMap(entry ->
                    anagrams(input.substring(0, entry.getKey()) + input.substring(entry.getKey() + 1))
                            .stream()
                            .map(s -> entry.getValue() + s))
            .collect(Collectors.toList());
}
 
Example #29
Source File: P12.java    From 99-problems with MIT License 5 votes vote down vote up
public static <T> List<T> decode(List<Object> encoded) {
    return encoded.stream().flatMap(e -> {
        if (e instanceof SimpleEntry) {
            SimpleEntry<Integer, T> entry = (SimpleEntry<Integer, T>) e;
            return Collections.nCopies(entry.getKey(), entry.getValue()).stream();
        }
        return Stream.of((T) e);
    }).collect(toList());
}
 
Example #30
Source File: ItemItemCF.java    From StreamingRec with Apache License 2.0 5 votes vote down vote up
@Override
protected void trainInternal(List<Item> items, List<ClickData> clickData) {
	//if we are supposed to only used the last N click and the number of training clicks is higher
	//we can just cut the data right here.
	if(buffer && clickData.size()>ringBuffer.size()){
		//for batch training
		ringBuffer.clear();
		clickData = clickData.subList(clickData.size()-bufferSize, clickData.size());
	}
	//iterate over the click data and update the click maps of each item
	for (ClickData c : clickData) {
		//update the click maps of each item
		updateMap(c.click.userId, c.click.item.id);
		if(buffer){
			//update the buffer so that these clicks are removed later from the click maps
			SimpleEntry<Long, Long> tuple = new AbstractMap.SimpleEntry<Long, Long>(c.click.userId, c.click.item.id);
			//if the click is already contained, remove it
			if(ringBuffer.contains(tuple)){
				ringBuffer.remove(tuple);
			}
			//in any case, add the click at the end in the buffer
			ringBuffer.add(tuple);
		}			
	}
	//if we are using only the most recent N clicks, remove "old" click from the map, here.
	if(buffer){
		ObjectListIterator<Entry<Long,Long>> iterator = ringBuffer.iterator();
		while(buffer && ringBuffer.size()>bufferSize){
			Entry<Long, Long> next = iterator.next();
			itemClickMap.get(next.getValue()).clear(userMap.get(next.getKey()));
			userItemMap.get(userMap.get(next.getKey())).remove(next.getValue());
			iterator.remove();
		}
	}		
}