List of usage examples for com.google.common.collect Iterables get
public static <T> T get(Iterable<T> iterable, int position)
From source file:org.jpmml.evaluator.mining.MiningModelEvaluator.java
public MiningModelEvaluator(PMML pmml, MiningModel miningModel) { super(pmml, miningModel); if (miningModel.hasEmbeddedModels()) { List<EmbeddedModel> embeddedModels = miningModel.getEmbeddedModels(); EmbeddedModel embeddedModel = Iterables.get(embeddedModels, 0); throw new UnsupportedFeatureException(embeddedModel); }// ww w .j av a 2s . c om Segmentation segmentation = miningModel.getSegmentation(); if (segmentation == null) { throw new InvalidFeatureException(miningModel); } // End if if (!segmentation.hasSegments()) { throw new InvalidFeatureException(segmentation); } LocalTransformations localTransformations = segmentation.getLocalTransformations(); if (localTransformations != null) { throw new UnsupportedFeatureException(localTransformations); } }
From source file:com.supaham.commons.bukkit.area.Poly2DRegion.java
@Override public boolean contains(@Nonnull Vector vector) { if (this.points.size() < 3) { return false; }//from ww w .j a va 2 s. c o m int targetX = vector.getBlockX(); //wide int targetY = vector.getBlockY(); //height int targetZ = vector.getBlockZ(); //depth if (targetY < this.min.getBlockY() || targetY > this.max.getBlockY()) { return false; } boolean inside = false; int npoints = this.points.size(); int xNew, zNew; int xOld, zOld; int x1, z1; int x2, z2; long crossproduct; int i; xOld = Iterables.get(this.points, npoints - 1).getBlockX(); zOld = Iterables.get(this.points, npoints - 1).getBlockZ(); for (Vector point : this.points) { xNew = point.getBlockX(); zNew = point.getBlockZ(); //Check for corner if (xNew == targetX && zNew == targetZ) { return true; } if (xNew > xOld) { x1 = xOld; x2 = xNew; z1 = zOld; z2 = zNew; } else { x1 = xNew; x2 = xOld; z1 = zNew; z2 = zOld; } if (x1 <= targetX && targetX <= x2) { crossproduct = ((long) targetZ - (long) z1) * (long) (x2 - x1) - ((long) z2 - (long) z1) * (long) (targetX - x1); if (crossproduct == 0) { if ((z1 <= targetZ) == (targetZ <= z2)) { return true; //on edge } } else if (crossproduct < 0 && (x1 != targetX)) { inside = !inside; } } xOld = xNew; zOld = zNew; } return inside; }
From source file:org.eclipse.elk.alg.layered.intermediate.compaction.LGraphToCGraphTransformer.java
/** * Collects the positions and dimensions of {@link LNode}s and vertical segments in the layered * graph and writes them to the {@link CNode}s. *//*from w w w . ja v a 2 s . co m*/ private void readNodes() { List<VerticalSegment> verticalSegments = Lists.newArrayList(); // resetting to avoid problems if this is called repeatedly cGraph.cNodes.clear(); // 1. collecting positions of graph elements Map<LNode, CNode> nodeMap = Maps.newHashMap(); for (Layer layer : layeredGraph) { for (LNode node : layer) { // comment boxes are part of a node's margins // hence we can neglect them here without the risk // of other nodes overlapping them after compaction if (node.getProperty(LayeredOptions.COMMENT_BOX)) { if (!Iterables.isEmpty(node.getConnectedEdges())) { LEdge e = Iterables.get(node.getConnectedEdges(), 0); LNode other = e.getSource().getNode(); if (other == node) { other = e.getTarget().getNode(); } Pair<LNode, KVector> p = Pair.of(other, node.getPosition().clone().sub(other.getPosition())); commentOffsets.put(node, p); continue; } } // add all nodes CLNode cNode = new CLNode(node, layeredGraph); cGraph.cNodes.add(cNode); nodeMap.put(node, cNode); } } for (Layer layer : layeredGraph) { for (LNode node : layer) { final CNode cNode = nodeMap.get(node); // add vertical edge segments for (LEdge edge : node.getOutgoingEdges()) { Iterator<KVector> bends = edge.getBendPoints().iterator(); boolean first = true; VerticalSegment lastSegment = null; // infer vertical segments from positions of bendpoints if (bends.hasNext()) { KVector bend1 = bends.next(); KVector bend2 = null; // get segment of source n/s port if (edge.getSource().getSide() == PortSide.NORTH) { VerticalSegment vs = new VerticalSegment(bend1, new KVector(bend1.x, cNode.hitbox.y), cNode, edge); vs.blockBottomSpacing = true; verticalSegments.add(vs); } if (edge.getSource().getSide() == PortSide.SOUTH) { VerticalSegment vs = new VerticalSegment(bend1, new KVector(bend1.x, cNode.hitbox.y + cNode.hitbox.height), cNode, edge); vs.blockTopSpacing = true; verticalSegments.add(vs); } // get regular segments while (bends.hasNext()) { bend2 = bends.next(); if (!CompareFuzzy.eq(bend1.y, bend2.y)) { lastSegment = new VerticalSegment(bend1, bend2, null, edge); verticalSegments.add(lastSegment); // the first vertical segment of an outgoing edge if (first) { first = false; if (bend2.y < cNode.hitbox.y) { lastSegment.blockBottomSpacing = true; } else if (bend2.y > cNode.hitbox.y + cNode.hitbox.height) { lastSegment.blockTopSpacing = true; } else { // completely surrounded lastSegment.blockTopSpacing = true; lastSegment.blockBottomSpacing = true; } } } if (bends.hasNext()) { bend1 = bend2; } } // handle last vertical segment if (lastSegment != null) { CNode cTargetNode = nodeMap.get(edge.getTarget().getNode()); if (bend1.y < cTargetNode.hitbox.y) { lastSegment.blockBottomSpacing = true; } else if (bend1.y > cTargetNode.hitbox.y + cTargetNode.hitbox.height) { lastSegment.blockTopSpacing = true; } else { // completely surrounded lastSegment.blockTopSpacing = true; lastSegment.blockBottomSpacing = true; } } } } // same for incoming edges to get NSSegments on target side for (LEdge edge : node.getIncomingEdges()) { if (!edge.getBendPoints().isEmpty()) { // get segment of target n/s port KVector bend1 = edge.getBendPoints().getLast(); if (edge.getTarget().getSide() == PortSide.NORTH) { VerticalSegment vs = new VerticalSegment(bend1, new KVector(bend1.x, cNode.hitbox.y), cNode, edge); vs.blockBottomSpacing = true; verticalSegments.add(vs); } if (edge.getTarget().getSide() == PortSide.SOUTH) { VerticalSegment vs = new VerticalSegment(bend1, new KVector(bend1.x, cNode.hitbox.y + cNode.hitbox.height), cNode, edge); vs.blockTopSpacing = true; verticalSegments.add(vs); } } } } } // 2. combining intersecting segments in CLEdges to process them as one if (!verticalSegments.isEmpty()) { // sorting the segments by position in ascending order Collections.sort(verticalSegments); // merging intersecting segments in the same CLEdge VerticalSegment last = verticalSegments.get(0); CLEdge c = new CLEdge(last, layeredGraph); for (int i = 1; i < verticalSegments.size(); i++) { VerticalSegment verticalSegment = verticalSegments.get(i); if (c.intersects(verticalSegment)) { c.addSegment(verticalSegment); } else { cGraph.cNodes.add(c); c = new CLEdge(verticalSegment, layeredGraph); } last = verticalSegment; } cGraph.cNodes.add(c); } verticalSegments.clear(); // 3. grouping nodes with their connected north/south segments groupCNodes(); }
From source file:org.jclouds.trmk.vcloud_0_8.binders.BindInstantiateVAppTemplateParamsToXmlPayload.java
@Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, "this binder is only valid for GeneratedHttpRequests!"); GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; String name = checkNotNull(postParams.remove("name"), "name").toString(); String template = checkNotNull(postParams.remove("template"), "template").toString(); SortedMap<ResourceType, String> virtualHardwareQuantity = Maps.newTreeMap(); InstantiateVAppTemplateOptions options = findOptionsInArgsOrNull(gRequest); String network = (defaultNetwork != null) ? defaultNetwork.get().getHref().toASCIIString() : null; String fenceMode = defaultFenceMode; String networkName = name;// ww w . j ava 2s . c om if (options != null) { if (options.getNetworkConfig().size() > 0) { NetworkConfig config = Iterables.get(options.getNetworkConfig(), 0); network = ifNullDefaultTo(config.getParentNetwork(), network); fenceMode = ifNullDefaultTo(config.getFenceMode(), defaultFenceMode); networkName = ifNullDefaultTo(config.getNetworkName(), networkName); } addQuantity(options, virtualHardwareQuantity); } try { return stringBinder.bindToRequest(request, generateXml(name, template, virtualHardwareQuantity, networkName, fenceMode, URI.create(network))); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (FactoryConfigurationError e) { throw new RuntimeException(e); } catch (TransformerException e) { throw new RuntimeException(e); } }
From source file:org.jclouds.vcloud.binders.BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayload.java
@Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) { checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest<?>, "this binder is only valid for GeneratedHttpRequests!"); GeneratedHttpRequest<?> gRequest = (GeneratedHttpRequest<?>) request; checkState(gRequest.getArgs() != null, "args should be initialized at this point"); String name = checkNotNull(postParams.remove("name"), "name"); String template = checkNotNull(postParams.remove("template"), "template"); SortedMap<ResourceType, String> virtualHardwareQuantity = Maps.newTreeMap(); InstantiateVAppTemplateOptions options = findOptionsInArgsOrNull(gRequest); String network = (defaultNetwork != null) ? defaultNetwork.toASCIIString() : null; String fenceMode = defaultFenceMode; String networkName = name;/* w ww . j a v a 2s . c o m*/ if (options != null) { if (options.getNetworkConfig().size() > 0) { NetworkConfig config = Iterables.get(options.getNetworkConfig(), 0); network = ifNullDefaultTo(config.getParentNetwork(), network); fenceMode = ifNullDefaultTo(config.getFenceMode(), defaultFenceMode); if (apiVersion.indexOf("0.8") != -1 && fenceMode.equals("bridged")) fenceMode = "allowInOut"; networkName = ifNullDefaultTo(config.getNetworkName(), networkName); } addQuantity(options, virtualHardwareQuantity); } try { return stringBinder.bindToRequest(request, generateXml(name, template, virtualHardwareQuantity, networkName, fenceMode, URI.create(network))); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (FactoryConfigurationError e) { throw new RuntimeException(e); } catch (TransformerException e) { throw new RuntimeException(e); } }
From source file:com.opengamma.financial.depgraph.provider.RemoteDependencyGraphTraceProvider.java
/** * Unpacks the requirements into URI form. * @param uri the uri to append to/* ww w. j a v a 2s .c o m*/ * @param requirements the requirements to append */ private URI processRequirements(URI uri, Collection<ValueRequirement> requirements) { for (ValueRequirement valueRequirement : requirements) { String valueName = valueRequirement.getValueName(); ValueProperties constraints = valueRequirement.getConstraints(); String contraintStr = constraints.isEmpty() ? "" : constraints.toString(); String constrainedValueName = valueName + contraintStr; ComputationTargetReference targetReference = valueRequirement.getTargetReference(); String targetType = targetReference.getType().toString(); if (targetReference instanceof ComputationTargetRequirement) { ComputationTargetRequirement requirement = (ComputationTargetRequirement) targetReference; Set<ExternalId> externalIds = requirement.getIdentifiers().getExternalIds(); ArgumentChecker.isTrue(externalIds.size() == 1, "One (and only one) external id must be specified currently."); ExternalId externalId = Iterables.get(externalIds, 0); uri = DependencyGraphTraceProviderResource.uriValueRequirementByExternalId(uri, constrainedValueName, targetType, externalId); } else if (targetReference instanceof ComputationTargetSpecification) { UniqueId uniqueId = ((ComputationTargetSpecification) targetReference).getUniqueId(); uri = DependencyGraphTraceProviderResource.uriValueRequirementByUniqueId(uri, constrainedValueName, targetType, uniqueId); } else { throw new IllegalArgumentException( format("Unrecognised ValueRequirement class: %s", ValueRequirement.class.getName())); } } return uri; }
From source file:msi.gama.common.util.FileUtils.java
/** * Construct an absolute file path.//w ww .ja va 2 s. c om * * @param scope * the scope * @param fp * the fp * @param mustExist * the must exist * @return the string * @throws GamaRuntimeException * the gama runtime exception */ static public String constructAbsoluteFilePath(final IScope scope, final String fp, final boolean mustExist) throws GamaRuntimeException { String filePath = null; Iterable<String> baseDirectories = null; final IExperimentAgent a = scope.getExperiment(); // final List<String> referenceDirectories = a.getWorkingPaths(); try { baseDirectories = Iterables.transform(a.getWorkingPaths(), each -> { try { return withTrailingSep(URLDecoder.decode(each, "UTF-8")); } catch (final UnsupportedEncodingException e1) { return each; } }); filePath = URLDecoder.decode(fp, "UTF-8"); } catch (final UnsupportedEncodingException e1) { filePath = fp; } final GamaRuntimeException ex = new GamaRuntimeFileException(scope, "File denoted by " + filePath + " not found."); File file = null; if (isAbsolutePath(filePath)) { file = new File(filePath); if (file.exists() || !mustExist) { try { return file.getCanonicalPath(); } catch (final IOException e) { e.printStackTrace(); return file.getAbsolutePath(); } } for (final String baseDirectory : baseDirectories) { file = new File(baseDirectory + removeRoot(filePath)); if (file.exists()) { try { return file.getCanonicalPath(); } catch (final IOException e) { e.printStackTrace(); return file.getAbsolutePath(); } } ex.addContext(file.getAbsolutePath()); } } else { for (final String baseDirectory : baseDirectories) { file = new File(baseDirectory + filePath); if (file.exists()) { try { // We have to try if the test is necessary. if (GAMA.isInHeadLessMode()) { return file.getAbsolutePath(); } else { return file.getCanonicalPath(); } } catch (final IOException e) { e.printStackTrace(); return file.getAbsolutePath(); } } ex.addContext(file.getAbsolutePath()); } // We havent found the file, but it may not exist. In that case, the // first directory is used as a reference. if (!mustExist) try { return new File(Iterables.get(baseDirectories, 0) + filePath).getCanonicalPath(); } catch (final IOException e) { throw ex; } } throw ex; }
From source file:com.groupon.jenkins.buildsetup.GithubReposController.java
public String getCurrentOrg() throws IOException { String currentOrg = (String) Stapler.getCurrentRequest().getSession() .getAttribute("setupOrg" + getCurrentGithubLogin()); return StringUtils.isEmpty(currentOrg) ? Iterables.get(getOrgs(), 0) : currentOrg; }
From source file:org.apache.whirr.service.zookeeper.ZooKeeperService.java
private Set<Instance> getInstances(List<NodeMetadata> nodes) { return Sets//from www . ja v a2 s . co m .newHashSet(Collections2.transform(Sets.newHashSet(nodes), new Function<NodeMetadata, Instance>() { @Override public Instance apply(NodeMetadata node) { return new Instance(Collections.singleton(ZOOKEEPER_ROLE), Iterables.get(node.getPublicAddresses(), 0), Iterables.get(node.getPrivateAddresses(), 0)); } })); }
From source file:org.jclouds.aws.ec2.compute.loaders.AWSEC2CreateSecurityGroupIfNeeded.java
private void createSecurityGroupInRegion(String region, String name, int... ports) { checkNotNull(region, "region"); checkNotNull(name, "name"); logger.debug(">> creating securityGroup region(%s) name(%s)", region, name); try {//w w w . j av a2 s.c om securityApi.createSecurityGroupInRegion(region, name, name); boolean created = securityGroupEventualConsistencyDelay.apply(new RegionAndName(region, name)); if (!created) throw new RuntimeException( String.format("security group %s/%s is not available after creating", region, name)); logger.debug("<< created securityGroup(%s)", name); ImmutableSet.Builder<IpPermission> permissions = ImmutableSet.builder(); String id; if (name.startsWith("sg-")) { id = name; } else { id = groupNameToId.apply(new RegionAndName(region, name).slashEncode()); } if (ports.length > 0) { for (Map.Entry<Integer, Integer> range : getPortRangesFromList(ports).entrySet()) { permissions.add(IpPermission.builder().fromPort(range.getKey()).toPort(range.getValue()) .ipProtocol(IpProtocol.TCP).cidrBlock("0.0.0.0/0").build()); } String myOwnerId = Iterables.get(securityApi.describeSecurityGroupsInRegion(region, name), 0) .getOwnerId(); permissions.add(IpPermission.builder().fromPort(0).toPort(65535).ipProtocol(IpProtocol.TCP) .tenantIdGroupNamePair(myOwnerId, id).build()); permissions.add(IpPermission.builder().fromPort(0).toPort(65535).ipProtocol(IpProtocol.UDP) .tenantIdGroupNamePair(myOwnerId, id).build()); } Set<IpPermission> perms = permissions.build(); if (perms.size() > 0) { logger.debug(">> authorizing securityGroup region(%s) name(%s) IpPermissions(%s)", region, name, perms); securityApi.authorizeSecurityGroupIngressInRegion(region, id, perms); logger.debug("<< authorized securityGroup(%s)", name); } } catch (IllegalStateException e) { logger.debug("<< reused securityGroup(%s)", name); } }