query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Updates the template with the specified id. @param id id of the template to update @param options a Map of options to update/add. @return {@link Response} @throws RequestException if request to transloadit server fails. @throws LocalOperationException if something goes wrong while running non-http operations.
[ "public Response updateTemplate(String id, Map<String, Object> options)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.put(\"/templates/\" + id, options));\n }" ]
[ "public long number(ImapRequestLineReader request) throws ProtocolException {\n String digits = consumeWord(request, new DigitCharValidator());\n return Long.parseLong(digits);\n }", "public void createLinks(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n for (ServiceReference<S> serviceReference : linkerManagement.getMatchedBinderServiceRef()) {\n if (linkerManagement.canBeLinked(declaration, serviceReference)) {\n linkerManagement.link(declaration, serviceReference);\n }\n }\n }", "private void readResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)\n {\n for (Project.Resources.Resource.Baseline baseline : xmlResource.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n Double cost = DatatypeConverter.parseCurrency(baseline.getCost());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpxjResource.setBaselineCost(cost);\n mpxjResource.setBaselineWork(work);\n }\n else\n {\n mpxjResource.setBaselineCost(number, cost);\n mpxjResource.setBaselineWork(number, work);\n }\n }\n }", "public void add(final String source, final T destination) {\n\n // replace multiple slashes with a single slash.\n String path = source.replaceAll(\"/+\", \"/\");\n\n path = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n\n String[] parts = path.split(\"/\", maxPathParts + 2);\n if (parts.length - 1 > maxPathParts) {\n throw new IllegalArgumentException(String.format(\"Number of parts of path %s exceeds allowed limit %s\",\n source, maxPathParts));\n }\n StringBuilder sb = new StringBuilder();\n List<String> groupNames = new ArrayList<>();\n\n for (String part : parts) {\n Matcher groupMatcher = GROUP_PATTERN.matcher(part);\n if (groupMatcher.matches()) {\n groupNames.add(groupMatcher.group(1));\n sb.append(\"([^/]+?)\");\n } else if (WILD_CARD_PATTERN.matcher(part).matches()) {\n sb.append(\".*?\");\n } else {\n sb.append(part);\n }\n sb.append(\"/\");\n }\n\n //Ignore the last \"/\"\n sb.setLength(sb.length() - 1);\n\n Pattern pattern = Pattern.compile(sb.toString());\n patternRouteList.add(ImmutablePair.of(pattern, new RouteDestinationWithGroups(destination, groupNames)));\n }", "public static Node removePartitionFromNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition));\n }", "public Deployment setServerGroups(final Collection<String> serverGroups) {\n this.serverGroups.clear();\n this.serverGroups.addAll(serverGroups);\n return this;\n }", "public List<String> subList(final long fromIndex, final long toIndex) {\n return doWithJedis(new JedisCallable<List<String>>() {\n @Override\n public List<String> call(Jedis jedis) {\n return jedis.lrange(getKey(), fromIndex, toIndex);\n }\n });\n }", "public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }", "public static void indexResourceRoot(final ResourceRoot resourceRoot) throws DeploymentUnitProcessingException {\n if (resourceRoot.getAttachment(Attachments.ANNOTATION_INDEX) != null) {\n return;\n }\n\n VirtualFile indexFile = resourceRoot.getRoot().getChild(ModuleIndexBuilder.INDEX_LOCATION);\n if (indexFile.exists()) {\n try {\n IndexReader reader = new IndexReader(indexFile.openStream());\n resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, reader.read());\n ServerLogger.DEPLOYMENT_LOGGER.tracef(\"Found and read index at: %s\", indexFile);\n return;\n } catch (Exception e) {\n ServerLogger.DEPLOYMENT_LOGGER.cannotLoadAnnotationIndex(indexFile.getPathName());\n }\n }\n\n // if this flag is present and set to false then do not index the resource\n Boolean shouldIndexResource = resourceRoot.getAttachment(Attachments.INDEX_RESOURCE_ROOT);\n if (shouldIndexResource != null && !shouldIndexResource) {\n return;\n }\n\n final List<String> indexIgnorePathList = resourceRoot.getAttachment(Attachments.INDEX_IGNORE_PATHS);\n final Set<String> indexIgnorePaths;\n if (indexIgnorePathList != null && !indexIgnorePathList.isEmpty()) {\n indexIgnorePaths = new HashSet<String>(indexIgnorePathList);\n } else {\n indexIgnorePaths = null;\n }\n\n final VirtualFile virtualFile = resourceRoot.getRoot();\n final Indexer indexer = new Indexer();\n try {\n final VisitorAttributes visitorAttributes = new VisitorAttributes();\n visitorAttributes.setLeavesOnly(true);\n visitorAttributes.setRecurseFilter(new VirtualFileFilter() {\n public boolean accepts(VirtualFile file) {\n return indexIgnorePaths == null || !indexIgnorePaths.contains(file.getPathNameRelativeTo(virtualFile));\n }\n });\n\n final List<VirtualFile> classChildren = virtualFile.getChildren(new SuffixMatchFilter(\".class\", visitorAttributes));\n for (VirtualFile classFile : classChildren) {\n InputStream inputStream = null;\n try {\n inputStream = classFile.openStream();\n indexer.index(inputStream);\n } catch (Exception e) {\n ServerLogger.DEPLOYMENT_LOGGER.cannotIndexClass(classFile.getPathNameRelativeTo(virtualFile), virtualFile.getPathName(), e);\n } finally {\n VFSUtils.safeClose(inputStream);\n }\n }\n final Index index = indexer.complete();\n resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, index);\n ServerLogger.DEPLOYMENT_LOGGER.tracef(\"Generated index for archive %s\", virtualFile);\n } catch (Throwable t) {\n throw ServerLogger.ROOT_LOGGER.deploymentIndexingFailed(t);\n }\n }" ]
Returns the output directory for reporting.
[ "public Path getReportDirectory()\n {\n WindupConfigurationModel cfg = WindupConfigurationService.getConfigurationModel(getGraphContext());\n Path path = cfg.getOutputPath().asFile().toPath().resolve(REPORTS_DIR);\n createDirectoryIfNeeded(path);\n return path.toAbsolutePath();\n }" ]
[ "public static String matchOrigin(HttpServerExchange exchange, Collection<String> allowedOrigins) throws Exception {\n HeaderMap headers = exchange.getRequestHeaders();\n String[] origins = headers.get(Headers.ORIGIN).toArray();\n if (allowedOrigins != null && !allowedOrigins.isEmpty()) {\n for (String allowedOrigin : allowedOrigins) {\n for (String origin : origins) {\n if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {\n return allowedOrigin;\n }\n }\n }\n }\n String allowedOrigin = defaultOrigin(exchange);\n for (String origin : origins) {\n if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {\n return allowedOrigin;\n }\n }\n ROOT_LOGGER.debug(\"Request rejected due to HOST/ORIGIN mis-match.\");\n ResponseCodeHandler.HANDLE_403.handleRequest(exchange);\n return null;\n }", "public Map<String, String> listConfig(String appName) {\n return connection.execute(new ConfigList(appName), apiKey);\n }", "public void setRoles(List<NamedRoleInfo> roles) {\n\t\tthis.roles = roles;\n\t\tList<AuthorizationInfo> authorizations = new ArrayList<AuthorizationInfo>();\n\t\tfor (NamedRoleInfo role : roles) {\n\t\t\tauthorizations.addAll(role.getAuthorizations());\n\t\t}\n\t\tsuper.setAuthorizations(authorizations);\n\t}", "static boolean shouldShowRequestPermissionRationale(Activity activity, String... permissions) {\n for (String permission : permissions) {\n if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {\n return true;\n }\n }\n return false;\n }", "public Conditionals addIfMatch(Tag tag) {\n Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE));\n Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH));\n List<Tag> match = new ArrayList<>(this.match);\n\n if (tag == null) {\n tag = Tag.ALL;\n }\n if (Tag.ALL.equals(tag)) {\n match.clear();\n }\n if (!match.contains(Tag.ALL)) {\n if (!match.contains(tag)) {\n match.add(tag);\n }\n }\n else {\n throw new IllegalArgumentException(\"Tag ALL already in the list\");\n }\n return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince);\n }", "private boolean isDepOfIdlArtifact(Artifact artifact, Map<String, Artifact> depsMap) {\n List<String> depTrail = artifact.getDependencyTrail();\n // depTrail can be null sometimes, which seems like a maven bug\n if (depTrail != null) {\n for (String name : depTrail) {\n Artifact dep = depsMap.get(name);\n if (dep != null && isIdlCalssifier(dep, classifier)) {\n return true;\n }\n }\n }\n return false;\n }", "public static void extract( DMatrixRMaj src,\n int rows[] , int rowsSize ,\n int cols[] , int colsSize , DMatrixRMaj dst ) {\n if( rowsSize != dst.numRows || colsSize != dst.numCols )\n throw new MatrixDimensionException(\"Unexpected number of rows and/or columns in dst matrix\");\n\n int indexDst = 0;\n for (int i = 0; i < rowsSize; i++) {\n int indexSrcRow = src.numCols*rows[i];\n for (int j = 0; j < colsSize; j++) {\n dst.data[indexDst++] = src.data[indexSrcRow + cols[j]];\n }\n }\n }", "public boolean canUploadVersion(String name, long fileSize) {\n\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"OPTIONS\");\n\n JsonObject preflightInfo = new JsonObject();\n if (name != null) {\n preflightInfo.add(\"name\", name);\n }\n\n preflightInfo.add(\"size\", fileSize);\n\n request.setBody(preflightInfo.toString());\n try {\n BoxAPIResponse response = request.send();\n\n return response.getResponseCode() == 200;\n } catch (BoxAPIException ex) {\n\n if (ex.getResponseCode() >= 400 && ex.getResponseCode() < 500) {\n // This looks like an error response, menaing the upload would fail\n return false;\n } else {\n // This looks like a network error or server error, rethrow exception\n throw ex;\n }\n }\n }", "public RgbaColor adjustHue(float degrees) {\n float[] HSL = convertToHsl();\n HSL[0] = hueCheck(HSL[0] + degrees); // ensure [0-360)\n return RgbaColor.fromHsl(HSL);\n }" ]
Take a string and make it an iterable ContentStream
[ "public static Collection<ContentStream> toContentStreams(final String str, final String contentType) {\n\n if (str == null) {\n return null;\n }\n\n ArrayList<ContentStream> streams = new ArrayList<>(1);\n ContentStreamBase ccc = new ContentStreamBase.StringStream(str);\n ccc.setContentType(contentType);\n streams.add(ccc);\n return streams;\n }" ]
[ "private String determineAndCacheOuterMostNullEmbeddable(String column, String[] path) {\n\t\tString embeddable = path[0];\n\t\t// process each embeddable from less specific to most specific\n\t\t// exclude path leaves as it's a column and not an embeddable\n\t\tfor ( int index = 0; index < path.length - 1; index++ ) {\n\t\t\tSet<String> columnsOfEmbeddable = getColumnsOfEmbeddableAndComputeEmbeddableNullness( embeddable );\n\n\t\t\tif ( nullEmbeddables.contains( embeddable ) ) {\n\t\t\t\t// the current embeddable only has null columns; cache that info for all the columns\n\t\t\t\tfor ( String columnOfEmbeddable : columnsOfEmbeddable ) {\n\t\t\t\t\tcolumnToOuterMostNullEmbeddableCache.put( columnOfEmbeddable, embeddable );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmaybeCacheOnNonNullEmbeddable( path, index, columnsOfEmbeddable );\n\t\t\t}\n\t\t\t// a more specific null embeddable might be present, carry on\n\t\t\tembeddable += \".\" + path[index + 1];\n\t\t}\n\t\treturn columnToOuterMostNullEmbeddableCache.get( column );\n\t}", "private float getQuaternionW(float x, float y, float z) {\n return (float) Math.cos(Math.asin(Math.sqrt(x * x + y * y + z * z)));\n }", "@SuppressWarnings(\"SameParameterValue\")\n private void sendField(Field field) throws IOException {\n if (isConnected()) {\n try {\n field.write(channel);\n } catch (IOException e) {\n logger.warn(\"Problem trying to write field to dbserver, closing connection\", e);\n close();\n throw e;\n }\n return;\n }\n throw new IOException(\"sendField() called after dbserver connection was closed\");\n }", "private static String getEncodedInstance(String encodedResponse) {\n if (isReturnValue(encodedResponse) || isThrownException(encodedResponse)) {\n return encodedResponse.substring(4);\n }\n\n return encodedResponse;\n }", "public void rollback()\r\n {\r\n try\r\n {\r\n Iterator iter = mvOrderOfIds.iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n if(log.isDebugEnabled())\r\n log.debug(\"rollback: \" + mod);\r\n // if the Object has been modified by transaction, mark object as dirty\r\n if(mod.hasChanged(transaction.getBroker()))\r\n {\r\n mod.setModificationState(mod.getModificationState().markDirty());\r\n }\r\n mod.getModificationState().rollback(mod);\r\n }\r\n }\r\n finally\r\n {\r\n needsCommit = false;\r\n }\r\n afterWriteCleanup();\r\n }", "public void setIndirectionHandlerClass(Class indirectionHandlerClass)\r\n {\r\n if(indirectionHandlerClass == null)\r\n {\r\n //throw new MetadataException(\"No IndirectionHandlerClass specified.\");\r\n /**\r\n * andrew.clute\r\n * Allow the default IndirectionHandler for the given ProxyFactory implementation\r\n * when the parameter is not given\r\n */\r\n indirectionHandlerClass = getDefaultIndirectionHandlerClass();\r\n }\r\n if(indirectionHandlerClass.isInterface()\r\n || Modifier.isAbstract(indirectionHandlerClass.getModifiers())\r\n || !getIndirectionHandlerBaseClass().isAssignableFrom(indirectionHandlerClass))\r\n {\r\n throw new MetadataException(\"Illegal class \"\r\n + indirectionHandlerClass.getName()\r\n + \" specified for IndirectionHandlerClass. Must be a concrete subclass of \"\r\n + getIndirectionHandlerBaseClass().getName());\r\n }\r\n _indirectionHandlerClass = indirectionHandlerClass;\r\n }", "public Triple<Double, Integer, Integer> getAccuracyInfo()\r\n {\r\n int totalCorrect = tokensCorrect;\r\n int totalWrong = tokensCount - tokensCorrect;\r\n return new Triple<Double, Integer, Integer>((((double) totalCorrect) / tokensCount),\r\n totalCorrect, totalWrong);\r\n }", "public void fillRect(int x, int y, int w, int h, Color c) {\n int color = c.getRGB();\n for (int i = x; i < x + w; i++) {\n for (int j = y; j < y + h; j++) {\n setIntColor(i, j, color);\n }\n }\n }", "private void writeResourceAssignment(ResourceAssignment record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(formatResource(record.getResource()));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatUnits(record.getUnits())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getBaselineWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getActualWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getOvertimeWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getBaselineCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getActualCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTime(record.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTime(record.getFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getDelay())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getResourceUniqueID()));\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n\n ResourceAssignmentWorkgroupFields workgroup = record.getWorkgroupAssignment();\n if (workgroup == null)\n {\n workgroup = ResourceAssignmentWorkgroupFields.EMPTY;\n }\n writeResourceAssignmentWorkgroupFields(workgroup);\n\n m_eventManager.fireAssignmentWrittenEvent(record);\n }" ]
Get the list of active tasks from the server. @return List of tasks @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/active_tasks.html"> Active tasks</a>
[ "public List<Task> getActiveTasks() {\n InputStream response = null;\n URI uri = new URIBase(getBaseUri()).path(\"_active_tasks\").build();\n try {\n response = couchDbClient.get(uri);\n return getResponseList(response, couchDbClient.getGson(), DeserializationTypes.TASKS);\n } finally {\n close(response);\n }\n }" ]
[ "private void processWorkingHours(ProjectCalendar mpxjCalendar, Sequence uniqueID, Day day, List<OverriddenDayType> typeList)\n {\n if (isWorkingDay(mpxjCalendar, day))\n {\n ProjectCalendarHours mpxjHours = mpxjCalendar.getCalendarHours(day);\n if (mpxjHours != null)\n {\n OverriddenDayType odt = m_factory.createOverriddenDayType();\n typeList.add(odt);\n odt.setId(getIntegerString(uniqueID.next()));\n List<Interval> intervalList = odt.getInterval();\n for (DateRange mpxjRange : mpxjHours)\n {\n Date rangeStart = mpxjRange.getStart();\n Date rangeEnd = mpxjRange.getEnd();\n\n if (rangeStart != null && rangeEnd != null)\n {\n Interval interval = m_factory.createInterval();\n intervalList.add(interval);\n interval.setStart(getTimeString(rangeStart));\n interval.setEnd(getTimeString(rangeEnd));\n }\n }\n }\n }\n }", "public static base_response apply(nitro_service client) throws Exception {\n\t\tnspbr6 applyresource = new nspbr6();\n\t\treturn applyresource.perform_operation(client,\"apply\");\n\t}", "public static CustomInfo getOrCreateCustomInfo(Message message) {\n CustomInfo customInfo = message.get(CustomInfo.class);\n if (customInfo == null) {\n customInfo = new CustomInfo();\n message.put(CustomInfo.class, customInfo);\n }\n return customInfo;\n }", "public List<Response> bulk(List<?> objects, boolean allOrNothing) {\n assertNotEmpty(objects, \"objects\");\n InputStream responseStream = null;\n HttpConnection connection;\n try {\n final JsonObject jsonObject = new JsonObject();\n if(allOrNothing) {\n jsonObject.addProperty(\"all_or_nothing\", true);\n }\n final URI uri = new DatabaseURIHelper(dbUri).bulkDocsUri();\n jsonObject.add(\"docs\", getGson().toJsonTree(objects));\n connection = Http.POST(uri, \"application/json\");\n if (jsonObject.toString().length() != 0) {\n connection.setRequestBody(jsonObject.toString());\n }\n couchDbClient.execute(connection);\n responseStream = connection.responseAsInputStream();\n List<Response> bulkResponses = getResponseList(responseStream, getGson(),\n DeserializationTypes.LC_RESPONSES);\n for(Response response : bulkResponses) {\n response.setStatusCode(connection.getConnection().getResponseCode());\n }\n return bulkResponses;\n }\n catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response input stream.\", e);\n } finally {\n close(responseStream);\n }\n }", "private void updateSession(Session newSession) {\n if (this.currentSession == null) {\n this.currentSession = newSession;\n } else {\n synchronized (this.currentSession) {\n this.currentSession = newSession;\n }\n }\n }", "public static void writeFlowId(Message message, String flowId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage)message;\n Header hdFlowId = soapMessage.getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n LOG.warning(\"FlowId already existing in soap header, need not to write FlowId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(FLOW_ID_QNAME, flowId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored flowId '\" + flowId + \"' in soap header: \" + FLOW_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create flowId header.\", e);\n }\n\n }", "public static boolean matches(Map<String, Object> nodeProperties, String[] keyColumnNames, Object[] keyColumnValues) {\n\t\tfor ( int i = 0; i < keyColumnNames.length; i++ ) {\n\t\t\tString property = keyColumnNames[i];\n\t\t\tObject expectedValue = keyColumnValues[i];\n\t\t\tboolean containsProperty = nodeProperties.containsKey( property );\n\t\t\tif ( containsProperty ) {\n\t\t\t\tObject actualValue = nodeProperties.get( property );\n\t\t\t\tif ( !sameValue( expectedValue, actualValue ) ) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( expectedValue != null ) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\n }", "public static String generateQuery(final String key, final Object value) {\n\t\tfinal Map<String, Object> params = new HashMap<>();\n\t\tparams.put(key, value);\n\t\treturn generateQuery(params);\n\t}" ]
Return the NTSC gray level of an RGB value. @param rgb1 the input pixel @return the gray level (0-255)
[ "public static int brightnessNTSC(int rgb) {\n\t\tint r = (rgb >> 16) & 0xff;\n\t\tint g = (rgb >> 8) & 0xff;\n\t\tint b = rgb & 0xff;\n\t\treturn (int)(r*0.299f + g*0.587f + b*0.114f);\n\t}" ]
[ "public void addNotIn(String attribute, Query subQuery)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }", "public synchronized Object[] getIds() {\n String[] keys = getAllKeys();\n int size = keys.length + indexedProps.size();\n Object[] res = new Object[size];\n System.arraycopy(keys, 0, res, 0, keys.length);\n int i = keys.length;\n // now add all indexed properties\n for (Object index : indexedProps.keySet()) {\n res[i++] = index;\n }\n return res;\n }", "public SerialMessage getSupportedMessage() {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_SUPPORTED_GET for node {}\", this.getNode().getNodeId());\r\n\t\t\r\n\t\tif (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) {\r\n\t\t\tlogger.warn(\"Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET.\");\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\t\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t2, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) SENSOR_ALARM_SUPPORTED_GET };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}", "private Event createEvent(Endpoint endpoint, EventTypeEnum type) {\n\n Event event = new Event();\n MessageInfo messageInfo = new MessageInfo();\n Originator originator = new Originator();\n event.setMessageInfo(messageInfo);\n event.setOriginator(originator);\n\n Date date = new Date();\n event.setTimestamp(date);\n event.setEventType(type);\n\n messageInfo.setPortType(\n endpoint.getBinding().getBindingInfo().getService().getInterface().getName().toString());\n\n String transportType = null;\n if (endpoint.getBinding() instanceof SoapBinding) {\n SoapBinding soapBinding = (SoapBinding)endpoint.getBinding();\n if (soapBinding.getBindingInfo() instanceof SoapBindingInfo) {\n SoapBindingInfo soapBindingInfo = (SoapBindingInfo)soapBinding.getBindingInfo();\n transportType = soapBindingInfo.getTransportURI();\n }\n }\n messageInfo.setTransportType((transportType != null) ? transportType : \"Unknown transport type\");\n\n originator.setProcessId(Converter.getPID());\n try {\n InetAddress inetAddress = InetAddress.getLocalHost();\n originator.setIp(inetAddress.getHostAddress());\n originator.setHostname(inetAddress.getHostName());\n } catch (UnknownHostException e) {\n originator.setHostname(\"Unknown hostname\");\n originator.setIp(\"Unknown ip address\");\n }\n\n String address = endpoint.getEndpointInfo().getAddress();\n event.getCustomInfo().put(\"address\", address);\n\n return event;\n }", "static String guessEntityTypeFromId(String id) {\n\t\tif(id.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"Entity ids should not be empty.\");\n\t\t}\n\t\tswitch (id.charAt(0)) {\n\t\t\tcase 'L':\n\t\t\t\tif(id.contains(\"-F\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_FORM;\n\t\t\t\t} else if(id.contains(\"-S\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_SENSE;\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_LEXEME;\n\t\t\t\t}\n\t\t\tcase 'P':\n\t\t\t\treturn JSON_ENTITY_TYPE_PROPERTY;\n\t\t\tcase 'Q':\n\t\t\t\treturn JSON_ENTITY_TYPE_ITEM;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}", "public ClassNode addInterface(String name) {\n ClassNode intf = infoBase.node(name);\n addInterface(intf);\n return this;\n }", "private void removeFromInverseAssociations(\n\t\t\tTuple resultset,\n\t\t\tint tableIndex,\n\t\t\tSerializable id,\n\t\t\tSharedSessionContractImplementor session) {\n\t\tnew EntityAssociationUpdater( this )\n\t\t\t\t.id( id )\n\t\t\t\t.resultset( resultset )\n\t\t\t\t.session( session )\n\t\t\t\t.tableIndex( tableIndex )\n\t\t\t\t.propertyMightRequireInverseAssociationManagement( propertyMightBeMainSideOfBidirectionalAssociation )\n\t\t\t\t.removeNavigationalInformationFromInverseSide();\n\t}", "public static Integer convertProfileIdentifier(String profileIdentifier) throws Exception {\n Integer profileId = -1;\n if (profileIdentifier == null) {\n throw new Exception(\"A profileIdentifier must be specified\");\n } else {\n try {\n profileId = Integer.parseInt(profileIdentifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n // try to get it by name instead\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n\n }\n }\n logger.info(\"Profile id is {}\", profileId);\n return profileId;\n }", "@Override\n public synchronized void stop(final StopContext context) {\n final boolean shutdownServers = runningModeControl.getRestartMode() == RestartMode.SERVERS;\n if (shutdownServers) {\n Runnable task = new Runnable() {\n @Override\n public void run() {\n try {\n serverInventory.shutdown(true, -1, true); // TODO graceful shutdown\n serverInventory = null;\n // client.getValue().setServerInventory(null);\n } finally {\n serverCallback.getValue().setCallbackHandler(null);\n context.complete();\n }\n }\n };\n try {\n executorService.getValue().execute(task);\n } catch (RejectedExecutionException e) {\n task.run();\n } finally {\n context.asynchronous();\n }\n } else {\n // We have to set the shutdown flag in any case\n serverInventory.shutdown(false, -1, true);\n serverInventory = null;\n }\n }" ]
Get a collection of tags used by the specified user. <p> This method does not require authentication. </p> @param userId The User ID @return The User object @throws FlickrException
[ "public Collection<Tag> getListUser(String userId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_USER);\n\n parameters.put(\"user_id\", userId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element whoElement = response.getPayload();\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) whoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n return tags;\n }" ]
[ "public Class<? extends MonetaryAmount> getAmountType() {\n Class<?> clazz = get(AMOUNT_TYPE, Class.class);\n return clazz.asSubclass(MonetaryAmount.class);\n }", "public static boolean isPassivatingScope(Bean<?> bean, BeanManagerImpl manager) {\n if (bean == null) {\n return false;\n } else {\n return manager.getServices().get(MetaAnnotationStore.class).getScopeModel(bean.getScope()).isPassivating();\n }\n }", "public JSONObject exportConfigurationAndProfile(String oldExport) {\n try {\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"oldExport\", oldExport)\n };\n String url = BASE_BACKUP_PROFILE + \"/\" + uriEncode(this._profileName) + \"/\" + this._clientId;\n return new JSONObject(doGet(url, new BasicNameValuePair[]{}));\n } catch (Exception e) {\n return new JSONObject();\n }\n }", "@Override\n\tpublic CrawlSession call() {\n\t\tsetMaximumCrawlTimeIfNeeded();\n\t\tplugins.runPreCrawlingPlugins(config);\n\t\tCrawlTaskConsumer firstConsumer = consumerFactory.get();\n\t\tStateVertex firstState = firstConsumer.crawlIndex();\n\t\tcrawlSessionProvider.setup(firstState);\n\t\tplugins.runOnNewStatePlugins(firstConsumer.getContext(), firstState);\n\t\texecuteConsumers(firstConsumer);\n\t\treturn crawlSessionProvider.get();\n\t}", "public void setBeliefValue(String agent_name, final String belief_name,\n final Object new_value, Connector connector) {\n\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Integer>() {\n\n public IFuture<Integer> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n bia.getBeliefbase().getBelief(belief_name)\n .setFact(new_value);\n return null;\n }\n }).get(new ThreadSuspendable());\n }", "private String registerEventHandler(GFXEventHandler h) {\n //checkInitialized();\n if (!registeredOnJS) {\n JSObject doc = (JSObject) runtime.execute(\"document\");\n doc.setMember(\"jsHandlers\", jsHandlers);\n registeredOnJS = true;\n }\n return jsHandlers.registerHandler(h);\n }", "public static void populateSubject(final LinkedHashMap<String, CommonProfile> profiles) {\n if (profiles != null && profiles.size() > 0) {\n final List<CommonProfile> listProfiles = ProfileHelper.flatIntoAProfileList(profiles);\n try {\n if (IS_FULLY_AUTHENTICATED_AUTHORIZER.isAuthorized(null, listProfiles)) {\n SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, false));\n } else if (IS_REMEMBERED_AUTHORIZER.isAuthorized(null, listProfiles)) {\n SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, true));\n }\n } catch (final HttpAction e) {\n throw new TechnicalException(e);\n }\n }\n }", "public static int getMpxField(int value)\n {\n int result = 0;\n\n if (value >= 0 && value < MPXJ_MPX_ARRAY.length)\n {\n result = MPXJ_MPX_ARRAY[value];\n }\n return (result);\n }", "public static Button createPublishButton(final I_CmsUpdateListener<String> updateListener) {\n\n Button publishButton = CmsToolBar.createButton(\n FontOpenCms.PUBLISH,\n CmsVaadinUtils.getMessageText(Messages.GUI_PUBLISH_BUTTON_TITLE_0));\n if (CmsAppWorkplaceUi.isOnlineProject()) {\n // disable publishing in online project\n publishButton.setEnabled(false);\n publishButton.setDescription(CmsVaadinUtils.getMessageText(Messages.GUI_TOOLBAR_NOT_AVAILABLE_ONLINE_0));\n }\n publishButton.addClickListener(new ClickListener() {\n\n /** Serial version id. */\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n CmsAppWorkplaceUi.get().disableGlobalShortcuts();\n CmsGwtDialogExtension extension = new CmsGwtDialogExtension(A_CmsUI.get(), updateListener);\n extension.openPublishDialog();\n }\n });\n return publishButton;\n }" ]
Set the numeric code. Setting it to -1 search for currencies that have no numeric code. @param codes the numeric codes. @return the query for chaining.
[ "public CurrencyQueryBuilder setNumericCodes(int... codes) {\n return set(CurrencyQuery.KEY_QUERY_NUMERIC_CODES,\n Arrays.stream(codes).boxed().collect(Collectors.toList()));\n }" ]
[ "public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context, final Procedure1<? super ContentAssistEntry> init) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, init);\n }", "public static AliasOperationTransformer replaceLastElement(final PathElement element) {\n return create(new AddressTransformer() {\n @Override\n public PathAddress transformAddress(final PathAddress original) {\n final PathAddress address = original.subAddress(0, original.size() -1);\n return address.append(element);\n }\n });\n }", "private static String decode(String s) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (ch == '%') {\n baos.write(hexToInt(s.charAt(i + 1)) * 16 + hexToInt(s.charAt(i + 2)));\n i += 2;\n continue;\n }\n baos.write(ch);\n }\n try {\n return new String(baos.toByteArray(), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n }\n }", "private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings)\n throws IOException\n {\n final String outputDirectory = settings.getOutputDirectory();\n\n final String fileName = type.getName() + settings.getLanguage().getFileExtension();\n final String packageName = type.getPackageName();\n\n // foo.Bar -> foo/Bar.java\n final String subDir = StringUtils.defaultIfEmpty(packageName, \"\").replace('.', File.separatorChar);\n final String outputPath = PathHelper.combine(outputDirectory, subDir, fileName);\n\n final File outputFile = new File(outputPath);\n final File parentDir = outputFile.getParentFile();\n\n if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs())\n {\n throw new IllegalStateException(\"Could not create directory:\" + parentDir);\n }\n\n if (!outputFile.exists() && !outputFile.createNewFile())\n {\n throw new IllegalStateException(\"Could not create output file: \" + outputPath);\n }\n\n return new FileOutputWriter(outputFile, settings);\n }", "public void removeFile(String name) {\n if(files.containsKey(name)) {\n files.remove(name);\n }\n\n if(fileStreams.containsKey(name)) {\n fileStreams.remove(name);\n }\n }", "private RekordboxAnlz.BeatGridTag findTag(RekordboxAnlz anlzFile) {\n for (RekordboxAnlz.TaggedSection section : anlzFile.sections()) {\n if (section.body() instanceof RekordboxAnlz.BeatGridTag) {\n return (RekordboxAnlz.BeatGridTag) section.body();\n }\n }\n throw new IllegalArgumentException(\"No beat grid found inside analysis file \" + anlzFile);\n }", "public void copyStructure( DMatrixSparseCSC orig ) {\n reshape(orig.numRows, orig.numCols, orig.nz_length);\n this.nz_length = orig.nz_length;\n System.arraycopy(orig.col_idx,0,col_idx,0,orig.numCols+1);\n System.arraycopy(orig.nz_rows,0,nz_rows,0,orig.nz_length);\n }", "public static Enum<?> findMatchingEnumVal(Field field, String unknownEnumName) {\n\t\tif (unknownEnumName == null || unknownEnumName.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tfor (Enum<?> enumVal : (Enum<?>[]) field.getType().getEnumConstants()) {\n\t\t\tif (enumVal.name().equals(unknownEnumName)) {\n\t\t\t\treturn enumVal;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unknwown enum unknown name \" + unknownEnumName + \" for field \" + field);\n\t}", "public static void sendTextEmail(String to, String from, String subject, String msg, final ServerSetup setup) {\r\n sendMimeMessage(createTextEmail(to, from, subject, msg, setup));\r\n }" ]
Add the given pair into the map. <p> If the pair key already exists in the map, its value is replaced by the value in the pair, and the old value in the map is returned. </p> @param <K> type of the map keys. @param <V> type of the map values. @param map the map to update. @param entry the entry (key, value) to add into the map. @return the value previously associated to the key, or <code>null</code> if the key was not present in the map before the addition. @since 2.15
[ "@Inline(value = \"$1.put($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> V operator_add(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\treturn map.put(entry.getKey(), entry.getValue());\n\t}" ]
[ "public static Predicate is(final String sql) {\n return new Predicate() {\n public String toSql() {\n return sql;\n }\n public void init(AbstractSqlCreator creator) {\n }\n };\n }", "protected String buildErrorSetMsg(Object obj, Object value, Field aField)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer buf = new StringBuffer();\r\n buf\r\n .append(eol + \"[try to set 'object value' in 'target object'\")\r\n .append(eol + \"target obj class: \" + (obj != null ? obj.getClass().getName() : null))\r\n .append(eol + \"target field name: \" + (aField != null ? aField.getName() : null))\r\n .append(eol + \"target field type: \" + (aField != null ? aField.getType() : null))\r\n .append(eol + \"target field declared in: \" + (aField != null ? aField.getDeclaringClass().getName() : null))\r\n .append(eol + \"object value class: \" + (value != null ? value.getClass().getName() : null))\r\n .append(eol + \"object value: \" + (value != null ? value : null))\r\n .append(eol + \"]\");\r\n return buf.toString();\r\n }", "@Override\n public EditMode editMode() {\n if(readInputrc) {\n try {\n return EditModeBuilder.builder().parseInputrc(new FileInputStream(inputrc())).create();\n }\n catch(FileNotFoundException e) {\n return EditModeBuilder.builder(mode()).create();\n }\n }\n else\n return EditModeBuilder.builder(mode()).create();\n }", "public static Map<FieldType, String> getDefaultResourceFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(ResourceField.UNIQUE_ID, \"rsrc_id\");\n map.put(ResourceField.GUID, \"guid\");\n map.put(ResourceField.NAME, \"rsrc_name\");\n map.put(ResourceField.CODE, \"employee_code\");\n map.put(ResourceField.EMAIL_ADDRESS, \"email_addr\");\n map.put(ResourceField.NOTES, \"rsrc_notes\");\n map.put(ResourceField.CREATED, \"create_date\");\n map.put(ResourceField.TYPE, \"rsrc_type\");\n map.put(ResourceField.INITIALS, \"rsrc_short_name\");\n map.put(ResourceField.PARENT_ID, \"parent_rsrc_id\");\n\n return map;\n }", "public void bootstrap() throws Exception {\n final HostRunningModeControl runningModeControl = environment.getRunningModeControl();\n final ControlledProcessState processState = new ControlledProcessState(true);\n shutdownHook.setControlledProcessState(processState);\n ServiceTarget target = serviceContainer.subTarget();\n ControlledProcessStateService controlledProcessStateService = ControlledProcessStateService.addService(target, processState).getValue();\n RunningStateJmx.registerMBean(controlledProcessStateService, null, runningModeControl, false);\n final HostControllerService hcs = new HostControllerService(environment, runningModeControl, authCode, processState);\n target.addService(HostControllerService.HC_SERVICE_NAME, hcs).install();\n }", "public static I_CmsMacroResolver newWorkplaceLocaleResolver(final CmsObject cms) {\n\n // Resolve macros in the property configuration\n CmsMacroResolver resolver = new CmsMacroResolver();\n resolver.setCmsObject(cms);\n CmsUserSettings userSettings = new CmsUserSettings(cms.getRequestContext().getCurrentUser());\n CmsMultiMessages multimessages = new CmsMultiMessages(userSettings.getLocale());\n multimessages.addMessages(OpenCms.getWorkplaceManager().getMessages(userSettings.getLocale()));\n resolver.setMessages(multimessages);\n resolver.setKeepEmptyMacros(true);\n\n return resolver;\n }", "public static boolean isBadXmlCharacter(char c) {\n boolean cDataCharacter = c < '\\u0020' && c != '\\t' && c != '\\r' && c != '\\n';\n cDataCharacter |= (c >= '\\uD800' && c < '\\uE000');\n cDataCharacter |= (c == '\\uFFFE' || c == '\\uFFFF');\n return cDataCharacter;\n }", "protected Integer getCorrectIndex(Integer index) {\n Integer size = jsonNode.size();\n Integer newIndex = index;\n\n // reverse walking through the array\n if(index < 0) {\n newIndex = size + index;\n }\n\n // the negative index would be greater than the size a second time!\n if(newIndex < 0) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n // the index is greater as the actual size\n if(index > size) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n return newIndex;\n }", "public static void main(String[] args) {\n if(args.length != 2) {\n System.out.println(\"Usage: SchemaEvolutionValidator pathToOldSchema pathToNewSchema\");\n return;\n }\n\n Schema oldSchema;\n Schema newSchema;\n\n try {\n oldSchema = Schema.parse(new File(args[0]));\n } catch(Exception ex) {\n oldSchema = null;\n System.out.println(\"Could not open or parse the old schema (\" + args[0] + \") due to \"\n + ex);\n }\n\n try {\n newSchema = Schema.parse(new File(args[1]));\n } catch(Exception ex) {\n newSchema = null;\n System.out.println(\"Could not open or parse the new schema (\" + args[1] + \") due to \"\n + ex);\n }\n\n if(oldSchema == null || newSchema == null) {\n return;\n }\n\n System.out.println(\"Comparing: \");\n System.out.println(\"\\t\" + args[0]);\n System.out.println(\"\\t\" + args[1]);\n\n List<Message> messages = SchemaEvolutionValidator.checkBackwardCompatibility(oldSchema,\n newSchema,\n oldSchema.getName());\n Level maxLevel = Level.ALL;\n for(Message message: messages) {\n System.out.println(message.getLevel() + \": \" + message.getMessage());\n if(message.getLevel().isGreaterOrEqual(maxLevel)) {\n maxLevel = message.getLevel();\n }\n }\n\n if(maxLevel.isGreaterOrEqual(Level.ERROR)) {\n System.out.println(Level.ERROR\n + \": The schema is not backward compatible. New clients will not be able to read existing data.\");\n } else if(maxLevel.isGreaterOrEqual(Level.WARN)) {\n System.out.println(Level.WARN\n + \": The schema is partially backward compatible, but old clients will not be able to read data serialized in the new format.\");\n } else {\n System.out.println(Level.INFO\n + \": The schema is backward compatible. Old and new clients will be able to read records serialized by one another.\");\n }\n }" ]
Removes all events from table @param table the table to remove events
[ "synchronized void removeEvents(Table table) {\n final String tName = table.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, null, null);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing all events from table \" + tName + \" Recreating DB\");\n deleteDB();\n } finally {\n dbHelper.close();\n }\n }" ]
[ "@Override\n public void checkin(K key, V resource) {\n super.checkin(key, resource);\n // NB: Blocking checkout calls for synchronous requests get the resource\n // checked in above before processQueueLoop() attempts checkout below.\n // There is therefore a risk that asynchronous requests will be starved.\n processQueueLoop(key);\n }", "private void mapText(String oldText, Map<String, String> replacements)\n {\n char c2 = 0;\n if (oldText != null && oldText.length() != 0 && !replacements.containsKey(oldText))\n {\n StringBuilder newText = new StringBuilder(oldText.length());\n for (int loop = 0; loop < oldText.length(); loop++)\n {\n char c = oldText.charAt(loop);\n if (Character.isUpperCase(c))\n {\n newText.append('X');\n }\n else\n {\n if (Character.isLowerCase(c))\n {\n newText.append('x');\n }\n else\n {\n if (Character.isDigit(c))\n {\n newText.append('0');\n }\n else\n {\n if (Character.isLetter(c))\n {\n // Handle other codepages etc. If possible find a way to\n // maintain the same code page as original.\n // E.g. replace with a character from the same alphabet.\n // This 'should' work for most cases\n if (c2 == 0)\n {\n c2 = c;\n }\n newText.append(c2);\n }\n else\n {\n newText.append(c);\n }\n }\n }\n }\n }\n\n replacements.put(oldText, newText.toString());\n }\n }", "public static base_responses delete(nitro_service client, String Dnssuffix[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (Dnssuffix != null && Dnssuffix.length > 0) {\n\t\t\tdnssuffix deleteresources[] = new dnssuffix[Dnssuffix.length];\n\t\t\tfor (int i=0;i<Dnssuffix.length;i++){\n\t\t\t\tdeleteresources[i] = new dnssuffix();\n\t\t\t\tdeleteresources[i].Dnssuffix = Dnssuffix[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "private Object getColumnValue(String table, String column, String data, int type, boolean epochDateFormat) throws MPXJException\n {\n try\n {\n Object value = null;\n\n switch (type)\n {\n case Types.BIT:\n {\n value = DatatypeConverter.parseBoolean(data);\n break;\n }\n\n case Types.VARCHAR:\n case Types.LONGVARCHAR:\n {\n value = DatatypeConverter.parseString(data);\n break;\n }\n\n case Types.TIME:\n {\n value = DatatypeConverter.parseBasicTime(data);\n break;\n }\n\n case Types.TIMESTAMP:\n {\n if (epochDateFormat)\n {\n value = DatatypeConverter.parseEpochTimestamp(data);\n }\n else\n {\n value = DatatypeConverter.parseBasicTimestamp(data);\n }\n break;\n }\n\n case Types.DOUBLE:\n {\n value = DatatypeConverter.parseDouble(data);\n break;\n }\n\n case Types.INTEGER:\n {\n value = DatatypeConverter.parseInteger(data);\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported SQL type: \" + type);\n }\n }\n\n return value;\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to parse \" + table + \".\" + column + \" (data=\" + data + \", type=\" + type + \")\", ex);\n }\n }", "public Set<String> getTags() {\r\n Set<String> tags = new HashSet<String>(classIndex.objectsList());\r\n tags.remove(flags.backgroundSymbol);\r\n return tags;\r\n }", "public ProjectCalendar addResourceCalendar() throws MPXJException\n {\n if (getResourceCalendar() != null)\n {\n throw new MPXJException(MPXJException.MAXIMUM_RECORDS);\n }\n\n ProjectCalendar calendar = new ProjectCalendar(getParentFile());\n setResourceCalendar(calendar);\n return calendar;\n }", "public static void composeThroughMask(Raster src, WritableRaster dst, Raster sel) {\n\t\tint x = src.getMinX();\n\t\tint y = src.getMinY();\n\t\tint w = src.getWidth();\n\t\tint h = src.getHeight();\n\n\t\tint srcRGB[] = null;\n\t\tint selRGB[] = null;\n\t\tint dstRGB[] = null;\n\n\t\tfor ( int i = 0; i < h; i++ ) {\n\t\t\tsrcRGB = src.getPixels(x, y, w, 1, srcRGB);\n\t\t\tselRGB = sel.getPixels(x, y, w, 1, selRGB);\n\t\t\tdstRGB = dst.getPixels(x, y, w, 1, dstRGB);\n\n\t\t\tint k = x;\n\t\t\tfor ( int j = 0; j < w; j++ ) {\n\t\t\t\tint sr = srcRGB[k];\n\t\t\t\tint dir = dstRGB[k];\n\t\t\t\tint sg = srcRGB[k+1];\n\t\t\t\tint dig = dstRGB[k+1];\n\t\t\t\tint sb = srcRGB[k+2];\n\t\t\t\tint dib = dstRGB[k+2];\n\t\t\t\tint sa = srcRGB[k+3];\n\t\t\t\tint dia = dstRGB[k+3];\n\n\t\t\t\tfloat a = selRGB[k+3]/255f;\n\t\t\t\tfloat ac = 1-a;\n\n\t\t\t\tdstRGB[k] = (int)(a*sr + ac*dir); \n\t\t\t\tdstRGB[k+1] = (int)(a*sg + ac*dig); \n\t\t\t\tdstRGB[k+2] = (int)(a*sb + ac*dib); \n\t\t\t\tdstRGB[k+3] = (int)(a*sa + ac*dia);\n\t\t\t\tk += 4;\n\t\t\t}\n\n\t\t\tdst.setPixels(x, y, w, 1, dstRGB);\n\t\t\ty++;\n\t\t}\n\t}", "public static <T> Set<T> toSet(Iterable<T> items) {\r\n Set<T> set = new HashSet<T>();\r\n addAll(set, items);\r\n return set;\r\n }", "protected void update(float scale) {\n GVRSceneObject owner = getOwnerObject();\n if (isEnabled() && (owner != null) && owner.isEnabled())\n {\n float w = getWidth();\n float h = getHeight();\n mPose.update(mARPlane.getCenterPose(), scale);\n Matrix4f m = new Matrix4f();\n m.set(mPose.getPoseMatrix());\n m.scaleLocal(w * 0.95f, h * 0.95f, 1.0f);\n owner.getTransform().setModelMatrix(m);\n }\n }" ]
Use this API to fetch clusterinstance resources of given names .
[ "public static clusterinstance[] get(nitro_service service, Long clid[]) throws Exception{\n\t\tif (clid !=null && clid.length>0) {\n\t\t\tclusterinstance response[] = new clusterinstance[clid.length];\n\t\t\tclusterinstance obj[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++) {\n\t\t\t\tobj[i] = new clusterinstance();\n\t\t\t\tobj[i].set_clid(clid[i]);\n\t\t\t\tresponse[i] = (clusterinstance) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
[ "@PostConstruct\n\tprotected void postConstruct() {\n\t\tif (pixelPerUnitBased) {\n\t\t\t//\tCalculate numerator and denominator\n\t\t\tif (pixelPerUnit > PIXEL_PER_METER) {\n\t\t\t\tthis.numerator = pixelPerUnit / conversionFactor;\n\t\t\t\tthis.denominator = 1;\n\t\t\t} else {\n\t\t\t\tthis.numerator = 1;\n\t\t\t\tthis.denominator = PIXEL_PER_METER / pixelPerUnit;\n\t\t\t}\n\t\t\tsetPixelPerUnitBased(false);\n\t\t} else {\n\t\t\t// Calculate PPU\n\t\t\tthis.pixelPerUnit = numerator / denominator * conversionFactor;\n\t\t\tsetPixelPerUnitBased(true);\n\t\t}\n\t}", "public ActionContext applyContentType(Result result) {\n if (!result.status().isError()) {\n return applyContentType();\n }\n return applyContentType(contentTypeForErrorResult(req()));\n }", "public void addRequiredBundles(Set<String> bundles) {\n\t\t// TODO manage transitive dependencies\n\t\t// don't require self\n\t\tSet<String> bundlesToMerge;\n\t\tString bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME);\n\t\tif (bundleName != null) {\n\t\t\tint idx = bundleName.indexOf(';');\n\t\t\tif (idx >= 0) {\n\t\t\t\tbundleName = bundleName.substring(0, idx);\n\t\t\t}\n\t\t}\n\t\tif (bundleName != null && bundles.contains(bundleName)\n\t\t\t\t|| projectName != null && bundles.contains(projectName)) {\n\t\t\tbundlesToMerge = new LinkedHashSet<String>(bundles);\n\t\t\tbundlesToMerge.remove(bundleName);\n\t\t\tbundlesToMerge.remove(projectName);\n\t\t} else {\n\t\t\tbundlesToMerge = bundles;\n\t\t}\n\t\tString s = (String) getMainAttributes().get(REQUIRE_BUNDLE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(REQUIRE_BUNDLE, result);\n\t}", "private void\n executeSubBatch(final int batchId,\n RebalanceBatchPlanProgressBar progressBar,\n final Cluster batchRollbackCluster,\n final List<StoreDefinition> batchRollbackStoreDefs,\n final List<RebalanceTaskInfo> rebalanceTaskPlanList,\n boolean hasReadOnlyStores,\n boolean hasReadWriteStores,\n boolean finishedReadOnlyStores) {\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Submitting rebalance tasks \");\n\n // Get an ExecutorService in place used for submitting our tasks\n ExecutorService service = RebalanceUtils.createExecutors(maxParallelRebalancing);\n\n // Sub-list of the above list\n final List<RebalanceTask> failedTasks = Lists.newArrayList();\n final List<RebalanceTask> incompleteTasks = Lists.newArrayList();\n\n // Semaphores for donor nodes - To avoid multiple disk sweeps\n Map<Integer, Semaphore> donorPermits = new HashMap<Integer, Semaphore>();\n for(Node node: batchRollbackCluster.getNodes()) {\n donorPermits.put(node.getId(), new Semaphore(1));\n }\n\n try {\n // List of tasks which will run asynchronously\n List<RebalanceTask> allTasks = executeTasks(batchId,\n progressBar,\n service,\n rebalanceTaskPlanList,\n donorPermits);\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"All rebalance tasks submitted\");\n\n // Wait and shutdown after (infinite) timeout\n RebalanceUtils.executorShutDown(service, Long.MAX_VALUE);\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Finished waiting for executors\");\n\n // Collects all failures + incomplete tasks from the rebalance\n // tasks.\n List<Exception> failures = Lists.newArrayList();\n for(RebalanceTask task: allTasks) {\n if(task.hasException()) {\n failedTasks.add(task);\n failures.add(task.getError());\n } else if(!task.isComplete()) {\n incompleteTasks.add(task);\n }\n }\n\n if(failedTasks.size() > 0) {\n throw new VoldemortRebalancingException(\"Rebalance task terminated unsuccessfully on tasks \"\n + failedTasks,\n failures);\n }\n\n // If there were no failures, then we could have had a genuine\n // timeout ( Rebalancing took longer than the operator expected ).\n // We should throw a VoldemortException and not a\n // VoldemortRebalancingException ( which will start reverting\n // metadata ). The operator may want to manually then resume the\n // process.\n if(incompleteTasks.size() > 0) {\n throw new VoldemortException(\"Rebalance tasks are still incomplete / running \"\n + incompleteTasks);\n }\n\n } catch(VoldemortRebalancingException e) {\n\n logger.error(\"Failure while migrating partitions for rebalance task \"\n + batchId);\n\n if(hasReadOnlyStores && hasReadWriteStores\n && finishedReadOnlyStores) {\n // Case 0\n adminClient.rebalanceOps.rebalanceStateChange(null,\n batchRollbackCluster,\n null,\n batchRollbackStoreDefs,\n null,\n true,\n true,\n false,\n false,\n false);\n } else if(hasReadWriteStores && finishedReadOnlyStores) {\n // Case 4\n adminClient.rebalanceOps.rebalanceStateChange(null,\n batchRollbackCluster,\n null,\n batchRollbackStoreDefs,\n null,\n false,\n true,\n false,\n false,\n false);\n }\n\n throw e;\n\n } finally {\n if(!service.isShutdown()) {\n RebalanceUtils.printErrorLog(batchId,\n logger,\n \"Could not shutdown service cleanly for rebalance task \"\n + batchId,\n null);\n service.shutdownNow();\n }\n }\n }", "private static void firstDotConstellation(int[] dollarPositions, int[] dotPositions, int nestingLevel) {\n int i = 0;\n int unassigned = dotPositions.length - nestingLevel;\n\n for (; i < unassigned; ++i) {\n dotPositions[i] = -1;\n }\n\n for (; i < dotPositions.length; ++i) {\n dotPositions[i] = dollarPositions[i];\n }\n }", "protected <T> T invokeJavascriptReturnValue(String function, Class<T> returnType) {\n Object returnObject = invokeJavascript(function);\n if (returnObject instanceof JSObject) {\n try {\n Constructor<T> constructor = returnType.getConstructor(JSObject.class);\n return constructor.newInstance((JSObject) returnObject);\n } catch (Exception ex) {\n throw new IllegalStateException(ex);\n }\n } else {\n return (T) returnObject;\n }\n }", "public List<Cluster> cluster(final Collection<Point2D> points) {\n \tfinal List<Cluster> clusters = new ArrayList<Cluster>();\n final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>();\n\n KDTree<Point2D> tree = new KDTree<Point2D>(2);\n \n // Populate the kdTree\n for (final Point2D point : points) {\n \tdouble[] key = {point.x, point.y};\n \ttree.insert(key, point);\n }\n \n for (final Point2D point : points) {\n if (visited.get(point) != null) {\n continue;\n }\n final List<Point2D> neighbors = getNeighbors(point, tree);\n if (neighbors.size() >= minPoints) {\n // DBSCAN does not care about center points\n final Cluster cluster = new Cluster(clusters.size());\n clusters.add(expandCluster(cluster, point, neighbors, tree, visited));\n } else {\n visited.put(point, PointStatus.NOISE);\n }\n }\n\n for (Cluster cluster : clusters) {\n \tcluster.calculateCentroid();\n }\n \n return clusters;\n }", "void setRightChild(final byte b, @NotNull final MutableNode child) {\n final ChildReference right = children.getRight();\n if (right == null || (right.firstByte & 0xff) != (b & 0xff)) {\n throw new IllegalArgumentException();\n }\n children.setAt(children.size() - 1, new ChildReferenceMutable(b, child));\n }", "private ProjectFile handleSQLiteFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".sqlite\");\n\n try\n {\n Class.forName(\"org.sqlite.JDBC\");\n String url = \"jdbc:sqlite:\" + file.getCanonicalPath();\n Set<String> tableNames = populateTableNames(url);\n\n if (tableNames.contains(\"EXCEPTIONN\"))\n {\n return readProjectFile(new AstaDatabaseFileReader(), file);\n }\n\n if (tableNames.contains(\"PROJWBS\"))\n {\n Connection connection = null;\n try\n {\n Properties props = new Properties();\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n connection = DriverManager.getConnection(url, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(connection);\n addListeners(reader);\n return reader.read();\n }\n finally\n {\n if (connection != null)\n {\n connection.close();\n }\n }\n }\n\n if (tableNames.contains(\"ZSCHEDULEITEM\"))\n {\n return readProjectFile(new MerlinReader(), file);\n }\n\n return null;\n }\n\n finally\n {\n FileHelper.deleteQuietly(file);\n }\n }" ]
Returns the getter method for field on an object. @param object the object @param fieldName the field name @return the getter associated with the field on the object @throws NullPointerException if object or fieldName is null @throws SuperCsvReflectionException if the getter doesn't exist or is not visible
[ "public Method getGetMethod(final Object object, final String fieldName) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t}\n\t\t\n\t\tMethod method = getCache.get(object.getClass().getName(), fieldName);\n\t\tif( method == null ) {\n\t\t\tmethod = ReflectionUtils.findGetter(object, fieldName);\n\t\t\tgetCache.set(object.getClass().getName(), fieldName, method);\n\t\t}\n\t\treturn method;\n\t}" ]
[ "private void init()\n {\n style = new BoxStyle(UNIT);\n textLine = new StringBuilder();\n textMetrics = null;\n graphicsPath = new Vector<PathSegment>();\n startPage = 0;\n endPage = Integer.MAX_VALUE;\n fontTable = new FontTable();\n }", "protected void checkJobType(final String jobName, final Class<?> jobType) {\n if (jobName == null) {\n throw new IllegalArgumentException(\"jobName must not be null\");\n }\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n if (!(Runnable.class.isAssignableFrom(jobType)) \n && !(Callable.class.isAssignableFrom(jobType))) {\n throw new IllegalArgumentException(\n \"jobType must implement either Runnable or Callable: \" + jobType);\n }\n }", "private void unregisterAllServlets() {\n\n for (String endpoint : registeredServlets) {\n registeredServlets.remove(endpoint);\n web.unregister(endpoint);\n LOG.info(\"endpoint {} unregistered\", endpoint);\n }\n\n }", "public void setConvergence( int maxIterations , double ftol , double gtol ) {\n this.maxIterations = maxIterations;\n this.ftol = ftol;\n this.gtol = gtol;\n }", "@Override\n public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {\n // Switch the current policy and compilation result for this unit to the requested one.\n CompilationResult unitResult =\n new CompilationResult(sourceUnit, this.totalUnits, this.totalUnits, this.options.maxProblemsPerUnit);\n unitResult.checkSecondaryTypes = true;\n try {\n if (this.options.verbose) {\n String count = String.valueOf(this.totalUnits + 1);\n this.out.println(\n Messages.bind(Messages.compilation_request,\n new String[] {\n count,\n count,\n new String(sourceUnit.getFileName())\n }));\n }\n // diet parsing for large collection of unit\n CompilationUnitDeclaration parsedUnit;\n if (this.totalUnits < this.parseThreshold) {\n parsedUnit = this.parser.parse(sourceUnit, unitResult);\n } else {\n parsedUnit = this.parser.dietParse(sourceUnit, unitResult);\n }\n // initial type binding creation\n this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);\n addCompilationUnit(sourceUnit, parsedUnit);\n\n // binding resolution\n this.lookupEnvironment.completeTypeBindings(parsedUnit);\n } catch (AbortCompilationUnit e) {\n // at this point, currentCompilationUnitResult may not be sourceUnit, but some other\n // one requested further along to resolve sourceUnit.\n if (unitResult.compilationUnit == sourceUnit) { // only report once\n this.requestor.acceptResult(unitResult.tagAsAccepted());\n } else {\n throw e; // want to abort enclosing request to compile\n }\n }\n }", "static ItemIdValueImpl fromIri(String iri) {\n\t\tint separator = iri.lastIndexOf('/') + 1;\n\t\ttry {\n\t\t\treturn new ItemIdValueImpl(iri.substring(separator), iri.substring(0, separator));\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tthrow new IllegalArgumentException(\"Invalid Wikibase entity IRI: \" + iri, e);\n\t\t}\n\t}", "public void initLocator() throws InterruptedException,\n ServiceLocatorException {\n if (locatorClient == null) {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Instantiate locatorClient client for Locator Server \"\n + locatorEndpoints + \"...\");\n }\n ServiceLocatorImpl client = new ServiceLocatorImpl();\n client.setLocatorEndpoints(locatorEndpoints);\n client.setConnectionTimeout(connectionTimeout);\n client.setSessionTimeout(sessionTimeout);\n if (null != authenticationName)\n client.setName(authenticationName);\n if (null != authenticationPassword)\n client.setPassword(authenticationPassword);\n locatorClient = client;\n locatorClient.connect();\n }\n }", "public void start() {\n nsLock.writeLock().lock();\n try {\n if (runnerThread != null) {\n return;\n }\n runnerThread =\n new Thread(new NamespaceChangeStreamRunner(\n new WeakReference<>(this), networkMonitor, logger));\n runnerThread.start();\n } finally {\n nsLock.writeLock().unlock();\n }\n }", "public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }" ]
Initializes the fields on the changes file with the values of the specified binary package control file. @param packageControlFile
[ "public void initialize(BinaryPackageControlFile packageControlFile) {\n set(\"Binary\", packageControlFile.get(\"Package\"));\n set(\"Source\", Utils.defaultString(packageControlFile.get(\"Source\"), packageControlFile.get(\"Package\")));\n set(\"Architecture\", packageControlFile.get(\"Architecture\"));\n set(\"Version\", packageControlFile.get(\"Version\"));\n set(\"Maintainer\", packageControlFile.get(\"Maintainer\"));\n set(\"Changed-By\", packageControlFile.get(\"Maintainer\"));\n set(\"Distribution\", packageControlFile.get(\"Distribution\"));\n\n for (Entry<String, String> entry : packageControlFile.getUserDefinedFields().entrySet()) {\n set(entry.getKey(), entry.getValue());\n }\n\n StringBuilder description = new StringBuilder();\n description.append(packageControlFile.get(\"Package\"));\n if (packageControlFile.get(\"Description\") != null) {\n description.append(\" - \");\n description.append(packageControlFile.getShortDescription());\n }\n set(\"Description\", description.toString());\n }" ]
[ "private void readPredecessor(Task currTask, Project.Tasks.Task.PredecessorLink link)\n {\n BigInteger uid = link.getPredecessorUID();\n if (uid != null)\n {\n Task prevTask = m_projectFile.getTaskByUniqueID(Integer.valueOf(uid.intValue()));\n if (prevTask != null)\n {\n RelationType type;\n if (link.getType() != null)\n {\n type = RelationType.getInstance(link.getType().intValue());\n }\n else\n {\n type = RelationType.FINISH_START;\n }\n\n TimeUnit lagUnits = DatatypeConverter.parseDurationTimeUnits(link.getLagFormat());\n\n Duration lagDuration;\n int lag = NumberHelper.getInt(link.getLinkLag());\n if (lag == 0)\n {\n lagDuration = Duration.getInstance(0, lagUnits);\n }\n else\n {\n if (lagUnits == TimeUnit.PERCENT || lagUnits == TimeUnit.ELAPSED_PERCENT)\n {\n lagDuration = Duration.getInstance(lag, lagUnits);\n }\n else\n {\n lagDuration = Duration.convertUnits(lag / 10.0, TimeUnit.MINUTES, lagUnits, m_projectFile.getProjectProperties());\n }\n }\n\n Relation relation = currTask.addPredecessor(prevTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }", "private RelationType getRelationType(Integer gpType)\n {\n RelationType result = null;\n if (gpType != null)\n {\n int index = NumberHelper.getInt(gpType);\n if (index > 0 && index < RELATION.length)\n {\n result = RELATION[index];\n }\n }\n\n if (result == null)\n {\n result = RelationType.FINISH_START;\n }\n\n return result;\n }", "public List<ServerRedirect> tableServers(int profileId, int serverGroupId) {\n ArrayList<ServerRedirect> servers = new ArrayList<>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = ?\"\n );\n queryStatement.setInt(1, profileId);\n queryStatement.setInt(2, serverGroupId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(profileId);\n servers.add(curServer);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return servers;\n }", "public DomainList getPhotosetDomains(Date date, String photosetId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_PHOTOSET_DOMAINS, \"photoset_id\", photosetId, date, perPage, page);\n }", "@Nullable public View findViewById(int id) {\n if (searchView != null) {\n return searchView.findViewById(id);\n } else if (supportView != null) {\n return supportView.findViewById(id);\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }", "private void appendLikeCriteria(TableAlias alias, PathInfo pathInfo, LikeCriteria c, StringBuffer buf)\r\n {\r\n appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);\r\n buf.append(c.getClause());\r\n appendParameter(c.getValue(), buf);\r\n\r\n buf.append(m_platform.getEscapeClause(c));\r\n }", "@SuppressWarnings({\"WeakerAccess\"})\n protected void initDeviceID() {\n getDeviceCachedInfo(); // put this here to avoid running on main thread\n\n // generate a provisional while we do the rest async\n generateProvisionalGUID();\n // grab and cache the googleAdID in any event if available\n // if we already have a deviceID we won't user ad id as the guid\n cacheGoogleAdID();\n\n // if we already have a device ID use it and just notify\n // otherwise generate one, either from ad id if available or the provisional\n String deviceID = getDeviceID();\n if (deviceID == null || deviceID.trim().length() <= 2) {\n generateDeviceID();\n }\n\n }", "public static boolean propertyExists(Class<?> clazz, String property, ElementType elementType) {\n\t\tif ( ElementType.FIELD.equals( elementType ) ) {\n\t\t\treturn getDeclaredField( clazz, property ) != null;\n\t\t}\n\t\telse {\n\t\t\tString capitalizedPropertyName = capitalize( property );\n\n\t\t\tMethod method = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_GET + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() != void.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tmethod = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_IS + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() == boolean.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}", "private static LogType findLogType() {\n\n\t\t// see if the log-type was specified as a system property\n\t\tString logTypeString = System.getProperty(LOG_TYPE_SYSTEM_PROPERTY);\n\t\tif (logTypeString != null) {\n\t\t\ttry {\n\t\t\t\treturn LogType.valueOf(logTypeString);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tLog log = new LocalLog(LoggerFactory.class.getName());\n\t\t\t\tlog.log(Level.WARNING, \"Could not find valid log-type from system property '\" + LOG_TYPE_SYSTEM_PROPERTY\n\t\t\t\t\t\t+ \"', value '\" + logTypeString + \"'\");\n\t\t\t}\n\t\t}\n\n\t\tfor (LogType logType : LogType.values()) {\n\t\t\tif (logType.isAvailable()) {\n\t\t\t\treturn logType;\n\t\t\t}\n\t\t}\n\t\t// fall back is always LOCAL, never reached\n\t\treturn LogType.LOCAL;\n\t}" ]
Retrieve the relative path to the pom of the module
[ "private String getRelativePomPath(MavenModule mavenModule, MavenModuleSetBuild mavenBuild) {\n String relativePath = mavenModule.getRelativePath();\n if (StringUtils.isBlank(relativePath)) {\n return POM_NAME;\n }\n\n // If this is the root module, return the root pom path.\n if (mavenModule.getModuleName().toString().\n equals(mavenBuild.getProject().getRootModule().getModuleName().toString())) {\n return mavenBuild.getProject().getRootPOM(null);\n }\n\n // to remove the project folder name if exists\n // keeps only the name of the module\n String modulePath = relativePath.substring(relativePath.indexOf(\"/\") + 1);\n for (String moduleName : mavenModules) {\n if (moduleName.contains(modulePath)) {\n return createPomPath(relativePath, moduleName);\n }\n }\n\n // In case this module is not in the parent pom\n return relativePath + \"/\" + POM_NAME;\n }" ]
[ "private void mapText(String oldText, Map<String, String> replacements)\n {\n char c2 = 0;\n if (oldText != null && oldText.length() != 0 && !replacements.containsKey(oldText))\n {\n StringBuilder newText = new StringBuilder(oldText.length());\n for (int loop = 0; loop < oldText.length(); loop++)\n {\n char c = oldText.charAt(loop);\n if (Character.isUpperCase(c))\n {\n newText.append('X');\n }\n else\n {\n if (Character.isLowerCase(c))\n {\n newText.append('x');\n }\n else\n {\n if (Character.isDigit(c))\n {\n newText.append('0');\n }\n else\n {\n if (Character.isLetter(c))\n {\n // Handle other codepages etc. If possible find a way to\n // maintain the same code page as original.\n // E.g. replace with a character from the same alphabet.\n // This 'should' work for most cases\n if (c2 == 0)\n {\n c2 = c;\n }\n newText.append(c2);\n }\n else\n {\n newText.append(c);\n }\n }\n }\n }\n }\n\n replacements.put(oldText, newText.toString());\n }\n }", "@Inline(value = \"$1.putAll($2)\", statementExpression = true)\n\tpublic static <K, V> void operator_add(Map<K, V> outputMap, Map<? extends K, ? extends V> inputMap) {\n\t\toutputMap.putAll(inputMap);\n\t}", "private void registerRequirement(RuntimeRequirementRegistration requirement) {\n assert writeLock.isHeldByCurrentThread();\n CapabilityId dependentId = requirement.getDependentId();\n if (!capabilities.containsKey(dependentId)) {\n throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(),\n dependentId.getScope().getName());\n }\n Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap =\n requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements;\n\n Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId);\n if (dependents == null) {\n dependents = new HashMap<>();\n requirementMap.put(dependentId, dependents);\n }\n RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName());\n if (existing == null) {\n dependents.put(requirement.getRequiredName(), requirement);\n } else {\n existing.addRegistrationPoint(requirement.getOldestRegistrationPoint());\n }\n modified = true;\n }", "protected void concatenateReports() {\n\n if (!concatenatedReports.isEmpty()) { // dummy group for page break if needed\n DJGroup globalGroup = createDummyGroup();\n report.getColumnsGroups().add(0, globalGroup);\n }\n\n for (Subreport subreport : concatenatedReports) {\n DJGroup globalGroup = createDummyGroup();\n globalGroup.getFooterSubreports().add(subreport);\n report.getColumnsGroups().add(0, globalGroup);\n }\n }", "static Shell createTelnetConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n // Set up nvt4j; ignore the initial clear & reposition\n final nvt4j.impl.Terminal nvt4jTerminal = new nvt4j.impl.Terminal(input, output) {\n private boolean cleared;\n private boolean moved;\n\n @Override\n public void clear() throws IOException {\n if (this.cleared)\n super.clear();\n this.cleared = true;\n }\n\n @Override\n public void move(int row, int col) throws IOException {\n if (this.moved)\n super.move(row, col);\n this.moved = true;\n }\n };\n nvt4jTerminal.put(nvt4j.impl.Terminal.AUTO_WRAP_ON);\n nvt4jTerminal.setCursor(true);\n\n // Have JLine do input & output through telnet terminal\n final InputStream jlineInput = new InputStream() {\n @Override\n public int read() throws IOException {\n return nvt4jTerminal.get();\n }\n };\n final OutputStream jlineOutput = new OutputStream() {\n @Override\n public void write(int value) throws IOException {\n nvt4jTerminal.put(value);\n }\n };\n\n return createTerminalConsoleShell(prompt, appName, mainHandler, jlineInput, jlineOutput);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }", "public CrosstabBuilder setRowStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {\r\n\t\tcrosstab.setRowHeaderStyle(headerStyle);\r\n\t\tcrosstab.setRowTotalheaderStyle(totalHeaderStyle);\r\n\t\tcrosstab.setRowTotalStyle(totalStyle);\r\n\t\treturn this;\r\n\t}", "@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Map<? extends K, ? extends V> right) {\n\t\treturn Maps.filterEntries(left, new Predicate<Entry<K, V>>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(Entry<K, V> input) {\n\t\t\t\tfinal V value = right.get(input.getKey());\n\t\t\t\tif (value == null) {\n\t\t\t\t\treturn input.getValue() == null && right.containsKey(input.getKey());\n\t\t\t\t}\n\t\t\t\treturn !Objects.equal(input.getValue(), value);\n\t\t\t}\n\t\t});\n\t}", "public void clearSelections() {\n for (CheckableViewHolder vh : mCheckedVisibleViewHolders) {\n vh.checkbox.setChecked(false);\n }\n mCheckedVisibleViewHolders.clear();\n mCheckedItems.clear();\n }", "public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) {\n // this is all the partitions the key replicates to.\n List<Integer> partitionIds = getReplicatingPartitionList(key);\n for(Integer partitionId: partitionIds) {\n // check which of the replicating partitions belongs to the node in\n // question\n if(getNodeIdForPartitionId(partitionId) == nodeId) {\n return partitionId;\n }\n }\n return null;\n }" ]
Stop Redwood, closing all tracks and prohibiting future log messages.
[ "public static void stop(){\r\n //--Close logger\r\n isClosed = true; // <- not a thread-safe boolean\r\n Thread.yield(); //poor man's synchronization attempt (let everything else log that wants to)\r\n Thread.yield();\r\n //--Close Tracks\r\n while(depth > 0){\r\n depth -= 1;\r\n //(send signal to handlers)\r\n handlers.process(null, MessageType.END_TRACK, depth, System.currentTimeMillis());\r\n }\r\n //--Shutdown\r\n handlers.process(null, MessageType.SHUTDOWN, 0, System.currentTimeMillis());\r\n }" ]
[ "public Object getProperty(Object object) {\n return java.lang.reflect.Array.getLength(object);\n }", "public void fire(TestCaseEvent event) {\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n notifier.fire(event);\n }", "public static snmpmanager[] get(nitro_service service) throws Exception{\n\t\tsnmpmanager obj = new snmpmanager();\n\t\tsnmpmanager[] response = (snmpmanager[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private void initDescriptor() throws CmsXmlException, CmsException {\n\n if (m_bundleType.equals(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR)) {\n m_desc = m_resource;\n } else {\n //First try to read from same folder like resource, if it fails use CmsMessageBundleEditorTypes.getDescriptor()\n try {\n m_desc = m_cms.readResource(m_sitepath + m_basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX);\n } catch (CmsVfsResourceNotFoundException e) {\n m_desc = CmsMessageBundleEditorTypes.getDescriptor(m_cms, m_basename);\n }\n }\n unmarshalDescriptor();\n\n }", "public ProductFactoryCascade<T> addFactoryBefore(ProductFactory<? extends T> factory) {\n\t\tArrayList<ProductFactory<? extends T>> factories = new ArrayList<ProductFactory<? extends T>>(this.factories.size()+1);\n\t\tfactories.addAll(this.factories);\n\t\tfactories.add(0, factory);\n\t\treturn new ProductFactoryCascade<>(factories);\n\t}", "private void logMigration(DbMigration migration, boolean wasSuccessful) {\n BoundStatement boundStatement = logMigrationStatement.bind(wasSuccessful, migration.getVersion(),\n migration.getScriptName(), migration.getMigrationScript(), new Date());\n session.execute(boundStatement);\n }", "protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) {\n\n\t\treturn (Connection) Proxy.newProxyInstance(\n\t\t\t\tConnectionProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {ConnectionProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "private void lockLocalization(Locale l) throws CmsException {\n\n if (null == m_lockedBundleFiles.get(l)) {\n LockedFile lf = LockedFile.lockResource(m_cms, m_bundleFiles.get(l));\n m_lockedBundleFiles.put(l, lf);\n }\n\n }", "public static Color cueColor(CueList.Entry entry) {\n if (entry.hotCueNumber > 0) {\n return Color.GREEN;\n }\n if (entry.isLoop) {\n return Color.ORANGE;\n }\n return Color.RED;\n }" ]
Defines how messages should be logged. This method can be modified to restrict the logging messages that are shown on the console or to change their formatting. See the documentation of Log4J for details on how to do this.
[ "public static void configureLogging() {\n\t\t// Create the appender that will write log messages to the console.\n\t\tConsoleAppender consoleAppender = new ConsoleAppender();\n\t\t// Define the pattern of log messages.\n\t\t// Insert the string \"%c{1}:%L\" to also show class name and line.\n\t\tString pattern = \"%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n\";\n\t\tconsoleAppender.setLayout(new PatternLayout(pattern));\n\t\t// Change to Level.ERROR for fewer messages:\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\n\t\tconsoleAppender.activateOptions();\n\t\tLogger.getRootLogger().addAppender(consoleAppender);\n\t}" ]
[ "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<AccountingDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<AccountingDate>) super.localDateTime(temporal);\n }", "public static boolean isAssignable(Type lhsType, Type rhsType) {\n\t\tAssert.notNull(lhsType, \"Left-hand side type must not be null\");\n\t\tAssert.notNull(rhsType, \"Right-hand side type must not be null\");\n\n\t\t// all types are assignable to themselves and to class Object\n\t\tif (lhsType.equals(rhsType) || lhsType.equals(Object.class)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (lhsType instanceof Class<?>) {\n\t\t\tClass<?> lhsClass = (Class<?>) lhsType;\n\n\t\t\t// just comparing two classes\n\t\t\tif (rhsType instanceof Class<?>) {\n\t\t\t\treturn ClassUtils.isAssignable(lhsClass, (Class<?>) rhsType);\n\t\t\t}\n\n\t\t\tif (rhsType instanceof ParameterizedType) {\n\t\t\t\tType rhsRaw = ((ParameterizedType) rhsType).getRawType();\n\n\t\t\t\t// a parameterized type is always assignable to its raw class type\n\t\t\t\tif (rhsRaw instanceof Class<?>) {\n\t\t\t\t\treturn ClassUtils.isAssignable(lhsClass, (Class<?>) rhsRaw);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (lhsClass.isArray() && rhsType instanceof GenericArrayType) {\n\t\t\t\tType rhsComponent = ((GenericArrayType) rhsType).getGenericComponentType();\n\n\t\t\t\treturn isAssignable(lhsClass.getComponentType(), rhsComponent);\n\t\t\t}\n\t\t}\n\n\t\t// parameterized types are only assignable to other parameterized types and class types\n\t\tif (lhsType instanceof ParameterizedType) {\n\t\t\tif (rhsType instanceof Class<?>) {\n\t\t\t\tType lhsRaw = ((ParameterizedType) lhsType).getRawType();\n\n\t\t\t\tif (lhsRaw instanceof Class<?>) {\n\t\t\t\t\treturn ClassUtils.isAssignable((Class<?>) lhsRaw, (Class<?>) rhsType);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rhsType instanceof ParameterizedType) {\n\t\t\t\treturn isAssignable((ParameterizedType) lhsType, (ParameterizedType) rhsType);\n\t\t\t}\n\t\t}\n\n\t\tif (lhsType instanceof GenericArrayType) {\n\t\t\tType lhsComponent = ((GenericArrayType) lhsType).getGenericComponentType();\n\n\t\t\tif (rhsType instanceof Class<?>) {\n\t\t\t\tClass<?> rhsClass = (Class<?>) rhsType;\n\n\t\t\t\tif (rhsClass.isArray()) {\n\t\t\t\t\treturn isAssignable(lhsComponent, rhsClass.getComponentType());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rhsType instanceof GenericArrayType) {\n\t\t\t\tType rhsComponent = ((GenericArrayType) rhsType).getGenericComponentType();\n\n\t\t\t\treturn isAssignable(lhsComponent, rhsComponent);\n\t\t\t}\n\t\t}\n\n\t\tif (lhsType instanceof WildcardType) {\n\t\t\treturn isAssignable((WildcardType) lhsType, rhsType);\n\t\t}\n\n\t\treturn false;\n\t}", "public void setBaselineDurationText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber), value);\n }", "private static String stripExtraLineEnd(String text, boolean formalRTF)\n {\n if (formalRTF && text.endsWith(\"\\n\"))\n {\n text = text.substring(0, text.length() - 1);\n }\n return text;\n }", "private InputStream prepareInputStream(InputStream stream) throws IOException\n {\n InputStream result;\n BufferedInputStream bis = new BufferedInputStream(stream);\n readHeaderProperties(bis);\n if (isCompressed())\n {\n result = new InflaterInputStream(bis);\n }\n else\n {\n result = bis;\n }\n return result;\n }", "static synchronized void clearLogContext() {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n // Remove the configurator and clear the log context\n final Configurator configurator = embeddedLogContext.getLogger(\"\").detach(Configurator.ATTACHMENT_KEY);\n // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext\n if (configurator instanceof PropertyConfigurator) {\n final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();\n clearLogContext(logContextConfiguration);\n } else if (configurator instanceof LogContextConfiguration) {\n clearLogContext((LogContextConfiguration) configurator);\n } else {\n // Remove all the handlers and close them as well as reset the loggers\n final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());\n for (String name : loggerNames) {\n final Logger logger = embeddedLogContext.getLoggerIfExists(name);\n if (logger != null) {\n final Handler[] handlers = logger.clearHandlers();\n if (handlers != null) {\n for (Handler handler : handlers) {\n handler.close();\n }\n }\n logger.setFilter(null);\n logger.setUseParentFilters(false);\n logger.setUseParentHandlers(true);\n logger.setLevel(Level.INFO);\n }\n }\n }\n }", "public static base_response enable(nitro_service client, String id) throws Exception {\n\t\tInterface enableresource = new Interface();\n\t\tenableresource.id = id;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "public CliCommandBuilder setTimeout(final int timeout) {\n if (timeout > 0) {\n addCliArgument(CliArgument.TIMEOUT, Integer.toString(timeout));\n } else {\n addCliArgument(CliArgument.TIMEOUT, null);\n }\n return this;\n }", "public static base_response add(nitro_service client, nspbr6 resource) throws Exception {\n\t\tnspbr6 addresource = new nspbr6();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\taddresource.action = resource.action;\n\t\taddresource.srcipv6 = resource.srcipv6;\n\t\taddresource.srcipop = resource.srcipop;\n\t\taddresource.srcipv6val = resource.srcipv6val;\n\t\taddresource.srcport = resource.srcport;\n\t\taddresource.srcportop = resource.srcportop;\n\t\taddresource.srcportval = resource.srcportval;\n\t\taddresource.destipv6 = resource.destipv6;\n\t\taddresource.destipop = resource.destipop;\n\t\taddresource.destipv6val = resource.destipv6val;\n\t\taddresource.destport = resource.destport;\n\t\taddresource.destportop = resource.destportop;\n\t\taddresource.destportval = resource.destportval;\n\t\taddresource.srcmac = resource.srcmac;\n\t\taddresource.protocol = resource.protocol;\n\t\taddresource.protocolnumber = resource.protocolnumber;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.Interface = resource.Interface;\n\t\taddresource.priority = resource.priority;\n\t\taddresource.state = resource.state;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.nexthop = resource.nexthop;\n\t\taddresource.nexthopval = resource.nexthopval;\n\t\taddresource.nexthopvlan = resource.nexthopvlan;\n\t\treturn addresource.add_resource(client);\n\t}" ]
Create a list out of the items in the Iterable. @param <T> The type of items in the Iterable. @param items The items to be made into a list. @return A list consisting of the items of the Iterable, in the same order.
[ "public static <T> List<T> toList(Iterable<T> items) {\r\n List<T> list = new ArrayList<T>();\r\n addAll(list, items);\r\n return list;\r\n }" ]
[ "public FieldType getField()\n {\n FieldType result = null;\n if (m_index < m_fields.length)\n {\n result = m_fields[m_index++];\n }\n\n return result;\n }", "public void addAliasToConfigSite(String alias, String redirect, String offset) {\n\n long timeOffset = 0;\n try {\n timeOffset = Long.parseLong(offset);\n } catch (Throwable e) {\n // ignore\n }\n CmsSiteMatcher siteMatcher = new CmsSiteMatcher(alias, timeOffset);\n boolean redirectVal = new Boolean(redirect).booleanValue();\n siteMatcher.setRedirect(redirectVal);\n m_aliases.add(siteMatcher);\n }", "public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) {\n ModelNode readOps = null;\n try {\n readOps = cliGuiCtx.getExecutor().doCommand(\"/subsystem=logging:read-children-types\");\n } catch (CommandFormatException | IOException e) {\n return false;\n }\n if (!readOps.get(\"result\").isDefined()) return false;\n for (ModelNode op: readOps.get(\"result\").asList()) {\n if (\"log-file\".equals(op.asString())) return true;\n }\n return false;\n }", "public T addBundle(final String moduleName, final String slot, final byte[] newHash) {\n final ContentItem item = createBundleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.ADD, NO_CONTENT));\n return returnThis();\n }", "private I_CmsSearchResultWrapper getSearchResults() {\n\n // The second parameter is just ignored - so it does not matter\n m_searchController.updateFromRequestParameters(pageContext.getRequest().getParameterMap(), false);\n I_CmsSearchControllerCommon common = m_searchController.getCommon();\n // Do not search for empty query, if configured\n if (common.getState().getQuery().isEmpty()\n && (!common.getConfig().getIgnoreQueryParam() && !common.getConfig().getSearchForEmptyQueryParam())) {\n return new CmsSearchResultWrapper(m_searchController, null, null, m_cms, null);\n }\n Map<String, String[]> queryParams = null;\n boolean isEditMode = CmsJspTagEditable.isEditableRequest(pageContext.getRequest());\n if (isEditMode) {\n String params = \"\";\n if (common.getConfig().getIgnoreReleaseDate()) {\n params += \"&fq=released:[* TO *]\";\n }\n if (common.getConfig().getIgnoreExpirationDate()) {\n params += \"&fq=expired:[* TO *]\";\n }\n if (!params.isEmpty()) {\n queryParams = CmsRequestUtil.createParameterMap(params.substring(1));\n }\n }\n CmsSolrQuery query = new CmsSolrQuery(null, queryParams);\n m_searchController.addQueryParts(query, m_cms);\n try {\n // use \"complicated\" constructor to allow more than 50 results -> set ignoreMaxResults to true\n // also set resource filter to allow for returning unreleased/expired resources if necessary.\n CmsSolrResultList solrResultList = m_index.search(\n m_cms,\n query.clone(), // use a clone of the query, since the search function manipulates the query (removes highlighting parts), but we want to keep the original one.\n true,\n isEditMode ? CmsResourceFilter.IGNORE_EXPIRATION : null);\n return new CmsSearchResultWrapper(m_searchController, solrResultList, query, m_cms, null);\n } catch (CmsSearchException e) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_TAG_SEARCH_SEARCH_FAILED_0), e);\n return new CmsSearchResultWrapper(m_searchController, null, query, m_cms, e);\n }\n }", "@SuppressWarnings(\"unchecked\")\n public <T extends ReportModel> T getReportByName(String name, Class<T> clazz)\n {\n WindupVertexFrame model = this.getUniqueByProperty(ReportModel.REPORT_NAME, name);\n try\n {\n return (T) model;\n }\n catch (ClassCastException ex)\n {\n throw new WindupException(\"The vertex is not of expected frame type \" + clazz.getName() + \": \" + model.toPrettyString());\n }\n }", "@RequestMapping(value=\"/soy/compileJs\", method=GET)\n public ResponseEntity<String> compile(@RequestParam(required = false, value=\"hash\", defaultValue = \"\") final String hash,\n @RequestParam(required = true, value = \"file\") final String[] templateFileNames,\n @RequestParam(required = false, value = \"locale\") String locale,\n @RequestParam(required = false, value = \"disableProcessors\", defaultValue = \"false\") String disableProcessors,\n final HttpServletRequest request) throws IOException {\n return compileJs(templateFileNames, hash, new Boolean(disableProcessors).booleanValue(), request, locale);\n }", "protected void emitWithBurstCheck(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n if ( burstMode )\n {\n if ( executeOnce )\n {\n emit(particlePositions, particleVelocities, particleTimeStamps);\n executeOnce = false;\n }\n }\n else\n {\n emit(particlePositions, particleVelocities, particleTimeStamps);\n }\n\n }", "private void ensureConversion(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n // we issue a warning if we encounter a field with a java.util.Date java type without a conversion\r\n if (\"java.util.Date\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE)) &&\r\n !fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_CONVERSION))\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureConversion\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\r\n \" of type java.util.Date is directly mapped to jdbc-type \"+\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)+\r\n \". However, most JDBC drivers can't handle java.util.Date directly so you might want to \"+\r\n \" use a conversion for converting it to a JDBC datatype like TIMESTAMP.\");\r\n }\r\n\r\n String conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_CONVERSION);\r\n\r\n if (((conversionClass == null) || (conversionClass.length() == 0)) &&\r\n fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION) &&\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE).equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)))\r\n {\r\n conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_CONVERSION, conversionClass);\r\n }\r\n // now checking\r\n if (CHECKLEVEL_STRICT.equals(checkLevel) && (conversionClass != null) && (conversionClass.length() > 0))\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(conversionClass, CONVERSION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" does not implement the necessary interface \"+CONVERSION_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+ex.getMessage()+\" hasn't been found on the classpath while checking the conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName());\r\n }\r\n }\r\n}" ]
Returns the ARGB components for the pixel at the given coordinates @param x the x coordinate of the pixel component to grab @param y the y coordinate of the pixel component to grab @return an array containing ARGB components in that order.
[ "public int[] argb(int x, int y) {\n Pixel p = pixel(x, y);\n return new int[]{p.alpha(), p.red(), p.green(), p.blue()};\n }" ]
[ "protected String sendRequestToDF(String df_service, Object msgContent) {\n\n IDFComponentDescription[] receivers = getReceivers(df_service);\n if (receivers.length > 0) {\n IMessageEvent mevent = createMessageEvent(\"send_request\");\n mevent.getParameter(SFipa.CONTENT).setValue(msgContent);\n for (int i = 0; i < receivers.length; i++) {\n mevent.getParameterSet(SFipa.RECEIVERS).addValue(\n receivers[i].getName());\n logger.info(\"The receiver is \" + receivers[i].getName());\n }\n sendMessage(mevent);\n }\n logger.info(\"Message sended to \" + df_service + \" to \"\n + receivers.length + \" receivers\");\n return (\"Message sended to \" + df_service);\n }", "public void updateEmbeddedColumn(GraphDatabaseService executionEngine, Object[] keyValues, String embeddedColumn, Object value) {\n\t\tString query = getUpdateEmbeddedColumnQuery( keyValues, embeddedColumn );\n\t\tMap<String, Object> params = params( ArrayHelper.concat( keyValues, value, value ) );\n\t\texecutionEngine.execute( query, params );\n\t}", "public static org.jfrog.hudson.ArtifactoryServer prepareArtifactoryServer(String artifactoryServerID,\n ArtifactoryServer pipelineServer) {\n\n if (artifactoryServerID == null && pipelineServer == null) {\n return null;\n }\n if (artifactoryServerID != null && pipelineServer != null) {\n return null;\n }\n if (pipelineServer != null) {\n CredentialsConfig credentials = pipelineServer.createCredentialsConfig();\n\n return new org.jfrog.hudson.ArtifactoryServer(null, pipelineServer.getUrl(), credentials,\n credentials, pipelineServer.getConnection().getTimeout(), pipelineServer.isBypassProxy(), pipelineServer.getConnection().getRetry(), pipelineServer.getDeploymentThreads());\n }\n org.jfrog.hudson.ArtifactoryServer server = RepositoriesUtils.getArtifactoryServer(artifactoryServerID, RepositoriesUtils.getArtifactoryServers());\n if (server == null) {\n return null;\n }\n return server;\n }", "public void prettyPrint(StringBuffer sb, int indent) {\n sb.append(Log.getSpaces(indent));\n sb.append(getClass().getSimpleName());\n sb.append(\" [name=\");\n sb.append(this.getName());\n sb.append(\"]\");\n sb.append(System.lineSeparator());\n GVRRenderData rdata = getRenderData();\n GVRTransform trans = getTransform();\n\n if (rdata == null) {\n sb.append(Log.getSpaces(indent + 2));\n sb.append(\"RenderData: null\");\n sb.append(System.lineSeparator());\n } else {\n rdata.prettyPrint(sb, indent + 2);\n }\n sb.append(Log.getSpaces(indent + 2));\n sb.append(\"Transform: \"); sb.append(trans);\n sb.append(System.lineSeparator());\n\n // dump its children\n for (GVRSceneObject child : getChildren()) {\n child.prettyPrint(sb, indent + 2);\n }\n }", "public Stats getCollectionStats(String collectionId, Date date) throws FlickrException {\n return getStats(METHOD_GET_COLLECTION_STATS, \"collection_id\", collectionId, date);\n }", "public void removeAt(int index) {\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.remove(index);\n } else {\n mObjects.remove(index);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }", "protected int adjustIndex(Widget child, int beforeIndex) {\n\n checkIndexBoundsForInsertion(beforeIndex);\n\n // Check to see if this widget is already a direct child.\n if (child.getParent() == this) {\n // If the Widget's previous position was left of the desired new position\n // shift the desired position left to reflect the removal\n int idx = getWidgetIndex(child);\n if (idx < beforeIndex) {\n beforeIndex--;\n }\n }\n\n return beforeIndex;\n }", "public static boolean isInteger(CharSequence self) {\n try {\n Integer.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "public int getJdbcType(String ojbType) throws SQLException\r\n {\r\n int result;\r\n if(ojbType == null) ojbType = \"\";\r\n\t\tojbType = ojbType.toLowerCase();\r\n if (ojbType.equals(\"bit\"))\r\n result = Types.BIT;\r\n else if (ojbType.equals(\"tinyint\"))\r\n result = Types.TINYINT;\r\n else if (ojbType.equals(\"smallint\"))\r\n result = Types.SMALLINT;\r\n else if (ojbType.equals(\"integer\"))\r\n result = Types.INTEGER;\r\n else if (ojbType.equals(\"bigint\"))\r\n result = Types.BIGINT;\r\n\r\n else if (ojbType.equals(\"float\"))\r\n result = Types.FLOAT;\r\n else if (ojbType.equals(\"real\"))\r\n result = Types.REAL;\r\n else if (ojbType.equals(\"double\"))\r\n result = Types.DOUBLE;\r\n\r\n else if (ojbType.equals(\"numeric\"))\r\n result = Types.NUMERIC;\r\n else if (ojbType.equals(\"decimal\"))\r\n result = Types.DECIMAL;\r\n\r\n else if (ojbType.equals(\"char\"))\r\n result = Types.CHAR;\r\n else if (ojbType.equals(\"varchar\"))\r\n result = Types.VARCHAR;\r\n else if (ojbType.equals(\"longvarchar\"))\r\n result = Types.LONGVARCHAR;\r\n\r\n else if (ojbType.equals(\"date\"))\r\n result = Types.DATE;\r\n else if (ojbType.equals(\"time\"))\r\n result = Types.TIME;\r\n else if (ojbType.equals(\"timestamp\"))\r\n result = Types.TIMESTAMP;\r\n\r\n else if (ojbType.equals(\"binary\"))\r\n result = Types.BINARY;\r\n else if (ojbType.equals(\"varbinary\"))\r\n result = Types.VARBINARY;\r\n else if (ojbType.equals(\"longvarbinary\"))\r\n result = Types.LONGVARBINARY;\r\n\r\n\t\telse if (ojbType.equals(\"clob\"))\r\n \t\tresult = Types.CLOB;\r\n\t\telse if (ojbType.equals(\"blob\"))\r\n\t\t\tresult = Types.BLOB;\r\n else\r\n throw new SQLException(\r\n \"The type '\"+ ojbType + \"' is not a valid jdbc type.\");\r\n return result;\r\n }" ]
Used to locate the first timephased resource assignment block which intersects with the target date range. @param <T> payload type @param range target date range @param assignments timephased resource assignments @param startIndex index at which to start the search @return index of timephased resource assignment which intersects with the target date range
[ "private <T extends TimephasedItem<?>> int getStartIndex(DateRange range, List<T> assignments, int startIndex)\n {\n int result = -1;\n if (assignments != null)\n {\n long rangeStart = range.getStart().getTime();\n long rangeEnd = range.getEnd().getTime();\n\n for (int loop = startIndex; loop < assignments.size(); loop++)\n {\n T assignment = assignments.get(loop);\n int compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeStart);\n\n //\n // The start of the target range falls after the assignment end -\n // move on to test the next assignment.\n //\n if (compareResult > 0)\n {\n continue;\n }\n\n //\n // The start of the target range falls within the assignment -\n // return the index of this assignment to the caller.\n //\n if (compareResult == 0)\n {\n result = loop;\n break;\n }\n\n //\n // At this point, we know that the start of the target range is before\n // the assignment start. We need to determine if the end of the\n // target range overlaps the assignment.\n //\n compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeEnd);\n if (compareResult >= 0)\n {\n result = loop;\n break;\n }\n }\n }\n return result;\n }" ]
[ "public PathAddress append(List<PathElement> additionalElements) {\n final ArrayList<PathElement> newList = new ArrayList<PathElement>(pathAddressList.size() + additionalElements.size());\n newList.addAll(pathAddressList);\n newList.addAll(additionalElements);\n return pathAddress(newList);\n }", "private String getName(CommandContext ctx, boolean failInBatch) throws CommandLineException {\n final ParsedCommandLine args = ctx.getParsedCommandLine();\n final String name = this.name.getValue(args, true);\n if (name == null) {\n throw new CommandFormatException(this.name + \" is missing value.\");\n }\n if (!ctx.isBatchMode() || failInBatch) {\n if (!Util.isValidPath(ctx.getModelControllerClient(), Util.DEPLOYMENT_OVERLAY, name)) {\n throw new CommandFormatException(\"Deployment overlay \" + name + \" does not exist.\");\n }\n }\n return name;\n }", "public static DesignDocument fromFile(File file) throws FileNotFoundException {\r\n assertNotEmpty(file, \"Design js file\");\r\n DesignDocument designDocument;\r\n Gson gson = new Gson();\r\n InputStreamReader reader = null;\r\n try {\r\n reader = new InputStreamReader(new FileInputStream(file),\"UTF-8\");\r\n //Deserialize JS file contents into DesignDocument object\r\n designDocument = gson.fromJson(reader, DesignDocument.class);\r\n return designDocument;\r\n } catch (UnsupportedEncodingException e) {\r\n //UTF-8 should be supported on all JVMs\r\n throw new RuntimeException(e);\r\n } finally {\r\n IOUtils.closeQuietly(reader);\r\n }\r\n }", "public static Set<String> commaDelimitedListToSet(String str) {\n Set<String> set = new TreeSet<String>();\n String[] tokens = commaDelimitedListToStringArray(str);\n Collections.addAll(set, tokens);\n return set;\n }", "protected void initializeJdbcConnection(Connection con, JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n try\r\n {\r\n PlatformFactory.getPlatformFor(jcd).initializeJdbcConnection(jcd, con);\r\n }\r\n catch (PlatformException e)\r\n {\r\n throw new LookupException(\"Platform dependent initialization of connection failed\", e);\r\n }\r\n }", "public int[] executeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSendBatch = (Method) m_batchStatementsInProgress.remove(stmt);\r\n final boolean statementBatchingSupported = methodSendBatch != null;\r\n\r\n int[] retval = null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // sendBatch() returns total row count as an Integer\r\n methodSendBatch.invoke(stmt, null);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n retval = super.executeBatch(stmt);\r\n }\r\n return retval;\r\n }", "public void validateOperation(final ModelNode operation) {\n if (operation == null) {\n return;\n }\n final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));\n final String name = operation.get(OP).asString();\n\n OperationEntry entry = root.getOperationEntry(address, name);\n if (entry == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationEntry(name, address));\n }\n //noinspection ConstantConditions\n if (entry.getType() == EntryType.PRIVATE || entry.getFlags().contains(OperationEntry.Flag.HIDDEN)) {\n return;\n }\n if (entry.getOperationHandler() == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationHandler(name, address));\n }\n final DescriptionProvider provider = getDescriptionProvider(operation);\n final ModelNode description = provider.getModelDescription(null);\n\n final Map<String, ModelNode> describedProperties = getDescribedRequestProperties(operation, description);\n final Map<String, ModelNode> actualParams = getActualRequestProperties(operation);\n\n checkActualOperationParamsAreDescribed(operation, describedProperties, actualParams);\n checkAllRequiredPropertiesArePresent(description, operation, describedProperties, actualParams);\n checkParameterTypes(description, operation, describedProperties, actualParams);\n\n //TODO check ranges\n }", "public void loadClassifier(File file, Properties props) throws ClassCastException, IOException,\r\n ClassNotFoundException {\r\n Timing.startDoing(\"Loading classifier from \" + file.getAbsolutePath());\r\n BufferedInputStream bis;\r\n if (file.getName().endsWith(\".gz\")) {\r\n bis = new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)));\r\n } else {\r\n bis = new BufferedInputStream(new FileInputStream(file));\r\n }\r\n loadClassifier(bis, props);\r\n bis.close();\r\n Timing.endDoing();\r\n }", "void endIfStarted(CodeAttribute b, ClassMethod method) {\n b.aload(getLocalVariableIndex(0));\n b.dup();\n final BranchEnd ifnotnull = b.ifnull();\n b.checkcast(Stack.class);\n b.invokevirtual(Stack.class.getName(), END_INTERCEPTOR_CONTEXT_METHOD_NAME, EMPTY_PARENTHESES + VOID_CLASS_DESCRIPTOR);\n BranchEnd ifnull = b.gotoInstruction();\n b.branchEnd(ifnotnull);\n b.pop(); // remove null Stack\n b.branchEnd(ifnull);\n }" ]
Get list of asynchronous operations on this node. By default, only the pending operations are returned. @param showCompleted Show completed operations @return A list of operation ids.
[ "public List<Integer> getAsyncOperationList(boolean showCompleted) {\n /**\n * Create a copy using an immutable set to avoid a\n * {@link java.util.ConcurrentModificationException}\n */\n Set<Integer> keySet = ImmutableSet.copyOf(operations.keySet());\n\n if(showCompleted)\n return new ArrayList<Integer>(keySet);\n\n List<Integer> keyList = new ArrayList<Integer>();\n for(int key: keySet) {\n AsyncOperation operation = operations.get(key);\n if(operation != null && !operation.getStatus().isComplete())\n keyList.add(key);\n }\n return keyList;\n }" ]
[ "protected Object[] getFieldObjects(Object data) throws SQLException {\n\t\tObject[] objects = new Object[argFieldTypes.length];\n\t\tfor (int i = 0; i < argFieldTypes.length; i++) {\n\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\tif (fieldType.isAllowGeneratedIdInsert()) {\n\t\t\t\tobjects[i] = fieldType.getFieldValueIfNotDefault(data);\n\t\t\t} else {\n\t\t\t\tobjects[i] = fieldType.extractJavaFieldToSqlArgValue(data);\n\t\t\t}\n\t\t\tif (objects[i] == null) {\n\t\t\t\t// NOTE: the default value could be null as well\n\t\t\t\tobjects[i] = fieldType.getDefaultValue();\n\t\t\t}\n\t\t}\n\t\treturn objects;\n\t}", "public static PacketType validateHeader(DatagramPacket packet, int port) {\n byte[] data = packet.getData();\n\n if (data.length < PACKET_TYPE_OFFSET) {\n logger.warn(\"Packet is too short to be a Pro DJ Link packet; must be at least \" + PACKET_TYPE_OFFSET +\n \" bytes long, was only \" + data.length + \".\");\n return null;\n }\n\n if (!getMagicHeader().equals(ByteBuffer.wrap(data, 0, MAGIC_HEADER.length))) {\n logger.warn(\"Packet did not have correct nine-byte header for the Pro DJ Link protocol.\");\n return null;\n }\n\n final Map<Byte, PacketType> portMap = PACKET_TYPE_MAP.get(port);\n if (portMap == null) {\n logger.warn(\"Do not know any Pro DJ Link packets that are received on port \" + port + \".\");\n return null;\n }\n\n final PacketType result = portMap.get(data[PACKET_TYPE_OFFSET]);\n if (result == null) {\n logger.warn(\"Do not know any Pro DJ Link packets received on port \" + port + \" with type \" +\n String.format(\"0x%02x\", data[PACKET_TYPE_OFFSET]) + \".\");\n }\n\n return result;\n }", "protected final void sendObjectToSocket(Object objectToSend, WriteCallback cb) {\n Session sess = this.getSession();\n if (sess != null) {\n String json;\n try {\n json = this.mapper.writeValueAsString(objectToSend);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(\"Failed to serialize object\", e);\n }\n sess.getRemote().sendString(json, cb);\n }\n }", "void updateFromResponseOnDeletePost(Response<ResponseBody> response) throws IOException {\n this.withResponse(response);\n String responseContent = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType));\n withStatus(AzureAsyncOperation.SUCCESS_STATUS, response.code());\n }", "public static Boolean compareSingleClientConfigAvro(String configAvro1, String configAvro2) {\n Properties props1 = readSingleClientConfigAvro(configAvro1);\n Properties props2 = readSingleClientConfigAvro(configAvro2);\n if(props1.equals(props2)) {\n return true;\n } else {\n return false;\n }\n }", "private String convertOutputToHtml(String content) {\n\n if (content.length() == 0) {\n return \"\";\n }\n StringBuilder buffer = new StringBuilder();\n for (String line : content.split(\"\\n\")) {\n buffer.append(CmsEncoder.escapeXml(line) + \"<br>\");\n }\n return buffer.toString();\n }", "public static void updatePathTable(String columnName, Object newData, int path_id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + columnName + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setObject(1, newData);\n statement.setInt(2, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public static void deleteFilePath(FilePath workspace, String path) throws IOException {\n if (StringUtils.isNotBlank(path)) {\n try {\n FilePath propertiesFile = new FilePath(workspace, path);\n propertiesFile.delete();\n } catch (Exception e) {\n throw new IOException(\"Could not delete temp file: \" + path);\n }\n }\n }", "@Nullable\n private static Object valueOf(String value, Class<?> cls) {\n if (cls == Boolean.TYPE) {\n return Boolean.valueOf(value);\n }\n if (cls == Character.TYPE) {\n return value.length() >= 1 ? value.charAt(0) : defaultValue(char.class);\n }\n if (cls == Byte.TYPE) {\n return Byte.valueOf(value);\n }\n if (cls == Short.TYPE) {\n return Short.valueOf(value);\n }\n if (cls == Integer.TYPE) {\n return Integer.valueOf(value);\n }\n if (cls == Long.TYPE) {\n return Long.valueOf(value);\n }\n if (cls == Float.TYPE) {\n return Float.valueOf(value);\n }\n if (cls == Double.TYPE) {\n return Double.valueOf(value);\n }\n return null;\n }" ]
Stops listening. Safe to call when already stopped. Ignored on devices without appropriate hardware.
[ "public void stop() {\n if (accelerometer != null) {\n queue.clear();\n sensorManager.unregisterListener(this, accelerometer);\n sensorManager = null;\n accelerometer = null;\n }\n }" ]
[ "public Where<T, ID> reset() {\n\t\tfor (int i = 0; i < clauseStackLevel; i++) {\n\t\t\t// help with gc\n\t\t\tclauseStack[i] = null;\n\t\t}\n\t\tclauseStackLevel = 0;\n\t\treturn this;\n\t}", "public void updateExceptions() {\n\n m_exceptionsList.setDates(m_model.getExceptions());\n if (m_model.getExceptions().size() > 0) {\n m_exceptionsPanel.setVisible(true);\n } else {\n m_exceptionsPanel.setVisible(false);\n }\n }", "static WeldContainer startInitialization(String id, Deployment deployment, Bootstrap bootstrap) {\n if (SINGLETON.isSet(id)) {\n throw WeldSELogger.LOG.weldContainerAlreadyRunning(id);\n }\n WeldContainer weldContainer = new WeldContainer(id, deployment, bootstrap);\n SINGLETON.set(id, weldContainer);\n RUNNING_CONTAINER_IDS.add(id);\n return weldContainer;\n }", "public <T> void cleanNullReferences(Class<T> clazz) {\n\t\tMap<Object, Reference<Object>> objectMap = getMapForClass(clazz);\n\t\tif (objectMap != null) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}", "public static CharSequence getRelativeTimeSpanString(Context context, ReadableInstant time, int flags) {\n boolean abbrevRelative = (flags & (FORMAT_ABBREV_RELATIVE | FORMAT_ABBREV_ALL)) != 0;\n\n // We set the millis to 0 so we aren't off by a fraction of a second when counting intervals\n DateTime now = DateTime.now(time.getZone()).withMillisOfSecond(0);\n DateTime timeDt = new DateTime(time).withMillisOfSecond(0);\n boolean past = !now.isBefore(timeDt);\n Interval interval = past ? new Interval(timeDt, now) : new Interval(now, timeDt);\n\n int resId;\n long count;\n if (Minutes.minutesIn(interval).isLessThan(Minutes.ONE)) {\n count = Seconds.secondsIn(interval).getSeconds();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_seconds_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_seconds_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_seconds;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_seconds;\n }\n }\n }\n else if (Hours.hoursIn(interval).isLessThan(Hours.ONE)) {\n count = Minutes.minutesIn(interval).getMinutes();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_minutes_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_minutes_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_minutes;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_minutes;\n }\n }\n }\n else if (Days.daysIn(interval).isLessThan(Days.ONE)) {\n count = Hours.hoursIn(interval).getHours();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_hours_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_hours_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_hours;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_hours;\n }\n }\n }\n else if (Weeks.weeksIn(interval).isLessThan(Weeks.ONE)) {\n count = Days.daysIn(interval).getDays();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_days_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_days_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_days;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_days;\n }\n }\n }\n else {\n return formatDateRange(context, time, time, flags);\n }\n\n String format = context.getResources().getQuantityString(resId, (int) count);\n return String.format(format, count);\n }", "private void setExceptions(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n List<net.sf.mpxj.ganttproject.schema.Date> dates = gpCalendar.getDate();\n for (net.sf.mpxj.ganttproject.schema.Date date : dates)\n {\n addException(mpxjCalendar, date);\n }\n }", "public void updateLockingValues(Object obj) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n if (fmd.isUpdateLock())\r\n {\r\n PersistentField f = fmd.getPersistentField();\r\n Object cv = f.get(obj);\r\n // int\r\n if ((f.getType() == int.class) || (f.getType() == Integer.class))\r\n {\r\n int newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).intValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Integer(newCv));\r\n }\r\n // long\r\n else if ((f.getType() == long.class) || (f.getType() == Long.class))\r\n {\r\n long newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).longValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Long(newCv));\r\n }\r\n // Timestamp\r\n else if (f.getType() == Timestamp.class)\r\n {\r\n long newCv = System.currentTimeMillis();\r\n f.set(obj, new Timestamp(newCv));\r\n }\r\n }\r\n }\r\n }", "public static DMatrixRMaj copyTriangle(DMatrixRMaj src , DMatrixRMaj dst , boolean upper ) {\n if( dst == null ) {\n dst = new DMatrixRMaj(src.numRows,src.numCols);\n } else if( src.numRows != dst.numRows || src.numCols != dst.numCols ) {\n throw new IllegalArgumentException(\"src and dst must have the same dimensions.\");\n }\n\n if( upper ) {\n int N = Math.min(src.numRows,src.numCols);\n for( int i = 0; i < N; i++ ) {\n int index = i*src.numCols+i;\n System.arraycopy(src.data,index,dst.data,index,src.numCols-i);\n }\n } else {\n for( int i = 0; i < src.numRows; i++ ) {\n int length = Math.min(i+1,src.numCols);\n int index = i*src.numCols;\n System.arraycopy(src.data,index,dst.data,index,length);\n }\n }\n\n return dst;\n }", "private void readTextsCompressed(File dir, HashMap results) throws IOException\r\n {\r\n if (dir.exists() && dir.isDirectory())\r\n {\r\n File[] files = dir.listFiles();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (files[idx].isDirectory())\r\n {\r\n continue;\r\n }\r\n results.put(files[idx].getName(), readTextCompressed(files[idx]));\r\n }\r\n }\r\n }" ]
Look up record by identity.
[ "public Record findRecordById(String id) {\n if (directory == null)\n init();\n\n Property idprop = config.getIdentityProperties().iterator().next();\n for (Record r : lookup(idprop, id))\n if (r.getValue(idprop.getName()).equals(id))\n return r;\n\n return null; // not found\n }" ]
[ "private static void createDirectory(Path path) throws IOException {\n\t\ttry {\n\t\t\tFiles.createDirectory(path);\n\t\t} catch (FileAlreadyExistsException e) {\n\t\t\tif (!Files.isDirectory(path)) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}", "public static List<QuotaType> getQuotaTypes(List<String> strQuotaTypes) {\n if(strQuotaTypes.size() < 1) {\n throw new VoldemortException(\"Quota type not specified.\");\n }\n List<QuotaType> quotaTypes;\n if(strQuotaTypes.size() == 1 && strQuotaTypes.get(0).equals(AdminToolUtils.QUOTATYPE_ALL)) {\n quotaTypes = Arrays.asList(QuotaType.values());\n } else {\n quotaTypes = new ArrayList<QuotaType>();\n for(String strQuotaType: strQuotaTypes) {\n QuotaType type = QuotaType.valueOf(strQuotaType);\n quotaTypes.add(type);\n }\n }\n return quotaTypes;\n }", "public List<FailedEventInvocation> getFailedInvocations() {\n synchronized (this.mutex) {\n if (this.failedEvents == null) {\n return Collections.emptyList();\n }\n return Collections.unmodifiableList(this.failedEvents);\n }\n }", "protected DataSource getDataSource(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n final PBKey key = jcd.getPBKey();\r\n DataSource ds = (DataSource) dsMap.get(key);\r\n if (ds == null)\r\n {\r\n // Found no pool for PBKey\r\n try\r\n {\r\n synchronized (poolSynch)\r\n {\r\n // Setup new object pool\r\n ObjectPool pool = setupPool(jcd);\r\n poolMap.put(key, pool);\r\n // Wrap the underlying object pool as DataSource\r\n ds = wrapAsDataSource(jcd, pool);\r\n dsMap.put(key, ds);\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Could not setup DBCP DataSource for \" + jcd, e);\r\n throw new LookupException(e);\r\n }\r\n }\r\n return ds;\r\n }", "private ClassLoaderInterface getClassLoader() {\n\t\tMap<String, Object> application = ActionContext.getContext().getApplication();\n\t\tif (application != null) {\n\t\t\treturn (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE);\n\t\t}\n\t\treturn null;\n\t}", "protected void countStatements(UsageStatistics usageStatistics,\n\t\t\tStatementDocument statementDocument) {\n\t\t// Count Statement data:\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\t// Count Statements:\n\t\t\tusageStatistics.countStatements += sg.size();\n\n\t\t\t// Count uses of properties in Statements:\n\t\t\tcountPropertyMain(usageStatistics, sg.getProperty(), sg.size());\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tfor (SnakGroup q : s.getQualifiers()) {\n\t\t\t\t\tcountPropertyQualifier(usageStatistics, q.getProperty(), q.size());\n\t\t\t\t}\n\t\t\t\tfor (Reference r : s.getReferences()) {\n\t\t\t\t\tusageStatistics.countReferencedStatements++;\n\t\t\t\t\tfor (SnakGroup snakGroup : r.getSnakGroups()) {\n\t\t\t\t\t\tcountPropertyReference(usageStatistics,\n\t\t\t\t\t\t\t\tsnakGroup.getProperty(), snakGroup.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public String[] getAttributeNames()\r\n {\r\n Set keys = (attributeMap == null ? new HashSet() : attributeMap.keySet());\r\n String[] result = new String[keys.size()];\r\n\r\n keys.toArray(result);\r\n return result;\r\n }", "public static void validate(final Module module) {\n if (null == module) {\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module cannot be null!\")\n .build());\n }\n if(module.getName() == null ||\n module.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module name cannot be null or empty!\")\n .build());\n }\n if(module.getVersion()== null ||\n module.getVersion().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module version cannot be null or empty!\")\n .build());\n }\n\n // Check artifacts\n for(final Artifact artifact: DataUtils.getAllArtifacts(module)){\n validate(artifact);\n }\n\n // Check dependencies\n for(final Dependency dependency: DataUtils.getAllDependencies(module)){\n validate(dependency.getTarget());\n }\n }", "public Where<T, ID> and() {\n\t\tManyClause clause = new ManyClause(pop(\"AND\"), ManyClause.AND_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}" ]
Use this API to fetch vlan_nsip_binding resources of given name .
[ "public static vlan_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvlan_nsip_binding obj = new vlan_nsip_binding();\n\t\tobj.set_id(id);\n\t\tvlan_nsip_binding response[] = (vlan_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public void setSymbolPosition(CurrencySymbolPosition posn)\n {\n if (posn == null)\n {\n posn = DEFAULT_CURRENCY_SYMBOL_POSITION;\n }\n set(ProjectField.CURRENCY_SYMBOL_POSITION, posn);\n }", "protected Class getClassCacheEntry(String name) {\n if (name == null) return null;\n synchronized (classCache) {\n return classCache.get(name);\n }\n }", "synchronized boolean reload(int permit, boolean suspend) {\n return internalSetState(new ReloadTask(permit, suspend), InternalState.SERVER_STARTED, InternalState.RELOADING);\n }", "public static base_responses update(nitro_service client, autoscaleprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleprofile updateresources[] = new autoscaleprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleprofile();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].url = resources[i].url;\n\t\t\t\tupdateresources[i].apikey = resources[i].apikey;\n\t\t\t\tupdateresources[i].sharedsecret = resources[i].sharedsecret;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public void map(Story story, MetaFilter metaFilter) {\n if (metaFilter.allow(story.getMeta())) {\n boolean allowed = false;\n for (Scenario scenario : story.getScenarios()) {\n // scenario also inherits meta from story\n Meta inherited = scenario.getMeta().inheritFrom(story.getMeta());\n if (metaFilter.allow(inherited)) {\n allowed = true;\n break;\n }\n }\n if (allowed) {\n add(metaFilter.asString(), story);\n }\n }\n }", "private void debugLogStart(String operationType,\n Long originTimeInMS,\n Long requestReceivedTimeInMs,\n String keyString) {\n long durationInMs = requestReceivedTimeInMs - originTimeInMS;\n logger.debug(\"Received a new request. Operation Type: \" + operationType + \" , key(s): \"\n + keyString + \" , Store: \" + this.storeName + \" , Origin time (in ms): \"\n + originTimeInMS + \" . Request received at time(in ms): \"\n + requestReceivedTimeInMs\n + \" , Duration from RESTClient to CoordinatorFatClient(in ms): \"\n + durationInMs);\n\n }", "private URL[] getClasspath(JobInstance ji, JobRunnerCallback cb) throws JqmPayloadException\n {\n switch (ji.getJD().getPathType())\n {\n case MAVEN:\n return mavenResolver.resolve(ji);\n case MEMORY:\n return new URL[0];\n case FS:\n default:\n return fsResolver.getLibraries(ji.getNode(), ji.getJD());\n }\n }", "public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) {\n\t\tdouble[] swapTenor = new double[fixingDates.length+1];\n\t\tSystem.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);\n\t\tswapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];\n\n\t\tTimeDiscretization fixTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tTimeDiscretization floatTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);\n\t\tdouble payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]);\n\t\treturn AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]);\n\t}", "public void addWatcher(final MongoNamespace namespace,\n final Callback<ChangeEvent<BsonDocument>, Object> watcher) {\n instanceChangeStreamListener.addWatcher(namespace, watcher);\n }" ]
Use this API to unset the properties of bridgetable resource. Properties that need to be unset are specified in args array.
[ "public static base_response unset(nitro_service client, bridgetable resource, String[] args) throws Exception{\n\t\tbridgetable unsetresource = new bridgetable();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
[ "private boolean setAvailable(NodeStatus nodeStatus, boolean isAvailable) {\n synchronized(nodeStatus) {\n boolean previous = nodeStatus.isAvailable();\n\n nodeStatus.setAvailable(isAvailable);\n nodeStatus.setLastChecked(getConfig().getTime().getMilliseconds());\n\n return previous;\n }\n }", "public static nsrollbackcmd get(nitro_service service) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public boolean isValid() {\n\t\tif(addressProvider.isUninitialized()) {\n\t\t\ttry {\n\t\t\t\tvalidate();\n\t\t\t\treturn true;\n\t\t\t} catch(AddressStringException e) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn !addressProvider.isInvalid();\n\t}", "public void addAliasToConfigSite(String alias, String redirect, String offset) {\n\n long timeOffset = 0;\n try {\n timeOffset = Long.parseLong(offset);\n } catch (Throwable e) {\n // ignore\n }\n CmsSiteMatcher siteMatcher = new CmsSiteMatcher(alias, timeOffset);\n boolean redirectVal = new Boolean(redirect).booleanValue();\n siteMatcher.setRedirect(redirectVal);\n m_aliases.add(siteMatcher);\n }", "public final static int readMdLink(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n boolean endReached = false;\n switch (ch)\n {\n case '(':\n counter++;\n break;\n case ' ':\n if (counter == 1)\n {\n endReached = true;\n }\n break;\n case ')':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n break;\n }\n if (endReached)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }", "void execute(ExecutableBuilder builder,\n int timeout,\n TimeUnit unit) throws\n CommandLineException,\n InterruptedException, ExecutionException, TimeoutException {\n Future<Void> task = executorService.submit(() -> {\n builder.build().execute();\n return null;\n });\n try {\n if (timeout <= 0) { //Synchronous\n task.get();\n } else { // Guarded execution\n try {\n task.get(timeout, unit);\n } catch (TimeoutException ex) {\n // First make the context unusable\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).timeout();\n }\n // Then cancel the task.\n task.cancel(true);\n throw ex;\n }\n }\n } catch (InterruptedException ex) {\n // Could have been interrupted by user (Ctrl-C)\n Thread.currentThread().interrupt();\n cancelTask(task, builder.getCommandContext(), null);\n // Interrupt running operation.\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).interrupted();\n }\n throw ex;\n }\n }", "public void put(String key, Object object, Envelope envelope) {\n\t\tindex.put(key, envelope);\n\t\tcache.put(key, object);\n\t}", "public static String getOperationName(final ModelNode op) {\n if (op.hasDefined(OP)) {\n return op.get(OP).asString();\n }\n throw ControllerClientLogger.ROOT_LOGGER.operationNameNotFound();\n }", "public final void begin() {\n this.file = this.getAppender().getIoFile();\n if (this.file == null) {\n this.getAppender().getErrorHandler()\n .error(\"Scavenger not started: missing log file name\");\n return;\n }\n if (this.getProperties().getScavengeInterval() > -1) {\n final Thread thread = new Thread(this, \"Log4J File Scavenger\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }" ]
Return a collection of Photo objects not in part of any sets. This method requires authentication with 'read' permission. @param perPage The per page @param page The page @return The collection of Photo objects @throws FlickrException
[ "public PhotoList<Photo> getNotInSet(int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", PhotosInterface.METHOD_GET_NOT_IN_SET);\r\n\r\n RequestContext requestContext = RequestContext.getRequestContext();\r\n\r\n List<String> extras = requestContext.getExtras();\r\n if (extras.size() > 0) {\r\n parameters.put(\"extras\", StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoElements = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }" ]
[ "@Override\n @SuppressFBWarnings(value = \"UL_UNRELEASED_LOCK\", justification = \"False positive from FindBugs\")\n public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n checkContextInitialized();\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n return null;\n }\n if (contextual == null) {\n throw ContextLogger.LOG.contextualIsNull();\n }\n BeanIdentifier id = getId(contextual);\n ContextualInstance<T> beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n } else if (creationalContext != null) {\n LockedBean lock = null;\n try {\n if (multithreaded) {\n lock = beanStore.lock(id);\n beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n }\n }\n T instance = contextual.create(creationalContext);\n if (instance != null) {\n beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));\n beanStore.put(id, beanInstance);\n }\n return instance;\n } finally {\n if (lock != null) {\n lock.unlock();\n }\n }\n } else {\n return null;\n }\n }", "private Project.Calendars.Calendar writeCalendar(ProjectCalendar bc)\n {\n //\n // Create a calendar\n //\n Project.Calendars.Calendar calendar = m_factory.createProjectCalendarsCalendar();\n calendar.setUID(NumberHelper.getBigInteger(bc.getUniqueID()));\n calendar.setIsBaseCalendar(Boolean.valueOf(!bc.isDerived()));\n\n ProjectCalendar base = bc.getParent();\n // SF-329: null default required to keep Powerproject happy when importing MSPDI files\n calendar.setBaseCalendarUID(base == null ? NULL_CALENDAR_ID : NumberHelper.getBigInteger(base.getUniqueID()));\n calendar.setName(bc.getName());\n\n //\n // Create a list of normal days\n //\n Project.Calendars.Calendar.WeekDays days = m_factory.createProjectCalendarsCalendarWeekDays();\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time;\n ProjectCalendarHours bch;\n\n List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList = days.getWeekDay();\n\n for (int loop = 1; loop < 8; loop++)\n {\n DayType workingFlag = bc.getWorkingDay(Day.getInstance(loop));\n\n if (workingFlag != DayType.DEFAULT)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay();\n dayList.add(day);\n day.setDayType(BigInteger.valueOf(loop));\n day.setDayWorking(Boolean.valueOf(workingFlag == DayType.WORKING));\n\n if (workingFlag == DayType.WORKING)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes();\n day.setWorkingTimes(times);\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n bch = bc.getCalendarHours(Day.getInstance(loop));\n if (bch != null)\n {\n for (DateRange range : bch)\n {\n if (range != null)\n {\n time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }\n }\n }\n\n //\n // Create a list of exceptions\n //\n // A quirk of MS Project is that these exceptions must be\n // in date order in the file, otherwise they are ignored\n //\n List<ProjectCalendarException> exceptions = new ArrayList<ProjectCalendarException>(bc.getCalendarExceptions());\n if (!exceptions.isEmpty())\n {\n Collections.sort(exceptions);\n writeExceptions(calendar, dayList, exceptions);\n }\n\n //\n // Do not add a weekdays tag to the calendar unless it\n // has valid entries.\n // Fixes SourceForge bug 1854747: MPXJ and MSP 2007 XML formats\n //\n if (!dayList.isEmpty())\n {\n calendar.setWeekDays(days);\n }\n\n writeWorkWeeks(calendar, bc);\n\n m_eventManager.fireCalendarWrittenEvent(bc);\n\n return (calendar);\n }", "public static <T> T columnStringToObject(Class<?> objClass, String str, Pattern delimiterPattern, String[] fieldNames)\r\n throws InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException\r\n {\r\n String[] fields = delimiterPattern.split(str);\r\n T item = ErasureUtils.<T>uncheckedCast(objClass.newInstance());\r\n for (int i = 0; i < fields.length; i++) {\r\n try {\r\n Field field = objClass.getDeclaredField(fieldNames[i]);\r\n field.set(item, fields[i]);\r\n } catch (IllegalAccessException ex) {\r\n Method method = objClass.getDeclaredMethod(\"set\" + StringUtils.capitalize(fieldNames[i]), String.class);\r\n method.invoke(item, fields[i]);\r\n }\r\n }\r\n return item;\r\n }", "public void setLoop(boolean doLoop, GVRContext gvrContext) {\n if (this.loop != doLoop ) {\n // a change in the loop\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n if (doLoop) gvrKeyFrameAnimation.setRepeatMode(GVRRepeatMode.REPEATED);\n else gvrKeyFrameAnimation.setRepeatMode(GVRRepeatMode.ONCE);\n }\n // be sure to start the animations if loop is true\n if ( doLoop ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n gvrKeyFrameAnimation.start(gvrContext.getAnimationEngine() );\n }\n }\n this.loop = doLoop;\n }\n }", "private void throwExceptionIfSafetyRestrictionsAreViolated(CmsObject cms, CmsSolrQuery query, boolean isSpell)\r\n throws CmsSearchException {\r\n\r\n if (!isDebug(cms, query)) {\r\n if (isSpell) {\r\n if (m_handlerSpellDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n } else {\r\n if (m_handlerSelectDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n int start = null != query.getStart() ? query.getStart().intValue() : 0;\r\n int rows = null != query.getRows() ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();\r\n if ((m_handlerMaxAllowedResultsAtAll >= 0) && ((rows + start) > m_handlerMaxAllowedResultsAtAll)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_AT_ALL_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsAtAll),\r\n Integer.valueOf(rows + start)));\r\n }\r\n if ((m_handlerMaxAllowedResultsPerPage >= 0) && (rows > m_handlerMaxAllowedResultsPerPage)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_PER_PAGE_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsPerPage),\r\n Integer.valueOf(rows)));\r\n }\r\n if ((null != m_handlerAllowedFields) && (Stream.of(m_handlerAllowedFields).anyMatch(x -> true))) {\r\n if (query.getFields().equals(CmsSolrQuery.ALL_RETURN_FIELDS)) {\r\n query.setFields(m_handlerAllowedFields);\r\n } else {\r\n for (String requestedField : query.getFields().split(\",\")) {\r\n if (Stream.of(m_handlerAllowedFields).noneMatch(\r\n allowedField -> allowedField.equals(requestedField))) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_REQUESTED_FIELD_NOT_ALLOWED_2,\r\n requestedField,\r\n Stream.of(m_handlerAllowedFields).reduce(\"\", (a, b) -> a + \",\" + b)));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }", "static void processRoot(final File root, final ProcessedLayers layers, final LayerPathSetter setter) throws IOException {\n final LayersConfig layersConfig = LayersConfig.getLayersConfig(root);\n // Process layers\n final File layersDir = new File(root, layersConfig.getLayersPath());\n if (!layersDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationNoLayersConfigFound(layersDir.getAbsolutePath());\n }\n // else this isn't a root that has layers and add-ons\n } else {\n // check for a valid layer configuration\n for (final String layer : layersConfig.getLayers()) {\n File layerDir = new File(layersDir, layer);\n if (!layerDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationMissingLayer(layer, layersDir.getAbsolutePath());\n }\n // else this isn't a standard layers and add-ons structure\n return;\n }\n layers.addLayer(layer, layerDir, setter);\n }\n }\n // Finally process the add-ons\n final File addOnsDir = new File(root, layersConfig.getAddOnsPath());\n final File[] addOnsList = addOnsDir.listFiles();\n if (addOnsList != null) {\n for (final File addOn : addOnsList) {\n layers.addAddOn(addOn.getName(), addOn, setter);\n }\n }\n }", "private String FCMGetFreshToken(final String senderID) {\n String token = null;\n try {\n if(senderID != null){\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token with Sender Id - \"+senderID);\n token = FirebaseInstanceId.getInstance().getToken(senderID, FirebaseMessaging.INSTANCE_ID_SCOPE);\n }else {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Requesting a FCM token\");\n token = FirebaseInstanceId.getInstance().getToken();\n }\n getConfigLogger().info(getAccountId(),\"FCM token: \"+token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"FcmManager: Error requesting FCM token\", t);\n }\n return token;\n }", "private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}", "public static base_responses update(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 updateresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsip6();\n\t\t\t\tupdateresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tupdateresources[i].td = resources[i].td;\n\t\t\t\tupdateresources[i].nd = resources[i].nd;\n\t\t\t\tupdateresources[i].icmp = resources[i].icmp;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t\tupdateresources[i].telnet = resources[i].telnet;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].gui = resources[i].gui;\n\t\t\t\tupdateresources[i].ssh = resources[i].ssh;\n\t\t\t\tupdateresources[i].snmp = resources[i].snmp;\n\t\t\t\tupdateresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\tupdateresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].map = resources[i].map;\n\t\t\t\tupdateresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\tupdateresources[i].hostroute = resources[i].hostroute;\n\t\t\t\tupdateresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\tupdateresources[i].metric = resources[i].metric;\n\t\t\t\tupdateresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\tupdateresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\tupdateresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Initialize elements from the duration panel.
[ "private void initDurationPanel() {\n\n m_durationPrefixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_PREFIX_0));\n m_durationAfterPostfixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_POSTFIX_0));\n m_seriesEndDate.setDateOnly(true);\n m_seriesEndDate.setAllowInvalidValue(true);\n m_seriesEndDate.setValue(m_model.getSeriesEndDate());\n m_seriesEndDate.getTextField().addFocusHandler(new FocusHandler() {\n\n public void onFocus(FocusEvent event) {\n\n if (handleChange()) {\n onSeriesEndDateFocus(event);\n }\n\n }\n });\n }" ]
[ "public static clusterinstance[] get(nitro_service service) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tclusterinstance[] response = (clusterinstance[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }", "private void setW() {\n if( saveW ) {\n W.col0 = Y.col0;\n W.col1 = Y.col1;\n W.row0 = Y.row0;\n W.row1 = Y.row1;\n } else {\n W.col1 = Y.col1 - Y.col0;\n W.row0 = Y.row0;\n }\n }", "public PeriodicEvent runEvery(Runnable task, float delay, float period) {\n return runEvery(task, delay, period, null);\n }", "@Override\n public HandlerRegistration addSearchNoResultHandler(final SearchNoResultEvent.SearchNoResultHandler handler) {\n return addHandler(handler, SearchNoResultEvent.TYPE);\n }", "private FieldType getFieldType(byte[] data, int offset)\n {\n int fieldIndex = MPPUtility.getInt(data, offset);\n return FieldTypeHelper.mapTextFields(FieldTypeHelper.getInstance14(fieldIndex));\n }", "private void processEncodedPayload() throws IOException {\n if (!readPayload) {\n payloadSpanCollector.reset();\n collect(payloadSpanCollector);\n Collection<byte[]> originalPayloadCollection = payloadSpanCollector\n .getPayloads();\n if (originalPayloadCollection.iterator().hasNext()) {\n byte[] payload = originalPayloadCollection.iterator().next();\n if (payload == null) {\n throw new IOException(\"no payload\");\n }\n MtasPayloadDecoder payloadDecoder = new MtasPayloadDecoder();\n payloadDecoder.init(startPosition(), payload);\n mtasPosition = payloadDecoder.getMtasPosition();\n } else {\n throw new IOException(\"no payload\");\n }\n }\n }", "public CmsScheduledJobInfo getJob(String id) {\n\n Iterator<CmsScheduledJobInfo> it = m_jobs.iterator();\n while (it.hasNext()) {\n CmsScheduledJobInfo job = it.next();\n if (job.getId().equals(id)) {\n return job;\n }\n }\n // not found\n return null;\n }", "int getItemViewType(T content) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n return getItemViewType(prototypeClass);\n }" ]
Gets a single byte return or -1 if no data is available.
[ "public synchronized int get() {\n if (available == 0) {\n return -1;\n }\n byte value = buffer[idxGet];\n idxGet = (idxGet + 1) % capacity;\n available--;\n return value;\n }" ]
[ "public void startAnimation()\n {\n Date time = new Date();\n this.beginAnimation = time.getTime();\n this.endAnimation = beginAnimation + (long) (animationTime * 1000);\n this.animate = true;\n }", "public static vpnsessionaction get(nitro_service service, String name) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tobj.set_name(name);\n\t\tvpnsessionaction response = (vpnsessionaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static <T> Set<T> toSet(Iterable<T> items) {\r\n Set<T> set = new HashSet<T>();\r\n addAll(set, items);\r\n return set;\r\n }", "public static void sendTextEmail(String to, String from, String subject, String msg, final ServerSetup setup) {\r\n sendMimeMessage(createTextEmail(to, from, subject, msg, setup));\r\n }", "public void load(List<E> result) {\n ++pageCount;\n if (this.result == null || this.result.isEmpty()) {\n this.result = result;\n } else {\n this.result.addAll(result);\n }\n }", "public SubReportBuilder setParameterMapPath(String path) {\r\n\t\tsubreport.setParametersExpression(path);\r\n\t\tsubreport.setParametersMapOrigin(DJConstants.SUBREPORT_PARAMETER_MAP_ORIGIN_PARAMETER);\r\n\t\treturn this;\r\n\t}", "public static final BigDecimal printCurrency(Number value)\n {\n return (value == null || value.doubleValue() == 0 ? null : new BigDecimal(value.doubleValue() * 100));\n }", "@Override\n public SuggestAccountsRequest suggestAccounts() throws RestApiException {\n return new SuggestAccountsRequest() {\n @Override\n public List<AccountInfo> get() throws RestApiException {\n return AccountsRestClient.this.suggestAccounts(this);\n }\n };\n }", "private static int getContainerPort(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Port) {\n Port port = (Port) q;\n if (port.value() > 0) {\n return port.value();\n }\n }\n }\n\n ServicePort servicePort = findQualifiedServicePort(service, qualifiers);\n if (servicePort != null) {\n return servicePort.getTargetPort().getIntVal();\n }\n return 0;\n }" ]
This method is called to alert project listeners to the fact that a calendar has been read from a project file. @param calendar calendar instance
[ "public void fireCalendarReadEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarRead(calendar);\n }\n }\n }" ]
[ "public static nssimpleacl[] get(nitro_service service, String aclname[]) throws Exception{\n\t\tif (aclname !=null && aclname.length>0) {\n\t\t\tnssimpleacl response[] = new nssimpleacl[aclname.length];\n\t\t\tnssimpleacl obj[] = new nssimpleacl[aclname.length];\n\t\t\tfor (int i=0;i<aclname.length;i++) {\n\t\t\t\tobj[i] = new nssimpleacl();\n\t\t\t\tobj[i].set_aclname(aclname[i]);\n\t\t\t\tresponse[i] = (nssimpleacl) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public void animate(float animationTime, Matrix4f mat)\n {\n mRotInterpolator.animate(animationTime, mRotKey);\n mPosInterpolator.animate(animationTime, mPosKey);\n mSclInterpolator.animate(animationTime, mScaleKey);\n mat.translationRotateScale(mPosKey[0], mPosKey[1], mPosKey[2], mRotKey[0], mRotKey[1], mRotKey[2], mRotKey[3], mScaleKey[0], mScaleKey[1], mScaleKey[2]);\n\n }", "public static Timer getNamedTimer(String timerName, int todoFlags) {\n\t\treturn getNamedTimer(timerName, todoFlags, Thread.currentThread()\n\t\t\t\t.getId());\n\t}", "public static <T> T[] concat(T[] first, T... second) {\n\t\tint firstLength = first.length;\n\t\tint secondLength = second.length;\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( first.getClass().getComponentType(), firstLength + secondLength );\n\t\tSystem.arraycopy( first, 0, result, 0, firstLength );\n\t\tSystem.arraycopy( second, 0, result, firstLength, secondLength );\n\n\t\treturn result;\n\t}", "@NotNull\n private String getFQName(@NotNull final String localName, Object... params) {\n final StringBuilder builder = new StringBuilder();\n builder.append(storeName);\n builder.append('.');\n builder.append(localName);\n for (final Object param : params) {\n builder.append('#');\n builder.append(param);\n }\n //noinspection ConstantConditions\n return StringInterner.intern(builder.toString());\n }", "public static boolean inArea(Point point, Rect area, float offsetRatio) {\n int offset = (int) (area.width() * offsetRatio);\n return point.x >= area.left - offset && point.x <= area.right + offset &&\n point.y >= area.top - offset && point.y <= area.bottom + offset;\n }", "public void setEnterpriseDuration(int index, Duration value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_DURATION, index), value);\n }", "private void addCriteria(List<GenericCriteria> list, byte[] block)\n {\n byte[] leftBlock = getChildBlock(block);\n byte[] rightBlock1 = getListNextBlock(leftBlock);\n byte[] rightBlock2 = getListNextBlock(rightBlock1);\n TestOperator operator = TestOperator.getInstance(MPPUtility.getShort(block, 0) - 0x3E7);\n FieldType leftValue = getFieldType(leftBlock);\n Object rightValue1 = getValue(leftValue, rightBlock1);\n Object rightValue2 = rightBlock2 == null ? null : getValue(leftValue, rightBlock2);\n\n GenericCriteria criteria = new GenericCriteria(m_properties);\n criteria.setLeftValue(leftValue);\n criteria.setOperator(operator);\n criteria.setRightValue(0, rightValue1);\n criteria.setRightValue(1, rightValue2);\n list.add(criteria);\n\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = leftValue.getFieldTypeClass() == FieldTypeClass.TASK;\n m_criteriaType[1] = !m_criteriaType[0];\n }\n\n if (m_fields != null)\n {\n m_fields.add(leftValue);\n }\n\n processBlock(list, getListNextBlock(block));\n }", "public static void openLogFile(String logPath) {\n\t\tif (logPath == null) {\n\t\t\tprintStream = System.out;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tprintStream = new PrintStream(new File(logPath));\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\tthrow new IllegalArgumentException(\"Log file \" + logPath + \" was not found\", e);\n\t\t\t}\n\t\t}\n\t}" ]
Create a handful of default currencies to keep Primavera happy.
[ "private void writeCurrency()\n {\n ProjectProperties props = m_projectFile.getProjectProperties();\n CurrencyType currency = m_factory.createCurrencyType();\n m_apibo.getCurrency().add(currency);\n\n String positiveSymbol = getCurrencyFormat(props.getSymbolPosition());\n String negativeSymbol = \"(\" + positiveSymbol + \")\";\n\n currency.setDecimalPlaces(props.getCurrencyDigits());\n currency.setDecimalSymbol(getSymbolName(props.getDecimalSeparator()));\n currency.setDigitGroupingSymbol(getSymbolName(props.getThousandsSeparator()));\n currency.setExchangeRate(Double.valueOf(1.0));\n currency.setId(\"CUR\");\n currency.setName(\"Default Currency\");\n currency.setNegativeSymbol(negativeSymbol);\n currency.setObjectId(DEFAULT_CURRENCY_ID);\n currency.setPositiveSymbol(positiveSymbol);\n currency.setSymbol(props.getCurrencySymbol());\n }" ]
[ "@Override\n @SuppressFBWarnings(value = \"UL_UNRELEASED_LOCK\", justification = \"False positive from FindBugs\")\n public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n checkContextInitialized();\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n return null;\n }\n if (contextual == null) {\n throw ContextLogger.LOG.contextualIsNull();\n }\n BeanIdentifier id = getId(contextual);\n ContextualInstance<T> beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n } else if (creationalContext != null) {\n LockedBean lock = null;\n try {\n if (multithreaded) {\n lock = beanStore.lock(id);\n beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n }\n }\n T instance = contextual.create(creationalContext);\n if (instance != null) {\n beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));\n beanStore.put(id, beanInstance);\n }\n return instance;\n } finally {\n if (lock != null) {\n lock.unlock();\n }\n }\n } else {\n return null;\n }\n }", "synchronized boolean reload(int permit, boolean suspend) {\n return internalSetState(new ReloadTask(permit, suspend), InternalState.SERVER_STARTED, InternalState.RELOADING);\n }", "public static int timezoneOffset(H.Session session) {\n String s = null != session ? session.get(SESSION_KEY) : null;\n return S.notBlank(s) ? Integer.parseInt(s) : serverTimezoneOffset();\n }", "public void addFile(String description, FileModel fileModel)\n {\n Map<FileModel, ProblemFileSummary> files = addDescription(description);\n\n if (files.containsKey(fileModel))\n {\n files.get(fileModel).addOccurrence();\n } else {\n files.put(fileModel, new ProblemFileSummary(fileModel, 1));\n }\n }", "public Integer getIdFromName(String profileName) {\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.PROFILE_PROFILE_NAME + \" = ?\");\n query.setString(1, profileName);\n results = query.executeQuery();\n if (results.next()) {\n Object toReturn = results.getObject(Constants.GENERIC_ID);\n query.close();\n return (Integer) toReturn;\n }\n query.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }", "public void seekToHolidayYear(String holidayString, String yearString) {\n Holiday holiday = Holiday.valueOf(holidayString);\n assert(holiday != null);\n \n seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary());\n }", "@Override\n public int getShadowSize() {\n\tElement shadowElement = shadow.getElement();\n\tshadowElement.setScrollTop(10000);\n\treturn shadowElement.getScrollTop();\n }", "public BoxFile.Info getFileInfo(String fileID) {\n URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }", "protected Path createTempDirectory(String prefix) {\n try {\n return Files.createTempDirectory(tempDirectory, prefix);\n } catch (IOException e) {\n throw new AllureCommandException(e);\n }\n }" ]
Converts a vector from eigen space into sample space. @param eigenData Eigen space data. @return Sample space projection.
[ "public double[] eigenToSampleSpace( double[] eigenData ) {\n if( eigenData.length != numComponents )\n throw new IllegalArgumentException(\"Unexpected sample length\");\n\n DMatrixRMaj s = new DMatrixRMaj(A.getNumCols(),1);\n DMatrixRMaj r = DMatrixRMaj.wrap(numComponents,1,eigenData);\n \n CommonOps_DDRM.multTransA(V_t,r,s);\n\n DMatrixRMaj mean = DMatrixRMaj.wrap(A.getNumCols(),1,this.mean);\n CommonOps_DDRM.add(s,mean,s);\n\n return s.data;\n }" ]
[ "protected boolean equivalentClaims(Claim claim1, Claim claim2) {\n\t\treturn claim1.getMainSnak().equals(claim2.getMainSnak())\n\t\t\t\t&& isSameSnakSet(claim1.getAllQualifiers(),\n\t\t\t\t\t\tclaim2.getAllQualifiers());\n\t}", "public static void validate(final Module module) {\n if (null == module) {\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module cannot be null!\")\n .build());\n }\n if(module.getName() == null ||\n module.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module name cannot be null or empty!\")\n .build());\n }\n if(module.getVersion()== null ||\n module.getVersion().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module version cannot be null or empty!\")\n .build());\n }\n\n // Check artifacts\n for(final Artifact artifact: DataUtils.getAllArtifacts(module)){\n validate(artifact);\n }\n\n // Check dependencies\n for(final Dependency dependency: DataUtils.getAllDependencies(module)){\n validate(dependency.getTarget());\n }\n }", "protected final ByteBuffer parseContent(ByteBuffer in) throws BaseExceptions.ParserException {\n if (contentComplete()) {\n throw new BaseExceptions.InvalidState(\"content already complete: \" + _endOfContent);\n } else {\n switch (_endOfContent) {\n case UNKNOWN_CONTENT:\n // This makes sense only for response parsing. Requests must always have\n // either Content-Length or Transfer-Encoding\n\n _endOfContent = EndOfContent.EOF_CONTENT;\n _contentLength = Long.MAX_VALUE; // Its up to the user to limit a body size\n return parseContent(in);\n\n case CONTENT_LENGTH:\n case EOF_CONTENT:\n return nonChunkedContent(in);\n\n case CHUNKED_CONTENT:\n return chunkedContent(in);\n\n default:\n throw new BaseExceptions.InvalidState(\"not implemented: \" + _endOfContent);\n }\n }\n }", "public static lbvserver_servicegroup_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_servicegroup_binding obj = new lbvserver_servicegroup_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_servicegroup_binding response[] = (lbvserver_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public String[] parseMFString(String mfString) {\n Vector<String> strings = new Vector<String>();\n\n StringReader sr = new StringReader(mfString);\n StreamTokenizer st = new StreamTokenizer(sr);\n st.quoteChar('\"');\n st.quoteChar('\\'');\n String[] mfStrings = null;\n\n int tokenType;\n try {\n while ((tokenType = st.nextToken()) != StreamTokenizer.TT_EOF) {\n\n strings.add(st.sval);\n\n }\n } catch (IOException e) {\n\n Log.d(TAG, \"String parsing Error: \" + e);\n\n e.printStackTrace();\n }\n mfStrings = new String[strings.size()];\n for (int i = 0; i < strings.size(); i++) {\n mfStrings[i] = strings.get(i);\n }\n return mfStrings;\n }", "public static String stringifyJavascriptObject(Object object) {\n StringBuilder bld = new StringBuilder();\n stringify(object, bld);\n return bld.toString();\n }", "private int[] convertBatch(int[] batch) {\n int[] conv = new int[batch.length];\n for (int i=0; i<batch.length; i++) {\n conv[i] = sample[batch[i]];\n }\n return conv;\n }", "public static <K,V> Map<K,V> asImmutable(Map<? extends K, ? extends V> self) {\n return Collections.unmodifiableMap(self);\n }", "@SuppressWarnings(\"deprecation\")\n protected ModelNode executeReadOnlyOperation(final ModelNode operation, final OperationMessageHandler handler, final OperationTransactionControl control, final OperationStepHandler prepareStep, final int operationId) {\n final AbstractOperationContext delegateContext = getDelegateContext(operationId);\n CurrentOperationIdHolder.setCurrentOperationID(operationId);\n try {\n return executeReadOnlyOperation(operation, delegateContext.getManagementModel(), control, prepareStep, delegateContext);\n } finally {\n CurrentOperationIdHolder.setCurrentOperationID(null);\n }\n }" ]
Button onClick listener. @param v
[ "public void buttonClick(View v) {\n switch (v.getId()) {\n case R.id.show:\n showAppMsg();\n break;\n case R.id.cancel_all:\n AppMsg.cancelAll(this);\n break;\n default:\n return;\n }\n }" ]
[ "public void removeFile(String name) {\n if(files.containsKey(name)) {\n files.remove(name);\n }\n\n if(fileStreams.containsKey(name)) {\n fileStreams.remove(name);\n }\n }", "public PreparedStatement getDeleteStatement(ClassDescriptor cld) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cld.getStatementsForClass(m_conMan).getDeleteStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }", "@RequestMapping(value = \"/api/profile\", method = RequestMethod.DELETE)\n public\n @ResponseBody\n HashMap<String, Object> deleteProfile(Model model, int id) throws Exception {\n profileService.remove(id);\n return Utils.getJQGridJSON(profileService.findAllProfiles(), \"profiles\");\n }", "public ResponseFromManager generateUpdateExecuteTask(ParallelTask task) {\n\n // add to map now; as can only pass final\n ParallelTaskManager.getInstance().addTaskToInProgressMap(\n task.getTaskId(), task);\n logger.info(\"Added task {} to the running inprogress map...\",\n task.getTaskId());\n\n boolean useReplacementVarMap = false;\n boolean useReplacementVarMapNodeSpecific = false;\n Map<String, StrStrMap> replacementVarMapNodeSpecific = null;\n Map<String, String> replacementVarMap = null;\n\n ResponseFromManager batchResponseFromManager = null;\n\n switch (task.getRequestReplacementType()) {\n case UNIFORM_VAR_REPLACEMENT:\n useReplacementVarMap = true;\n useReplacementVarMapNodeSpecific = false;\n replacementVarMap = task.getReplacementVarMap();\n break;\n case TARGET_HOST_SPECIFIC_VAR_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = true;\n replacementVarMapNodeSpecific = task\n .getReplacementVarMapNodeSpecific();\n break;\n case NO_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = false;\n break;\n default:\n logger.error(\"error request replacement type. default as no replacement\");\n }// end switch\n\n // generate content in nodedata\n InternalDataProvider dp = InternalDataProvider.getInstance();\n dp.genNodeDataMap(task);\n\n VarReplacementProvider.getInstance()\n .updateRequestWithReplacement(task, useReplacementVarMap,\n replacementVarMap, useReplacementVarMapNodeSpecific,\n replacementVarMapNodeSpecific);\n\n batchResponseFromManager = \n sendTaskToExecutionManager(task);\n\n removeTaskFromInProgressMap(task.getTaskId());\n logger.info(\n \"Removed task {} from the running inprogress map... \"\n + \". This task should be garbage collected if there are no other pointers.\",\n task.getTaskId());\n return batchResponseFromManager;\n\n }", "public final void setHost(final String host) throws UnknownHostException {\n this.host = host;\n final InetAddress[] inetAddresses = InetAddress.getAllByName(host);\n\n for (InetAddress address: inetAddresses) {\n final AddressHostMatcher matcher = new AddressHostMatcher();\n matcher.setIp(address.getHostAddress());\n this.matchersForHost.add(matcher);\n }\n }", "public static Set<Dependency> getAllDependencies(final Module module, final List<String> producedArtifacts) {\n final Set<Dependency> dependencies = new HashSet<Dependency>();\n\n for(final Dependency dependency: module.getDependencies()){\n if(!producedArtifacts.contains(dependency.getTarget().getGavc())){\n dependencies.add(dependency);\n }\n }\n\n for(final Module subModule: module.getSubmodules()){\n dependencies.addAll(getAllDependencies(subModule, producedArtifacts));\n }\n\n return dependencies;\n }", "public OJBLock atomicGetOrCreateLock(Object resourceId, Object isolationId)\r\n {\r\n synchronized(globalLocks)\r\n {\r\n MultiLevelLock lock = getLock(resourceId);\r\n if(lock == null)\r\n {\r\n lock = createLock(resourceId, isolationId);\r\n }\r\n return (OJBLock) lock;\r\n }\r\n }", "private static void query(String filename) throws Exception\n {\n ProjectFile mpx = new UniversalProjectReader().read(filename);\n\n listProjectProperties(mpx);\n\n listResources(mpx);\n\n listTasks(mpx);\n\n listAssignments(mpx);\n\n listAssignmentsByTask(mpx);\n\n listAssignmentsByResource(mpx);\n\n listHierarchy(mpx);\n\n listTaskNotes(mpx);\n\n listResourceNotes(mpx);\n\n listRelationships(mpx);\n\n listSlack(mpx);\n\n listCalendars(mpx);\n\n }", "public Map<String,Object> getAttributeValues()\n throws AttributeNotFoundException, InstanceNotFoundException, ReflectionException {\n\n HashSet<String> attributeSet = new HashSet<String>();\n\n for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {\n attributeSet.add(attributeInfo.getName());\n }\n\n AttributeList attributeList =\n mBeanServer.getAttributes(objectName, attributeSet.toArray(new String[attributeSet.size()]));\n\n Map<String, Object> attributeValueMap = new TreeMap<String, Object>();\n for (Attribute attribute : attributeList.asList()) {\n attributeValueMap.put(attribute.getName(), sanitizer.escapeValue(attribute.getValue()));\n }\n\n return attributeValueMap;\n }" ]
Promote a module in the Grapes server @param name @param version @throws GrapesCommunicationException @throws javax.naming.AuthenticationException
[ "public void promoteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.promoteModulePath(name, version));\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"promote module\", name, version);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }" ]
[ "private void executeBatch(int batchId, final RebalanceBatchPlan batchPlan) {\n final Cluster batchCurrentCluster = batchPlan.getCurrentCluster();\n final List<StoreDefinition> batchCurrentStoreDefs = batchPlan.getCurrentStoreDefs();\n final Cluster batchFinalCluster = batchPlan.getFinalCluster();\n final List<StoreDefinition> batchFinalStoreDefs = batchPlan.getFinalStoreDefs();\n\n try {\n final List<RebalanceTaskInfo> rebalanceTaskInfoList = batchPlan.getBatchPlan();\n\n if(rebalanceTaskInfoList.isEmpty()) {\n RebalanceUtils.printBatchLog(batchId, logger, \"Skipping batch \"\n + batchId + \" since it is empty.\");\n // Even though there is no rebalancing work to do, cluster\n // metadata must be updated so that the server is aware of the\n // new cluster xml.\n adminClient.rebalanceOps.rebalanceStateChange(batchCurrentCluster,\n batchFinalCluster,\n batchCurrentStoreDefs,\n batchFinalStoreDefs,\n rebalanceTaskInfoList,\n false,\n true,\n false,\n false,\n true);\n return;\n }\n\n RebalanceUtils.printBatchLog(batchId, logger, \"Starting batch \"\n + batchId + \".\");\n\n // Split the store definitions\n List<StoreDefinition> readOnlyStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n true);\n List<StoreDefinition> readWriteStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n false);\n boolean hasReadOnlyStores = readOnlyStoreDefs != null\n && readOnlyStoreDefs.size() > 0;\n boolean hasReadWriteStores = readWriteStoreDefs != null\n && readWriteStoreDefs.size() > 0;\n\n // STEP 1 - Cluster state change\n boolean finishedReadOnlyPhase = false;\n List<RebalanceTaskInfo> filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readOnlyStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 2 - Move RO data\n if(hasReadOnlyStores) {\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n // STEP 3 - Cluster change state\n finishedReadOnlyPhase = true;\n filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readWriteStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 4 - Move RW data\n if(hasReadWriteStores) {\n proxyPause();\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Successfully terminated batch \"\n + batchId + \".\");\n\n } catch(Exception e) {\n RebalanceUtils.printErrorLog(batchId, logger, \"Error in batch \"\n + batchId + \" - \" + e.getMessage(), e);\n throw new VoldemortException(\"Rebalance failed on batch \" + batchId,\n e);\n }\n }", "@SuppressWarnings(\"deprecation\")\n public BUILDER addAccessConstraint(final AccessConstraintDefinition accessConstraint) {\n if (accessConstraints == null) {\n accessConstraints = new AccessConstraintDefinition[] {accessConstraint};\n } else {\n accessConstraints = Arrays.copyOf(accessConstraints, accessConstraints.length + 1);\n accessConstraints[accessConstraints.length - 1] = accessConstraint;\n }\n return (BUILDER) this;\n }", "private void handleGlobalArguments(CommandLine cmd) {\n\t\tif (cmd.hasOption(CMD_OPTION_DUMP_LOCATION)) {\n\t\t\tthis.dumpDirectoryLocation = cmd\n\t\t\t\t\t.getOptionValue(CMD_OPTION_DUMP_LOCATION);\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_OFFLINE_MODE)) {\n\t\t\tthis.offlineMode = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_QUIET)) {\n\t\t\tthis.quiet = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CREATE_REPORT)) {\n\t\t\tthis.reportFilename = cmd.getOptionValue(CMD_OPTION_CREATE_REPORT);\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_LANGUAGES)) {\n\t\t\tsetLanguageFilters(cmd.getOptionValue(OPTION_FILTER_LANGUAGES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_SITES)) {\n\t\t\tsetSiteFilters(cmd.getOptionValue(OPTION_FILTER_SITES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_PROPERTIES)) {\n\t\t\tsetPropertyFilters(cmd.getOptionValue(OPTION_FILTER_PROPERTIES));\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_LOCAL_DUMPFILE)) {\n\t\t\tthis.inputDumpLocation = cmd.getOptionValue(OPTION_LOCAL_DUMPFILE);\n\t\t}\n\t}", "public static Iterable<Metadata> getAllMetadata(BoxItem item, String ... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new BoxResourceIterable<Metadata>(\n item.getAPI(),\n GET_ALL_METADATA_URL_TEMPLATE.buildWithQuery(item.getItemURL().toString(), builder.toString()),\n DEFAULT_LIMIT) {\n\n @Override\n protected Metadata factory(JsonObject jsonObject) {\n return new Metadata(jsonObject);\n }\n\n };\n }", "public void emitEvent(\n final NamespaceSynchronizationConfig nsConfig,\n final ChangeEvent<BsonDocument> event) {\n listenersLock.lock();\n try {\n if (nsConfig.getNamespaceListenerConfig() == null) {\n return;\n }\n final NamespaceListenerConfig namespaceListener =\n nsConfig.getNamespaceListenerConfig();\n eventDispatcher.dispatch(() -> {\n try {\n if (namespaceListener.getEventListener() != null) {\n namespaceListener.getEventListener().onEvent(\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ChangeEvents.transformChangeEventForUser(\n event, namespaceListener.getDocumentCodec()));\n }\n } catch (final Exception ex) {\n logger.error(String.format(\n Locale.US,\n \"emitEvent ns=%s documentId=%s emit exception: %s\",\n event.getNamespace(),\n BsonUtils.getDocumentId(event.getDocumentKey()),\n ex), ex);\n }\n return null;\n });\n } finally {\n listenersLock.unlock();\n }\n }", "public static<T> Vendor<T> vendor(Callable<T> f) {\n\treturn j.vendor(f);\n }", "public void addImportedPackages(String... importedPackages) {\n\t\tString oldBundles = mainAttributes.get(IMPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : importedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(IMPORT_PACKAGE, result);\n\t}", "public String getStatement() throws SQLException {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendSql(null, sb, new ArrayList<ArgumentHolder>());\n\t\treturn sb.toString();\n\t}", "@Override\n\tpublic String toNormalizedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.normalizedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.normalizedString = result = toNormalizedString(IPv6StringCache.normalizedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toNormalizedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}" ]
Sets the SCXML model with an InputStream @param inputFileStream the model input stream
[ "public void setModelByInputFileStream(InputStream inputFileStream) {\r\n try {\r\n this.model = SCXMLParser.parse(new InputSource(inputFileStream), null, customActionsFromTagExtensions());\r\n this.setStateMachine(this.model);\r\n } catch (IOException | SAXException | ModelException e) {\r\n e.printStackTrace();\r\n }\r\n }" ]
[ "public static void validate(final Module module) {\n if (null == module) {\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module cannot be null!\")\n .build());\n }\n if(module.getName() == null ||\n module.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module name cannot be null or empty!\")\n .build());\n }\n if(module.getVersion()== null ||\n module.getVersion().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Module version cannot be null or empty!\")\n .build());\n }\n\n // Check artifacts\n for(final Artifact artifact: DataUtils.getAllArtifacts(module)){\n validate(artifact);\n }\n\n // Check dependencies\n for(final Dependency dependency: DataUtils.getAllDependencies(module)){\n validate(dependency.getTarget());\n }\n }", "public static float noise1(float x) {\n int bx0, bx1;\n float rx0, rx1, sx, t, u, v;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n sx = sCurve(rx0);\n\n u = rx0 * g1[p[bx0]];\n v = rx1 * g1[p[bx1]];\n return 2.3f*lerp(sx, u, v);\n }", "@Nullable\n public Boolean getBoolean(@Nonnull final String key) {\n return (Boolean) this.values.get(key);\n }", "private static boolean syncWithMaster(final Resource domain, final PathElement hostElement) {\n final Resource host = domain.getChild(hostElement);\n assert host != null;\n\n final Set<String> profiles = new HashSet<>();\n final Set<String> serverGroups = new HashSet<>();\n final Set<String> socketBindings = new HashSet<>();\n\n for (final Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {\n final ModelNode model = serverConfig.getModel();\n final String group = model.require(GROUP).asString();\n if (!serverGroups.contains(group)) {\n serverGroups.add(group);\n }\n if (model.hasDefined(SOCKET_BINDING_GROUP)) {\n processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings);\n }\n\n }\n\n // process referenced server-groups\n for (final Resource.ResourceEntry serverGroup : domain.getChildren(SERVER_GROUP)) {\n // If we have an unreferenced server-group\n if (!serverGroups.remove(serverGroup.getName())) {\n return true;\n }\n final ModelNode model = serverGroup.getModel();\n\n final String profile = model.require(PROFILE).asString();\n // Process the profile\n processProfile(domain, profile, profiles);\n // Process the socket-binding-group\n processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings);\n }\n // If we are missing a server group\n if (!serverGroups.isEmpty()) {\n return true;\n }\n // Process profiles\n for (final Resource.ResourceEntry profile : domain.getChildren(PROFILE)) {\n // We have an unreferenced profile\n if (!profiles.remove(profile.getName())) {\n return true;\n }\n }\n // We are missing a profile\n if (!profiles.isEmpty()) {\n return true;\n }\n // Process socket-binding groups\n for (final Resource.ResourceEntry socketBindingGroup : domain.getChildren(SOCKET_BINDING_GROUP)) {\n // We have an unreferenced socket-binding group\n if (!socketBindings.remove(socketBindingGroup.getName())) {\n return true;\n }\n }\n // We are missing a socket-binding group\n if (!socketBindings.isEmpty()) {\n return true;\n }\n // Looks good!\n return false;\n }", "public T update(T entity) throws RowNotFoundException, OptimisticLockException {\n\n if (!hasPrimaryKey(entity)) {\n throw new RuntimeException(String.format(\"Tried to update entity of type %s without a primary key\", entity\n .getClass().getSimpleName()));\n }\n\n UpdateCreator update = new UpdateCreator(table);\n\n update.whereEquals(idColumn.getColumnName(), getPrimaryKey(entity));\n\n if (versionColumn != null) {\n update.set(versionColumn.getColumnName() + \" = \" + versionColumn.getColumnName() + \" + 1\");\n update.whereEquals(versionColumn.getColumnName(), getVersion(entity));\n }\n\n for (Column column : columns) {\n if (!column.isReadOnly()) {\n update.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));\n }\n }\n\n int rows = new JdbcTemplate(ormConfig.getDataSource()).update(update);\n\n if (rows == 1) {\n\n if (versionColumn != null) {\n ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), getVersion(entity) + 1);\n }\n\n return entity;\n\n } else if (rows > 1) {\n\n throw new RuntimeException(\n String.format(\"Updating table %s with id %s updated %d rows. There must be a mapping problem. Is column %s really the primary key?\",\n table, getPrimaryKey(entity), rows, idColumn));\n\n } else {\n\n //\n // Updated zero rows. This could be because our ID is wrong, or\n // because our object is out-of date. Let's try querying just by ID.\n //\n\n SelectCreator selectById = new SelectCreator()\n .column(\"count(*)\")\n .from(table)\n .whereEquals(idColumn.getColumnName(), getPrimaryKey(entity));\n\n rows = new JdbcTemplate(ormConfig.getDataSource()).query(selectById, new ResultSetExtractor<Integer>() {\n @Override\n public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {\n rs.next();\n return rs.getInt(1);\n }\n });\n\n if (rows == 0) {\n throw new RowNotFoundException(table, getPrimaryKey(entity));\n } else {\n throw new OptimisticLockException(table, getPrimaryKey(entity));\n }\n }\n }", "private void writeUserFieldDefinitions()\n {\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n if (cf.getFieldType() != null && cf.getFieldType().getDataType() != null)\n {\n UDFTypeType udf = m_factory.createUDFTypeType();\n udf.setObjectId(Integer.valueOf(FieldTypeHelper.getFieldID(cf.getFieldType())));\n\n udf.setDataType(UserFieldDataType.inferUserFieldDataType(cf.getFieldType().getDataType()));\n udf.setSubjectArea(UserFieldDataType.inferUserFieldSubjectArea(cf.getFieldType()));\n udf.setTitle(cf.getAlias());\n m_apibo.getUDFType().add(udf);\n }\n }\n }", "public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength);\n recordResourceRequestQueueLength(null, queueLength);\n } else {\n this.resourceRequestQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }", "public static Broker createBroker(int id, String brokerInfoString) {\n String[] brokerInfo = brokerInfoString.split(\":\");\n String creator = brokerInfo[0].replace('#', ':');\n String hostname = brokerInfo[1].replace('#', ':');\n String port = brokerInfo[2];\n boolean autocreated = Boolean.valueOf(brokerInfo.length > 3 ? brokerInfo[3] : \"true\");\n return new Broker(id, creator, hostname, Integer.parseInt(port), autocreated);\n }", "public static cmppolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_policybinding_binding obj = new cmppolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_policybinding_binding response[] = (cmppolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Login for a specific authentication, creating a specific token if given. @param token token to use @param authentication authentication to assign to token @return token
[ "public String login(String token, Authentication authentication) {\n\t\tif (null == token) {\n\t\t\treturn login(authentication);\n\t\t}\n\t\ttokens.put(token, new TokenContainer(authentication));\n\t\treturn token;\n\t}" ]
[ "protected void mergeImmutableContainerTypesFrom(Configuration otherConfiguration) {\r\n Set<Dotted> union =\r\n Sets.union(hardcodedImmutableContainerClasses.build(), otherConfiguration.immutableContainerClasses());\r\n\r\n hardcodedImmutableContainerClasses = ImmutableSet.<Dotted>builder().addAll(union);\r\n }", "private static final void writeJson(Writer os, //\n Object object, //\n SerializeConfig config, //\n SerializeFilter[] filters, //\n DateFormat dateFormat, //\n int defaultFeatures, //\n SerializerFeature... features) {\n SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features);\n\n try {\n JSONSerializer serializer = new JSONSerializer(writer, config);\n\n if (dateFormat != null) {\n serializer.setDateFormat(dateFormat);\n serializer.config(SerializerFeature.WriteDateUseDateFormat, true);\n }\n\n if (filters != null) {\n for (SerializeFilter filter : filters) {\n serializer.addFilter(filter);\n }\n }\n serializer.write(object);\n } finally {\n writer.close();\n }\n }", "private double u_neg_inf(double x, double tau) {\n\t\treturn f(boundaryCondition.getValueAtLowerBoundary(model, f_t(tau), f_s(x)), x, tau);\n\t}", "public double getValue(double x)\n\t{\n\t\tsynchronized(interpolatingRationalFunctionsLazyInitLock) {\n\t\t\tif(interpolatingRationalFunctions == null) {\n\t\t\t\tdoCreateRationalFunctions();\n\t\t\t}\n\t\t}\n\n\t\t// Get interpolating rational function for the given point x\n\t\tint pointIndex = java.util.Arrays.binarySearch(points, x);\n\t\tif(pointIndex >= 0) {\n\t\t\treturn values[pointIndex];\n\t\t}\n\n\t\tint intervallIndex = -pointIndex-2;\n\n\t\t// Check for extrapolation\n\t\tif(intervallIndex < 0) {\n\t\t\t// Extrapolation\n\t\t\tif(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) {\n\t\t\t\treturn values[0];\n\t\t\t} else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) {\n\t\t\t\treturn values[0]+(values[1]-values[0])/(points[1]-points[0])*(x-points[0]);\n\t\t\t} else {\n\t\t\t\tintervallIndex = 0;\n\t\t\t}\n\t\t}\n\t\telse if(intervallIndex > points.length-2) {\n\t\t\t// Extrapolation\n\t\t\tif(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) {\n\t\t\t\treturn values[points.length-1];\n\t\t\t} else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) {\n\t\t\t\treturn values[points.length-1]+(values[points.length-2]-values[points.length-1])/(points[points.length-2]-points[points.length-1])*(x-points[points.length-1]);\n\t\t\t} else {\n\t\t\t\tintervallIndex = points.length-2;\n\t\t\t}\n\t\t}\n\n\t\tRationalFunction rationalFunction = interpolatingRationalFunctions[intervallIndex];\n\n\t\t// Calculate interpolating value\n\t\treturn rationalFunction.getValue(x-points[intervallIndex]);\n\t}", "public void addProfile(Object key, DescriptorRepository repository)\r\n {\r\n if (metadataProfiles.contains(key))\r\n {\r\n throw new MetadataException(\"Duplicate profile key. Key '\" + key + \"' already exists.\");\r\n }\r\n metadataProfiles.put(key, repository);\r\n }", "public boolean overrides(Link other) {\n if (other.getStatus() == LinkStatus.ASSERTED &&\n status != LinkStatus.ASSERTED)\n return false;\n else if (status == LinkStatus.ASSERTED &&\n other.getStatus() != LinkStatus.ASSERTED)\n return true;\n\n // the two links are from equivalent sources of information, so we\n // believe the most recent\n\n return timestamp > other.getTimestamp();\n }", "public StandaloneCommandBuilder addSecurityProperty(final String key, final String value) {\n securityProperties.put(key, value);\n return this;\n }", "public void visitMethodInsn(int opcode, String owner, String name,\n String desc, boolean itf) {\n if (mv != null) {\n mv.visitMethodInsn(opcode, owner, name, desc, itf);\n }\n }", "public static base_responses update(nitro_service client, responderpolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tresponderpolicy updateresources[] = new responderpolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new responderpolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].undefaction = resources[i].undefaction;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].logaction = resources[i].logaction;\n\t\t\t\tupdateresources[i].appflowaction = resources[i].appflowaction;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Performs the closure within a transaction using a cached connection. If the closure takes a single argument, it will be called with the connection, otherwise it will be called with no arguments. @param closure the given closure @throws SQLException if a database error occurs
[ "public synchronized void withTransaction(Closure closure) throws SQLException {\n boolean savedCacheConnection = cacheConnection;\n cacheConnection = true;\n Connection connection = null;\n boolean savedAutoCommit = true;\n try {\n connection = createConnection();\n savedAutoCommit = connection.getAutoCommit();\n connection.setAutoCommit(false);\n callClosurePossiblyWithConnection(closure, connection);\n connection.commit();\n } catch (SQLException e) {\n handleError(connection, e);\n throw e;\n } catch (RuntimeException e) {\n handleError(connection, e);\n throw e;\n } catch (Error e) {\n handleError(connection, e);\n throw e;\n } catch (Exception e) {\n handleError(connection, e);\n throw new SQLException(\"Unexpected exception during transaction\", e);\n } finally {\n if (connection != null) {\n try {\n connection.setAutoCommit(savedAutoCommit);\n }\n catch (SQLException e) {\n LOG.finest(\"Caught exception resetting auto commit: \" + e.getMessage() + \" - continuing\");\n }\n }\n cacheConnection = false;\n closeResources(connection, null);\n cacheConnection = savedCacheConnection;\n if (dataSource != null && !cacheConnection) {\n useConnection = null;\n }\n }\n }" ]
[ "public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,\n TimeUnit timeUnit)\n throws InterruptedException {\n long timeoutMs = timeUnit.toMillis(timeout);\n long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;\n while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {\n long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());\n if(logger.isDebugEnabled()) {\n logger.debug(\"Start waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n this.wait(remainingMs);\n if(logger.isDebugEnabled()) {\n logger.debug(\"End waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n }\n return responseQueue.poll();\n }", "final public void setRealOffset(Integer start, Integer end) {\n if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\n \"Start real offset after end real offset\");\n } else {\n tokenRealOffset = new MtasOffset(start, end);\n }\n }", "synchronized public void completeTask(int taskId, int partitionStoresMigrated) {\n tasksInFlight.remove(taskId);\n\n numTasksCompleted++;\n numPartitionStoresMigrated += partitionStoresMigrated;\n\n updateProgressBar();\n }", "public ItemRequest<Section> createInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }", "public static final BigInteger printEarnedValueMethod(EarnedValueMethod value)\n {\n return (value == null ? BigInteger.valueOf(EarnedValueMethod.PERCENT_COMPLETE.getValue()) : BigInteger.valueOf(value.getValue()));\n }", "public void setValue(Quaternionf rot) {\n mX = rot.x;\n mY = rot.y;\n mZ = rot.z;\n mW = rot.w;\n }", "private void readResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n for (Project.Resources.Resource.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n ResourceField mpxFieldID = MPPResourceField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }", "public static float calcDet(Vector3 a ,Vector3 b, Vector3 c) {\n\t\treturn (a.x*(b.y-c.y)) - (a.y*(b.x-c.x)) + (b.x*c.y-b.y*c.x);\n\t}", "public void addProjectListeners(List<ProjectListener> listeners)\n {\n if (listeners != null)\n {\n for (ProjectListener listener : listeners)\n {\n addProjectListener(listener);\n }\n }\n }" ]
Returns the value of the matrix at the specified index of the 1D row major array. @see DMatrixRMaj#get(int) @param index The element's index whose value is to be returned @return The value of the specified element.
[ "public double get( int index ) {\n MatrixType type = mat.getType();\n\n if( type.isReal()) {\n if (type.getBits() == 64) {\n return ((DMatrixRMaj) mat).data[index];\n } else {\n return ((FMatrixRMaj) mat).data[index];\n }\n } else {\n throw new IllegalArgumentException(\"Complex matrix. Call get(int,Complex64F) instead\");\n }\n }" ]
[ "public static appfwprofile_safeobject_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_safeobject_binding obj = new appfwprofile_safeobject_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_safeobject_binding response[] = (appfwprofile_safeobject_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void appendLikeCriteria(TableAlias alias, PathInfo pathInfo, LikeCriteria c, StringBuffer buf)\r\n {\r\n appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);\r\n buf.append(c.getClause());\r\n appendParameter(c.getValue(), buf);\r\n\r\n buf.append(m_platform.getEscapeClause(c));\r\n }", "public void postConstruct(GeoService geoService, DtoConverterService converterService) throws GeomajasException {\n\t\tif (null == layerInfo) {\n\t\t\tlayerInfo = new RasterLayerInfo();\n\t\t}\n\t\tlayerInfo.setCrs(TiledRasterLayerService.MERCATOR);\n\t\tcrs = geoService.getCrs2(TiledRasterLayerService.MERCATOR);\n\t\tlayerInfo.setTileWidth(tileSize);\n\t\tlayerInfo.setTileHeight(tileSize);\n\t\tBbox bbox = new Bbox(-TiledRasterLayerService.HALF_EQUATOR_IN_METERS,\n\t\t\t\t-TiledRasterLayerService.HALF_EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS,\n\t\t\t\tTiledRasterLayerService.EQUATOR_IN_METERS);\n\t\tlayerInfo.setMaxExtent(bbox);\n\t\tmaxBounds = converterService.toInternal(bbox);\n\n\t\tresolutions = new double[maxZoomLevel + 1];\n\t\tdouble powerOfTwo = 1;\n\t\tfor (int zoomLevel = 0; zoomLevel <= maxZoomLevel; zoomLevel++) {\n\t\t\tdouble resolution = (TiledRasterLayerService.EQUATOR_IN_METERS) / (tileSize * powerOfTwo);\n\t\t\tresolutions[zoomLevel] = resolution;\n\t\t\tpowerOfTwo *= 2;\n\t\t}\n\t}", "private void updateWorkTimeUnit(FastTrackColumn column)\n {\n if (m_workTimeUnit == null && isWorkColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_workTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }", "public static base_response add(nitro_service client, cmppolicylabel resource) throws Exception {\n\t\tcmppolicylabel addresource = new cmppolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.type = resource.type;\n\t\treturn addresource.add_resource(client);\n\t}", "public static csvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_spilloverpolicy_binding obj = new csvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_spilloverpolicy_binding response[] = (csvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static List<ContentRepositoryElement> listFiles(final Path rootPath, Path tempDir, final ContentFilter filter) throws IOException {\n List<ContentRepositoryElement> result = new ArrayList<>();\n if (Files.exists(rootPath)) {\n if(isArchive(rootPath)) {\n return listZipContent(rootPath, filter);\n }\n Files.walkFileTree(rootPath, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n if (filter.acceptFile(rootPath, file)) {\n result.add(ContentRepositoryElement.createFile(formatPath(rootPath.relativize(file)), Files.size(file)));\n }\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n if (filter.acceptDirectory(rootPath, dir)) {\n String directoryPath = formatDirectoryPath(rootPath.relativize(dir));\n if(! \"/\".equals(directoryPath)) {\n result.add(ContentRepositoryElement.createFolder(directoryPath));\n }\n }\n return FileVisitResult.CONTINUE;\n }\n\n private String formatDirectoryPath(Path path) {\n return formatPath(path) + '/';\n }\n\n private String formatPath(Path path) {\n return path.toString().replace(File.separatorChar, '/');\n }\n });\n } else {\n Path file = getFile(rootPath);\n if(isArchive(file)) {\n Path relativePath = file.relativize(rootPath);\n Path target = createTempDirectory(tempDir, \"unarchive\");\n unzip(file, target);\n return listFiles(target.resolve(relativePath), tempDir, filter);\n } else {\n throw new FileNotFoundException(rootPath.toString());\n }\n }\n return result;\n }", "public static final PatchOperationTarget createLocal(final File jbossHome, List<File> moduleRoots, List<File> bundlesRoots) throws IOException {\n final PatchTool tool = PatchTool.Factory.createLocalTool(jbossHome, moduleRoots, bundlesRoots);\n return new LocalPatchOperationTarget(tool);\n }", "static void handleNotificationClicked(Context context,Bundle notification) {\n if (notification == null) return;\n\n String _accountId = null;\n try {\n _accountId = notification.getString(Constants.WZRK_ACCT_ID_KEY);\n } catch (Throwable t) {\n // no-op\n }\n\n if (instances == null) {\n CleverTapAPI instance = createInstanceIfAvailable(context, _accountId);\n if (instance != null) {\n instance.pushNotificationClickedEvent(notification);\n }\n return;\n }\n\n for (String accountId: instances.keySet()) {\n CleverTapAPI instance = CleverTapAPI.instances.get(accountId);\n boolean shouldProcess = false;\n if (instance != null) {\n shouldProcess = (_accountId == null && instance.config.isDefaultInstance()) || instance.getAccountId().equals(_accountId);\n }\n if (shouldProcess) {\n instance.pushNotificationClickedEvent(notification);\n break;\n }\n }\n }" ]
Finds the parent group of the given one and returns it @param group Group for which the parent is needed @return The parent group of the given one. If the given one is the first one, it returns the same group
[ "protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\n }" ]
[ "public IndexDef getIndex(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n IndexDef def = null;\r\n\r\n for (Iterator it = getIndices(); it.hasNext();)\r\n {\r\n def = (IndexDef)it.next();\r\n if (def.getName().equals(realName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }", "public static boolean isFormatCorrect(String fileName, ReadOnlyStorageFormat format) {\n switch(format) {\n case READONLY_V0:\n case READONLY_V1:\n if(fileName.matches(\"^[\\\\d]+_[\\\\d]+\\\\.(data|index)\")) {\n return true;\n } else {\n return false;\n }\n\n case READONLY_V2:\n if(fileName.matches(\"^[\\\\d]+_[\\\\d]+_[\\\\d]+\\\\.(data|index)\")) {\n return true;\n } else {\n return false;\n }\n\n default:\n throw new VoldemortException(\"Format type not supported\");\n }\n }", "public Optional<ServerPort> activePort() {\n final Server server = this.server;\n return server != null ? server.activePort() : Optional.empty();\n }", "public void fireAssignmentReadEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentRead(resourceAssignment);\n }\n }\n }", "public static boolean isMessageContentToBeLogged(final Message message, final boolean logMessageContent,\n boolean logMessageContentOverride) {\n\n /*\n * If controlling of logging behavior is not allowed externally\n * then log according to global property value\n */\n if (!logMessageContentOverride) {\n return logMessageContent;\n }\n\n Object logMessageContentExtObj = message.getContextualProperty(EXTERNAL_PROPERTY_NAME);\n\n if (null == logMessageContentExtObj) {\n\n return logMessageContent;\n\n } else if (logMessageContentExtObj instanceof Boolean) {\n\n return ((Boolean) logMessageContentExtObj).booleanValue();\n\n } else if (logMessageContentExtObj instanceof String) {\n\n String logMessageContentExtVal = (String) logMessageContentExtObj;\n\n if (logMessageContentExtVal.equalsIgnoreCase(\"true\")) {\n\n return true;\n\n } else if (logMessageContentExtVal.equalsIgnoreCase(\"false\")) {\n\n return false;\n\n } else {\n\n return logMessageContent;\n }\n } else {\n\n return logMessageContent;\n }\n }", "private List<TransformEntry> readTransformEntries(File file) throws Exception {\n\n List<TransformEntry> result = new ArrayList<>();\n try (FileInputStream fis = new FileInputStream(file)) {\n byte[] data = CmsFileUtil.readFully(fis, false);\n Document doc = CmsXmlUtils.unmarshalHelper(data, null, false);\n for (Node node : doc.selectNodes(\"//transform\")) {\n Element elem = ((Element)node);\n String xslt = elem.attributeValue(\"xslt\");\n String conf = elem.attributeValue(\"config\");\n TransformEntry entry = new TransformEntry(conf, xslt);\n result.add(entry);\n }\n }\n return result;\n }", "public String getString(String fieldName) {\n\t\treturn hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null;\n\t}", "private Collection<? extends ResourceRoot> handleClassPathItems(final DeploymentUnit deploymentUnit) {\n final Set<ResourceRoot> additionalRoots = new HashSet<ResourceRoot>();\n final ArrayDeque<ResourceRoot> toProcess = new ArrayDeque<ResourceRoot>();\n final List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);\n toProcess.addAll(resourceRoots);\n final Set<ResourceRoot> processed = new HashSet<ResourceRoot>(resourceRoots);\n\n while (!toProcess.isEmpty()) {\n final ResourceRoot root = toProcess.pop();\n final List<ResourceRoot> classPathRoots = root.getAttachmentList(Attachments.CLASS_PATH_RESOURCE_ROOTS);\n for(ResourceRoot cpRoot : classPathRoots) {\n if(!processed.contains(cpRoot)) {\n additionalRoots.add(cpRoot);\n toProcess.add(cpRoot);\n processed.add(cpRoot);\n }\n }\n }\n return additionalRoots;\n }", "private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) {\n\t\treturn valueGeneration != null && valueGeneration.getValueGenerator() == null &&\n\t\t\t\ttimingsMatch( valueGeneration.getGenerationTiming(), matchTiming );\n\t}" ]
Set keyboard done listener to detect when the user click "DONE" on his keyboard @param listener IntlPhoneInputListener
[ "public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\n }" ]
[ "public InsertIntoTable set(String name, Object value) {\n builder.set(name, value);\n return this;\n }", "@SuppressWarnings(\"unchecked\")\n private static synchronized Map<String, Boolean> getCache(GraphRewrite event)\n {\n Map<String, Boolean> result = (Map<String, Boolean>)event.getRewriteContext().get(ClassificationServiceCache.class);\n if (result == null)\n {\n result = Collections.synchronizedMap(new LRUMap(30000));\n event.getRewriteContext().put(ClassificationServiceCache.class, result);\n }\n return result;\n }", "private void doBatchWork(BatchBackend backend) throws InterruptedException {\n\t\tExecutorService executor = Executors.newFixedThreadPool( typesToIndexInParallel, \"BatchIndexingWorkspace\" );\n\t\tfor ( IndexedTypeIdentifier indexedTypeIdentifier : rootIndexedTypes ) {\n\t\t\texecutor.execute( new BatchIndexingWorkspace( gridDialect, searchFactoryImplementor, sessionFactory, indexedTypeIdentifier,\n\t\t\t\t\tcacheMode, endAllSignal, monitor, backend, tenantId ) );\n\t\t}\n\t\texecutor.shutdown();\n\t\tendAllSignal.await(); // waits for the executor to finish\n\t}", "public ItemRequest<Workspace> update(String workspace) {\n \n String path = String.format(\"/workspaces/%s\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"PUT\");\n }", "public static base_response delete(nitro_service client, application resource) throws Exception {\n\t\tapplication deleteresource = new application();\n\t\tdeleteresource.appname = resource.appname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void localRollback()\r\n {\r\n log.info(\"Rollback was called, do rollback on current connection \" + con);\r\n if (!this.isInLocalTransaction)\r\n {\r\n throw new PersistenceBrokerException(\"Not in transaction, cannot abort\");\r\n }\r\n try\r\n {\r\n //truncate the local transaction\r\n this.isInLocalTransaction = false;\r\n if(!broker.isManaged())\r\n {\r\n if (batchCon != null)\r\n {\r\n batchCon.rollback();\r\n }\r\n else if (con != null && !con.isClosed())\r\n {\r\n con.rollback();\r\n }\r\n }\r\n else\r\n {\r\n if(log.isEnabledFor(Logger.INFO)) log.info(\r\n \"Found managed environment setting in PB, will ignore rollback call on connection, this should be done by JTA\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"Rollback on the underlying connection failed\", e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n \trestoreAutoCommitState();\r\n\t\t }\r\n catch(OJBRuntimeException ignore)\r\n {\r\n\t\t\t // Ignore or log exception\r\n\t\t }\r\n releaseConnection();\r\n }\r\n }", "public static dnspolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tdnspolicylabel obj = new dnspolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tdnspolicylabel response = (dnspolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setMesh(GVRMesh mesh) {\n mMesh = mesh;\n NativeMeshCollider.setMesh(getNative(), mesh.getNative());\n }", "@Override\n public <K, V> StoreClient<K, V> getStoreClient(final String storeName,\n final InconsistencyResolver<Versioned<V>> resolver) {\n // wrap it in LazyStoreClient here so any direct calls to this method\n // returns a lazy client\n return new LazyStoreClient<K, V>(new Callable<StoreClient<K, V>>() {\n\n @Override\n public StoreClient<K, V> call() throws Exception {\n Store<K, V, Object> clientStore = getRawStore(storeName, resolver);\n return new RESTClient<K, V>(storeName, clientStore);\n }\n }, true);\n }" ]
Finds and returns the date for the given event summary and year within the given ics file, or null if not present.
[ "private Date seasonalDateFromIcs(String icsFileName, String eventSummary, int year) {\n Map<Integer, Date> dates = getDatesFromIcs(icsFileName, eventSummary, year, year);\n return dates.get(year - (eventSummary.equals(Holiday.NEW_YEARS_EVE.getSummary()) ? 1 : 0));\n }" ]
[ "public void clearTmpData() {\n\t\tfor (Enumeration<?> e = breadthFirstEnumeration(); e.hasMoreElements(); ) {\n\t\t\t((LblTree) e.nextElement()).setTmpData(null);\n\t\t}\n\t}", "private void appendClazzColumnForSelect(StringBuffer buf)\r\n {\r\n ClassDescriptor cld = getSearchClassDescriptor();\r\n ClassDescriptor[] clds = getMultiJoinedClassDescriptors(cld);\r\n\r\n if (clds.length == 0)\r\n {\r\n return;\r\n }\r\n \r\n buf.append(\",CASE\");\r\n\r\n for (int i = clds.length; i > 0; i--)\r\n {\r\n buf.append(\" WHEN \");\r\n\r\n ClassDescriptor subCld = clds[i - 1];\r\n FieldDescriptor[] fieldDescriptors = subCld.getPkFields();\r\n\r\n TableAlias alias = getTableAliasForClassDescriptor(subCld);\r\n for (int j = 0; j < fieldDescriptors.length; j++)\r\n {\r\n FieldDescriptor field = fieldDescriptors[j];\r\n if (j > 0)\r\n {\r\n buf.append(\" AND \");\r\n }\r\n appendColumn(alias, field, buf);\r\n buf.append(\" IS NOT NULL\");\r\n }\r\n buf.append(\" THEN '\").append(subCld.getClassNameOfObject()).append(\"'\");\r\n }\r\n buf.append(\" ELSE '\").append(cld.getClassNameOfObject()).append(\"'\");\r\n buf.append(\" END AS \" + SqlHelper.OJB_CLASS_COLUMN);\r\n }", "private List<StyleFilter> initStyleFilters(List<FeatureStyleInfo> styleDefinitions) throws GeomajasException {\n\t\tList<StyleFilter> styleFilters = new ArrayList<StyleFilter>();\n\t\tif (styleDefinitions == null || styleDefinitions.size() == 0) {\n\t\t\tstyleFilters.add(new StyleFilterImpl()); // use default.\n\t\t} else {\n\t\t\tfor (FeatureStyleInfo styleDef : styleDefinitions) {\n\t\t\t\tStyleFilterImpl styleFilterImpl = null;\n\t\t\t\tString formula = styleDef.getFormula();\n\t\t\t\tif (null != formula && formula.length() > 0) {\n\t\t\t\t\tstyleFilterImpl = new StyleFilterImpl(filterService.parseFilter(formula), styleDef);\n\t\t\t\t} else {\n\t\t\t\t\tstyleFilterImpl = new StyleFilterImpl(Filter.INCLUDE, styleDef);\n\t\t\t\t}\n\t\t\t\tstyleFilters.add(styleFilterImpl);\n\t\t\t}\n\t\t}\n\t\treturn styleFilters;\n\t}", "public PhotoContext getContext(String photoId, String userId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Collection<Element> payload = response.getPayloadCollection();\r\n PhotoContext photoContext = new PhotoContext();\r\n for (Element element : payload) {\r\n String elementName = element.getTagName();\r\n if (elementName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (elementName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setNextPhoto(photo);\r\n } else {\r\n if (logger.isInfoEnabled()) {\r\n logger.info(\"unsupported element name: \" + elementName);\r\n }\r\n }\r\n }\r\n return photoContext;\r\n }", "protected static boolean setCustomForDefaultClient(String profileName, String pathName, Boolean isResponse, String customData) {\n try {\n Client client = new Client(profileName, false);\n client.toggleProfile(true);\n client.setCustom(isResponse, pathName, customData);\n if (isResponse) {\n client.toggleResponseOverride(pathName, true);\n } else {\n client.toggleRequestOverride(pathName, true);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public Object extractJavaFieldValue(Object object) throws SQLException {\n\n\t\tObject val = extractRawJavaFieldValue(object);\n\n\t\t// if this is a foreign object then we want its reference field\n\t\tif (foreignRefField != null && val != null) {\n\t\t\tval = foreignRefField.extractRawJavaFieldValue(val);\n\t\t}\n\n\t\treturn val;\n\t}", "public static byte[] getContentBytes(String stringUrl) throws IOException {\n URL url = new URL(stringUrl);\n byte[] data = MyStreamUtils.readContentBytes(url.openStream());\n return data;\n }", "private void addOp(String op, String path, String value) {\n if (this.operations == null) {\n this.operations = new JsonArray();\n }\n\n this.operations.add(new JsonObject()\n .add(\"op\", op)\n .add(\"path\", path)\n .add(\"value\", value));\n }", "public CRFDatum<List<String>, CRFLabel> makeDatum(List<IN> info, int loc,\r\n edu.stanford.nlp.sequences.FeatureFactory<IN> featureFactory) {\r\n pad.set(AnswerAnnotation.class, flags.backgroundSymbol);\r\n PaddedList<IN> pInfo = new PaddedList<IN>(info, pad);\r\n\r\n ArrayList<List<String>> features = new ArrayList<List<String>>();\r\n\r\n // for (int i = 0; i < windowSize; i++) {\r\n // List featuresC = new ArrayList();\r\n // for (int j = 0; j < FeatureFactory.win[i].length; j++) {\r\n // featuresC.addAll(featureFactory.features(info, loc,\r\n // FeatureFactory.win[i][j]));\r\n // }\r\n // features.add(featuresC);\r\n // }\r\n\r\n Collection<Clique> done = new HashSet<Clique>();\r\n for (int i = 0; i < windowSize; i++) {\r\n List<String> featuresC = new ArrayList<String>();\r\n List<Clique> windowCliques = FeatureFactory.getCliques(i, 0);\r\n windowCliques.removeAll(done);\r\n done.addAll(windowCliques);\r\n for (Clique c : windowCliques) {\r\n featuresC.addAll(featureFactory.getCliqueFeatures(pInfo, loc, c)); //todo useless copy because of typing reasons\r\n }\r\n features.add(featuresC);\r\n }\r\n\r\n int[] labels = new int[windowSize];\r\n\r\n for (int i = 0; i < windowSize; i++) {\r\n String answer = pInfo.get(loc + i - windowSize + 1).get(AnswerAnnotation.class);\r\n labels[i] = classIndex.indexOf(answer);\r\n }\r\n\r\n printFeatureLists(pInfo.get(loc), features);\r\n\r\n CRFDatum<List<String>, CRFLabel> d = new CRFDatum<List<String>, CRFLabel>(features, new CRFLabel(labels));\r\n // System.err.println(d);\r\n return d;\r\n }" ]
Returns the position of the specified value in the specified array. @param value the value to search for @param array the array to search in @return the position of the specified value in the specified array
[ "public static int positionOf(char value, char[] array) {\n for (int i = 0; i < array.length; i++) {\n if (value == array[i]) {\n return i;\n }\n }\n throw new OkapiException(\"Unable to find character '\" + value + \"' in character array.\");\n }" ]
[ "public static final String printTime(Date value)\n {\n return (value == null ? null : TIME_FORMAT.get().format(value));\n }", "public void setEnterpriseCost(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_COST, index), value);\n }", "public static String base64Encode(byte[] bytes) {\n if (bytes == null) {\n throw new IllegalArgumentException(\"Input bytes must not be null.\");\n }\n if (bytes.length >= BASE64_UPPER_BOUND) {\n throw new IllegalArgumentException(\n \"Input bytes length must not exceed \" + BASE64_UPPER_BOUND);\n }\n\n // Every three bytes is encoded into four characters.\n //\n // Example:\n // input |0 1 0 1 0 0 1 0|0 1 1 0 1 1 1 1|0 1 1 0 0 0 1 0|\n // encode grouping |0 1 0 1 0 0|1 0 0 1 1 0|1 1 1 1 0 1|1 0 0 0 1 0|\n // encoded ascii | U | m | 9 | i |\n\n int triples = bytes.length / 3;\n\n // If the number of input bytes is not a multiple of three, padding characters will be added.\n if (bytes.length % 3 != 0) {\n triples += 1;\n }\n\n // The encoded string will have four characters for every three bytes.\n char[] encoding = new char[triples << 2];\n\n for (int in = 0, out = 0; in < bytes.length; in += 3, out += 4) {\n int triple = (bytes[in] & 0xff) << 16;\n if (in + 1 < bytes.length) {\n triple |= ((bytes[in + 1] & 0xff) << 8);\n }\n if (in + 2 < bytes.length) {\n triple |= (bytes[in + 2] & 0xff);\n }\n encoding[out] = BASE64_CHARS.charAt((triple >> 18) & 0x3f);\n encoding[out + 1] = BASE64_CHARS.charAt((triple >> 12) & 0x3f);\n encoding[out + 2] = BASE64_CHARS.charAt((triple >> 6) & 0x3f);\n encoding[out + 3] = BASE64_CHARS.charAt(triple & 0x3f);\n }\n\n // Add padding characters if needed.\n for (int i = encoding.length - (triples * 3 - bytes.length); i < encoding.length; i++) {\n encoding[i] = '=';\n }\n\n return String.valueOf(encoding);\n }", "public static <T> T callConstructor(Class<T> klass, Object[] args) {\n Class<?>[] klasses = new Class[args.length];\n for(int i = 0; i < args.length; i++)\n klasses[i] = args[i].getClass();\n return callConstructor(klass, klasses, args);\n }", "public void flush() throws IOException {\n checkMutable();\n long startTime = System.currentTimeMillis();\n channel.force(true);\n long elapsedTime = System.currentTimeMillis() - startTime;\n LogFlushStats.recordFlushRequest(elapsedTime);\n logger.debug(\"flush time \" + elapsedTime);\n setHighWaterMark.set(getSizeInBytes());\n logger.debug(\"flush high water mark:\" + highWaterMark());\n }", "public void transform(DataPipe cr) {\n Map<String, String> map = cr.getDataMap();\n\n for (String key : map.keySet()) {\n String value = map.get(key);\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n map.put(key, String.valueOf(ran));\n } else if (value.equals(\"#{divideBy2}\")) {\n String i = map.get(\"var_out_V3\");\n String result = String.valueOf(Integer.valueOf(i) / 2);\n map.put(key, result);\n }\n }\n }", "private static int checkResult(int result)\n {\n if (exceptionsEnabled && result !=\n cudnnStatus.CUDNN_STATUS_SUCCESS)\n {\n throw new CudaException(cudnnStatus.stringFor(result));\n }\n return result;\n }", "private void rotatorPushRight( int m )\n {\n double b11 = off[m];\n double b21 = diag[m+1];\n\n computeRotator(b21,-b11);\n\n // apply rotator on the right\n off[m] = 0;\n diag[m+1] = b21*c-b11*s;\n\n if( m+2 < N) {\n double b22 = off[m+1];\n off[m+1] = b22*c;\n bulge = b22*s;\n } else {\n bulge = 0;\n }\n\n// SimpleMatrix Q = createQ(m,m+1, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+1,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }", "protected List<I_CmsFacetQueryItem> parseFacetQueryItems(final String path) throws Exception {\n\n final List<I_CmsXmlContentValue> values = m_xml.getValues(path, m_locale);\n if (values == null) {\n return null;\n } else {\n List<I_CmsFacetQueryItem> parsedItems = new ArrayList<I_CmsFacetQueryItem>(values.size());\n for (I_CmsXmlContentValue value : values) {\n I_CmsFacetQueryItem item = parseFacetQueryItem(value.getPath() + \"/\");\n if (null != item) {\n parsedItems.add(item);\n } else {\n // TODO: log\n }\n }\n return parsedItems;\n }\n }" ]
returns the bytesize of the give bitmap
[ "public static int byteSizeOf(Bitmap bitmap) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n return bitmap.getAllocationByteCount();\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {\n return bitmap.getByteCount();\n } else {\n return bitmap.getRowBytes() * bitmap.getHeight();\n }\n }" ]
[ "public static Cluster getCluster(ZkClient zkClient) {\n Cluster cluster = new Cluster();\n List<String> nodes = getChildrenParentMayNotExist(zkClient, BrokerIdsPath);\n for (String node : nodes) {\n final String brokerInfoString = readData(zkClient, BrokerIdsPath + \"/\" + node);\n cluster.add(Broker.createBroker(Integer.valueOf(node), brokerInfoString));\n }\n return cluster;\n }", "public void printProbs(String filename,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n ObjectBank<List<IN>> docs =\r\n makeObjectBankFromFile(filename, readerAndWriter);\r\n printProbsDocuments(docs);\r\n }", "public static rnatip_stats[] get(nitro_service service, options option) throws Exception{\n\t\trnatip_stats obj = new rnatip_stats();\n\t\trnatip_stats[] response = (rnatip_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}", "private void processProjectID()\n {\n if (m_projectID == null)\n {\n List<Row> rows = getRows(\"project\", null, null);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_projectID = row.getInteger(\"proj_id\");\n }\n }\n }", "public IntBuffer getIntVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n IntBuffer data = buffer.asIntBuffer();\n if (!NativeVertexBuffer.getIntVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }", "public Object moveToNextValue(Object val) throws SQLException {\n\t\tif (dataPersister == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn dataPersister.moveToNextValue(val);\n\t\t}\n\t}", "private String getProjectName() {\n String pName = Strings.emptyToNull(projectName);\n if (pName == null) { \n pName = Strings.emptyToNull(junit4.getProject().getName());\n }\n if (pName == null) {\n pName = \"(unnamed project)\"; \n }\n return pName;\n }", "public void startTask(int id, String taskName) {\n if (isActivated) {\n durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));\n }\n }", "public boolean isHoliday(String dateString) {\n boolean isHoliday = false;\n for (Holiday date : EquivalenceClassTransformer.HOLIDAYS) {\n if (convertToReadableDate(date.forYear(Integer.parseInt(dateString.substring(0, 4)))).equals(dateString)) {\n isHoliday = true;\n }\n }\n return isHoliday;\n }" ]
Gives the "roots" of a list of folders, i.e. the list of folders which are not descendants of any other folders in the original list @param folders the original list of folders @return the root folders of the list
[ "protected List<CmsResource> getTopFolders(List<CmsResource> folders) {\n\n List<String> folderPaths = new ArrayList<String>();\n List<CmsResource> topFolders = new ArrayList<CmsResource>();\n Map<String, CmsResource> foldersByPath = new HashMap<String, CmsResource>();\n for (CmsResource folder : folders) {\n folderPaths.add(folder.getRootPath());\n foldersByPath.put(folder.getRootPath(), folder);\n }\n Collections.sort(folderPaths);\n Set<String> topFolderPaths = new HashSet<String>(folderPaths);\n for (int i = 0; i < folderPaths.size(); i++) {\n for (int j = i + 1; j < folderPaths.size(); j++) {\n if (folderPaths.get(j).startsWith((folderPaths.get(i)))) {\n topFolderPaths.remove(folderPaths.get(j));\n } else {\n break;\n }\n }\n }\n for (String path : topFolderPaths) {\n topFolders.add(foldersByPath.get(path));\n }\n return topFolders;\n }" ]
[ "public static base_response add(nitro_service client, onlinkipv6prefix resource) throws Exception {\n\t\tonlinkipv6prefix addresource = new onlinkipv6prefix();\n\t\taddresource.ipv6prefix = resource.ipv6prefix;\n\t\taddresource.onlinkprefix = resource.onlinkprefix;\n\t\taddresource.autonomusprefix = resource.autonomusprefix;\n\t\taddresource.depricateprefix = resource.depricateprefix;\n\t\taddresource.decrementprefixlifetimes = resource.decrementprefixlifetimes;\n\t\taddresource.prefixvalidelifetime = resource.prefixvalidelifetime;\n\t\taddresource.prefixpreferredlifetime = resource.prefixpreferredlifetime;\n\t\treturn addresource.add_resource(client);\n\t}", "public Set<TupleOperation> getOperations() {\n\t\tif ( currentState == null ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\treturn new SetFromCollection<TupleOperation>( currentState.values() );\n\t\t}\n\t}", "private static void listTimephasedWork(ResourceAssignment assignment)\n {\n Task task = assignment.getTask();\n int days = (int) ((task.getFinish().getTime() - task.getStart().getTime()) / (1000 * 60 * 60 * 24)) + 1;\n if (days > 1)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yy\");\n\n TimescaleUtility timescale = new TimescaleUtility();\n ArrayList<DateRange> dates = timescale.createTimescale(task.getStart(), TimescaleUnits.DAYS, days);\n TimephasedUtility timephased = new TimephasedUtility();\n\n ArrayList<Duration> durations = timephased.segmentWork(assignment.getCalendar(), assignment.getTimephasedWork(), TimescaleUnits.DAYS, dates);\n for (DateRange range : dates)\n {\n System.out.print(df.format(range.getStart()) + \"\\t\");\n }\n System.out.println();\n for (Duration duration : durations)\n {\n System.out.print(duration.toString() + \" \".substring(0, 7) + \"\\t\");\n }\n System.out.println();\n }\n }", "public boolean isIPv4Compatible() {\n\t\treturn getSegment(0).isZero() && getSegment(1).isZero() && getSegment(2).isZero() &&\n\t\t\t\tgetSegment(3).isZero() && getSegment(4).isZero() && getSegment(5).isZero();\n\t}", "private Date readOptionalDate(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n try {\n return new Date(Long.parseLong(str.stringValue()));\n } catch (@SuppressWarnings(\"unused\") NumberFormatException e) {\n // do nothing - return the default value\n }\n }\n return null;\n }", "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "private void processClientId(HttpServletRequest httpServletRequest, History history) {\n // get the client id from the request header if applicable.. otherwise set to default\n // also set the client uuid in the history object\n if (httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME) != null &&\n !httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME).equals(\"\")) {\n history.setClientUUID(httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME));\n } else {\n history.setClientUUID(Constants.PROFILE_CLIENT_DEFAULT_ID);\n }\n logger.info(\"Client UUID is: {}\", history.getClientUUID());\n }", "public Diff compare(String left, String right) {\n\t\treturn compare(getCtType(left), getCtType(right));\n\t}", "private void readRelationship(Link link)\n {\n Task sourceTask = m_taskIdMap.get(link.getSourceTaskID());\n Task destinationTask = m_taskIdMap.get(link.getDestinationTaskID());\n if (sourceTask != null && destinationTask != null)\n {\n Duration lag = getDuration(link.getLagUnit(), link.getLag());\n RelationType type = link.getType();\n Relation relation = destinationTask.addPredecessor(sourceTask, type, lag);\n relation.setUniqueID(link.getID());\n }\n }" ]
Saves a matrix to disk using Java binary serialization. @param A The matrix being saved. @param fileName Name of the file its being saved at. @throws java.io.IOException
[ "public static void saveBin(DMatrix A, String fileName)\n throws IOException\n {\n FileOutputStream fileStream = new FileOutputStream(fileName);\n ObjectOutputStream stream = new ObjectOutputStream(fileStream);\n\n try {\n stream.writeObject(A);\n stream.flush();\n } finally {\n // clean up\n try {\n stream.close();\n } finally {\n fileStream.close();\n }\n }\n\n }" ]
[ "public static double ChiSquare(double[] histogram1, double[] histogram2) {\n double r = 0;\n for (int i = 0; i < histogram1.length; i++) {\n double t = histogram1[i] + histogram2[i];\n if (t != 0)\n r += Math.pow(histogram1[i] - histogram2[i], 2) / t;\n }\n\n return 0.5 * r;\n }", "static InjectionProvider<?>[] toArray(final Set<InjectionProvider<?>> injectionProviders) {\n return injectionProviders.toArray(new InjectionProvider<?>[injectionProviders.size()]);\n }", "private static Class getClassForClassNode(ClassNode type) {\r\n // todo hamlet - move to a different \"InferenceUtil\" object\r\n Class primitiveType = getPrimitiveType(type);\r\n if (primitiveType != null) {\r\n return primitiveType;\r\n } else if (classNodeImplementsType(type, String.class)) {\r\n return String.class;\r\n } else if (classNodeImplementsType(type, ReentrantLock.class)) {\r\n return ReentrantLock.class;\r\n } else if (type.getName() != null && type.getName().endsWith(\"[]\")) {\r\n return Object[].class; // better type inference could be done, but oh well\r\n }\r\n return null;\r\n }", "public double distanceFrom(LatLong end) {\n\n double dLat = (end.getLatitude() - getLatitude()) * Math.PI / 180;\n double dLon = (end.getLongitude() - getLongitude()) * Math.PI / 180;\n\n double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)\n + Math.cos(getLatitude() * Math.PI / 180)\n * Math.cos(end.getLatitude() * Math.PI / 180)\n * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n\n double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n double d = EarthRadiusMeters * c;\n return d;\n }", "public void calculateSize(PdfContext context) {\n\t\tfloat width = 0;\n\t\tfloat height = 0;\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.calculateSize(context);\n\t\t\tfloat cw = child.getBounds().getWidth() + 2 * child.getConstraint().getMarginX();\n\t\t\tfloat ch = child.getBounds().getHeight() + 2 * child.getConstraint().getMarginY();\n\t\t\tswitch (getConstraint().getFlowDirection()) {\n\t\t\t\tcase LayoutConstraint.FLOW_NONE:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_X:\n\t\t\t\t\twidth += cw;\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_Y:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight += ch;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unknown flow direction \" + getConstraint().getFlowDirection());\n\t\t\t}\n\t\t}\n\t\tif (getConstraint().getWidth() != 0) {\n\t\t\twidth = getConstraint().getWidth();\n\t\t}\n\t\tif (getConstraint().getHeight() != 0) {\n\t\t\theight = getConstraint().getHeight();\n\t\t}\n\t\tsetBounds(new Rectangle(0, 0, width, height));\n\t}", "public ItemRequest<Task> removeDependencies(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public static int getIbanLength(final CountryCode countryCode) {\n final BbanStructure structure = getBbanStructure(countryCode);\n return COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH + structure.getBbanLength();\n }", "private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }", "public static csvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cachepolicy_binding obj = new csvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cachepolicy_binding response[] = (csvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Utility method to convert an array of bytes into a long. Byte ordered is assumed to be big-endian. @param bytes The data to read from. @param offset The position to start reading the 8-byte long from. @return The 64-bit integer represented by the eight bytes. @since 1.1
[ "public static long convertBytesToLong(byte[] bytes, int offset)\n {\n long value = 0;\n for (int i = offset; i < offset + 8; i++)\n {\n byte b = bytes[i];\n value <<= 8;\n value |= b;\n }\n return value;\n\n }" ]
[ "private void store(final PrintJobStatus printJobStatus) throws JSONException {\n JSONObject metadata = new JSONObject();\n metadata.put(JSON_REQUEST_DATA, printJobStatus.getEntry().getRequestData().getInternalObj());\n metadata.put(JSON_STATUS, printJobStatus.getStatus().toString());\n metadata.put(JSON_START_DATE, printJobStatus.getStartTime());\n metadata.put(JSON_REQUEST_COUNT, printJobStatus.getRequestCount());\n if (printJobStatus.getCompletionDate() != null) {\n metadata.put(JSON_COMPLETION_DATE, printJobStatus.getCompletionTime());\n }\n metadata.put(JSON_ACCESS_ASSERTION, this.assertionPersister.marshal(printJobStatus.getAccess()));\n if (printJobStatus.getError() != null) {\n metadata.put(JSON_ERROR, printJobStatus.getError());\n }\n if (printJobStatus.getResult() != null) {\n metadata.put(JSON_REPORT_URI, printJobStatus.getResult().getReportURIString());\n metadata.put(JSON_FILENAME, printJobStatus.getResult().getFileName());\n metadata.put(JSON_FILE_EXT, printJobStatus.getResult().getFileExtension());\n metadata.put(JSON_MIME_TYPE, printJobStatus.getResult().getMimeType());\n }\n this.registry.put(RESULT_METADATA + printJobStatus.getReferenceId(), metadata);\n }", "public static Object executeXPath(Node document, String xpathExpression, Map<String, String> namespaceMapping, QName result)\n throws XPathException, MarshallingException\n {\n NamespaceMapContext mapContext = new NamespaceMapContext(namespaceMapping);\n try\n {\n XPathFactory xPathfactory = XPathFactory.newInstance();\n XPath xpath = xPathfactory.newXPath();\n xpath.setNamespaceContext(mapContext);\n XPathExpression expr = xpath.compile(xpathExpression);\n\n return executeXPath(document, expr, result);\n }\n catch (XPathExpressionException e)\n {\n throw new XPathException(\"Xpath(\" + xpathExpression + \") cannot be compiled\", e);\n }\n catch (Exception e)\n {\n throw new MarshallingException(\"Exception unmarshalling XML.\", e);\n }\n }", "public Record findRecordById(String id) {\n if (directory == null)\n init();\n\n Property idprop = config.getIdentityProperties().iterator().next();\n for (Record r : lookup(idprop, id))\n if (r.getValue(idprop.getName()).equals(id))\n return r;\n\n return null; // not found\n }", "public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize)\n throws InterruptedException, IOException {\n URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL());\n return new LargeFileUpload().\n upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize);\n }", "public DiscreteInterval minus(DiscreteInterval other) {\n return new DiscreteInterval(this.min - other.max, this.max - other.min);\n }", "public static boolean isAllWhitespace(CharSequence self) {\n String s = self.toString();\n for (int i = 0; i < s.length(); i++) {\n if (!Character.isWhitespace(s.charAt(i)))\n return false;\n }\n return true;\n }", "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }", "public static void updatePathTable(String columnName, Object newData, int path_id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + columnName + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setObject(1, newData);\n statement.setInt(2, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public int[] getTenors() {\r\n\t\tSet<Integer> setTenors\t= new HashSet<>();\r\n\r\n\t\tfor(int moneyness : getGridNodesPerMoneyness().keySet()) {\r\n\t\t\tsetTenors.addAll(Arrays.asList((IntStream.of(keyMap.get(moneyness)[1]).boxed().toArray(Integer[]::new))));\r\n\t\t}\r\n\t\treturn setTenors.stream().sorted().mapToInt(Integer::intValue).toArray();\r\n\t}" ]
Gets existing config files. @return the existing config files
[ "private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }" ]
[ "public static dnspolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tdnspolicylabel obj = new dnspolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tdnspolicylabel response = (dnspolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}", "public Date getTimestamp(FastTrackField dateName, FastTrackField timeName)\n {\n Date result = null;\n Date date = getDate(dateName);\n if (date != null)\n {\n Calendar dateCal = DateHelper.popCalendar(date);\n Date time = getDate(timeName);\n if (time != null)\n {\n Calendar timeCal = DateHelper.popCalendar(time);\n dateCal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY));\n dateCal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE));\n dateCal.set(Calendar.SECOND, timeCal.get(Calendar.SECOND));\n dateCal.set(Calendar.MILLISECOND, timeCal.get(Calendar.MILLISECOND));\n DateHelper.pushCalendar(timeCal);\n }\n\n result = dateCal.getTime();\n DateHelper.pushCalendar(dateCal);\n }\n\n return result;\n }", "public static Node removePartitionsFromNode(final Node node,\n final Set<Integer> donatedPartitions) {\n List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());\n deepCopy.removeAll(donatedPartitions);\n return updateNode(node, deepCopy);\n }", "public String getOriginalValue(ParsedCommandLine parsedLine, boolean required) throws CommandFormatException {\n String value = null;\n if(parsedLine.hasProperties()) {\n if(index >= 0) {\n List<String> others = parsedLine.getOtherProperties();\n if(others.size() > index) {\n return others.get(index);\n }\n }\n\n value = parsedLine.getPropertyValue(fullName);\n if(value == null && shortName != null) {\n value = parsedLine.getPropertyValue(shortName);\n }\n }\n\n if(required && value == null && !isPresent(parsedLine)) {\n StringBuilder buf = new StringBuilder();\n buf.append(\"Required argument \");\n buf.append('\\'').append(fullName).append('\\'');\n buf.append(\" is missing.\");\n throw new CommandFormatException(buf.toString());\n }\n return value;\n }", "public BoxLock lock(Date expiresAt, boolean isDownloadPrevented) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", \"lock\").toString();\n URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject lockConfig = new JsonObject();\n lockConfig.add(\"type\", \"lock\");\n if (expiresAt != null) {\n lockConfig.add(\"expires_at\", BoxDateFormat.format(expiresAt));\n }\n lockConfig.add(\"is_download_prevented\", isDownloadPrevented);\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"lock\", lockConfig);\n request.setBody(requestJSON.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n JsonValue lockValue = responseJSON.get(\"lock\");\n JsonObject lockJSON = JsonObject.readFrom(lockValue.toString());\n\n return new BoxLock(lockJSON, this.getAPI());\n }", "public static base_response update(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy updateresource = new spilloverpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.action = resource.action;\n\t\tupdateresource.comment = resource.comment;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable,\n final Collection<ControlFlowBlock> controlFlowBlocks) {\n return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks));\n }", "public RandomVariable[] getBasisFunctions(double fixingDate, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\n\n\t\tArrayList<RandomVariable> basisFunctions = new ArrayList<>();\n\n\t\t// Constant\n\t\tRandomVariable basisFunction = new RandomVariableFromDoubleArray(1.0);//.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\tint fixingDateIndex = Arrays.binarySearch(fixingDates, fixingDate);\n\t\tif(fixingDateIndex < 0) {\n\t\t\tfixingDateIndex = -fixingDateIndex;\n\t\t}\n\t\tif(fixingDateIndex >= fixingDates.length) {\n\t\t\tfixingDateIndex = fixingDates.length-1;\n\t\t}\n\n\t\t// forward rate to the next period\n\t\tRandomVariable rateShort = model.getLIBOR(fixingDate, fixingDate, paymentDates[fixingDateIndex]);\n\t\tRandomVariable discountShort = rateShort.mult(paymentDates[fixingDateIndex]-fixingDate).add(1.0).invert();\n\t\tbasisFunctions.add(discountShort);\n\t\tbasisFunctions.add(discountShort.pow(2.0));\n\t\t//\t\tbasisFunctions.add(rateShort.pow(3.0));\n\n\t\t// forward rate to the end of the product\n\t\tRandomVariable rateLong = model.getLIBOR(fixingDate, fixingDates[fixingDateIndex], paymentDates[paymentDates.length-1]);\n\t\tRandomVariable discountLong = rateLong.mult(paymentDates[paymentDates.length-1]-fixingDates[fixingDateIndex]).add(1.0).invert();\n\t\tbasisFunctions.add(discountLong);\n\t\tbasisFunctions.add(discountLong.pow(2.0));\n\t\t//\t\tbasisFunctions.add(rateLong.pow(3.0));\n\n\t\t// Numeraire\n\t\tRandomVariable numeraire = model.getNumeraire(fixingDate).invert();\n\t\tbasisFunctions.add(numeraire);\n\t\t//\t\tbasisFunctions.add(numeraire.pow(2.0));\n\t\t//\t\tbasisFunctions.add(numeraire.pow(3.0));\n\n\t\treturn basisFunctions.toArray(new RandomVariable[basisFunctions.size()]);\n\t}", "private int getCacheKey(InputDevice device, GVRControllerType controllerType) {\n if (controllerType != GVRControllerType.UNKNOWN &&\n controllerType != GVRControllerType.EXTERNAL) {\n // Sometimes a device shows up using two device ids\n // here we try to show both devices as one using the\n // product and vendor id\n\n int key = device.getVendorId();\n key = 31 * key + device.getProductId();\n key = 31 * key + controllerType.hashCode();\n\n return key;\n }\n return -1; // invalid key\n }" ]
Gets the flags associated with this attribute. @return the flags. Will not return {@code null}
[ "public Set<AttributeAccess.Flag> getFlags() {\n if (attributeAccess == null) {\n return Collections.emptySet();\n }\n return attributeAccess.getFlags();\n }" ]
[ "private ModelNode createCPUNode() throws OperationFailedException {\n ModelNode cpu = new ModelNode().setEmptyObject();\n cpu.get(ARCH).set(getProperty(\"os.arch\"));\n cpu.get(AVAILABLE_PROCESSORS).set(ProcessorInfo.availableProcessors());\n return cpu;\n }", "protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) {\r\n Map<String, AbstractServer> srvc = new HashMap<>();\r\n for (ServerSetup setup : config) {\r\n if (srvc.containsKey(setup.getProtocol())) {\r\n throw new IllegalArgumentException(\"Server '\" + setup.getProtocol() + \"' was found at least twice in the array\");\r\n }\r\n final String protocol = setup.getProtocol();\r\n if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) {\r\n srvc.put(protocol, new SmtpServer(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) {\r\n srvc.put(protocol, new Pop3Server(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) {\r\n srvc.put(protocol, new ImapServer(setup, mgr));\r\n }\r\n }\r\n return srvc;\r\n }", "private String GCMGetFreshToken(final String senderID) {\n getConfigLogger().verbose(getAccountId(), \"GcmManager: Requesting a GCM token for Sender ID - \" + senderID);\n String token = null;\n try {\n token = InstanceID.getInstance(context)\n .getToken(senderID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);\n getConfigLogger().info(getAccountId(), \"GCM token : \" + token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"GcmManager: Error requesting GCM token\", t);\n }\n return token;\n }", "public Map<String, MBeanAttributeInfo> getAttributeMetadata() {\n\n MBeanAttributeInfo[] attributeList = mBeanInfo.getAttributes();\n\n Map<String, MBeanAttributeInfo> attributeMap = new TreeMap<String, MBeanAttributeInfo>();\n for (MBeanAttributeInfo attribute: attributeList) {\n attributeMap.put(attribute.getName(), attribute);\n }\n return attributeMap;\n }", "List<W3CEndpointReference> lookupEndpoints(QName serviceName,\n MatcherDataType matcherData) throws ServiceLocatorFault,\n InterruptedExceptionFault {\n SLPropertiesMatcher matcher = createMatcher(matcherData);\n List<String> names = null;\n List<W3CEndpointReference> result = new ArrayList<W3CEndpointReference>();\n String adress;\n try {\n initLocator();\n if (matcher == null) {\n names = locatorClient.lookup(serviceName);\n } else {\n names = locatorClient.lookup(serviceName, matcher);\n }\n } catch (ServiceLocatorException e) {\n ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail();\n serviceFaultDetail.setLocatorFaultDetail(serviceName.toString()\n + \"throws ServiceLocatorFault\");\n throw new ServiceLocatorFault(e.getMessage(), serviceFaultDetail);\n } catch (InterruptedException e) {\n InterruptionFaultDetail interruptionFaultDetail = new InterruptionFaultDetail();\n interruptionFaultDetail.setInterruptionDetail(serviceName\n .toString() + \"throws InterruptionFault\");\n throw new InterruptedExceptionFault(e.getMessage(),\n interruptionFaultDetail);\n }\n if (names != null && !names.isEmpty()) {\n for (int i = 0; i < names.size(); i++) {\n adress = names.get(i);\n result.add(buildEndpoint(serviceName, adress));\n }\n } else {\n if (LOG.isLoggable(Level.WARNING)) {\n LOG.log(Level.WARNING, \"lookup Endpoints for \" + serviceName\n + \" failed, service is not known.\");\n }\n ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail();\n serviceFaultDetail.setLocatorFaultDetail(\"lookup Endpoint for \"\n + serviceName + \" failed, service is not known.\");\n throw new ServiceLocatorFault(\"Can not find Endpoint\",\n serviceFaultDetail);\n }\n return result;\n }", "public static PropertyOrder.Builder makeOrder(String property,\n PropertyOrder.Direction direction) {\n return PropertyOrder.newBuilder()\n .setProperty(makePropertyReference(property))\n .setDirection(direction);\n }", "public static List<String> toList(CharSequence self) {\n String s = self.toString();\n int size = s.length();\n List<String> answer = new ArrayList<String>(size);\n for (int i = 0; i < size; i++) {\n answer.add(s.substring(i, i + 1));\n }\n return answer;\n }", "public static vpnglobal_authenticationsamlpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_authenticationsamlpolicy_binding obj = new vpnglobal_authenticationsamlpolicy_binding();\n\t\tvpnglobal_authenticationsamlpolicy_binding response[] = (vpnglobal_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void selectTab() {\n for (Widget child : getChildren()) {\n if (child instanceof HasHref) {\n String href = ((HasHref) child).getHref();\n if (parent != null && !href.isEmpty()) {\n parent.selectTab(href.replaceAll(\"[^a-zA-Z\\\\d\\\\s:]\", \"\"));\n parent.reload();\n break;\n }\n }\n }\n }" ]
Determines whether the object is a materialized object, i.e. no proxy or a proxy that has already been loaded from the database. @param object The object to test @return <code>true</code> if the object is materialized
[ "public boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }" ]
[ "public void updateFrontFacingRotation(float rotation) {\n if (!Float.isNaN(rotation) && !equal(rotation, frontFacingRotation)) {\n final float oldRotation = frontFacingRotation;\n frontFacingRotation = rotation % 360;\n for (OnFrontRotationChangedListener listener : mOnFrontRotationChangedListeners) {\n try {\n listener.onFrontRotationChanged(this, frontFacingRotation, oldRotation);\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(TAG, e, \"updateFrontFacingRotation()\");\n }\n }\n }\n }", "private String readOptionalString(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n return str.stringValue();\n }\n return null;\n }", "public int deleteTopic(String topic, String password) throws IOException {\n KV<Receive, ErrorMapping> response = send(new DeleterRequest(topic, password));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }", "protected void append(Env env) {\n addAllWithFilter(this.envVars, env.envVars, filter.getPatternFilter());\n addAllWithFilter(this.sysVars, env.sysVars, filter.getPatternFilter());\n }", "public synchronized void start() throws SocketException {\n\n if (!isRunning()) {\n socket.set(new DatagramSocket(ANNOUNCEMENT_PORT));\n startTime.set(System.currentTimeMillis());\n deliverLifecycleAnnouncement(logger, true);\n\n final byte[] buffer = new byte[512];\n final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);\n Thread receiver = new Thread(null, new Runnable() {\n @Override\n public void run() {\n boolean received;\n while (isRunning()) {\n try {\n if (getCurrentDevices().isEmpty()) {\n socket.get().setSoTimeout(60000); // We have no devices to check for timeout; block for a whole minute to check for shutdown\n } else {\n socket.get().setSoTimeout(1000); // Check every second to see if a device has vanished\n }\n socket.get().receive(packet);\n received = !ignoredAddresses.contains(packet.getAddress());\n } catch (SocketTimeoutException ste) {\n received = false;\n } catch (IOException e) {\n // Don't log a warning if the exception was due to the socket closing at shutdown.\n if (isRunning()) {\n // We did not expect to have a problem; log a warning and shut down.\n logger.warn(\"Problem reading from DeviceAnnouncement socket, stopping\", e);\n stop();\n }\n received = false;\n }\n try {\n if (received && (packet.getLength() == 54)) {\n final Util.PacketType kind = Util.validateHeader(packet, ANNOUNCEMENT_PORT);\n if (kind == Util.PacketType.DEVICE_KEEP_ALIVE) {\n // Looks like the kind of packet we need\n if (packet.getLength() < 54) {\n logger.warn(\"Ignoring too-short \" + kind.name + \" packet; expected 54 bytes, but only got \" +\n packet.getLength() + \".\");\n } else {\n if (packet.getLength() > 54) {\n logger.warn(\"Processing too-long \" + kind.name + \" packet; expected 54 bytes, but got \" +\n packet.getLength() + \".\");\n }\n DeviceAnnouncement announcement = new DeviceAnnouncement(packet);\n final boolean foundNewDevice = isDeviceNew(announcement);\n updateDevices(announcement);\n if (foundNewDevice) {\n deliverFoundAnnouncement(announcement);\n }\n }\n }\n }\n expireDevices();\n } catch (Throwable t) {\n logger.warn(\"Problem processing DeviceAnnouncement packet\", t);\n }\n }\n }\n }, \"beat-link DeviceFinder receiver\");\n receiver.setDaemon(true);\n receiver.start();\n }\n }", "public AiTextureInfo getTextureInfo(AiTextureType type, int index) {\n return new AiTextureInfo(type, index, getTextureFile(type, index), \n getTextureUVIndex(type, index), getBlendFactor(type, index), \n getTextureOp(type, index), getTextureMapModeW(type, index), \n getTextureMapModeW(type, index), \n getTextureMapModeW(type, index));\n }", "private int findAvailablePortNumber( Integer portNumberStartingPoint, List<Integer> reservedPorts )\n {\n assert portNumberStartingPoint != null;\n int candidate = portNumberStartingPoint;\n while ( reservedPorts.contains( candidate ) )\n {\n candidate++;\n }\n return candidate;\n }", "@SuppressWarnings({ \"unchecked\", \"rawtypes\", \"unused\" })\n private void commitToVoldemort(List<String> storeNamesToCommit) {\n\n if(logger.isDebugEnabled()) {\n logger.debug(\"Trying to commit to Voldemort\");\n }\n\n boolean hasError = false;\n if(nodesToStream == null || nodesToStream.size() == 0) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"No nodes to stream to. Returning.\");\n }\n return;\n }\n\n for(Node node: nodesToStream) {\n\n for(String store: storeNamesToCommit) {\n if(!nodeIdStoreInitialized.get(new Pair(store, node.getId())))\n continue;\n\n nodeIdStoreInitialized.put(new Pair(store, node.getId()), false);\n\n DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair(store,\n node.getId()));\n\n try {\n ProtoUtils.writeEndOfStream(outputStream);\n outputStream.flush();\n DataInputStream inputStream = nodeIdStoreToInputStreamRequest.get(new Pair(store,\n node.getId()));\n VAdminProto.UpdatePartitionEntriesResponse.Builder updateResponse = ProtoUtils.readToBuilder(inputStream,\n VAdminProto.UpdatePartitionEntriesResponse.newBuilder());\n if(updateResponse.hasError()) {\n hasError = true;\n }\n\n } catch(IOException e) {\n logger.error(\"Exception during commit\", e);\n hasError = true;\n if(!faultyNodes.contains(node.getId()))\n faultyNodes.add(node.getId());\n }\n }\n\n }\n\n if(streamingresults == null) {\n logger.warn(\"StreamingSession may not have been initialized since Variable streamingresults is null. Skipping callback \");\n return;\n }\n\n // remove redundant callbacks\n if(hasError) {\n\n logger.info(\"Invoking the Recovery Callback\");\n Future future = streamingresults.submit(recoveryCallback);\n try {\n future.get();\n\n } catch(InterruptedException e1) {\n MARKED_BAD = true;\n logger.error(\"Recovery Callback failed\", e1);\n throw new VoldemortException(\"Recovery Callback failed\");\n } catch(ExecutionException e1) {\n MARKED_BAD = true;\n logger.error(\"Recovery Callback failed during execution\", e1);\n throw new VoldemortException(\"Recovery Callback failed during execution\");\n }\n } else {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Commit successful\");\n logger.debug(\"calling checkpoint callback\");\n }\n Future future = streamingresults.submit(checkpointCallback);\n try {\n future.get();\n\n } catch(InterruptedException e1) {\n logger.warn(\"Checkpoint callback failed!\", e1);\n } catch(ExecutionException e1) {\n logger.warn(\"Checkpoint callback failed during execution!\", e1);\n }\n }\n\n }", "public static appfwlearningdata[] get(nitro_service service, appfwlearningdata_args args) throws Exception{\n\t\tappfwlearningdata obj = new appfwlearningdata();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tappfwlearningdata[] response = (appfwlearningdata[])obj.get_resources(service, option);\n\t\treturn response;\n\t}" ]
Reads data from the SP file. @return Project File instance
[ "private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n m_project.getProjectProperties().setFileApplication(\"Synchro\");\n m_project.getProjectProperties().setFileType(\"SP\");\n\n CustomFieldContainer fields = m_project.getCustomFields();\n fields.getCustomField(TaskField.TEXT1).setAlias(\"Code\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n processCalendars();\n processResources();\n processTasks();\n processPredecessors();\n\n return m_project;\n }" ]
[ "public static Integer getDurationValue(ProjectProperties properties, Duration duration)\n {\n Integer result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.MINUTES)\n {\n duration = duration.convertUnits(TimeUnit.MINUTES, properties);\n }\n result = Integer.valueOf((int) duration.getDuration());\n }\n return (result);\n }", "@JsonProperty\n public String timestamp() {\n if (timestampAsText == null) {\n timestampAsText = DateTimeFormatter.ISO_INSTANT.format(timestamp);\n }\n return timestampAsText;\n }", "public static vridparam get(nitro_service service) throws Exception{\n\t\tvridparam obj = new vridparam();\n\t\tvridparam[] response = (vridparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "private CmsSpellcheckingRequest parseJsonRequest(JSONObject jsonRequest) {\n\n final String id = jsonRequest.optString(JSON_ID);\n\n final JSONObject params = jsonRequest.optJSONObject(JSON_PARAMS);\n\n if (null == params) {\n LOG.debug(\"Invalid JSON request: No field \\\"params\\\" defined. \");\n return null;\n }\n final JSONArray words = params.optJSONArray(JSON_WORDS);\n final String lang = params.optString(JSON_LANG, LANG_DEFAULT);\n if (null == words) {\n LOG.debug(\"Invalid JSON request: No field \\\"words\\\" defined. \");\n return null;\n }\n\n // Convert JSON array to array of type String\n final List<String> wordsToCheck = new LinkedList<String>();\n for (int i = 0; i < words.length(); i++) {\n final String word = words.opt(i).toString();\n wordsToCheck.add(word);\n\n if (Character.isUpperCase(word.codePointAt(0))) {\n wordsToCheck.add(word.toLowerCase());\n }\n }\n\n return new CmsSpellcheckingRequest(wordsToCheck.toArray(new String[wordsToCheck.size()]), lang, id);\n }", "public MACAddress toEUI64(boolean asMAC) {\r\n\t\tif(!isExtended()) {//getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT\r\n\t\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\t\tMACAddressSegment segs[] = creator.createSegmentArray(EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT);\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tsection.getSegments(0, 3, segs, 0);\r\n\t\t\tMACAddressSegment ffSegment = creator.createSegment(0xff);\r\n\t\t\tsegs[3] = ffSegment;\r\n\t\t\tsegs[4] = asMAC ? ffSegment : creator.createSegment(0xfe);\r\n\t\t\tsection.getSegments(3, 6, segs, 5);\r\n\t\t\tInteger prefLength = getPrefixLength();\r\n\t\t\tif(prefLength != null) {\r\n\t\t\t\tMACAddressSection resultSection = creator.createSectionInternal(segs, true);\r\n\t\t\t\tif(prefLength >= 24) {\r\n\t\t\t\t\tprefLength += MACAddress.BITS_PER_SEGMENT << 1; //two segments\r\n\t\t\t\t}\r\n\t\t\t\tresultSection.assignPrefixLength(prefLength);\r\n\t\t\t}\r\n\t\t\treturn creator.createAddressInternal(segs);\r\n\t\t} else {\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tMACAddressSegment seg3 = section.getSegment(3);\r\n\t\t\tMACAddressSegment seg4 = section.getSegment(4);\r\n\t\t\tif(seg3.matches(0xff) && seg4.matches(asMAC ? 0xff : 0xfe)) {\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new IncompatibleAddressException(this, \"ipaddress.mac.error.not.eui.convertible\");\r\n\t}", "public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }", "public boolean removeHandlerFactory(ManagementRequestHandlerFactory instance) {\n for(;;) {\n final ManagementRequestHandlerFactory[] snapshot = updater.get(this);\n final int length = snapshot.length;\n int index = -1;\n for(int i = 0; i < length; i++) {\n if(snapshot[i] == instance) {\n index = i;\n break;\n }\n }\n if(index == -1) {\n return false;\n }\n final ManagementRequestHandlerFactory[] newVal = new ManagementRequestHandlerFactory[length - 1];\n System.arraycopy(snapshot, 0, newVal, 0, index);\n System.arraycopy(snapshot, index + 1, newVal, index, length - index - 1);\n if (updater.compareAndSet(this, snapshot, newVal)) {\n return true;\n }\n }\n }", "public void run() {\r\n\t\tConnectionHandle connection = null;\r\n\t\tlong tmp;\r\n\t\tlong nextCheckInMs = this.maxAgeInMs;\r\n\r\n\t\tint partitionSize= this.partition.getAvailableConnections();\r\n\t\tlong currentTime = System.currentTimeMillis();\r\n\t\tfor (int i=0; i < partitionSize; i++){\r\n\t\t\ttry {\r\n\t\t\t\tconnection = this.partition.getFreeConnections().poll();\r\n\r\n\t\t\t\tif (connection != null){\r\n\t\t\t\t\tconnection.setOriginatingPartition(this.partition);\r\n\r\n\t\t\t\t\ttmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); \r\n\r\n\t\t\t\t\tif (tmp < nextCheckInMs){\r\n\t\t\t\t\t\tnextCheckInMs = tmp; \r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (connection.isExpired(currentTime)){\r\n\t\t\t\t\t\t// kill off this connection\r\n\t\t\t\t\t\tcloseConnection(connection);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (this.lifoMode){\r\n\t\t\t\t\t\t// we can't put it back normally or it will end up in front again.\r\n\t\t\t\t\t\tif (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){\r\n\t\t\t\t\t\t\tconnection.internalClose();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tthis.pool.putConnectionBackInPartition(connection);\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tThread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)...\r\n\t\t\t\t}\r\n\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tlogger.error(\"Connection max age thread exception.\", e);\r\n\t\t\t}\r\n\r\n\t\t} // throw it back on the queue\r\n\r\n\t}", "public static appflowpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_binding obj = new appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_binding response = (appflowpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Get maximum gray value in the image. @param fastBitmap Image to be processed. @param startX Initial X axis coordinate. @param startY Initial Y axis coordinate. @param width Width. @param height Height. @return Maximum gray.
[ "public static int Maximum(ImageSource fastBitmap, int startX, int startY, int width, int height) {\r\n int max = 0;\r\n\r\n if (fastBitmap.isGrayscale()) {\r\n for (int i = startX; i < height; i++) {\r\n for (int j = startY; j < width; j++) {\r\n int gray = fastBitmap.getRGB(j, i);\r\n if (gray > max) {\r\n max = gray;\r\n }\r\n }\r\n }\r\n } else {\r\n for (int i = startX; i < height; i++) {\r\n for (int j = startY; j < width; j++) {\r\n int gray = fastBitmap.getG(j, i);\r\n if (gray > max) {\r\n max = gray;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return max;\r\n }" ]
[ "private void addEdgesForVertex(Vertex vertex)\r\n {\r\n ClassDescriptor cld = vertex.getEnvelope().getClassDescriptor();\r\n Iterator rdsIter = cld.getObjectReferenceDescriptors(true).iterator();\r\n while (rdsIter.hasNext())\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) rdsIter.next();\r\n addObjectReferenceEdges(vertex, rds);\r\n }\r\n Iterator cdsIter = cld.getCollectionDescriptors(true).iterator();\r\n while (cdsIter.hasNext())\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) cdsIter.next();\r\n addCollectionEdges(vertex, cds);\r\n }\r\n }", "@SuppressWarnings(\"deprecation\")\n @Deprecated\n public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException {\n validateOperation(operationObject);\n for (AttributeDefinition ad : this.parameters) {\n ad.validateAndSet(operationObject, model);\n }\n }", "public EndpointOverride getPath(int pathId, String clientUUID, String[] filters) throws Exception {\n EndpointOverride endpoint = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID + \"=\" + pathId + \";\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n results = statement.executeQuery();\n\n if (results.next()) {\n endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return endpoint;\n }", "public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getInsertStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }", "private void getDailyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n while (moreDates(calendar, dates))\n {\n dates.add(calendar.getTime());\n calendar.add(Calendar.DAY_OF_YEAR, frequency);\n }\n }", "public static double elementMin( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n // if every element is assigned a value then the first element can be a minimum.\n // Otherwise zero needs to be considered\n double min = A.isFull() ? A.nz_values[0] : 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n double val = A.nz_values[i];\n if( val < min ) {\n min = val;\n }\n }\n\n return min;\n }", "private Bpmn2Resource unmarshall(JsonParser parser,\n String preProcessingData) throws IOException {\n try {\n parser.nextToken(); // open the object\n ResourceSet rSet = new ResourceSetImpl();\n rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(\"bpmn2\",\n new JBPMBpmn2ResourceFactoryImpl());\n Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI(\"virtual.bpmn2\"));\n rSet.getResources().add(bpmn2);\n _currentResource = bpmn2;\n\n if (preProcessingData == null || preProcessingData.length() < 1) {\n preProcessingData = \"ReadOnlyService\";\n }\n\n // do the unmarshalling now:\n Definitions def = (Definitions) unmarshallItem(parser,\n preProcessingData);\n def.setExporter(exporterName);\n def.setExporterVersion(exporterVersion);\n revisitUserTasks(def);\n revisitServiceTasks(def);\n revisitMessages(def);\n revisitCatchEvents(def);\n revisitThrowEvents(def);\n revisitLanes(def);\n revisitSubProcessItemDefs(def);\n revisitArtifacts(def);\n revisitGroups(def);\n revisitTaskAssociations(def);\n revisitTaskIoSpecification(def);\n revisitSendReceiveTasks(def);\n reconnectFlows();\n revisitGateways(def);\n revisitCatchEventsConvertToBoundary(def);\n revisitBoundaryEventsPositions(def);\n createDiagram(def);\n updateIDs(def);\n revisitDataObjects(def);\n revisitAssociationsIoSpec(def);\n revisitWsdlImports(def);\n revisitMultiInstanceTasks(def);\n addSimulation(def);\n revisitItemDefinitions(def);\n revisitProcessDoc(def);\n revisitDI(def);\n revisitSignalRef(def);\n orderDiagramElements(def);\n\n // return def;\n _currentResource.getContents().add(def);\n return _currentResource;\n } catch (Exception e) {\n _logger.error(e.getMessage());\n return _currentResource;\n } finally {\n parser.close();\n _objMap.clear();\n _idMap.clear();\n _outgoingFlows.clear();\n _sequenceFlowTargets.clear();\n _bounds.clear();\n _currentResource = null;\n }\n }", "protected static Statement memorize(final Statement target, final ConnectionHandle connectionHandle) {\n\t\treturn (Statement) Proxy.newProxyInstance(\n\t\t\t\tStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {StatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "public static String toJson(Date date) {\n if (date == null) {\n return NULL_VALUE;\n }\n\n CharBuf buffer = CharBuf.create(26);\n writeDate(date, buffer);\n\n return buffer.toString();\n }" ]
This method returns an array containing all of the unique identifiers for which data has been stored in the Var2Data block. @return array of unique identifiers
[ "@Override public Integer[] getUniqueIdentifierArray()\n {\n Integer[] result = new Integer[m_table.size()];\n int index = 0;\n for (Integer value : m_table.keySet())\n {\n result[index] = value;\n ++index;\n }\n return (result);\n }" ]
[ "protected DatabaseConnection getSavedConnection() {\n\t\tNestedConnection nested = specialConnection.get();\n\t\tif (nested == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn nested.connection;\n\t\t}\n\t}", "public CollectionRequest<Task> findByProject(String projectId) {\n \n String path = String.format(\"/projects/%s/tasks\", projectId);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "public void executeDelete(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeDelete: \" + obj);\r\n }\r\n\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n try\r\n {\r\n stmt = sm.getDeleteStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getDeleteStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"JdbcAccessImpl: getDeleteStatement returned a null statement\");\r\n }\r\n\r\n sm.bindDelete(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeDelete: \" + stmt);\r\n\r\n // @todo: clearify semantics\r\n // thma: the following check is not secure. The object could be deleted *or* changed.\r\n // if it was deleted it makes no sense to throw an OL exception.\r\n // does is make sense to throw an OL exception if the object was changed?\r\n if (stmt.executeUpdate() == 0 && cld.isLocking()) //BRJ\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tString objToString = \"\";\r\n \ttry {\r\n \t\tobjToString = obj.toString();\r\n \t} catch (Exception ex) {}\r\n throw new OptimisticLockException(\"Object has been modified or deleted by someone else: \" + objToString, obj);\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getDeleteProcedure(), obj, stmt);\r\n }\r\n catch (OptimisticLockException e)\r\n {\r\n // Don't log as error\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"OptimisticLockException during the execution of delete: \"\r\n + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of delete: \"\r\n + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedDeleteStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }", "public static boolean start(RootDoc root) {\n\troot.printNotice(\"UmlGraphDoc version \" + Version.VERSION + \", running the standard doclet\");\n\tStandard.start(root);\n\troot.printNotice(\"UmlGraphDoc version \" + Version.VERSION + \", altering javadocs\");\n\ttry {\n\t String outputFolder = findOutputPath(root.options());\n\n Options opt = UmlGraph.buildOptions(root);\n\t opt.setOptions(root.options());\n\t // in javadoc enumerations are always printed\n\t opt.showEnumerations = true;\n\t opt.relativeLinksForSourcePackages = true;\n\t // enable strict matching for hide expressions\n\t opt.strictMatching = true;\n//\t root.printNotice(opt.toString());\n\n\t generatePackageDiagrams(root, opt, outputFolder);\n\t generateContextDiagrams(root, opt, outputFolder);\n\t} catch(Throwable t) {\n\t root.printWarning(\"Error: \" + t.toString());\n\t t.printStackTrace();\n\t return false;\n\t}\n\treturn true;\n }", "private void merge(ExecutionStatistics otherStatistics) {\n for (String s : otherStatistics.executionInfo.keySet())\n {\n TimingData thisStats = this.executionInfo.get(s);\n TimingData otherStats = otherStatistics.executionInfo.get(s);\n if(thisStats == null) {\n this.executionInfo.put(s,otherStats);\n } else {\n thisStats.merge(otherStats);\n }\n\n }\n }", "public void setBackgroundColor(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }", "public static base_response convert(nitro_service client, sslpkcs12 resource) throws Exception {\n\t\tsslpkcs12 convertresource = new sslpkcs12();\n\t\tconvertresource.outfile = resource.outfile;\n\t\tconvertresource.Import = resource.Import;\n\t\tconvertresource.pkcs12file = resource.pkcs12file;\n\t\tconvertresource.des = resource.des;\n\t\tconvertresource.des3 = resource.des3;\n\t\tconvertresource.export = resource.export;\n\t\tconvertresource.certfile = resource.certfile;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.password = resource.password;\n\t\tconvertresource.pempassphrase = resource.pempassphrase;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}", "private static boolean typeEquals(ParameterizedType from,\n\t\t\tParameterizedType to, Map<String, Type> typeVarMap) {\n\t\tif (from.getRawType().equals(to.getRawType())) {\n\t\t\tType[] fromArgs = from.getActualTypeArguments();\n\t\t\tType[] toArgs = to.getActualTypeArguments();\n\t\t\tfor (int i = 0; i < fromArgs.length; i++) {\n\t\t\t\tif (!matches(fromArgs[i], toArgs[i], typeVarMap)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "public void forAllForeignkeyColumnPairs(String template, Properties attributes) throws XDocletException\r\n {\r\n for (int idx = 0; idx < _curForeignkeyDef.getNumColumnPairs(); idx++)\r\n {\r\n _curPairLeft = _curForeignkeyDef.getLocalColumn(idx);\r\n _curPairRight = _curForeignkeyDef.getRemoteColumn(idx);\r\n generate(template);\r\n }\r\n _curPairLeft = null;\r\n _curPairRight = null;\r\n }" ]
Option check, forwards options to the standard doclet, if that one refuses them, they are sent to UmlGraph
[ "public static int optionLength(String option) {\n\tint result = Standard.optionLength(option);\n\tif (result != 0)\n\t return result;\n\telse\n\t return UmlGraph.optionLength(option);\n }" ]
[ "protected Object[] escape(final Format format, Object... args) {\n // Transformer that escapes HTML,XML,JSON strings\n Transformer<Object, Object> escapingTransformer = new Transformer<Object, Object>() {\n @Override\n public Object transform(Object object) {\n return format.escapeValue(object);\n }\n };\n List<Object> list = Arrays.asList(ArrayUtils.clone(args));\n CollectionUtils.transform(list, escapingTransformer);\n return list.toArray();\n }", "public MessageSet read(long readOffset, long size) throws IOException {\n return new FileMessageSet(channel, this.offset + readOffset, //\n Math.min(this.offset + readOffset + size, highWaterMark()), false, new AtomicBoolean(false));\n }", "private Duration getDuration(String value)\n {\n Duration result = null;\n\n if (value != null && value.length() != 0)\n {\n double seconds = getLong(value);\n double hours = seconds / (60 * 60);\n double days = hours / 8;\n\n if (days < 1)\n {\n result = Duration.getInstance(hours, TimeUnit.HOURS);\n }\n else\n {\n double durationDays = hours / 8;\n result = Duration.getInstance(durationDays, TimeUnit.DAYS);\n }\n }\n\n return (result);\n }", "public ModelNode getDeploymentSubsystemModel(final String subsystemName) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit);\n }", "private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(ClientConfig.ENABLE_JMX_PROPERTY)) {\n this.setEnableJmx(props.getBoolean(ClientConfig.ENABLE_JMX_PROPERTY));\n }\n\n if(props.containsKey(ClientConfig.BOOTSTRAP_URLS_PROPERTY)) {\n List<String> urls = props.getList(ClientConfig.BOOTSTRAP_URLS_PROPERTY);\n if(urls.size() > 0) {\n setHttpBootstrapURL(urls.get(0));\n }\n }\n\n if(props.containsKey(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY)) {\n setMaxR2ConnectionPoolSize(props.getInt(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY,\n maxR2ConnectionPoolSize));\n }\n\n if(props.containsKey(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY))\n this.setTimeoutMs(props.getLong(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY, timeoutMs),\n TimeUnit.MILLISECONDS);\n\n // By default, make all the timeouts equal to routing timeout\n timeoutConfig = new TimeoutConfig(timeoutMs, false);\n\n if(props.containsKey(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_ALL_OP_CODE,\n props.getInt(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_OP_CODE,\n props.getInt(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY)) {\n long putTimeoutMs = props.getInt(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY);\n timeoutConfig.setOperationTimeout(VoldemortOpCode.PUT_OP_CODE, putTimeoutMs);\n // By default, use the same thing for getVersions() also\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE, putTimeoutMs);\n }\n\n // of course, if someone overrides it, we will respect that\n if(props.containsKey(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE,\n props.getInt(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.DELETE_OP_CODE,\n props.getInt(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY))\n timeoutConfig.setPartialGetAllAllowed(props.getBoolean(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY));\n\n }", "private static String loadUA(ClassLoader loader, String filename){\n String ua = \"cloudant-http\";\n String version = \"unknown\";\n final InputStream propStream = loader.getResourceAsStream(filename);\n final Properties properties = new Properties();\n try {\n if (propStream != null) {\n try {\n properties.load(propStream);\n } finally {\n propStream.close();\n }\n }\n ua = properties.getProperty(\"user.agent.name\", ua);\n version = properties.getProperty(\"user.agent.version\", version);\n } catch (IOException e) {\n // Swallow exception and use default values.\n }\n\n return String.format(Locale.ENGLISH, \"%s/%s\", ua,version);\n }", "private String getIntegerString(Number value)\n {\n return (value == null ? null : Integer.toString(value.intValue()));\n }", "void update(JsonObject jsonObject) {\n for (JsonObject.Member member : jsonObject) {\n if (member.getValue().isNull()) {\n continue;\n }\n\n this.parseJSONMember(member);\n }\n\n this.clearPendingChanges();\n }", "public static String md5(byte[] source) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(source);\n byte tmp[] = md.digest();\n char str[] = new char[32];\n int k = 0;\n for (byte b : tmp) {\n str[k++] = hexDigits[b >>> 4 & 0xf];\n str[k++] = hexDigits[b & 0xf];\n }\n return new String(str);\n\n } catch (Exception e) {\n throw new IllegalArgumentException(e);\n }\n }" ]
read all brokers in the zookeeper @param zkClient zookeeper client @return all brokers
[ "public static Cluster getCluster(ZkClient zkClient) {\n Cluster cluster = new Cluster();\n List<String> nodes = getChildrenParentMayNotExist(zkClient, BrokerIdsPath);\n for (String node : nodes) {\n final String brokerInfoString = readData(zkClient, BrokerIdsPath + \"/\" + node);\n cluster.add(Broker.createBroker(Integer.valueOf(node), brokerInfoString));\n }\n return cluster;\n }" ]
[ "public void addCell(TableLayoutCell cell) {\n GridBagConstraints constraints = cell.getConstraints();\n constraints.insets = new Insets(cellpadding, cellpadding, cellpadding, cellpadding);\n add(cell.getComponent(), constraints);\n }", "private void readUnread(CommitData cd, Consumer<Entry<Key, Value>> locksSeen) {\n // TODO make async\n // TODO need to keep track of ranges read (not ranges passed in, but actual data read... user\n // may not iterate over entire range\n Map<Bytes, Set<Column>> columnsToRead = new HashMap<>();\n\n for (Entry<Bytes, Set<Column>> entry : cd.getRejected().entrySet()) {\n Set<Column> rowColsRead = columnsRead.get(entry.getKey());\n if (rowColsRead == null) {\n columnsToRead.put(entry.getKey(), entry.getValue());\n } else {\n HashSet<Column> colsToRead = new HashSet<>(entry.getValue());\n colsToRead.removeAll(rowColsRead);\n if (!colsToRead.isEmpty()) {\n columnsToRead.put(entry.getKey(), colsToRead);\n }\n }\n }\n\n for (Entry<Bytes, Set<Column>> entry : columnsToRead.entrySet()) {\n getImpl(entry.getKey(), entry.getValue(), locksSeen);\n }\n }", "public void setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tif(targetTranslator!=null){\r\n\t\t\tthis.targetTranslator = targetTranslator;\r\n\t\t\tthis.charTranslator = null;\r\n\t\t\tthis.htmlElementTranslator = null;\r\n\t\t}\r\n\t}", "public static Optional<Field> getField(Class<?> type, final String fieldName) {\n Optional<Field> field = Iterables.tryFind(newArrayList(type.getDeclaredFields()), havingFieldName(fieldName));\n\n if (!field.isPresent() && type.getSuperclass() != null){\n field = getField(type.getSuperclass(), fieldName);\n }\n\n return field;\n }", "@Override\n public final Boolean optBool(final String key, final Boolean defaultValue) {\n Boolean result = optBool(key);\n return result == null ? defaultValue : result;\n }", "public String getRecordSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String recSchema = schema.toString();\n return recSchema;\n }", "public GeoPermissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // response:\r\n // <perms id=\"240935723\" ispublic=\"1\" iscontact=\"0\" isfriend=\"0\" isfamily=\"0\"/>\r\n GeoPermissions perms = new GeoPermissions();\r\n Element permsElement = response.getPayload();\r\n perms.setPublic(\"1\".equals(permsElement.getAttribute(\"ispublic\")));\r\n perms.setContact(\"1\".equals(permsElement.getAttribute(\"iscontact\")));\r\n perms.setFriend(\"1\".equals(permsElement.getAttribute(\"isfriend\")));\r\n perms.setFamily(\"1\".equals(permsElement.getAttribute(\"isfamily\")));\r\n perms.setId(permsElement.getAttribute(\"id\"));\r\n // I ignore the id attribute. should be the same as the given\r\n // photo id.\r\n return perms;\r\n }", "public void update(short number) {\n byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_SHORT];\n ByteUtils.writeShort(numberInBytes, number, 0);\n update(numberInBytes);\n }", "public BoxFileUploadSession.Info createUploadSession(long fileSize) {\n URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.addHeader(\"Content-Type\", \"application/json\");\n\n JsonObject body = new JsonObject();\n body.add(\"file_size\", fileSize);\n request.setBody(body.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n String sessionId = jsonObject.get(\"id\").asString();\n BoxFileUploadSession session = new BoxFileUploadSession(this.getAPI(), sessionId);\n return session.new Info(jsonObject);\n }" ]
Insert a new value prior to the index location in the existing value array, increasing the field length accordingly. @param index - where the new values in an SFVec2f object will be placed in the array list @param newValue - the new x, y value for the array list
[ "public void insertValue(int index, float[] newValue) {\n if ( newValue.length == 2) {\n try {\n value.add( index, new SFVec2f(newValue[0], newValue[1]) );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFVec2f get1Value(index) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFVec2f get1Value(index) exception \" + e);\n }\n }\n else {\n Log.e(TAG, \"X3D MFVec2f insertValue set with array length not equal to 2\");\n }\n }" ]
[ "public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_WHITELIST_ENTRY_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE);\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public static base_responses add(nitro_service client, dbdbprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdbdbprofile addresources[] = new dbdbprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dbdbprofile();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].interpretquery = resources[i].interpretquery;\n\t\t\t\taddresources[i].stickiness = resources[i].stickiness;\n\t\t\t\taddresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\taddresources[i].conmultiplex = resources[i].conmultiplex;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private static void validateIfAvroSchema(SerializerDefinition serializerDef) {\n if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerDef.getName().equals(AVRO_GENERIC_TYPE_NAME)) {\n SchemaEvolutionValidator.validateAllAvroSchemas(serializerDef);\n // check backwards compatibility if needed\n if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)) {\n SchemaEvolutionValidator.checkSchemaCompatibility(serializerDef);\n }\n }\n }", "public Curve getRegressionCurve(){\n\t\t// @TODO Add threadsafe lazy init.\n\t\tif(regressionCurve !=null) {\n\t\t\treturn regressionCurve;\n\t\t}\n\t\tDoubleMatrix a = solveEquationSystem();\n\t\tdouble[] curvePoints=new double[partition.getLength()];\n\t\tcurvePoints[0]=a.get(0);\n\t\tfor(int i=1;i<curvePoints.length;i++) {\n\t\t\tcurvePoints[i]=curvePoints[i-1]+a.get(i)*(partition.getIntervalLength(i-1));\n\t\t}\n\t\treturn new CurveInterpolation(\n\t\t\t\t\"RegressionCurve\",\n\t\t\t\treferenceDate,\n\t\t\t\tCurveInterpolation.InterpolationMethod.LINEAR,\n\t\t\t\tCurveInterpolation.ExtrapolationMethod.CONSTANT,\n\t\t\t\tCurveInterpolation.InterpolationEntity.VALUE,\n\t\t\t\tpartition.getPoints(),\n\t\t\t\tcurvePoints);\n\t}", "private ModelNode createOSNode() throws OperationFailedException {\n String osName = getProperty(\"os.name\");\n final ModelNode os = new ModelNode();\n if (osName != null && osName.toLowerCase().contains(\"linux\")) {\n try {\n os.set(GnuLinuxDistribution.discover());\n } catch (IOException ex) {\n throw new OperationFailedException(ex);\n }\n } else {\n os.set(osName);\n }\n return os;\n }", "protected void setWhenNoDataBand() {\n log.debug(\"setting up WHEN NO DATA band\");\n String whenNoDataText = getReport().getWhenNoDataText();\n Style style = getReport().getWhenNoDataStyle();\n if (whenNoDataText == null || \"\".equals(whenNoDataText))\n return;\n JRDesignBand band = new JRDesignBand();\n getDesign().setNoData(band);\n\n JRDesignTextField text = new JRDesignTextField();\n JRDesignExpression expression = ExpressionUtils.createStringExpression(\"\\\"\" + whenNoDataText + \"\\\"\");\n text.setExpression(expression);\n\n if (style == null) {\n style = getReport().getOptions().getDefaultDetailStyle();\n }\n\n if (getReport().isWhenNoDataShowTitle()) {\n LayoutUtils.copyBandElements(band, getDesign().getTitle());\n LayoutUtils.copyBandElements(band, getDesign().getPageHeader());\n }\n if (getReport().isWhenNoDataShowColumnHeader())\n LayoutUtils.copyBandElements(band, getDesign().getColumnHeader());\n\n int offset = LayoutUtils.findVerticalOffset(band);\n text.setY(offset);\n applyStyleToElement(style, text);\n text.setWidth(getReport().getOptions().getPrintableWidth());\n text.setHeight(50);\n band.addElement(text);\n log.debug(\"OK setting up WHEN NO DATA band\");\n\n }", "private static void checkPreconditions(final Map<Object, Object> mapping) {\n\t\tif( mapping == null ) {\n\t\t\tthrow new NullPointerException(\"mapping should not be null\");\n\t\t} else if( mapping.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"mapping should not be empty\");\n\t\t}\n\t}", "public static Object lookup(String jndiName)\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"lookup(\"+jndiName+\") was called\");\r\n try\r\n {\r\n return getContext().lookup(jndiName);\r\n }\r\n catch (NamingException e)\r\n {\r\n throw new OJBRuntimeException(\"Lookup failed for: \" + jndiName, e);\r\n }\r\n catch(OJBRuntimeException e)\r\n {\r\n throw e;\r\n }\r\n }", "public String getDynamicValue(String attribute) {\n\n return null == m_dynamicValues ? null : m_dynamicValues.get(attribute);\n }" ]
Optionally specify the variable name to use for the output of this condition
[ "@Override\n public ConditionBuilder as(String variable)\n {\n Assert.notNull(variable, \"Variable name must not be null.\");\n this.setOutputVariablesName(variable);\n return this;\n }" ]
[ "void forcedUndeployScan() {\n\n if (acquireScanLock()) {\n try {\n ROOT_LOGGER.tracef(\"Performing a post-boot forced undeploy scan for scan directory %s\", deploymentDir.getAbsolutePath());\n ScanContext scanContext = new ScanContext(deploymentOperations);\n\n // Add remove actions to the plan for anything we count as\n // deployed that we didn't find on the scan\n for (Map.Entry<String, DeploymentMarker> missing : scanContext.toRemove.entrySet()) {\n // remove successful deployment and left will be removed\n if (scanContext.registeredDeployments.containsKey(missing.getKey())) {\n scanContext.registeredDeployments.remove(missing.getKey());\n }\n }\n Set<String> scannedDeployments = new HashSet<String>(scanContext.registeredDeployments.keySet());\n scannedDeployments.removeAll(scanContext.persistentDeployments);\n\n List<ScannerTask> scannerTasks = scanContext.scannerTasks;\n for (String toUndeploy : scannedDeployments) {\n scannerTasks.add(new UndeployTask(toUndeploy, deploymentDir, scanContext.scanStartTime, true));\n }\n try {\n executeScannerTasks(scannerTasks, deploymentOperations, true);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n\n ROOT_LOGGER.tracef(\"Forced undeploy scan complete\");\n } catch (Exception e) {\n ROOT_LOGGER.scanException(e, deploymentDir.getAbsolutePath());\n } finally {\n releaseScanLock();\n }\n }\n }", "public static Object instantiate(Constructor constructor) throws InstantiationException\r\n {\r\n if(constructor == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided!\");\r\n }\r\n\r\n Object result = null;\r\n try\r\n {\r\n result = constructor.newInstance(NO_ARGS);\r\n }\r\n catch(InstantiationException e)\r\n {\r\n throw e;\r\n }\r\n catch(Exception e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (constructor != null ? constructor.getDeclaringClass().getName() : \"null\")\r\n + \"' with given constructor: \" + e.getMessage(), e);\r\n }\r\n return result;\r\n }", "public static Calendar popCalendar()\n {\n Calendar result;\n Deque<Calendar> calendars = CALENDARS.get();\n if (calendars.isEmpty())\n {\n result = Calendar.getInstance();\n }\n else\n {\n result = calendars.pop();\n }\n return result;\n }", "public Class<T> getProxyClass() {\n String suffix = \"_$$_Weld\" + getProxyNameSuffix();\n String proxyClassName = getBaseProxyName();\n if (!proxyClassName.endsWith(suffix)) {\n proxyClassName = proxyClassName + suffix;\n }\n if (proxyClassName.startsWith(JAVA)) {\n proxyClassName = proxyClassName.replaceFirst(JAVA, \"org.jboss.weld\");\n }\n Class<T> proxyClass = null;\n Class<?> originalClass = bean != null ? bean.getBeanClass() : proxiedBeanType;\n BeanLogger.LOG.generatingProxyClass(proxyClassName);\n try {\n // First check to see if we already have this proxy class\n proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName));\n } catch (ClassNotFoundException e) {\n // Create the proxy class for this instance\n try {\n proxyClass = createProxyClass(originalClass, proxyClassName);\n } catch (Throwable e1) {\n //attempt to load the class again, just in case another thread\n //defined it between the check and the create method\n try {\n proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName));\n } catch (ClassNotFoundException e2) {\n BeanLogger.LOG.catchingDebug(e1);\n throw BeanLogger.LOG.unableToLoadProxyClass(bean, proxiedBeanType, e1);\n }\n }\n }\n return proxyClass;\n }", "public void convertToDense() {\n switch ( mat.getType() ) {\n case DSCC: {\n DMatrix m = new DMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrix) mat, m);\n setMatrix(m);\n } break;\n case FSCC: {\n FMatrix m = new FMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrix) mat, m);\n setMatrix(m);\n } break;\n case DDRM:\n case FDRM:\n case ZDRM:\n case CDRM:\n break;\n default:\n throw new RuntimeException(\"Not a sparse matrix!\");\n }\n }", "public static base_response add(nitro_service client, dnspolicylabel resource) throws Exception {\n\t\tdnspolicylabel addresource = new dnspolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.transform = resource.transform;\n\t\treturn addresource.add_resource(client);\n\t}", "private void onChangedImpl(final int preferableCenterPosition) {\n for (ListOnChangedListener listener: mOnChangedListeners) {\n listener.onChangedStart(this);\n }\n\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"onChangedImpl(%s): items [%d] views [%d] mLayouts.size() = %d \" +\n \"preferableCenterPosition = %d\",\n getName(), getDataCount(), getViewCount(), mContent.mLayouts.size(), preferableCenterPosition);\n\n // TODO: selectively recycle data based on the changes in the data set\n mPreferableCenterPosition = preferableCenterPosition;\n recycleChildren();\n }", "public boolean toggleProfile(Boolean enabled) {\n // TODO: make this return values properly\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"active\", enabled.toString())\n };\n try {\n String uri = BASE_PROFILE + uriEncode(this._profileName) + \"/\" + BASE_CLIENTS + \"/\";\n if (_clientId == null) {\n uri += \"-1\";\n } else {\n uri += _clientId;\n }\n JSONObject response = new JSONObject(doPost(uri, params));\n } catch (Exception e) {\n // some sort of error\n System.out.println(e.getMessage());\n return false;\n }\n return true;\n }", "public double getValueAsPrice(double evaluationTime, AnalyticModel model) {\n\t\tForwardCurve\tforwardCurve\t= model.getForwardCurve(forwardCurveName);\n\t\tDiscountCurve\tdiscountCurve\t= model.getDiscountCurve(discountCurveName);\n\n\t\tDiscountCurve\tdiscountCurveForForward = null;\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\t// User might like to get forward from discount curve.\n\t\t\tdiscountCurveForForward\t= model.getDiscountCurve(forwardCurveName);\n\n\t\t\tif(discountCurveForForward == null) {\n\t\t\t\t// User specified a name for the forward curve, but no curve was found.\n\t\t\t\tthrow new IllegalArgumentException(\"No curve of the name \" + forwardCurveName + \" was found in the model.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble value = 0.0;\n\t\tfor(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {\n\t\t\tdouble fixingDate\t= schedule.getFixing(periodIndex);\n\t\t\tdouble paymentDate\t= schedule.getPayment(periodIndex);\n\t\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\n\t\t\t/*\n\t\t\t * We do not count empty periods.\n\t\t\t * Since empty periods are an indication for a ill-specified product,\n\t\t\t * it might be reasonable to throw an illegal argument exception instead.\n\t\t\t */\n\t\t\tif(periodLength == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble forward = 0.0;\n\t\t\tif(forwardCurve != null) {\n\t\t\t\tforward\t\t\t+= forwardCurve.getForward(model, fixingDate, paymentDate-fixingDate);\n\t\t\t}\n\t\t\telse if(discountCurveForForward != null) {\n\t\t\t\t/*\n\t\t\t\t * Classical single curve case: using a discount curve as a forward curve.\n\t\t\t\t * This is only implemented for demonstration purposes (an exception would also be appropriate :-)\n\t\t\t\t */\n\t\t\t\tif(fixingDate != paymentDate) {\n\t\t\t\t\tforward\t\t\t+= (discountCurveForForward.getDiscountFactor(fixingDate) / discountCurveForForward.getDiscountFactor(paymentDate) - 1.0) / (paymentDate-fixingDate);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble discountFactor\t= paymentDate > evaluationTime ? discountCurve.getDiscountFactor(model, paymentDate) : 0.0;\n\t\t\tdouble payoffUnit = discountFactor * periodLength;\n\n\t\t\tdouble effektiveStrike = strike;\n\t\t\tif(isStrikeMoneyness) {\n\t\t\t\teffektiveStrike += getATMForward(model, true);\n\t\t\t}\n\n\t\t\tVolatilitySurface volatilitySurface\t= model.getVolatilitySurface(volatiltiySufaceName);\n\t\t\tif(volatilitySurface == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"Volatility surface not found in model: \" + volatiltiySufaceName);\n\t\t\t}\n\t\t\tif(volatilitySurface.getQuotingConvention() == QuotingConvention.VOLATILITYLOGNORMAL) {\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYLOGNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Default to normal volatility as quoting convention\n\t\t\t\tdouble volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYNORMAL);\n\t\t\t\tvalue += AnalyticFormulas.bachelierOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);\n\t\t\t}\n\t\t}\n\n\t\treturn value / discountCurve.getDiscountFactor(model, evaluationTime);\n\t}" ]
Use this API to fetch sslvserver_sslcipher_binding resources of given name .
[ "public static sslvserver_sslcipher_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcipher_binding obj = new sslvserver_sslcipher_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcipher_binding response[] = (sslvserver_sslcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public int deleteTopic(String topic, String password) throws IOException {\n KV<Receive, ErrorMapping> response = send(new DeleterRequest(topic, password));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }", "private void readColumn(int startIndex, int length) throws Exception\n {\n if (m_currentTable != null)\n {\n int value = FastTrackUtility.getByte(m_buffer, startIndex);\n Class<?> klass = COLUMN_MAP[value];\n if (klass == null)\n {\n klass = UnknownColumn.class;\n }\n\n FastTrackColumn column = (FastTrackColumn) klass.newInstance();\n m_currentColumn = column;\n\n logColumnData(startIndex, length);\n\n column.read(m_currentTable.getType(), m_buffer, startIndex, length);\n FastTrackField type = column.getType();\n\n //\n // Don't try to add this data if:\n // 1. We don't know what type it is\n // 2. We have seen the type already\n //\n if (type != null && !m_currentFields.contains(type))\n {\n m_currentFields.add(type);\n m_currentTable.addColumn(column);\n updateDurationTimeUnit(column);\n updateWorkTimeUnit(column);\n\n logColumn(column);\n }\n }\n }", "@Override\n public String getPartialFilterSelector() {\n return (def.selector != null) ? def.selector.toString() : null;\n }", "public static systemcore get(nitro_service service) throws Exception{\n\t\tsystemcore obj = new systemcore();\n\t\tsystemcore[] response = (systemcore[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public void value2x2( double a11 , double a12, double a21 , double a22 )\n {\n // apply a rotators such that th a11 and a22 elements are the same\n double c,s;\n\n if( a12 + a21 == 0 ) { // is this pointless since\n c = s = 1.0 / Math.sqrt(2);\n } else {\n double aa = (a11-a22);\n double bb = (a12+a21);\n\n double t_hat = aa/bb;\n double t = t_hat/(1.0 + Math.sqrt(1.0+t_hat*t_hat));\n\n c = 1.0/ Math.sqrt(1.0+t*t);\n s = c*t;\n }\n\n double c2 = c*c;\n double s2 = s*s;\n double cs = c*s;\n\n double b11 = c2*a11 + s2*a22 - cs*(a12+a21);\n double b12 = c2*a12 - s2*a21 + cs*(a11-a22);\n double b21 = c2*a21 - s2*a12 + cs*(a11-a22);\n// double b22 = c2*a22 + s2*a11 + cs*(a12+a21);\n\n // apply second rotator to make A upper triangular if real eigenvalues\n if( b21*b12 >= 0 ) {\n if( b12 == 0 ) {\n c = 0;\n s = 1;\n } else {\n s = Math.sqrt(b21/(b12+b21));\n c = Math.sqrt(b12/(b12+b21));\n }\n\n// c2 = b12;//c*c;\n// s2 = b21;//s*s;\n cs = c*s;\n\n a11 = b11 - cs*(b12 + b21);\n// a12 = c2*b12 - s2*b21;\n// a21 = c2*b21 - s2*b12;\n a22 = b11 + cs*(b12 + b21);\n\n value0.real = a11;\n value1.real = a22;\n\n value0.imaginary = value1.imaginary = 0;\n\n } else {\n value0.real = value1.real = b11;\n value0.imaginary = Math.sqrt(-b21*b12);\n value1.imaginary = -value0.imaginary;\n }\n }", "@SuppressWarnings(\"rawtypes\") public static final Map getMap(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return ((Map) bundle.getObject(key));\n }", "public void addRelation(RelationType relationType, RelationDirection direction) {\n\tint idx = relationType.ordinal();\n\tdirections[idx] = directions[idx].sum(direction);\n }", "public static void main(String args[]) throws Exception {\n final StringBuffer buffer = new StringBuffer(\"The lazy fox\");\n Thread t1 = new Thread() {\n public void run() {\n synchronized(buffer) {\n buffer.delete(0,4);\n buffer.append(\" in the middle\");\n System.err.println(\"Middle\");\n try { Thread.sleep(4000); } catch(Exception e) {}\n buffer.append(\" of fall\");\n System.err.println(\"Fall\");\n }\n }\n };\n Thread t2 = new Thread() {\n public void run() {\n try { Thread.sleep(1000); } catch(Exception e) {}\n buffer.append(\" jump over the fence\");\n System.err.println(\"Fence\");\n }\n };\n t1.start();\n t2.start();\n\n t1.join();\n t2.join();\n System.err.println(buffer);\n }", "protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }" ]
Sets the default pattern values dependent on the provided start date. @param startDate the date, the default values are determined with.
[ "void setPatternDefaultValues(Date startDate) {\r\n\r\n if ((m_patternDefaultValues == null) || !Objects.equals(m_patternDefaultValues.getDate(), startDate)) {\r\n m_patternDefaultValues = new PatternDefaultValues(startDate);\r\n }\r\n }" ]
[ "public T copy() {\n T ret = createLike();\n ret.getMatrix().set(this.getMatrix());\n return ret;\n }", "public History[] refreshHistory(int limit, int offset) throws Exception {\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"limit\", String.valueOf(limit)),\n new BasicNameValuePair(\"offset\", String.valueOf(offset))\n };\n return constructHistory(params);\n }", "public void fire(StepFinishedEvent event) {\n Step step = stepStorage.adopt();\n event.process(step);\n\n notifier.fire(event);\n }", "public static Platform detect() throws UnsupportedPlatformException {\n String osArch = getProperty(\"os.arch\");\n String osName = getProperty(\"os.name\");\n\n for (Arch arch : Arch.values()) {\n if (arch.pattern.matcher(osArch).matches()) {\n for (OS os : OS.values()) {\n if (os.pattern.matcher(osName).matches()) {\n return new Platform(arch, os);\n }\n }\n }\n }\n\n String msg = String.format(\"Unsupported platform %s %s\", osArch, osName);\n throw new UnsupportedPlatformException(msg);\n }", "public static spilloverpolicy get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy obj = new spilloverpolicy();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy response = (spilloverpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void addCalendarException(MpxjTreeNode parentNode, final ProjectCalendarException exception)\n {\n MpxjTreeNode exceptionNode = new MpxjTreeNode(exception, CALENDAR_EXCEPTION_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return m_dateFormat.format(exception.getFromDate());\n }\n };\n parentNode.add(exceptionNode);\n addHours(exceptionNode, exception);\n }", "public void notifySubscriberCallback(ContentNotification cn) {\n String content = fetchContentFromPublisher(cn);\n\n distributeContentToSubscribers(content, cn.getUrl());\n }", "private void writeDurationField(String fieldName, Object value) throws IOException\n {\n if (value instanceof String)\n {\n m_writer.writeNameValuePair(fieldName + \"_text\", (String) value);\n }\n else\n {\n Duration val = (Duration) value;\n if (val.getDuration() != 0)\n {\n Duration minutes = val.convertUnits(TimeUnit.MINUTES, m_projectFile.getProjectProperties());\n long seconds = (long) (minutes.getDuration() * 60.0);\n m_writer.writeNameValuePair(fieldName, seconds);\n }\n }\n }", "public static Map<String, Map<String, Metadata>> parseAndPopulateMetadataMap(JsonObject jsonObject) {\n Map<String, Map<String, Metadata>> metadataMap = new HashMap<String, Map<String, Metadata>>();\n //Parse all templates\n for (JsonObject.Member templateMember : jsonObject) {\n if (templateMember.getValue().isNull()) {\n continue;\n } else {\n String templateName = templateMember.getName();\n Map<String, Metadata> scopeMap = metadataMap.get(templateName);\n //If templateName doesn't yet exist then create an entry with empty scope map\n if (scopeMap == null) {\n scopeMap = new HashMap<String, Metadata>();\n metadataMap.put(templateName, scopeMap);\n }\n //Parse all scopes in a template\n for (JsonObject.Member scopeMember : templateMember.getValue().asObject()) {\n String scope = scopeMember.getName();\n Metadata metadataObject = new Metadata(scopeMember.getValue().asObject());\n scopeMap.put(scope, metadataObject);\n }\n }\n\n }\n return metadataMap;\n }" ]
Prepares all files added for tus uploads. @param assemblyUrl the assembly url affiliated with the tus upload. @throws IOException when there's a failure with file retrieval. @throws ProtocolException when there's a failure with tus upload.
[ "protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }" ]
[ "public static final void setPosition(UIObject o, Rect pos) {\n Style style = o.getElement().getStyle();\n style.setPropertyPx(\"left\", pos.x);\n style.setPropertyPx(\"top\", pos.y);\n }", "private PersistenceBroker obtainBroker()\r\n {\r\n PersistenceBroker _broker;\r\n try\r\n {\r\n if (pbKey == null)\r\n {\r\n //throw new OJBRuntimeException(\"Not possible to do action, cause no tx runnning and no PBKey is set\");\r\n log.warn(\"No tx runnning and PBKey is null, try to use the default PB\");\r\n _broker = PersistenceBrokerFactory.defaultPersistenceBroker();\r\n }\r\n else\r\n {\r\n _broker = PersistenceBrokerFactory.createPersistenceBroker(pbKey);\r\n }\r\n }\r\n catch (PBFactoryException e)\r\n {\r\n log.error(\"Could not obtain PB for PBKey \" + pbKey, e);\r\n throw new OJBRuntimeException(\"Unexpected micro-kernel exception\", e);\r\n }\r\n return _broker;\r\n }", "private void checkGAs(List l)\r\n\t{\r\n\t\tfor (final Iterator i = l.iterator(); i.hasNext();)\r\n\t\t\tif (!(i.next() instanceof GroupAddress))\r\n\t\t\t\tthrow new KNXIllegalArgumentException(\"not a group address list\");\r\n\t}", "public void convertToDense() {\n switch ( mat.getType() ) {\n case DSCC: {\n DMatrix m = new DMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrix) mat, m);\n setMatrix(m);\n } break;\n case FSCC: {\n FMatrix m = new FMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrix) mat, m);\n setMatrix(m);\n } break;\n case DDRM:\n case FDRM:\n case ZDRM:\n case CDRM:\n break;\n default:\n throw new RuntimeException(\"Not a sparse matrix!\");\n }\n }", "static void writePatch(final Patch rollbackPatch, final File file) throws IOException {\n final File parent = file.getParentFile();\n if (!parent.isDirectory()) {\n if (!parent.mkdirs() && !parent.exists()) {\n throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(file.getAbsolutePath());\n }\n }\n try {\n try (final OutputStream os = new FileOutputStream(file)){\n PatchXml.marshal(os, rollbackPatch);\n }\n } catch (XMLStreamException e) {\n throw new IOException(e);\n }\n }", "public void setTargetDirectory(String directory) {\n if (directory != null && directory.length() > 0) {\n this.targetDirectory = new File(directory);\n } else {\n this.targetDirectory = null;\n }\n }", "public static CmsResource getDescriptor(CmsObject cms, String basename) {\n\n CmsSolrQuery query = new CmsSolrQuery();\n query.setResourceTypes(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString());\n query.setFilterQueries(\"filename:\\\"\" + basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX + \"\\\"\");\n query.add(\"fl\", \"path\");\n CmsSolrResultList results;\n try {\n boolean isOnlineProject = cms.getRequestContext().getCurrentProject().isOnlineProject();\n String indexName = isOnlineProject\n ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE\n : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE;\n results = OpenCms.getSearchManager().getIndexSolr(indexName).search(cms, query, true, null, true, null);\n } catch (CmsSearchException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_SEARCH_ERROR_0), e);\n return null;\n }\n\n switch (results.size()) {\n case 0:\n return null;\n case 1:\n return results.get(0);\n default:\n String files = \"\";\n for (CmsResource res : results) {\n files += \" \" + res.getRootPath();\n }\n LOG.warn(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_NOT_UNIQUE_1, files));\n return results.get(0);\n }\n }", "private void processHyperlinkData(Resource resource, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n String hyperlink;\n String address;\n String subaddress;\n\n offset += 12;\n hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n subaddress = MPPUtility.getUnicodeString(data, offset);\n\n resource.setHyperlink(hyperlink);\n resource.setHyperlinkAddress(address);\n resource.setHyperlinkSubAddress(subaddress);\n }\n }", "public static void write(Path self, String text, String charset) throws IOException {\n Writer writer = null;\n try {\n writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.forName(charset));\n writer.write(text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }" ]
Add an exact path to the routing table. @throws RouteAlreadyMappedException
[ "public void addRoute(String path, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(path, false), actorClass);\n }" ]
[ "public void removeExtension(Resource rootResource, String moduleName, ManagementResourceRegistration rootRegistration) throws IllegalStateException {\n final ManagementResourceRegistration profileReg;\n if (rootRegistration.getPathAddress().size() == 0) {\n //domain or server extension\n // Can't use processType.isServer() to determine where to look for profile reg because a lot of test infrastructure\n // doesn't add the profile mrr even in HC-based tests\n ManagementResourceRegistration reg = rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(PROFILE)));\n if (reg == null) {\n reg = rootRegistration;\n }\n profileReg = reg;\n } else {\n //host model extension\n profileReg = rootRegistration;\n }\n ManagementResourceRegistration deploymentsReg = processType.isServer() ? rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT))) : null;\n\n ExtensionInfo extension = extensions.remove(moduleName);\n if (extension != null) {\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (extension) {\n Set<String> subsystemNames = extension.subsystems.keySet();\n\n final boolean dcExtension = processType.isHostController() ?\n rootRegistration.getPathAddress().size() == 0 : false;\n\n for (String subsystem : subsystemNames) {\n if (hasSubsystemsRegistered(rootResource, subsystem, dcExtension)) {\n // Restore the data\n extensions.put(moduleName, extension);\n throw ControllerLogger.ROOT_LOGGER.removingExtensionWithRegisteredSubsystem(moduleName, subsystem);\n }\n }\n for (Map.Entry<String, SubsystemInformation> entry : extension.subsystems.entrySet()) {\n String subsystem = entry.getKey();\n profileReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, subsystem));\n if (deploymentsReg != null) {\n deploymentsReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, subsystem));\n deploymentsReg.unregisterSubModel(PathElement.pathElement(ModelDescriptionConstants.SUBDEPLOYMENT, subsystem));\n }\n\n if (extension.xmlMapper != null) {\n SubsystemInformationImpl subsystemInformation = SubsystemInformationImpl.class.cast(entry.getValue());\n for (String namespace : subsystemInformation.getXMLNamespaces()) {\n extension.xmlMapper.unregisterRootElement(new QName(namespace, SUBSYSTEM));\n }\n }\n }\n }\n }\n }", "private void doDelete(Object obj, boolean ignoreReferences) throws PersistenceBrokerException\n {\n //logger.info(\"DELETING \" + obj);\n // object is not null\n if (obj != null)\n {\n obj = getProxyFactory().getRealObject(obj);\n /**\n * Kuali Foundation modification -- 8/24/2007\n */\n if ( obj == null ) return;\n /**\n * End of Kuali Foundation modification\n */\n /**\n * MBAIRD\n * 1. if we are marked for delete already, avoid recursing on this object\n *\n * arminw:\n * use object instead Identity object in markedForDelete List,\n * because using objects we get a better performance. I can't find\n * side-effects in doing so.\n */\n if (markedForDelete.contains(obj))\n {\n return;\n }\n \n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n //BRJ: check for valid pk\n if (!serviceBrokerHelper().assertValidPkForDelete(cld, obj))\n {\n String msg = \"Cannot delete object without valid PKs. \" + obj;\n logger.error(msg);\n return;\n }\n \n /**\n * MBAIRD\n * 2. register object in markedForDelete map.\n */\n markedForDelete.add(obj);\n Identity oid = serviceIdentity().buildIdentity(cld, obj);\n\n // Invoke events on PersistenceBrokerAware instances and listeners\n BEFORE_DELETE_EVENT.setTarget(obj);\n fireBrokerEvent(BEFORE_DELETE_EVENT);\n BEFORE_DELETE_EVENT.setTarget(null);\n\n // now perform deletion\n performDeletion(cld, obj, oid, ignoreReferences);\n \t \t \n // Invoke events on PersistenceBrokerAware instances and listeners\n AFTER_DELETE_EVENT.setTarget(obj);\n fireBrokerEvent(AFTER_DELETE_EVENT);\n AFTER_DELETE_EVENT.setTarget(null);\n \t \t \t\n // let the connection manager to execute batch\n connectionManager.executeBatchIfNecessary();\n }\n }", "private Event createEvent(Endpoint endpoint, EventTypeEnum type) {\n\n Event event = new Event();\n MessageInfo messageInfo = new MessageInfo();\n Originator originator = new Originator();\n event.setMessageInfo(messageInfo);\n event.setOriginator(originator);\n\n Date date = new Date();\n event.setTimestamp(date);\n event.setEventType(type);\n\n messageInfo.setPortType(\n endpoint.getBinding().getBindingInfo().getService().getInterface().getName().toString());\n\n String transportType = null;\n if (endpoint.getBinding() instanceof SoapBinding) {\n SoapBinding soapBinding = (SoapBinding)endpoint.getBinding();\n if (soapBinding.getBindingInfo() instanceof SoapBindingInfo) {\n SoapBindingInfo soapBindingInfo = (SoapBindingInfo)soapBinding.getBindingInfo();\n transportType = soapBindingInfo.getTransportURI();\n }\n }\n messageInfo.setTransportType((transportType != null) ? transportType : \"Unknown transport type\");\n\n originator.setProcessId(Converter.getPID());\n try {\n InetAddress inetAddress = InetAddress.getLocalHost();\n originator.setIp(inetAddress.getHostAddress());\n originator.setHostname(inetAddress.getHostName());\n } catch (UnknownHostException e) {\n originator.setHostname(\"Unknown hostname\");\n originator.setIp(\"Unknown ip address\");\n }\n\n String address = endpoint.getEndpointInfo().getAddress();\n event.getCustomInfo().put(\"address\", address);\n\n return event;\n }", "private void parseMetadataItem(Message item) {\n switch (item.getMenuItemType()) {\n case TRACK_TITLE:\n title = ((StringField) item.arguments.get(3)).getValue();\n artworkId = (int) ((NumberField) item.arguments.get(8)).getValue();\n break;\n\n case ARTIST:\n artist = buildSearchableItem(item);\n break;\n\n case ORIGINAL_ARTIST:\n originalArtist = buildSearchableItem(item);\n break;\n\n case REMIXER:\n remixer = buildSearchableItem(item);\n\n case ALBUM_TITLE:\n album = buildSearchableItem(item);\n break;\n\n case LABEL:\n label = buildSearchableItem(item);\n break;\n\n case DURATION:\n duration = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case TEMPO:\n tempo = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case COMMENT:\n comment = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case KEY:\n key = buildSearchableItem(item);\n break;\n\n case RATING:\n rating = (int) ((NumberField)item.arguments.get(1)).getValue();\n break;\n\n case COLOR_NONE:\n case COLOR_AQUA:\n case COLOR_BLUE:\n case COLOR_GREEN:\n case COLOR_ORANGE:\n case COLOR_PINK:\n case COLOR_PURPLE:\n case COLOR_RED:\n case COLOR_YELLOW:\n color = buildColorItem(item);\n break;\n\n case GENRE:\n genre = buildSearchableItem(item);\n break;\n\n case DATE_ADDED:\n dateAdded = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case YEAR:\n year = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case BIT_RATE:\n bitRate = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n default:\n logger.warn(\"Ignoring track metadata item with unknown type: {}\", item);\n }\n }", "public static IPAddressSeqRange[] join(IPAddressSeqRange... ranges) {\n\t\tint joinedCount = 0;\n\t\tArrays.sort(ranges, Address.ADDRESS_LOW_VALUE_COMPARATOR);\n\t\tfor(int i = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(int j = i + 1; j < ranges.length; j++) {\n\t\t\t\tIPAddressSeqRange range2 = ranges[j];\n\t\t\t\tif(range2 == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tIPAddress upper = range.getUpper();\n\t\t\t\tIPAddress lower = range2.getLower();\n\t\t\t\tif(compareLowValues(upper, lower) >= 0\n\t\t\t\t\t\t|| upper.increment(1).equals(lower)) {\n\t\t\t\t\t//join them\n\t\t\t\t\tranges[i] = range = range.create(range.getLower(), range2.getUpper());\n\t\t\t\t\tranges[j] = null;\n\t\t\t\t\tjoinedCount++;\n\t\t\t\t} else break;\n\t\t\t}\n\t\t}\n\t\tif(joinedCount == 0) {\n\t\t\treturn ranges;\n\t\t}\n\t\tIPAddressSeqRange joined[] = new IPAddressSeqRange[ranges.length - joinedCount];\n\t\tfor(int i = 0, j = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tjoined[j++] = range;\n\t\t\tif(j >= joined.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn joined;\n\t}", "public static lbvserver_filterpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_filterpolicy_binding obj = new lbvserver_filterpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_filterpolicy_binding response[] = (lbvserver_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static RgbaColor fromHsl(float H, float S, float L) {\n\n // convert to [0-1]\n H /= 360f;\n S /= 100f;\n L /= 100f;\n\n float R, G, B;\n\n if (S == 0) {\n // grey\n R = G = B = L;\n }\n else {\n float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S;\n float m1 = 2f * L - m2;\n R = hue2rgb(m1, m2, H + 1 / 3f);\n G = hue2rgb(m1, m2, H);\n B = hue2rgb(m1, m2, H - 1 / 3f);\n }\n\n // convert [0-1] to [0-255]\n int r = Math.round(R * 255f);\n int g = Math.round(G * 255f);\n int b = Math.round(B * 255f);\n\n return new RgbaColor(r, g, b, 1);\n }", "private String getHierarchyTable(ClassDescriptorDef classDef)\r\n {\r\n ArrayList queue = new ArrayList();\r\n String tableName = null;\r\n\r\n queue.add(classDef);\r\n\r\n while (!queue.isEmpty())\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)queue.get(0);\r\n\r\n queue.remove(0);\r\n\r\n if (curClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true))\r\n {\r\n if (tableName != null)\r\n {\r\n if (!tableName.equals(curClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n return null;\r\n }\r\n }\r\n else\r\n {\r\n tableName = curClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE);\r\n }\r\n }\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n curClassDef = (ClassDescriptorDef)it.next();\r\n\r\n if (curClassDef.getReference(\"super\") == null)\r\n {\r\n queue.add(curClassDef);\r\n }\r\n }\r\n }\r\n return tableName;\r\n }", "public PhotoList<Photo> getPhotos(String photosetId, Set<String> extras, int privacy_filter, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n if (privacy_filter > 0) {\r\n parameters.put(\"privacy_filter\", \"\" + privacy_filter);\r\n }\r\n\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element photoset = response.getPayload();\r\n NodeList photoElements = photoset.getElementsByTagName(\"photo\");\r\n photos.setPage(photoset.getAttribute(\"page\"));\r\n photos.setPages(photoset.getAttribute(\"pages\"));\r\n photos.setPerPage(photoset.getAttribute(\"per_page\"));\r\n photos.setTotal(photoset.getAttribute(\"total\"));\r\n\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement, photoset));\r\n }\r\n\r\n return photos;\r\n }" ]
Iterate through dependencies
[ "private Set<Artifact> findThriftDependencies() throws IOException, MojoExecutionException {\n Set<Artifact> thriftDependencies = new HashSet<Artifact>();\n\n Set<Artifact> deps = new HashSet<Artifact>();\n deps.addAll(project.getArtifacts());\n deps.addAll(project.getDependencyArtifacts());\n\n Map<String, Artifact> depsMap = new HashMap<String, Artifact>();\n for (Artifact dep : deps) {\n depsMap.put(dep.getId(), dep);\n }\n\n for (Artifact artifact : deps) {\n // This artifact has an idl classifier.\n if (isIdlCalssifier(artifact, classifier)) {\n thriftDependencies.add(artifact);\n } else {\n if (isDepOfIdlArtifact(artifact, depsMap)) {\n // Fetch idl artifact for dependency of an idl artifact.\n try {\n Artifact idlArtifact = MavenScroogeCompilerUtil.getIdlArtifact(\n artifact,\n artifactFactory,\n artifactResolver,\n localRepository,\n remoteArtifactRepositories,\n classifier);\n thriftDependencies.add(idlArtifact);\n } catch (MojoExecutionException e) {\n /* Do nothing as this artifact is not an idl artifact\n binary jars may have dependency on thrift lib etc.\n */\n getLog().debug(\"Could not fetch idl jar for \" + artifact);\n }\n }\n }\n }\n return thriftDependencies;\n }" ]
[ "public static double[] singularValues( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n double sv[] = svd.getSingularValues();\n Arrays.sort(sv,0,svd.numberOfSingularValues());\n\n // change the ordering to ascending\n for (int i = 0; i < sv.length/2; i++) {\n double tmp = sv[i];\n sv[i] = sv[sv.length-i-1];\n sv[sv.length-i-1] = tmp;\n }\n\n return sv;\n }", "public synchronized boolean undoRoleMappingRemove(final Object removalKey) {\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n RoleMappingImpl toRestore = removedRoles.remove(removalKey);\n if (toRestore != null && newRoles.containsKey(toRestore.getName()) == false) {\n newRoles.put(toRestore.getName(), toRestore);\n roleMappings = Collections.unmodifiableMap(newRoles);\n return true;\n }\n\n return false;\n }", "public static final BigInteger printDurationInIntegerTenthsOfMinutes(Duration duration)\n {\n BigInteger result = null;\n\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigInteger.valueOf((long) printDurationFractionsOfMinutes(duration, 10));\n }\n\n return result;\n }", "public synchronized void shutdown(){\r\n\r\n\t\tif (!this.poolShuttingDown){\r\n\t\t\tlogger.info(\"Shutting down connection pool...\");\r\n\t\t\tthis.poolShuttingDown = true;\r\n\t\t\tthis.shutdownStackTrace = captureStackTrace(SHUTDOWN_LOCATION_TRACE);\r\n\t\t\tthis.keepAliveScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.maxAliveScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.connectionsScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.asyncExecutor.shutdownNow();\r\n\r\n\t\t\ttry {\r\n\t\t\t\tthis.connectionsScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\r\n\t\t\t\tthis.maxAliveScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\tthis.keepAliveScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\tthis.asyncExecutor.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\t\r\n\t\t\t\tif (this.closeConnectionExecutor != null){\r\n\t\t\t\t\tthis.closeConnectionExecutor.shutdownNow();\r\n\t\t\t\t\tthis.closeConnectionExecutor.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} catch (InterruptedException e) {\r\n\t\t\t\t// do nothing\r\n\t\t\t}\r\n\t\t\tthis.connectionStrategy.terminateAllConnections();\r\n\t\t\tunregisterDriver();\r\n\t\t\tregisterUnregisterJMX(false);\r\n\t\t\tif (finalizableRefQueue != null) {\r\n\t\t\t\tfinalizableRefQueue.close();\r\n\t\t\t}\r\n\t\t\t logger.info(\"Connection pool has been shutdown.\");\r\n\t\t}\r\n\t}", "@DELETE\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response removeCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an remove a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to remove!\");\n return Response.serverError().status(HttpStatus.BAD_REQUEST_400).build();\n }\n\n getOrganizationHandler().removeCorporateGroupId(organizationId, corporateGroupId);\n\n return Response.ok(\"done\").build();\n }", "Item newStringishItem(final int type, final String value) {\n key2.set(type, value, null, null);\n Item result = get(key2);\n if (result == null) {\n pool.put12(type, newUTF8(value));\n result = new Item(index++, key2);\n put(result);\n }\n return result;\n }", "public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }", "public static sslcertkey_sslvserver_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslvserver_binding obj = new sslcertkey_sslvserver_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslvserver_binding response[] = (sslcertkey_sslvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }" ]
Use this API to fetch clusternodegroup_binding resource of given name .
[ "public static clusternodegroup_binding get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup_binding obj = new clusternodegroup_binding();\n\t\tobj.set_name(name);\n\t\tclusternodegroup_binding response = (clusternodegroup_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public static InstalledIdentity load(final File jbossHome, final ProductConfig productConfig, final File... repoRoots) throws IOException {\n final InstalledImage installedImage = installedImage(jbossHome);\n return load(installedImage, productConfig, Arrays.<File>asList(repoRoots), Collections.<File>emptyList());\n }", "public static base_response disable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature disableresource = new nsfeature();\n\t\tdisableresource.feature = resource.feature;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "private void sendEmptyRequest(String path, String method) throws DatastoreEmulatorException {\n HttpURLConnection connection = null;\n try {\n URL url = new URL(this.host + path);\n connection = (HttpURLConnection) url.openConnection();\n connection.setDoOutput(true);\n connection.setRequestMethod(method);\n connection.getOutputStream().close();\n if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {\n throw new DatastoreEmulatorException(\n String.format(\n \"%s request to %s returned HTTP status %s\",\n method, path, connection.getResponseCode()));\n }\n } catch (IOException e) {\n throw new DatastoreEmulatorException(\n String.format(\"Exception connecting to emulator on %s request to %s\", method, path), e);\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n }", "public void load(File file) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(file);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }", "protected String buildErrorSetMsg(Object obj, Object value, Field aField)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer buf = new StringBuffer();\r\n buf\r\n .append(eol + \"[try to set 'object value' in 'target object'\")\r\n .append(eol + \"target obj class: \" + (obj != null ? obj.getClass().getName() : null))\r\n .append(eol + \"target field name: \" + (aField != null ? aField.getName() : null))\r\n .append(eol + \"target field type: \" + (aField != null ? aField.getType() : null))\r\n .append(eol + \"target field declared in: \" + (aField != null ? aField.getDeclaringClass().getName() : null))\r\n .append(eol + \"object value class: \" + (value != null ? value.getClass().getName() : null))\r\n .append(eol + \"object value: \" + (value != null ? value : null))\r\n .append(eol + \"]\");\r\n return buf.toString();\r\n }", "private String getCurrencyFormat(CurrencySymbolPosition position)\n {\n String result;\n\n switch (position)\n {\n case AFTER:\n {\n result = \"1.1#\";\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n result = \"1.1 #\";\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n result = \"# 1.1\";\n break;\n }\n\n default:\n case BEFORE:\n {\n result = \"#1.1\";\n break;\n }\n }\n\n return result;\n }", "public static DatabaseFieldConfig fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseFieldConfig config = new DatabaseFieldConfig();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseFieldConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseFieldConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}", "private boolean checkConverged(DMatrixRMaj A) {\n double worst = 0;\n double worst2 = 0;\n for( int j = 0; j < A.numRows; j++ ) {\n double val = Math.abs(q2.data[j] - q0.data[j]);\n if( val > worst ) worst = val;\n val = Math.abs(q2.data[j] + q0.data[j]);\n if( val > worst2 ) worst2 = val;\n }\n\n // swap vectors\n DMatrixRMaj temp = q0;\n q0 = q2;\n q2 = temp;\n\n if( worst < tol )\n return true;\n else if( worst2 < tol )\n return true;\n else\n return false;\n }", "public void addValue(double value)\n {\n if (dataSetSize == dataSet.length)\n {\n // Increase the capacity of the array.\n int newLength = (int) (GROWTH_RATE * dataSetSize);\n double[] newDataSet = new double[newLength];\n System.arraycopy(dataSet, 0, newDataSet, 0, dataSetSize);\n dataSet = newDataSet;\n }\n dataSet[dataSetSize] = value;\n updateStatsWithNewValue(value);\n ++dataSetSize;\n }" ]
Close the Closeable. Logging a warning if any problems occur. @param c the thing to close
[ "public static void closeWithWarning(Closeable c) {\n if (c != null) {\n try {\n c.close();\n } catch (IOException e) {\n LOG.warning(\"Caught exception during close(): \" + e);\n }\n }\n }" ]
[ "public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }", "public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }", "public AT_Row setPaddingLeftRight(int padding){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public MaterialSection getSectionByTitle(String title) {\n\n for(MaterialSection section : sectionList) {\n if(section.getTitle().equals(title)) {\n return section;\n }\n }\n\n for(MaterialSection section : bottomSectionList) {\n if(section.getTitle().equals(title))\n return section;\n }\n\n return null;\n }", "public IPlan[] getAgentPlans(final String agent_name, Connector connector) {\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Plan>() {\n\n public IFuture<Plan> execute(IInternalAccess ia) {\n\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n plans = bia.getPlanbase().getPlans();\n return null;\n }\n }).get(new ThreadSuspendable());\n\n return plans;\n }", "public static void configure(Job conf, SimpleConfiguration config) {\n try {\n FluoConfiguration fconfig = new FluoConfiguration(config);\n try (Environment env = new Environment(fconfig)) {\n long ts =\n env.getSharedResources().getTimestampTracker().allocateTimestamp().getTxTimestamp();\n conf.getConfiguration().setLong(TIMESTAMP_CONF_KEY, ts);\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n config.save(baos);\n conf.getConfiguration().set(PROPS_CONF_KEY,\n new String(baos.toByteArray(), StandardCharsets.UTF_8));\n\n AccumuloInputFormat.setZooKeeperInstance(conf, fconfig.getAccumuloInstance(),\n fconfig.getAccumuloZookeepers());\n AccumuloInputFormat.setConnectorInfo(conf, fconfig.getAccumuloUser(),\n new PasswordToken(fconfig.getAccumuloPassword()));\n AccumuloInputFormat.setInputTableName(conf, env.getTable());\n AccumuloInputFormat.setScanAuthorizations(conf, env.getAuthorizations());\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public boolean mapsCell(String cell) {\n return mappers.values().stream().anyMatch(mapper -> mapper.mapsCell(cell));\n }", "public static Region fromName(String name) {\n if (name == null) {\n return null;\n }\n\n Region region = VALUES_BY_NAME.get(name.toLowerCase().replace(\" \", \"\"));\n if (region != null) {\n return region;\n } else {\n return Region.create(name.toLowerCase().replace(\" \", \"\"), name);\n }\n }", "public static Object invoke(Object object, String methodName, Object[] parameters) {\n try {\n Class[] classTypes = new Class[parameters.length];\n for (int i = 0; i < classTypes.length; i++) {\n classTypes[i] = parameters[i].getClass();\n }\n Method method = object.getClass().getMethod(methodName, classTypes);\n return method.invoke(object, parameters);\n } catch (Throwable t) {\n return InvokerHelper.invokeMethod(object, methodName, parameters);\n }\n }" ]
Helper method to check that we got the right size packet. @param packet a packet that has been received @param expectedLength the number of bytes we expect it to contain @param name the description of the packet in case we need to report issues with the length @return {@code true} if enough bytes were received to process the packet
[ "private boolean isPacketLongEnough(DatagramPacket packet, int expectedLength, String name) {\n final int length = packet.getLength();\n if (length < expectedLength) {\n logger.warn(\"Ignoring too-short \" + name + \" packet; expecting \" + expectedLength + \" bytes and got \" +\n length + \".\");\n return false;\n }\n\n if (length > expectedLength) {\n logger.warn(\"Processing too-long \" + name + \" packet; expecting \" + expectedLength +\n \" bytes and got \" + length + \".\");\n }\n\n return true;\n }" ]
[ "public static void findSomeStringProperties(ApiConnection connection)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\tWikibaseDataFetcher wbdf = new WikibaseDataFetcher(connection, siteIri);\n\t\twbdf.getFilter().excludeAllProperties();\n\t\twbdf.getFilter().setLanguageFilter(Collections.singleton(\"en\"));\n\n\t\tArrayList<PropertyIdValue> stringProperties = new ArrayList<>();\n\n\t\tSystem.out\n\t\t\t\t.println(\"*** Trying to find string properties for the example ... \");\n\t\tint propertyNumber = 1;\n\t\twhile (stringProperties.size() < 5) {\n\t\t\tArrayList<String> fetchProperties = new ArrayList<>();\n\t\t\tfor (int i = propertyNumber; i < propertyNumber + 10; i++) {\n\t\t\t\tfetchProperties.add(\"P\" + i);\n\t\t\t}\n\t\t\tpropertyNumber += 10;\n\t\t\tMap<String, EntityDocument> results = wbdf\n\t\t\t\t\t.getEntityDocuments(fetchProperties);\n\t\t\tfor (EntityDocument ed : results.values()) {\n\t\t\t\tPropertyDocument pd = (PropertyDocument) ed;\n\t\t\t\tif (DatatypeIdValue.DT_STRING.equals(pd.getDatatype().getIri())\n\t\t\t\t\t\t&& pd.getLabels().containsKey(\"en\")) {\n\t\t\t\t\tstringProperties.add(pd.getEntityId());\n\t\t\t\t\tSystem.out.println(\"* Found string property \"\n\t\t\t\t\t\t\t+ pd.getEntityId().getId() + \" (\"\n\t\t\t\t\t\t\t+ pd.getLabels().get(\"en\") + \")\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstringProperty1 = stringProperties.get(0);\n\t\tstringProperty2 = stringProperties.get(1);\n\t\tstringProperty3 = stringProperties.get(2);\n\t\tstringProperty4 = stringProperties.get(3);\n\t\tstringProperty5 = stringProperties.get(4);\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}", "public static boolean zipFolder(File folder, String fileName){\n\t\tboolean success = false;\n\t\tif(!folder.isDirectory()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(fileName == null){\n\t\t\tfileName = folder.getAbsolutePath()+ZIP_EXT;\n\t\t}\n\t\t\n\t\tZipArchiveOutputStream zipOutput = null;\n\t\ttry {\n\t\t\tzipOutput = new ZipArchiveOutputStream(new File(fileName));\n\t\t\t\n\t\t\tsuccess = addFolderContentToZip(folder,zipOutput,\"\");\n\n\t\t\tzipOutput.close();\n\t\t\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\tfinally{\n\t\t\ttry {\n\t\t\t\tif(zipOutput != null){\n\t\t\t\t\tzipOutput.close();\n\t\t\t\t}\n\t\t\t} catch (IOException e) {}\n\t\t}\n\t\treturn success;\n\t}", "@Override\n public <T> Producer<T> createProducer(final Bean<X> declaringBean, final Bean<T> bean, DisposalMethod<X, T> disposalMethod) {\n EnhancedAnnotatedField<T, X> enhancedField = getManager().getServices().get(MemberTransformer.class).loadEnhancedMember(field, getManager().getId());\n return new ProducerFieldProducer<X, T>(enhancedField, disposalMethod) {\n\n @Override\n public AnnotatedField<X> getAnnotated() {\n return field;\n }\n\n @Override\n public BeanManagerImpl getBeanManager() {\n return getManager();\n }\n\n @Override\n public Bean<X> getDeclaringBean() {\n return declaringBean;\n }\n\n @Override\n public Bean<T> getBean() {\n return bean;\n }\n };\n }", "public PlaybackState getFurthestPlaybackState() {\n PlaybackState result = null;\n for (PlaybackState state : playbackStateMap.values()) {\n if (result == null || (!result.playing && state.playing) ||\n (result.position < state.position) && (state.playing || !result.playing)) {\n result = state;\n }\n }\n return result;\n }", "public static boolean strictCheckMatchingTags(Collection<String> tags, Set<String> includeTags, Set<String> excludeTags)\n {\n boolean includeTagsEnabled = !includeTags.isEmpty();\n\n for (String tag : tags)\n {\n boolean isIncluded = includeTags.contains(tag);\n boolean isExcluded = excludeTags.contains(tag);\n\n if ((includeTagsEnabled && isIncluded) || (!includeTagsEnabled && !isExcluded))\n {\n return true;\n }\n }\n\n return false;\n }", "@Nullable\n private static Object valueOf(String value, Class<?> cls) {\n if (cls == Boolean.TYPE) {\n return Boolean.valueOf(value);\n }\n if (cls == Character.TYPE) {\n return value.length() >= 1 ? value.charAt(0) : defaultValue(char.class);\n }\n if (cls == Byte.TYPE) {\n return Byte.valueOf(value);\n }\n if (cls == Short.TYPE) {\n return Short.valueOf(value);\n }\n if (cls == Integer.TYPE) {\n return Integer.valueOf(value);\n }\n if (cls == Long.TYPE) {\n return Long.valueOf(value);\n }\n if (cls == Float.TYPE) {\n return Float.valueOf(value);\n }\n if (cls == Double.TYPE) {\n return Double.valueOf(value);\n }\n return null;\n }", "private void rebalanceStore(String storeName,\n final AdminClient adminClient,\n RebalanceTaskInfo stealInfo,\n boolean isReadOnlyStore) {\n // Move partitions\n if (stealInfo.getPartitionIds(storeName) != null && stealInfo.getPartitionIds(storeName).size() > 0) {\n\n logger.info(getHeader(stealInfo) + \"Starting partitions migration for store \"\n + storeName + \" from donor node \" + stealInfo.getDonorId());\n\n int asyncId = adminClient.storeMntOps.migratePartitions(stealInfo.getDonorId(),\n metadataStore.getNodeId(),\n storeName,\n stealInfo.getPartitionIds(storeName),\n null,\n stealInfo.getInitialCluster());\n rebalanceStatusList.add(asyncId);\n\n if(logger.isDebugEnabled()) {\n logger.debug(getHeader(stealInfo) + \"Waiting for completion for \" + storeName\n + \" with async id \" + asyncId);\n }\n adminClient.rpcOps.waitForCompletion(metadataStore.getNodeId(),\n asyncId,\n voldemortConfig.getRebalancingTimeoutSec(),\n TimeUnit.SECONDS,\n getStatus());\n\n rebalanceStatusList.remove((Object) asyncId);\n\n logger.info(getHeader(stealInfo) + \"Completed partition migration for store \"\n + storeName + \" from donor node \" + stealInfo.getDonorId());\n }\n\n logger.info(getHeader(stealInfo) + \"Finished all migration for store \" + storeName);\n }", "public static RelationType getInstance(Locale locale, String type)\n {\n int index = -1;\n\n String[] relationTypes = LocaleData.getStringArray(locale, LocaleData.RELATION_TYPES);\n for (int loop = 0; loop < relationTypes.length; loop++)\n {\n if (relationTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n RelationType result = null;\n if (index != -1)\n {\n result = RelationType.getInstance(index);\n }\n\n return (result);\n }", "public Set<BsonValue> getPausedDocumentIds(final MongoNamespace namespace) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final Set<BsonValue> pausedDocumentIds = new HashSet<>();\n\n for (final CoreDocumentSynchronizationConfig config :\n this.syncConfig.getSynchronizedDocuments(namespace)) {\n if (config.isPaused()) {\n pausedDocumentIds.add(config.getDocumentId());\n }\n }\n\n return pausedDocumentIds;\n } finally {\n ongoingOperationsGroup.exit();\n }\n }" ]
Build copyright map once.
[ "@PostConstruct\n\tprotected void buildCopyrightMap() {\n\t\tif (null == declaredPlugins) {\n\t\t\treturn;\n\t\t}\n\t\t// go over all plug-ins, adding copyright info, avoiding duplicates (on object key)\n\t\tfor (PluginInfo plugin : declaredPlugins.values()) {\n\t\t\tfor (CopyrightInfo copyright : plugin.getCopyrightInfo()) {\n\t\t\t\tString key = copyright.getKey();\n\t\t\t\tString msg = copyright.getKey() + \": \" + copyright.getCopyright() + \" : licensed as \" +\n\t\t\t\t\t\tcopyright.getLicenseName() + \", see \" + copyright.getLicenseUrl();\n\t\t\t\tif (null != copyright.getSourceUrl()) {\n\t\t\t\t\tmsg += \" source \" + copyright.getSourceUrl();\n\t\t\t\t}\n\t\t\t\tif (!copyrightMap.containsKey(key)) {\n\t\t\t\t\tlog.info(msg);\n\t\t\t\t\tcopyrightMap.put(key, copyright);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}" ]
[ "public static Value.Builder makeValue(Date date) {\n return Value.newBuilder().setTimestampValue(toTimestamp(date.getTime() * 1000L));\n }", "public void process(DMatrixSparseCSC A , int parent[], int post[], int counts[] ) {\n if( counts.length < A.numCols )\n throw new IllegalArgumentException(\"counts must be at least of length A.numCols\");\n\n initialize(A);\n\n int delta[] = counts;\n findFirstDescendant(parent, post, delta);\n\n if( ata ) {\n init_ata(post);\n }\n for (int i = 0; i < n; i++)\n w[ancestor+i] = i;\n\n int[] ATp = At.col_idx; int []ATi = At.nz_rows;\n\n for (int k = 0; k < n; k++) {\n int j = post[k];\n if( parent[j] != -1 )\n delta[parent[j]]--; // j is not a root\n for (int J = HEAD(k,j); J != -1; J = NEXT(J)) {\n for (int p = ATp[J]; p < ATp[J+1]; p++) {\n int i = ATi[p];\n int q = isLeaf(i,j);\n if( jleaf >= 1)\n delta[j]++;\n if( jleaf == 2 )\n delta[q]--;\n }\n }\n if( parent[j] != -1 )\n w[ancestor+j] = parent[j];\n }\n\n // sum up delta's of each child\n for ( int j = 0; j < n; j++) {\n if( parent[j] != -1)\n counts[parent[j]] += counts[j];\n }\n }", "public UniqueEntityLoader buildLoader(\n\t\t\tOuterJoinLoadable persister,\n\t\t\tint batchSize,\n\t\t\tLockMode lockMode,\n\t\t\tSessionFactoryImplementor factory,\n\t\t\tLoadQueryInfluencers influencers,\n\t\t\tBatchableEntityLoaderBuilder innerEntityLoaderBuilder) {\n\t\tif ( batchSize <= 1 ) {\n\t\t\t// no batching\n\t\t\treturn buildNonBatchingLoader( persister, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t\t}\n\t\treturn buildBatchingLoader( persister, batchSize, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t}", "public String getAuthorizationUri(final String redirectUri, final Set<String> scopes, final String state) {\n if (account == null)\n throw new IllegalArgumentException(\"Auth is not set\");\n if (account.getClientId() == null)\n throw new IllegalArgumentException(\"client_id is not set\");\n StringBuilder builder = new StringBuilder();\n builder.append(URI_AUTHENTICATION);\n builder.append(\"?\");\n builder.append(\"response_type=\");\n builder.append(encode(\"code\"));\n builder.append(\"&redirect_uri=\");\n builder.append(encode(redirectUri));\n builder.append(\"&client_id=\");\n builder.append(encode(account.getClientId()));\n builder.append(\"&scope=\");\n builder.append(encode(getScopesString(scopes)));\n builder.append(\"&state=\");\n builder.append(encode(state));\n builder.append(\"&code_challenge\");\n builder.append(getCodeChallenge()); // Already url encoded\n builder.append(\"&code_challenge_method=\");\n builder.append(encode(\"S256\"));\n return builder.toString();\n }", "private static double threePointsAngle(Point vertex, Point A, Point B) {\n double b = pointsDistance(vertex, A);\n double c = pointsDistance(A, B);\n double a = pointsDistance(B, vertex);\n\n return Math.toDegrees(Math.acos((a * a + b * b - c * c) / (2 * a * b)));\n\n }", "public double getProgressFromResponse(ResponseOnSingeRequest myResponse) {\n\n double progress = 0.0;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return progress;\n }\n\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(progressRegex);\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n String progressStr = matcher.group(1);\n progress = Double.parseDouble(progressStr);\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n\n return progress;\n }", "public static String getTextContent(Document document, boolean individualTokens) {\n String textContent = null;\n if (individualTokens) {\n List<String> tokens = getTextTokens(document);\n textContent = StringUtils.join(tokens, \",\");\n } else {\n textContent =\n document.getDocumentElement().getTextContent().trim().replaceAll(\"\\\\s+\", \",\");\n }\n return textContent;\n }", "protected FieldDescriptor getFieldDescriptor(TableAlias aTableAlias, PathInfo aPathInfo)\r\n {\r\n FieldDescriptor fld = null;\r\n String colName = aPathInfo.column;\r\n\r\n if (aTableAlias != null)\r\n {\r\n fld = aTableAlias.cld.getFieldDescriptorByName(colName);\r\n if (fld == null)\r\n {\r\n ObjectReferenceDescriptor ord = aTableAlias.cld.getObjectReferenceDescriptorByName(colName);\r\n if (ord != null)\r\n {\r\n fld = getFldFromReference(aTableAlias, ord);\r\n }\r\n else\r\n {\r\n fld = getFldFromJoin(aTableAlias, colName);\r\n }\r\n }\r\n }\r\n\r\n return fld;\r\n }", "public static String getDateTimeStr(Date d) {\n if (d == null)\n return \"\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSSZ\");\n // 20140315 test will problem +0000\n return sdf.format(d);\n }" ]
This method is called to alert project listeners to the fact that a relation has been written to a project file. @param relation relation instance
[ "public void fireRelationWrittenEvent(Relation relation)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.relationWritten(relation);\n }\n }\n }" ]
[ "@RequestMapping(value = \"api/servergroup\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getServerGroups(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"search\", required = false) String search,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId);\n\n if (search != null) {\n Iterator<ServerGroup> iterator = serverGroups.iterator();\n while (iterator.hasNext()) {\n ServerGroup serverGroup = iterator.next();\n if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) {\n iterator.remove();\n }\n }\n }\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, \"servergroups\");\n return returnJson;\n }", "public void addHeader(String key, String value) {\n if (key.equals(\"As-User\")) {\n for (int i = 0; i < this.headers.size(); i++) {\n if (this.headers.get(i).getKey().equals(\"As-User\")) {\n this.headers.remove(i);\n }\n }\n }\n if (key.equals(\"X-Box-UA\")) {\n throw new IllegalArgumentException(\"Altering the X-Box-UA header is not permitted\");\n }\n this.headers.add(new RequestHeader(key, value));\n }", "protected String sourceLine(ASTNode node) {\r\n return sourceCode.getLines().get(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }", "public static aaagroup_vpntrafficpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_vpntrafficpolicy_binding obj = new aaagroup_vpntrafficpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_vpntrafficpolicy_binding response[] = (aaagroup_vpntrafficpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Script updateName(int id, String name) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SCRIPT +\n \" SET \" + Constants.SCRIPT_NAME + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return this.getScript(id);\n }", "public Iterable<? extends WindupVertexFrame> findVariable(String name, int maxDepth)\n {\n int currentDepth = 0;\n Iterable<? extends WindupVertexFrame> result = null;\n for (Map<String, Iterable<? extends WindupVertexFrame>> frame : deque)\n {\n result = frame.get(name);\n if (result != null)\n {\n break;\n }\n currentDepth++;\n if (currentDepth >= maxDepth)\n break;\n }\n return result;\n }", "private String getPropertyName(Expression expression) {\n\t\tif (!(expression instanceof PropertyName)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a PropertyName.\");\n\t\t}\n\t\tString name = ((PropertyName) expression).getPropertyName();\n\t\tif (name.endsWith(FilterService.ATTRIBUTE_ID)) {\n\t\t\t// replace by Hibernate id property, always refers to the id, even if named differently\n\t\t\tname = name.substring(0, name.length() - FilterService.ATTRIBUTE_ID.length()) + HIBERNATE_ID;\n\t\t}\n\t\treturn name;\n\t}", "public static String getURLParentDirectory(String urlString) throws IllegalArgumentException {\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n throw Exceptions.IllegalArgument(\"Malformed URL: %s\", url);\n }\n\n String path = url.getPath();\n int lastSlashIndex = path.lastIndexOf(\"/\");\n String directory = lastSlashIndex == -1 ? \"\" : path.substring(0, lastSlashIndex);\n return String.format(\"%s://%s%s%s%s\", url.getProtocol(),\n url.getUserInfo() == null ? \"\" : url.getUserInfo() + \"@\",\n url.getHost(),\n url.getPort() == -1 ? \"\" : \":\" + Integer.toString(url.getPort()),\n directory);\n }", "public void switchDataSource(BoneCPConfig newConfig) throws SQLException {\n\t\tlogger.info(\"Switch to new datasource requested. New Config: \"+newConfig);\n\t\tDataSource oldDS = getTargetDataSource();\n \n\t\tif (!(oldDS instanceof BoneCPDataSource)){\n\t\t\tthrow new SQLException(\"Unknown datasource type! Was expecting BoneCPDataSource but received \"+oldDS.getClass()+\". Not switching datasource!\");\n\t\t}\n\t\t\n\t\tBoneCPDataSource newDS = new BoneCPDataSource(newConfig);\n\t\tnewDS.getConnection().close(); // initialize a connection (+ throw it away) to force the datasource to initialize the pool\n\t\t\n\t\t// force application to start using the new one \n\t\tsetTargetDataSource(newDS);\n\t\t\n\t\tlogger.info(\"Shutting down old datasource slowly. Old Config: \"+oldDS);\n\t\t// tell the old datasource to terminate. This terminates the pool lazily so existing checked out connections can still be used.\n\t\t((BoneCPDataSource)oldDS).close();\n\t}" ]
Return total number of connections created in all partitions. @return number of created connections
[ "public int getTotalCreatedConnections(){\r\n\t\tint total=0;\r\n\t\tfor (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){\r\n\t\t\ttotal+=this.partitions[i].getCreatedConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}" ]
[ "@SuppressWarnings({\"deprecation\", \"WeakerAccess\"})\n protected void removeShutdownHook(ClassLoaderLeakPreventor preventor, Thread shutdownHook) {\n final String displayString = \"'\" + shutdownHook + \"' of type \" + shutdownHook.getClass().getName();\n preventor.error(\"Removing shutdown hook: \" + displayString);\n Runtime.getRuntime().removeShutdownHook(shutdownHook);\n\n if(executeShutdownHooks) { // Shutdown hooks should be executed\n \n preventor.info(\"Executing shutdown hook now: \" + displayString);\n // Make sure it's from protected ClassLoader\n shutdownHook.start(); // Run cleanup immediately\n \n if(shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish\n try {\n shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run\n }\n catch (InterruptedException e) {\n // Do nothing\n }\n if(shutdownHook.isAlive()) {\n preventor.warn(shutdownHook + \"still running after \" + shutdownHookWaitMs + \" ms - Stopping!\");\n shutdownHook.stop();\n }\n }\n }\n }", "private void registerPerformanceMonitor(String beanName,\n BeanDefinitionRegistry registry) {\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n if (!registry.containsBeanDefinition(perfMonitorName)) {\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class);\n registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition());\n }\n }", "public void localBegin()\r\n {\r\n if (this.isInLocalTransaction)\r\n {\r\n throw new TransactionInProgressException(\"Connection is already in transaction\");\r\n }\r\n Connection connection = null;\r\n try\r\n {\r\n connection = this.getConnection();\r\n }\r\n catch (LookupException e)\r\n {\r\n /**\r\n * must throw to notify user that we couldn't start a connection\r\n */\r\n throw new PersistenceBrokerException(\"Can't lookup a connection\", e);\r\n }\r\n if (log.isDebugEnabled()) log.debug(\"localBegin was called for con \" + connection);\r\n // change autoCommit state only if we are not in a managed environment\r\n // and it is enabled by user\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"Try to change autoCommit state to 'false'\");\r\n platform.changeAutoCommitState(jcd, connection, false);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n this.isInLocalTransaction = true;\r\n }", "protected String getKey(final String ref, final String filename, final String extension) {\n return prefix + ref + \"/\" + filename + \".\" + extension;\n }", "public static vpnvserver_authenticationradiuspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationradiuspolicy_binding obj = new vpnvserver_authenticationradiuspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationradiuspolicy_binding response[] = (vpnvserver_authenticationradiuspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void addBeanToBeanMapping(BeanToBeanMapping beanToBeanMapping) {\r\n\t\tbeanToBeanMappings.put(ClassPair.get(beanToBeanMapping\r\n\t\t\t\t.getSourceClass(), beanToBeanMapping.getDestinationClass()),\r\n\t\t\t\tbeanToBeanMapping);\r\n\t}", "protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\n }", "public static clusternodegroup[] get(nitro_service service) throws Exception{\n\t\tclusternodegroup obj = new clusternodegroup();\n\t\tclusternodegroup[] response = (clusternodegroup[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private void handleUpdate(final CdjStatus update) {\n // First see if any metadata caches need evicting or mount sets need updating.\n if (update.isLocalUsbEmpty()) {\n final SlotReference slot = SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.USB_SLOT);\n detachMetadataCache(slot);\n flushHotCacheSlot(slot);\n removeMount(slot);\n } else if (update.isLocalUsbLoaded()) {\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.USB_SLOT));\n }\n\n if (update.isLocalSdEmpty()) {\n final SlotReference slot = SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.SD_SLOT);\n detachMetadataCache(slot);\n flushHotCacheSlot(slot);\n removeMount(slot);\n } else if (update.isLocalSdLoaded()){\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.SD_SLOT));\n }\n\n if (update.isDiscSlotEmpty()) {\n removeMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.CD_SLOT));\n } else {\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.CD_SLOT));\n }\n\n // Now see if a track has changed that needs new metadata.\n if (update.getTrackType() == CdjStatus.TrackType.UNKNOWN ||\n update.getTrackType() == CdjStatus.TrackType.NO_TRACK ||\n update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK ||\n update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.UNKNOWN ||\n update.getRekordboxId() == 0) { // We no longer have metadata for this device.\n clearDeck(update);\n } else { // We can offer metadata for this device; check if we already looked up this track.\n final TrackMetadata lastMetadata = hotCache.get(DeckReference.getDeckReference(update.getDeviceNumber(), 0));\n final DataReference trackReference = new DataReference(update.getTrackSourcePlayer(),\n update.getTrackSourceSlot(), update.getRekordboxId());\n if (lastMetadata == null || !lastMetadata.trackReference.equals(trackReference)) { // We have something new!\n // First see if we can find the new track in the hot cache as a hot cue\n for (TrackMetadata cached : hotCache.values()) {\n if (cached.trackReference.equals(trackReference)) { // Found a hot cue hit, use it.\n updateMetadata(update, cached);\n return;\n }\n }\n\n // Not in the hot cache so try actually retrieving it.\n if (activeRequests.add(update.getTrackSourcePlayer())) {\n // We had to make sure we were not already asking for this track.\n clearDeck(update); // We won't know what it is until our request completes.\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n TrackMetadata data = requestMetadataInternal(trackReference, update.getTrackType(), true);\n if (data != null) {\n updateMetadata(update, data);\n }\n } catch (Exception e) {\n logger.warn(\"Problem requesting track metadata from update\" + update, e);\n } finally {\n activeRequests.remove(update.getTrackSourcePlayer());\n }\n }\n }, \"MetadataFinder metadata request\").start();\n }\n }\n }\n }" ]
Marks inbox message as read for given messageId @param messageId String messageId @return boolean value depending on success of operation
[ "synchronized boolean markReadMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n ContentValues cv = new ContentValues();\n cv.put(IS_READ,1);\n db.update(Table.INBOX_MESSAGES.getName(), cv,_ID + \" = ? AND \" + USER_ID + \" = ?\",new String[]{messageId,userId});\n return true;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }" ]
[ "private void writeResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)\n {\n Project.Resources.Resource.Baseline baseline = m_factory.createProjectResourcesResourceBaseline();\n boolean populated = false;\n\n Number cost = mpxjResource.getBaselineCost();\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n Duration work = mpxjResource.getBaselineWork();\n if (work != null && work.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, work));\n }\n\n if (populated)\n {\n xmlResource.getBaseline().add(baseline);\n baseline.setNumber(BigInteger.ZERO);\n }\n\n for (int loop = 1; loop <= 10; loop++)\n {\n baseline = m_factory.createProjectResourcesResourceBaseline();\n populated = false;\n\n cost = mpxjResource.getBaselineCost(loop);\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n work = mpxjResource.getBaselineWork(loop);\n if (work != null && work.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, work));\n }\n\n if (populated)\n {\n xmlResource.getBaseline().add(baseline);\n baseline.setNumber(BigInteger.valueOf(loop));\n }\n }\n }", "protected I_CmsSearchConfigurationFacetRange parseRangeFacet(String pathPrefix) {\n\n try {\n final String range = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_RANGE);\n final String name = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_NAME);\n final String label = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_LABEL);\n final Integer minCount = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_MINCOUNT);\n final String start = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_START);\n final String end = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_END);\n final String gap = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_GAP);\n final String sother = parseOptionalStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_OTHER);\n List<I_CmsSearchConfigurationFacetRange.Other> other = null;\n if (sother != null) {\n final List<String> sothers = Arrays.asList(sother.split(\",\"));\n other = new ArrayList<I_CmsSearchConfigurationFacetRange.Other>(sothers.size());\n for (String so : sothers) {\n try {\n I_CmsSearchConfigurationFacetRange.Other o = I_CmsSearchConfigurationFacetRange.Other.valueOf(\n so);\n other.add(o);\n } catch (final Exception e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_INVALID_OTHER_OPTION_1, so), e);\n }\n }\n }\n final Boolean hardEnd = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_RANGE_FACET_HARDEND);\n final Boolean isAndFacet = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_FACET_ISANDFACET);\n final List<String> preselection = parseOptionalStringValues(pathPrefix + XML_ELEMENT_FACET_PRESELECTION);\n final Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n pathPrefix + XML_ELEMENT_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetRange(\n range,\n start,\n end,\n gap,\n other,\n hardEnd,\n name,\n minCount,\n label,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (final Exception e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_RANGE_FACET_MANDATORY_KEY_MISSING_1,\n XML_ELEMENT_RANGE_FACET_RANGE\n + \", \"\n + XML_ELEMENT_RANGE_FACET_START\n + \", \"\n + XML_ELEMENT_RANGE_FACET_END\n + \", \"\n + XML_ELEMENT_RANGE_FACET_GAP),\n e);\n return null;\n }\n\n }", "public void setDefault() {\n try {\n TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);\n String phone = telephonyManager.getLine1Number();\n if (phone != null && !phone.isEmpty()) {\n this.setNumber(phone);\n } else {\n String iso = telephonyManager.getNetworkCountryIso();\n setEmptyDefault(iso);\n }\n } catch (SecurityException e) {\n setEmptyDefault();\n }\n }", "public Collection<String> getCurrencyCodes() {\n Collection<String> result = get(KEY_QUERY_CURRENCY_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "private Auth constructAuth(String authToken, String tokenSecret, String username) throws IOException {\n\n Auth auth = new Auth();\n auth.setToken(authToken);\n auth.setTokenSecret(tokenSecret);\n\n // Prompt to ask what permission is needed: read, update or delete.\n auth.setPermission(Permission.fromString(\"delete\"));\n\n User user = new User();\n // Later change the following 3. Either ask user to pass on command line or read\n // from saved file.\n user.setId(nsid);\n user.setUsername((username));\n user.setRealName(\"\");\n auth.setUser(user);\n this.authStore.store(auth);\n return auth;\n }", "private static List<String> parseModifiers(int modifiers) {\n List<String> result = new ArrayList<String>();\n if (Modifier.isPrivate(modifiers)) {\n result.add(\"private\");\n }\n if (Modifier.isProtected(modifiers)) {\n result.add(\"protected\");\n }\n if (Modifier.isPublic(modifiers)) {\n result.add(\"public\");\n }\n if (Modifier.isAbstract(modifiers)) {\n result.add(\"abstract\");\n }\n if (Modifier.isFinal(modifiers)) {\n result.add(\"final\");\n }\n if (Modifier.isNative(modifiers)) {\n result.add(\"native\");\n }\n if (Modifier.isStatic(modifiers)) {\n result.add(\"static\");\n }\n if (Modifier.isStrict(modifiers)) {\n result.add(\"strict\");\n }\n if (Modifier.isSynchronized(modifiers)) {\n result.add(\"synchronized\");\n }\n if (Modifier.isTransient(modifiers)) {\n result.add(\"transient\");\n }\n if (Modifier.isVolatile(modifiers)) {\n result.add(\"volatile\");\n }\n if (Modifier.isInterface(modifiers)) {\n result.add(\"interface\");\n }\n return result;\n }", "public int[] getCurrentValuesArray() {\n int[] currentValues = new int[5];\n\n currentValues[0] = getMinFilterType().getFilterValue(); // MIN FILTER\n currentValues[1] = getMagFilterType().getFilterValue(); // MAG FILTER\n currentValues[2] = getAnisotropicValue(); // ANISO FILTER\n currentValues[3] = getWrapSType().getWrapValue(); // WRAP S\n currentValues[4] = getWrapTType().getWrapValue(); // WRAP T\n\n return currentValues;\n }", "public static NodeCache startAppIdWatcher(Environment env) {\n try {\n CuratorFramework curator = env.getSharedResources().getCurator();\n\n byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n if (uuidBytes == null) {\n Halt.halt(\"Fluo Application UUID not found\");\n throw new RuntimeException(); // make findbugs happy\n }\n\n final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);\n\n final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n nodeCache.getListenable().addListener(() -> {\n ChildData node = nodeCache.getCurrentData();\n if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {\n Halt.halt(\"Fluo Application UUID has changed or disappeared\");\n }\n });\n nodeCache.start();\n return nodeCache;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public void setPatternScheme(final boolean isByWeekDay, final boolean fireChange) {\n\n if (isByWeekDay ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isByWeekDay) {\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n } else {\n m_model.clearWeekDays();\n m_model.clearWeeksOfMonth();\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n }\n m_model.setInterval(getPatternDefaultValues().getInterval());\n if (fireChange) {\n onValueChange();\n }\n }\n });\n }\n\n }" ]
generate a prepared DELETE-Statement according to query @param query the Query @param cld the ClassDescriptor
[ "public SqlStatement getPreparedDeleteStatement(Query query, ClassDescriptor cld)\r\n {\r\n return new SqlDeleteByQuery(m_platform, cld, query, logger);\r\n }" ]
[ "public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final EObject rootTrace, final StringConcatenationClient code) {\n final CompositeGeneratorNode node = this.trace(rootTrace, code);\n this.generateTracedFile(fsa, path, node);\n }", "protected static PreparedStatement memorize(final PreparedStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (PreparedStatement) Proxy.newProxyInstance(\n\t\t\t\tPreparedStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {PreparedStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "private void complete(final InstallationManager.InstallationModification modification, final FinalizeCallback callback) {\n final List<File> processed = new ArrayList<File>();\n List<File> reenabled = Collections.emptyList();\n List<File> disabled = Collections.emptyList();\n try {\n try {\n // Update the state to invalidate and process module resources\n if (stateUpdater.compareAndSet(this, State.PREPARED, State.INVALIDATE)) {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n // Only invalidate modules when applying patches; on rollback files are immediately restored\n for (final File invalidation : moduleInvalidations) {\n processed.add(invalidation);\n PatchModuleInvalidationUtils.processFile(this, invalidation, mode);\n }\n if (!modulesToReenable.isEmpty()) {\n reenabled = new ArrayList<File>(modulesToReenable.size());\n for (final File path : modulesToReenable) {\n reenabled.add(path);\n PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.ROLLBACK);\n }\n }\n } else if(mode == PatchingTaskContext.Mode.ROLLBACK) {\n if (!modulesToDisable.isEmpty()) {\n disabled = new ArrayList<File>(modulesToDisable.size());\n for (final File path : modulesToDisable) {\n disabled.add(path);\n PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.APPLY);\n }\n }\n }\n\n }\n modification.complete();\n callback.completed(this);\n state = State.COMPLETED;\n } catch (Exception e) {\n this.moduleInvalidations.clear();\n this.moduleInvalidations.addAll(processed);\n this.modulesToReenable.clear();\n this.modulesToReenable.addAll(reenabled);\n this.modulesToDisable.clear();\n this.moduleInvalidations.addAll(disabled);\n throw new RuntimeException(e);\n }\n } finally {\n if (state != State.COMPLETED) {\n try {\n modification.cancel();\n } finally {\n try {\n undoChanges();\n } finally {\n callback.operationCancelled(this);\n }\n }\n } else {\n try {\n if (checkForGarbageOnRestart) {\n final File cleanupMarker = new File(installedImage.getInstallationMetadata(), \"cleanup-patching-dirs\");\n cleanupMarker.createNewFile();\n }\n storeFailedRenaming();\n } catch (IOException e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to create cleanup marker\");\n }\n }\n }\n }", "@PrefMetadata(type = CmsHiddenBuiltinPreference.class)\n public String getExplorerFileEntryOptions() {\n\n if (m_settings.getExplorerFileEntryOptions() == null) {\n return \"\";\n } else {\n return \"\" + m_settings.getExplorerFileEntryOptions();\n }\n }", "public boolean canBypassConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {\n\t\tAssert.notNull(targetType, \"The targetType to convert to cannot be null\");\n\t\tif (sourceType == null) {\n\t\t\treturn true;\n\t\t}\n\t\tGenericConverter converter = getConverter(sourceType, targetType);\n\t\treturn (converter == NO_OP_CONVERTER);\n\t}", "public static void installDomainConnectorServices(final OperationContext context,\n final ServiceTarget serviceTarget,\n final ServiceName endpointName,\n final ServiceName networkInterfaceBinding,\n final int port,\n final OptionMap options,\n final ServiceName securityRealm,\n final ServiceName saslAuthenticationFactory,\n final ServiceName sslContext) {\n String sbmCap = \"org.wildfly.management.socket-binding-manager\";\n ServiceName sbmName = context.hasOptionalCapability(sbmCap, NATIVE_MANAGEMENT_RUNTIME_CAPABILITY.getName(), null)\n ? context.getCapabilityServiceName(sbmCap, SocketBindingManager.class) : null;\n installConnectorServicesForNetworkInterfaceBinding(serviceTarget, endpointName, MANAGEMENT_CONNECTOR,\n networkInterfaceBinding, port, options, securityRealm, saslAuthenticationFactory, sslContext, sbmName);\n }", "public static Range toRange(Span span) {\n return new Range(toKey(span.getStart()), span.isStartInclusive(), toKey(span.getEnd()),\n span.isEndInclusive());\n }", "public LayerType toDto(Class<? extends com.vividsolutions.jts.geom.Geometry> geometryClass) {\n\t\tif (geometryClass == LineString.class) {\n\t\t\treturn LayerType.LINESTRING;\n\t\t} else if (geometryClass == MultiLineString.class) {\n\t\t\treturn LayerType.MULTILINESTRING;\n\t\t} else if (geometryClass == Point.class) {\n\t\t\treturn LayerType.POINT;\n\t\t} else if (geometryClass == MultiPoint.class) {\n\t\t\treturn LayerType.MULTIPOINT;\n\t\t} else if (geometryClass == Polygon.class) {\n\t\t\treturn LayerType.POLYGON;\n\t\t} else if (geometryClass == MultiPolygon.class) {\n\t\t\treturn LayerType.MULTIPOLYGON;\n\t\t} else {\n\t\t\treturn LayerType.GEOMETRY;\n\t\t}\n\t}", "public void setBackgroundColor(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }" ]
Infer app name from scan package @param packageName the package name @return app name inferred from the package name
[ "static String fromPackageName(String packageName) {\n List<String> tokens = tokenOf(packageName);\n return fromTokens(tokens);\n }" ]
[ "public Map<AssociationKey, Map<RowKey, Map<String, Object>>> getAssociationsMap() {\n\t\treturn Collections.unmodifiableMap( associationsKeyValueStorage );\n\t}", "public void addFile(InputStream inputStream) {\n String name = \"file\";\n fileStreams.put(normalizeDuplicateName(name), inputStream);\n }", "public static TestSuiteResult unmarshal(File testSuite) throws IOException {\n try (InputStream stream = new FileInputStream(testSuite)) {\n return unmarshal(stream);\n }\n }", "public void read(File file, Table table) throws IOException\n {\n //System.out.println(\"Reading \" + file.getName());\n InputStream is = null;\n try\n {\n is = new FileInputStream(file);\n read(is, table);\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n }\n }", "public static Chart getTrajectoryChart(String title, Trajectory t){\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[t.size()];\n\t\t double[] yData = new double[t.size()];\n\t\t for(int i = 0; i < t.size(); i++){\n\t\t \txData[i] = t.get(i).x;\n\t\t \tyData[i] = t.get(i).y;\n\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(title, \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\n\t\t return chart;\n\t\t //Show it\n\t\t // SwingWrapper swr = new SwingWrapper(chart);\n\t\t // swr.displayChart();\n\t\t} \n\t\treturn null;\n\t}", "private void calcCurrentItem() {\n int pointerAngle;\n\n // calculate the correct pointer angle, depending on clockwise drawing or not\n if(mOpenClockwise) {\n pointerAngle = (mIndicatorAngle + 360 - mPieRotation) % 360;\n }\n else {\n pointerAngle = (mIndicatorAngle + 180 + mPieRotation) % 360;\n }\n\n for (int i = 0; i < mPieData.size(); ++i) {\n PieModel model = mPieData.get(i);\n if (model.getStartAngle() <= pointerAngle && pointerAngle <= model.getEndAngle()) {\n if (i != mCurrentItem) {\n setCurrentItem(i, false);\n }\n break;\n }\n }\n }", "private List<PermissionFactory> retrievePermissionSet(final OperationContext context, final ModelNode node) throws OperationFailedException {\n\n final List<PermissionFactory> permissions = new ArrayList<>();\n\n if (node != null && node.isDefined()) {\n for (ModelNode permissionNode : node.asList()) {\n String permissionClass = CLASS.resolveModelAttribute(context, permissionNode).asString();\n String permissionName = null;\n if (permissionNode.hasDefined(PERMISSION_NAME))\n permissionName = NAME.resolveModelAttribute(context, permissionNode).asString();\n String permissionActions = null;\n if (permissionNode.hasDefined(PERMISSION_ACTIONS))\n permissionActions = ACTIONS.resolveModelAttribute(context, permissionNode).asString();\n String moduleName = null;\n if(permissionNode.hasDefined(PERMISSION_MODULE)) {\n moduleName = MODULE.resolveModelAttribute(context, permissionNode).asString();\n }\n ClassLoader cl = WildFlySecurityManager.getClassLoaderPrivileged(this.getClass());\n if(moduleName != null) {\n try {\n cl = Module.getBootModuleLoader().loadModule(ModuleIdentifier.fromString(moduleName)).getClassLoader();\n } catch (ModuleLoadException e) {\n throw new OperationFailedException(e);\n }\n }\n\n permissions.add(new LoadedPermissionFactory(cl,\n permissionClass, permissionName, permissionActions));\n }\n }\n return permissions;\n }", "@SuppressForbidden(\"legitimate sysstreams.\")\n public static void warn(String message, Throwable t) {\n PrintStream w = (warnings == null ? System.err : warnings);\n try {\n w.print(\"WARN: \");\n w.print(message);\n if (t != null) {\n w.print(\" -> \");\n try {\n t.printStackTrace(w);\n } catch (OutOfMemoryError e) {\n // Ignore, OOM.\n w.print(t.getClass().getName());\n w.print(\": \");\n w.print(t.getMessage());\n w.println(\" (stack unavailable; OOM)\");\n }\n } else {\n w.println();\n }\n w.flush();\n } catch (OutOfMemoryError t2) {\n w.println(\"ERROR: Couldn't even serialize a warning (out of memory).\");\n } catch (Throwable t2) {\n // Can't do anything, really. Probably an OOM?\n w.println(\"ERROR: Couldn't even serialize a warning.\");\n }\n }", "public TwoDHashMap<K2, K3, V> getAs2d(final K1 firstKey) {\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);\n\t\tif( innerMap1 != null ) {\n\t\t\treturn new TwoDHashMap<K2, K3, V>(innerMap1);\n\t\t} else {\n\t\t\treturn new TwoDHashMap<K2, K3, V>();\n\t\t}\n\t\t\n\t}" ]
Returns the name of the operation. @param op the operation @return the name of the operation @throws IllegalArgumentException if the operation was not defined.
[ "public static String getOperationName(final ModelNode op) {\n if (op.hasDefined(OP)) {\n return op.get(OP).asString();\n }\n throw ControllerClientLogger.ROOT_LOGGER.operationNameNotFound();\n }" ]
[ "private static boolean scanForEndSig(File file, FileChannel channel) throws IOException, NonScannableZipException {\n\n // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long start = channel.size();\n long end = Math.max(0, start - MAX_REVERSE_SCAN);\n long channelPos = Math.max(0, start - CHUNK_SIZE);\n long lastChannelPos = channelPos;\n boolean firstRead = true;\n while (lastChannelPos >= end) {\n\n read(bb, channel, channelPos);\n\n int actualRead = bb.limit();\n if (firstRead) {\n long expectedRead = Math.min(CHUNK_SIZE, start);\n if (actualRead > expectedRead) {\n // File is still growing\n return false;\n }\n firstRead = false;\n }\n\n int bufferPos = actualRead -1;\n while (bufferPos >= SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the pattern is static\n // b) the pattern has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && ENDSIG_PATTERN[patternPos] == bb.get(bufferPos - patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid end of central dir record\n long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1;\n if (validateEndRecord(file, channel, startEndRecord)) {\n return true;\n }\n // wasn't a valid end record; continue scan\n bufferPos -= 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE;\n bufferPos -= END_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos -= 4;\n }\n }\n\n // Move back a full chunk. If we didn't read a full chunk, that's ok,\n // it means we read all data and the outer while loop will terminate\n if (channelPos <= bufferPos) {\n break;\n }\n lastChannelPos = channelPos;\n channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos);\n }\n\n return false;\n }", "public static Operation createDeployOperation(final Set<DeploymentDescription> deployments) {\n Assertions.requiresNotNullOrNotEmptyParameter(\"deployments\", deployments);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n for (DeploymentDescription deployment : deployments) {\n addDeployOperationStep(builder, deployment);\n }\n return builder.build();\n }", "public String stripThreadName(String threadId)\n {\n if (threadId == null)\n {\n return null;\n }\n else\n {\n int index = threadId.lastIndexOf('@');\n return index >= 0 ? threadId.substring(0, index) : threadId;\n }\n }", "private List<Row> join(List<Row> leftRows, String leftColumn, String rightTable, List<Row> rightRows, String rightColumn)\n {\n List<Row> result = new LinkedList<Row>();\n\n RowComparator leftComparator = new RowComparator(new String[]\n {\n leftColumn\n });\n RowComparator rightComparator = new RowComparator(new String[]\n {\n rightColumn\n });\n Collections.sort(leftRows, leftComparator);\n Collections.sort(rightRows, rightComparator);\n\n ListIterator<Row> rightIterator = rightRows.listIterator();\n Row rightRow = rightIterator.hasNext() ? rightIterator.next() : null;\n\n for (Row leftRow : leftRows)\n {\n Integer leftValue = leftRow.getInteger(leftColumn);\n boolean match = false;\n\n while (rightRow != null)\n {\n Integer rightValue = rightRow.getInteger(rightColumn);\n int comparison = leftValue.compareTo(rightValue);\n if (comparison == 0)\n {\n match = true;\n break;\n }\n\n if (comparison < 0)\n {\n if (rightIterator.hasPrevious())\n {\n rightRow = rightIterator.previous();\n }\n break;\n }\n\n rightRow = rightIterator.next();\n }\n\n if (match && rightRow != null)\n {\n Map<String, Object> newMap = new HashMap<String, Object>(((MapRow) leftRow).getMap());\n\n for (Entry<String, Object> entry : ((MapRow) rightRow).getMap().entrySet())\n {\n String key = entry.getKey();\n if (newMap.containsKey(key))\n {\n key = rightTable + \".\" + key;\n }\n newMap.put(key, entry.getValue());\n }\n\n result.add(new MapRow(newMap));\n }\n }\n\n return result;\n }", "public static URL asUrlOrResource(String s) {\n if (Strings.isNullOrEmpty(s)) {\n return null;\n }\n\n try {\n return new URL(s);\n } catch (MalformedURLException e) {\n //If its not a valid URL try to treat it as a local resource.\n return findConfigResource(s);\n }\n }", "public void setModificationState(ModificationState newModificationState)\r\n {\r\n if(newModificationState != modificationState)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"object state transition for object \" + this.oid + \" (\"\r\n + modificationState + \" --> \" + newModificationState + \")\");\r\n// try{throw new Exception();}catch(Exception e)\r\n// {\r\n// e.printStackTrace();\r\n// }\r\n }\r\n modificationState = newModificationState;\r\n }\r\n }", "protected static BoxCollaboration.Info create(BoxAPIConnection api, JsonObject accessibleBy, JsonObject item,\n BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) {\n\n\n String queryString = \"\";\n if (notify != null) {\n queryString = new QueryStringBuilder().appendParam(\"notify\", notify.toString()).toString();\n }\n URL url;\n if (queryString.length() > 0) {\n url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString);\n } else {\n url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL());\n }\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", item);\n requestJSON.add(\"accessible_by\", accessibleBy);\n requestJSON.add(\"role\", role.toJSONString());\n if (canViewPath != null) {\n requestJSON.add(\"can_view_path\", canViewPath.booleanValue());\n }\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxCollaboration newCollaboration = new BoxCollaboration(api, responseJSON.get(\"id\").asString());\n return newCollaboration.new Info(responseJSON);\n }", "public SslHandler create(ByteBufAllocator bufferAllocator) {\n SSLEngine engine = sslContext.newEngine(bufferAllocator);\n engine.setNeedClientAuth(needClientAuth);\n engine.setUseClientMode(false);\n return new SslHandler(engine);\n }", "private InputStream runSparqlQuery(String query) throws IOException {\n\t\ttry {\n\t\t\tString queryString = \"query=\" + URLEncoder.encode(query, \"UTF-8\")\n\t\t\t\t\t+ \"&format=json\";\n\t\t\tURL url = new URL(\"https://query.wikidata.org/sparql?\"\n\t\t\t\t\t+ queryString);\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url\n\t\t\t\t\t.openConnection();\n\t\t\tconnection.setRequestMethod(\"GET\");\n\n\t\t\treturn connection.getInputStream();\n\t\t} catch (UnsupportedEncodingException | MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}" ]
Adds another scene object to pick against. Each frame all the colliders in the scene will be compared against the bounding volumes of all the collidables associated with this picker. @param sceneObj new collidable @return index of collidable added, this is the CursorID in the GVRPickedObject
[ "public int addCollidable(GVRSceneObject sceneObj)\n {\n synchronized (mCollidables)\n {\n int index = mCollidables.indexOf(sceneObj);\n if (index >= 0)\n {\n return index;\n }\n mCollidables.add(sceneObj);\n return mCollidables.size() - 1;\n }\n }" ]
[ "public static synchronized Class< ? > locate(final String serviceName) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null && !l.isEmpty() ) {\n Callable<Class< ? >> c = l.get( l.size() - 1 );\n try {\n return c.call();\n } catch ( Exception e ) {\n }\n }\n }\n return null;\n }", "public final PJsonObject optJSONObject(final String key) {\n final JSONObject val = this.obj.optJSONObject(key);\n return val != null ? new PJsonObject(this, val, key) : null;\n }", "public Object get(int dataSet) throws SerializationException {\r\n\t\tObject result = null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult = getData(ds);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}", "private void writeResourceAssignmentWorkgroupFields(ResourceAssignmentWorkgroupFields record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_WORKGROUP_FIELDS_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getMessageUniqueID()));\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getConfirmed() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getResponsePending() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getScheduleID()));\n\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }", "public Jar setJarPrefix(String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (value != null && jarPrefixFile != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixFile + \")\");\n this.jarPrefixStr = value;\n return this;\n }", "public static Collection<Field> getAttributes(\n final Class<?> classToInspect, final Predicate<Field> filter) {\n Set<Field> allFields = new HashSet<>();\n getAllAttributes(classToInspect, allFields, Function.identity(), filter);\n return allFields;\n }", "protected int parseZoneId() {\n int result = -1;\n String zoneIdStr = this.request.getHeader(RestMessageHeaders.X_VOLD_ZONE_ID);\n if(zoneIdStr != null) {\n try {\n int zoneId = Integer.parseInt(zoneIdStr);\n if(zoneId < 0) {\n logger.error(\"ZoneId cannot be negative. Assuming the default zone id.\");\n } else {\n result = zoneId;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect zone id parameter. Cannot parse this to int: \"\n + zoneIdStr,\n nfe);\n }\n }\n return result;\n }", "public void setHighlightStrength(float _highlightStrength) {\n mHighlightStrength = _highlightStrength;\n for (PieModel model : mPieData) {\n highlightSlice(model);\n }\n invalidateGlobal();\n }", "public static rnatip_stats get(nitro_service service, String Rnatip) throws Exception{\n\t\trnatip_stats obj = new rnatip_stats();\n\t\tobj.set_Rnatip(Rnatip);\n\t\trnatip_stats response = (rnatip_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
Compress contiguous partitions into format "e-i" instead of "e, f, g, h, i". This helps illustrate contiguous partitions within a zone. @param cluster @param zoneId @return pretty string of partitions per zone
[ "public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster,\n zoneId);\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"[\");\n boolean first = true;\n Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet());\n for(int initPartitionId: sortedInitPartitionIds) {\n if(!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n\n int runLength = idToRunLength.get(initPartitionId);\n if(runLength == 1) {\n sb.append(initPartitionId);\n } else {\n int endPartitionId = (initPartitionId + runLength - 1)\n % cluster.getNumberOfPartitions();\n sb.append(initPartitionId).append(\"-\").append(endPartitionId);\n }\n }\n sb.append(\"]\");\n\n return sb.toString();\n }" ]
[ "public GVRMesh findMesh(GVRSceneObject model)\n {\n class MeshFinder implements GVRSceneObject.ComponentVisitor\n {\n private GVRMesh meshFound = null;\n public GVRMesh getMesh() { return meshFound; }\n public boolean visit(GVRComponent comp)\n {\n GVRRenderData rdata = (GVRRenderData) comp;\n meshFound = rdata.getMesh();\n return (meshFound == null);\n }\n };\n MeshFinder findMesh = new MeshFinder();\n model.forAllComponents(findMesh, GVRRenderData.getComponentType());\n return findMesh.getMesh();\n }", "public void fire(StepEvent event) {\n Step step = stepStorage.getLast();\n event.process(step);\n\n notifier.fire(event);\n }", "public RedwoodConfiguration showOnlyChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.showOnlyChannels(channels); } });\r\n return this;\r\n }", "public static appfwsignatures get(nitro_service service) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tappfwsignatures[] response = (appfwsignatures[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "private void saveToBundleDescriptor() throws CmsException {\n\n if (null != m_descFile) {\n m_removeDescriptorOnCancel = false;\n updateBundleDescriptorContent();\n m_descFile.getFile().setContents(m_descContent.marshal());\n m_cms.writeFile(m_descFile.getFile());\n }\n }", "public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs);\n recordSyncOpTimeNs(null, opTimeNs);\n } else {\n this.syncOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }", "public final Object getRealObject(Object objectOrProxy)\r\n {\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n return getIndirectionHandler(objectOrProxy).getRealSubject();\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for given Proxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n try\r\n {\r\n return ((VirtualProxy) objectOrProxy).getRealSubject();\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for VirtualProxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else\r\n {\r\n return objectOrProxy;\r\n }\r\n }", "private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(BOOTSTRAP_URLS_PROPERTY)) {\n setBootstrapURLs(props.getList(BOOTSTRAP_URLS_PROPERTY));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_SOURCE)) {\n setFatClientConfigSource(StoreClientConfigSource.get(props.getString(FAT_CLIENTS_CONFIG_SOURCE)));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY)) {\n setFatClientConfigPath(props.getString(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY));\n }\n\n if(props.containsKey(METADATA_CHECK_INTERVAL_IN_MS)) {\n setMetadataCheckIntervalInMs(props.getInt(METADATA_CHECK_INTERVAL_IN_MS));\n }\n\n if(props.containsKey(NETTY_SERVER_PORT)) {\n setServerPort(props.getInt(NETTY_SERVER_PORT));\n }\n\n if(props.containsKey(NETTY_SERVER_BACKLOG)) {\n setNettyServerBacklog(props.getInt(NETTY_SERVER_BACKLOG));\n }\n\n if(props.containsKey(COORDINATOR_CORE_THREADS)) {\n setCoordinatorCoreThreads(props.getInt(COORDINATOR_CORE_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_MAX_THREADS)) {\n setCoordinatorMaxThreads(props.getInt(COORDINATOR_MAX_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_QUEUED_REQUESTS)) {\n setCoordinatorQueuedRequestsSize(props.getInt(COORDINATOR_QUEUED_REQUESTS));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH)) {\n setHttpMessageDecoderMaxInitialLength(props.getInt(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE)) {\n setHttpMessageDecoderMaxHeaderSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE)) {\n setHttpMessageDecoderMaxChunkSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE));\n }\n\n if(props.containsKey(ADMIN_ENABLE)) {\n setAdminServiceEnabled(props.getBoolean(ADMIN_ENABLE));\n }\n\n if(props.containsKey(ADMIN_PORT)) {\n setAdminPort(props.getInt(ADMIN_PORT));\n }\n\n }", "public static UndeployDescription of(final DeploymentDescription deploymentDescription) {\n Assert.checkNotNullParam(\"deploymentDescription\", deploymentDescription);\n return of(deploymentDescription.getName()).addServerGroups(deploymentDescription.getServerGroups());\n }" ]
Search for a publisher of the given type in a project and return it, or null if it is not found. @return The publisher
[ "public static <T extends Publisher> T getPublisher(AbstractProject<?, ?> project, Class<T> type) {\n // Search for a publisher of the given type in the project and return it if found:\n T publisher = new PublisherFindImpl<T>().find(project, type);\n if (publisher != null) {\n return publisher;\n }\n // If not found, the publisher might be wrapped by a \"Flexible Publish\" publisher. The below searches for it inside the\n // Flexible Publisher:\n publisher = new PublisherFlexible<T>().find(project, type);\n return publisher;\n }" ]
[ "public static final String printDuration(Duration duration)\n {\n String result = null;\n if (duration != null)\n {\n result = duration.getDuration() + \" \" + printTimeUnits(duration.getUnits());\n }\n return result;\n }", "private void readTaskCustomFields(net.sf.mpxj.ganttproject.schema.Task gpTask, Task mpxjTask)\n {\n //\n // Populate custom field default values\n //\n Map<FieldType, Object> customFields = new HashMap<FieldType, Object>();\n for (Pair<FieldType, String> definition : m_taskPropertyDefinitions.values())\n {\n customFields.put(definition.getFirst(), definition.getSecond());\n }\n\n //\n // Update with custom field actual values\n //\n for (CustomTaskProperty property : gpTask.getCustomproperty())\n {\n Pair<FieldType, String> definition = m_taskPropertyDefinitions.get(property.getTaskpropertyId());\n if (definition != null)\n {\n //\n // Retrieve the value. If it is empty, use the default.\n //\n String value = property.getValueAttribute();\n if (value.isEmpty())\n {\n value = null;\n }\n\n //\n // If we have a value,convert it to the correct type\n //\n if (value != null)\n {\n Object result;\n\n switch (definition.getFirst().getDataType())\n {\n case NUMERIC:\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n result = Double.valueOf(value);\n }\n break;\n }\n\n case DATE:\n {\n try\n {\n result = m_dateFormat.parse(value);\n }\n catch (ParseException ex)\n {\n result = null;\n }\n break;\n }\n\n case BOOLEAN:\n {\n result = Boolean.valueOf(value.equals(\"true\"));\n break;\n }\n\n default:\n {\n result = value;\n break;\n }\n }\n\n if (result != null)\n {\n customFields.put(definition.getFirst(), result);\n }\n }\n }\n }\n\n for (Map.Entry<FieldType, Object> item : customFields.entrySet())\n {\n if (item.getValue() != null)\n {\n mpxjTask.set(item.getKey(), item.getValue());\n }\n }\n }", "protected void animateOffsetTo(int position, int velocity, boolean animate) {\n endDrag();\n endPeek();\n\n final int startX = (int) mOffsetPixels;\n final int dx = position - startX;\n if (dx == 0 || !animate) {\n setOffsetPixels(position);\n setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN);\n stopLayerTranslation();\n return;\n }\n\n int duration;\n\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));\n } else {\n duration = (int) (600.f * Math.abs((float) dx / mMenuSize));\n }\n\n duration = Math.min(duration, mMaxAnimationDuration);\n animateOffsetTo(position, duration);\n }", "public static String groupFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null;\n }", "public boolean add(final String member, final double score) {\n return doWithJedis(new JedisCallable<Boolean>() {\n @Override\n public Boolean call(Jedis jedis) {\n return jedis.zadd(getKey(), score, member) > 0;\n }\n });\n }", "public void abortExternalTx(TransactionImpl odmgTrans)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"abortExternTransaction was called\");\r\n if (odmgTrans == null) return;\r\n TxBuffer buf = (TxBuffer) txRepository.get();\r\n Transaction extTx = buf != null ? buf.getExternTx() : null;\r\n try\r\n {\r\n if (extTx != null && extTx.getStatus() == Status.STATUS_ACTIVE)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Set extern transaction to rollback\");\r\n }\r\n extTx.setRollbackOnly();\r\n }\r\n }\r\n catch (Exception ignore)\r\n {\r\n }\r\n txRepository.set(null);\r\n }", "protected boolean isReserved( String name ) {\n if( functions.isFunctionName(name))\n return true;\n\n for (int i = 0; i < name.length(); i++) {\n if( !isLetter(name.charAt(i)) )\n return true;\n }\n return false;\n }", "public void setDoubleAttribute(String name, Double value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DoubleAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\n\t}", "public static base_response unset(nitro_service client, aaaparameter resource, String[] args) throws Exception{\n\t\taaaparameter unsetresource = new aaaparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Add tables to the tree. @param parentNode parent tree node @param file tables container
[ "private void addTables(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Table table : file.getTables())\n {\n final Table t = table;\n MpxjTreeNode childNode = new MpxjTreeNode(table, TABLE_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return t.getName();\n }\n };\n parentNode.add(childNode);\n\n addColumns(childNode, table);\n }\n }" ]
[ "static void undoChanges(final PatchEntry entry, final PatchContentLoader loader) {\n final List<ContentModification> modifications = new ArrayList<ContentModification>(entry.rollbackActions);\n for (final ContentModification modification : modifications) {\n final ContentItem item = modification.getItem();\n if (item.getContentType() != ContentType.MISC) {\n // Skip modules and bundles they should be removed as part of the {@link FinalizeCallback}\n continue;\n }\n final PatchingTaskDescription description = new PatchingTaskDescription(entry.applyPatchId, modification, loader, false, false, false);\n try {\n final PatchingTask task = PatchingTask.Factory.create(description, entry);\n task.execute(entry);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.failedToUndoChange(item.toString());\n }\n }\n }", "public static Enum<?> findMatchingEnumVal(Field field, String unknownEnumName) {\n\t\tif (unknownEnumName == null || unknownEnumName.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tfor (Enum<?> enumVal : (Enum<?>[]) field.getType().getEnumConstants()) {\n\t\t\tif (enumVal.name().equals(unknownEnumName)) {\n\t\t\t\treturn enumVal;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unknwown enum unknown name \" + unknownEnumName + \" for field \" + field);\n\t}", "public synchronized int cancelByTag(String tagToCancel) {\n int i = 0;\n if (taskList.containsKey(tagToCancel)) {\n removeDoneTasks();\n\n for (Future<BlurWorker.Result> future : taskList.get(tagToCancel)) {\n BuilderUtil.logVerbose(Dali.getConfig().logTag, \"Canceling task with tag \" + tagToCancel, Dali.getConfig().debugMode);\n future.cancel(true);\n i++;\n }\n\n //remove all canceled tasks\n Iterator<Future<BlurWorker.Result>> iter = taskList.get(tagToCancel).iterator();\n while (iter.hasNext()) {\n if (iter.next().isCancelled()) {\n iter.remove();\n }\n }\n }\n return i;\n }", "public Collection<Tag> getListUser(String userId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_USER);\n\n parameters.put(\"user_id\", userId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element whoElement = response.getPayload();\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) whoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n return tags;\n }", "private boolean absoluteAdvanced(int row)\r\n {\r\n boolean retval = false;\r\n \r\n try\r\n {\r\n if (getRsAndStmt().m_rs != null)\r\n {\r\n if (row == 0)\r\n {\r\n getRsAndStmt().m_rs.beforeFirst();\r\n }\r\n else\r\n {\r\n retval = getRsAndStmt().m_rs.absolute(row); \r\n }\r\n m_current_row = row;\r\n setHasCalledCheck(false);\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n advancedJDBCSupport = false;\r\n }\r\n return retval;\r\n }", "void processDumpFile(MwDumpFile dumpFile,\n\t\t\tMwDumpFileProcessor dumpFileProcessor) {\n\t\ttry (InputStream inputStream = dumpFile.getDumpFileStream()) {\n\t\t\tdumpFileProcessor.processDumpFileContents(inputStream, dumpFile);\n\t\t} catch (FileAlreadyExistsException e) {\n\t\t\tlogger.error(\"Dump file \"\n\t\t\t\t\t+ dumpFile.toString()\n\t\t\t\t\t+ \" could not be processed since file \"\n\t\t\t\t\t+ e.getFile()\n\t\t\t\t\t+ \" already exists. Try deleting the file or dumpfile directory to attempt a new download.\");\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"Dump file \" + dumpFile.toString()\n\t\t\t\t\t+ \" could not be processed: \" + e.toString());\n\t\t}\n\t}", "private boolean getRelative(int value)\n {\n boolean result;\n if (value < 0 || value >= RELATIVE_MAP.length)\n {\n result = false;\n }\n else\n {\n result = RELATIVE_MAP[value];\n }\n\n return result;\n }", "public void addRelation(RelationType relationType, RelationDirection direction) {\n\tint idx = relationType.ordinal();\n\tdirections[idx] = directions[idx].sum(direction);\n }", "protected static void appendHandler(Class<? extends LogRecordHandler> parent, LogRecordHandler child){\r\n List<LogRecordHandler> toAdd = new LinkedList<LogRecordHandler>();\r\n //--Find Parents\r\n for(LogRecordHandler term : handlers){\r\n if(parent.isAssignableFrom(term.getClass())){\r\n toAdd.add(term);\r\n }\r\n }\r\n //--Add Handler\r\n for(LogRecordHandler p : toAdd){\r\n appendHandler(p, child);\r\n }\r\n }" ]
Get the features collection from a GeoJson inline string or URL. @param template the template @param features what to parse @return the feature collection @throws IOException
[ "public final SimpleFeatureCollection autoTreat(final Template template, final String features)\n throws IOException {\n SimpleFeatureCollection featuresCollection = treatStringAsURL(template, features);\n if (featuresCollection == null) {\n featuresCollection = treatStringAsGeoJson(features);\n }\n return featuresCollection;\n }" ]
[ "public void addDataSource(int groupno, DataSource datasource) {\n // the loader takes care of validation\n if (groupno == 0)\n datasources.add(datasource);\n else if (groupno == 1)\n group1.add(datasource);\n else if (groupno == 2)\n group2.add(datasource);\n }", "@Override\n public final Boolean optBool(final String key, final Boolean defaultValue) {\n Boolean result = optBool(key);\n return result == null ? defaultValue : result;\n }", "public <V> V attachIfAbsent(final AttachmentKey<V> key, final V value) {\n assert key != null;\n return key.cast(contextAttachments.putIfAbsent(key, value));\n }", "public static String escapeDoubleQuotesForJson(String text) {\n\t\tif ( text == null ) {\n\t\t\treturn null;\n\t\t}\n\t\tStringBuilder builder = new StringBuilder( text.length() );\n\t\tfor ( int i = 0; i < text.length(); i++ ) {\n\t\t\tchar c = text.charAt( i );\n\t\t\tswitch ( c ) {\n\t\t\t\tcase '\"':\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tbuilder.append( \"\\\\\" );\n\t\t\t\tdefault:\n\t\t\t\t\tbuilder.append( c );\n\t\t\t}\n\t\t}\n\t\treturn builder.toString();\n\t}", "public IdRange[] parseIdRange(ImapRequestLineReader request)\n throws ProtocolException {\n CharacterValidator validator = new MessageSetCharValidator();\n String nextWord = consumeWord(request, validator);\n\n int commaPos = nextWord.indexOf(',');\n if (commaPos == -1) {\n return new IdRange[]{IdRange.parseRange(nextWord)};\n }\n\n List<IdRange> rangeList = new ArrayList<>();\n int pos = 0;\n while (commaPos != -1) {\n String range = nextWord.substring(pos, commaPos);\n IdRange set = IdRange.parseRange(range);\n rangeList.add(set);\n\n pos = commaPos + 1;\n commaPos = nextWord.indexOf(',', pos);\n }\n String range = nextWord.substring(pos);\n rangeList.add(IdRange.parseRange(range));\n return rangeList.toArray(new IdRange[rangeList.size()]);\n }", "public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) {\r\n String[] coVariables = action.getCoVariables().split(\",\");\r\n int n = Integer.valueOf(action.getN());\n\r\n List<Map<String, String>> newPossibleStateList = new ArrayList<>();\n\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n Map<String, String[]> variableDomains = new HashMap<>();\r\n Map<String, String> defaultVariableValues = new HashMap<>();\r\n for (String variable : coVariables) {\r\n String variableMetaInfo = possibleState.get(variable);\r\n String[] variableDomain = variableMetaInfo.split(\",\");\r\n variableDomains.put(variable, variableDomain);\r\n defaultVariableValues.put(variable, variableDomain[0]);\r\n }\n\r\n List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains);\r\n for (Map<String, String> nWiseCombination : nWiseCombinations) {\r\n Map<String, String> newPossibleState = new HashMap<>(possibleState);\r\n newPossibleState.putAll(defaultVariableValues);\r\n newPossibleState.putAll(nWiseCombination);\r\n newPossibleStateList.add(newPossibleState);\r\n }\r\n }\n\r\n return newPossibleStateList;\r\n }", "public static Timer getNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tTimer key = new Timer(timerName, todoFlags, threadId);\n\t\tregisteredTimers.putIfAbsent(key, key);\n\t\treturn registeredTimers.get(key);\n\t}", "private static AbstractProject<?, ?> getProject(String fullName) {\n Item item = Hudson.getInstance().getItemByFullName(fullName);\n if (item != null && item instanceof AbstractProject) {\n return (AbstractProject<?, ?>) item;\n }\n return null;\n }", "protected BufferedImage createErrorImage(final Rectangle area) {\n final BufferedImage bufferedImage = new BufferedImage(area.width, area.height, TYPE_INT_ARGB_PRE);\n final Graphics2D graphics = bufferedImage.createGraphics();\n try {\n graphics.setBackground(ColorParser.toColor(this.configuration.getTransparentTileErrorColor()));\n graphics.clearRect(0, 0, area.width, area.height);\n return bufferedImage;\n } finally {\n graphics.dispose();\n }\n }" ]
Run through all maps and remove any references that have been null'd out by the GC.
[ "public <T> void cleanNullReferencesAll() {\n\t\tfor (Map<Object, Reference<Object>> objectMap : classMaps.values()) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}" ]
[ "public void stop() {\n instanceLock.writeLock().lock();\n try {\n for (final NamespaceChangeStreamListener streamer : nsStreamers.values()) {\n streamer.stop();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }", "private String escapeAndJoin(String[] commandline) {\n // TODO: we should try to escape special characters here, depending on the OS.\n StringBuilder b = new StringBuilder();\n Pattern specials = Pattern.compile(\"[\\\\ ]\");\n for (String arg : commandline) {\n if (b.length() > 0) {\n b.append(\" \");\n }\n\n if (specials.matcher(arg).find()) {\n b.append('\"').append(arg).append('\"');\n } else {\n b.append(arg);\n }\n }\n return b.toString();\n }", "public synchronized void shutdown() {\n checkIsRunning();\n try {\n beanManager().fireEvent(new ContainerBeforeShutdown(id), BeforeDestroyed.Literal.APPLICATION);\n } finally {\n discard(id);\n // Destroy all the dependent beans correctly\n creationalContext.release();\n beanManager().fireEvent(new ContainerShutdown(id), Destroyed.Literal.APPLICATION);\n bootstrap.shutdown();\n WeldSELogger.LOG.weldContainerShutdown(id);\n }\n }", "public static Result get(XmlFileModel key)\n {\n String cacheKey = getKey(key);\n\n Result result = null;\n CacheDocument reference = map.get(cacheKey);\n\n if (reference == null)\n return new Result(false, null);\n\n if (reference.parseFailure)\n return new Result(true, null);\n\n Document document = reference.getDocument();\n if (document == null)\n LOG.info(\"Cache miss on XML document: \" + cacheKey);\n\n return new Result(false, document);\n }", "public double response( double[] sample ) {\n if( sample.length != A.numCols )\n throw new IllegalArgumentException(\"Expected input vector to be in sample space\");\n\n DMatrixRMaj dots = new DMatrixRMaj(numComponents,1);\n DMatrixRMaj s = DMatrixRMaj.wrap(A.numCols,1,sample);\n\n CommonOps_DDRM.mult(V_t,s,dots);\n\n return NormOps_DDRM.normF(dots);\n }", "public static LinearSolverDense<DMatrixRMaj> symmPosDef(int matrixWidth ) {\n if(matrixWidth < EjmlParameters.SWITCH_BLOCK64_CHOLESKY ) {\n CholeskyDecompositionCommon_DDRM decomp = new CholeskyDecompositionInner_DDRM(true);\n return new LinearSolverChol_DDRM(decomp);\n } else {\n if( EjmlParameters.MEMORY == EjmlParameters.MemoryUsage.FASTER )\n return new LinearSolverChol_DDRB();\n else {\n CholeskyDecompositionCommon_DDRM decomp = new CholeskyDecompositionInner_DDRM(true);\n return new LinearSolverChol_DDRM(decomp);\n }\n }\n }", "public void seekToHoliday(String holidayString, String direction, String seekAmount) {\n Holiday holiday = Holiday.valueOf(holidayString);\n assert(holiday != null);\n \n seekToIcsEvent(HOLIDAY_ICS_FILE, holiday.getSummary(), direction, seekAmount);\n }", "public static LayersConfig getLayersConfig(final File repoRoot) throws IOException {\n final File layersList = new File(repoRoot, LAYERS_CONF);\n if (!layersList.exists()) {\n return new LayersConfig();\n }\n final Properties properties = PatchUtils.loadProperties(layersList);\n return new LayersConfig(properties);\n }", "protected TypeReference<?> getBeanPropertyType(Class<?> clazz,\r\n\t\t\tString propertyName, TypeReference<?> originalType) {\r\n\t\tTypeReference<?> propertyDestinationType = null;\r\n\t\tif (beanDestinationPropertyTypeProvider != null) {\r\n\t\t\tpropertyDestinationType = beanDestinationPropertyTypeProvider\r\n\t\t\t\t\t.getPropertyType(clazz, propertyName, originalType);\r\n\t\t}\r\n\t\tif (propertyDestinationType == null) {\r\n\t\t\tpropertyDestinationType = originalType;\r\n\t\t}\r\n\t\treturn propertyDestinationType;\r\n\t}" ]
This method takes the textual version of a relation type and returns an appropriate class instance. Note that unrecognised values will cause this method to return null. @param locale target locale @param type text version of the relation type @return RelationType instance
[ "public static RelationType getInstance(Locale locale, String type)\n {\n int index = -1;\n\n String[] relationTypes = LocaleData.getStringArray(locale, LocaleData.RELATION_TYPES);\n for (int loop = 0; loop < relationTypes.length; loop++)\n {\n if (relationTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n RelationType result = null;\n if (index != -1)\n {\n result = RelationType.getInstance(index);\n }\n\n return (result);\n }" ]
[ "@Around(\"@annotation(retryableAnnotation)\")\n public Object call(final ProceedingJoinPoint pjp, Retryable retryableAnnotation) throws Throwable {\n final int maxTries = retryableAnnotation.maxTries();\n final int retryDelayMillies = retryableAnnotation.retryDelayMillis();\n final Class<? extends Throwable>[] retryOn = retryableAnnotation.retryOn();\n final boolean doubleDelay = retryableAnnotation.doubleDelay();\n final boolean throwCauseException = retryableAnnotation.throwCauseException();\n\n if (logger.isDebugEnabled()) {\n logger.debug(\"Have @Retryable method wrapping call on method {} of target object {}\",\n new Object[] {\n pjp.getSignature().getName(),\n pjp.getTarget()\n });\n }\n\n ServiceRetrier serviceRetrier =\n new ServiceRetrier(retryDelayMillies, maxTries, doubleDelay, throwCauseException, retryOn);\n\n return serviceRetrier.invoke(\n new Callable<Object>() {\n public Object call() throws Exception {\n try {\n return pjp.proceed();\n }\n catch (Exception e) {\n throw e;\n }\n catch (Error e) {\n throw e;\n }\n catch (Throwable t) {\n throw new RuntimeException(t);\n }\n }\n }\n );\n }", "@Nonnull\n public BiMap<String, String> getOutputMapper() {\n final BiMap<String, String> outputMapper = this.processor.getOutputMapperBiMap();\n if (outputMapper == null) {\n return HashBiMap.create();\n }\n return outputMapper;\n }", "@Override\n public final Integer optInt(final String key) {\n final int result = this.obj.optInt(key, Integer.MIN_VALUE);\n return result == Integer.MIN_VALUE ? null : result;\n }", "public static int findVerticalOffset(JRDesignBand band) {\n\t\tint finalHeight = 0;\n\t\tif (band != null) {\n\t\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\t\tJRDesignElement element = (JRDesignElement) jrChild;\n\t\t\t\tint currentHeight = element.getY() + element.getHeight();\n\t\t\t\tif (currentHeight > finalHeight) finalHeight = currentHeight;\n\t\t\t}\n\t\t\treturn finalHeight;\n\t\t}\n\t\treturn finalHeight;\n\t}", "private Entry getEntry(Object key)\r\n {\r\n if (key == null) return null;\r\n int hash = hashCode(key);\r\n int index = indexFor(hash);\r\n for (Entry entry = table[index]; entry != null; entry = entry.next)\r\n {\r\n if ((entry.hash == hash) && equals(key, entry.getKey()))\r\n {\r\n return entry;\r\n }\r\n }\r\n return null;\r\n }", "public Collection<QName> getPortComponentQNames()\n {\n //TODO:Check if there is just one QName that drives all portcomponents\n //or each port component can have a distinct QName (namespace/prefix)\n //Maintain uniqueness of the QName\n Map<String, QName> map = new HashMap<String, QName>();\n for (PortComponentMetaData pcm : portComponents)\n {\n QName qname = pcm.getWsdlPort();\n map.put(qname.getPrefix(), qname);\n }\n return map.values();\n }", "public static String buildDynamicCapabilityName(String baseName, String dynamicNameElement) {\n return buildDynamicCapabilityName(baseName, new String[]{dynamicNameElement});\n }", "private Map<String, I_CmsSearchConfigurationFacetField> getDefaultFieldFacets(boolean categoryConjunction) {\n\n Map<String, I_CmsSearchConfigurationFacetField> fieldFacets = new HashMap<String, I_CmsSearchConfigurationFacetField>();\n fieldFacets.put(\n CmsListManager.FIELD_CATEGORIES,\n new CmsSearchConfigurationFacetField(\n CmsListManager.FIELD_CATEGORIES,\n null,\n Integer.valueOf(1),\n Integer.valueOf(200),\n null,\n \"Category\",\n SortOrder.index,\n null,\n Boolean.valueOf(categoryConjunction),\n null,\n Boolean.TRUE));\n fieldFacets.put(\n CmsListManager.FIELD_PARENT_FOLDERS,\n new CmsSearchConfigurationFacetField(\n CmsListManager.FIELD_PARENT_FOLDERS,\n null,\n Integer.valueOf(1),\n Integer.valueOf(200),\n null,\n \"Folders\",\n SortOrder.index,\n null,\n Boolean.FALSE,\n null,\n Boolean.TRUE));\n return Collections.unmodifiableMap(fieldFacets);\n\n }", "public static base_response clear(nitro_service client) throws Exception {\n\t\tnspbr6 clearresource = new nspbr6();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}" ]
Use this API to update vpnsessionaction.
[ "public static base_response update(nitro_service client, vpnsessionaction resource) throws Exception {\n\t\tvpnsessionaction updateresource = new vpnsessionaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.httpport = resource.httpport;\n\t\tupdateresource.winsip = resource.winsip;\n\t\tupdateresource.dnsvservername = resource.dnsvservername;\n\t\tupdateresource.splitdns = resource.splitdns;\n\t\tupdateresource.sesstimeout = resource.sesstimeout;\n\t\tupdateresource.clientsecurity = resource.clientsecurity;\n\t\tupdateresource.clientsecuritygroup = resource.clientsecuritygroup;\n\t\tupdateresource.clientsecuritymessage = resource.clientsecuritymessage;\n\t\tupdateresource.clientsecuritylog = resource.clientsecuritylog;\n\t\tupdateresource.splittunnel = resource.splittunnel;\n\t\tupdateresource.locallanaccess = resource.locallanaccess;\n\t\tupdateresource.rfc1918 = resource.rfc1918;\n\t\tupdateresource.spoofiip = resource.spoofiip;\n\t\tupdateresource.killconnections = resource.killconnections;\n\t\tupdateresource.transparentinterception = resource.transparentinterception;\n\t\tupdateresource.windowsclienttype = resource.windowsclienttype;\n\t\tupdateresource.defaultauthorizationaction = resource.defaultauthorizationaction;\n\t\tupdateresource.authorizationgroup = resource.authorizationgroup;\n\t\tupdateresource.clientidletimeout = resource.clientidletimeout;\n\t\tupdateresource.proxy = resource.proxy;\n\t\tupdateresource.allprotocolproxy = resource.allprotocolproxy;\n\t\tupdateresource.httpproxy = resource.httpproxy;\n\t\tupdateresource.ftpproxy = resource.ftpproxy;\n\t\tupdateresource.socksproxy = resource.socksproxy;\n\t\tupdateresource.gopherproxy = resource.gopherproxy;\n\t\tupdateresource.sslproxy = resource.sslproxy;\n\t\tupdateresource.proxyexception = resource.proxyexception;\n\t\tupdateresource.proxylocalbypass = resource.proxylocalbypass;\n\t\tupdateresource.clientcleanupprompt = resource.clientcleanupprompt;\n\t\tupdateresource.forcecleanup = resource.forcecleanup;\n\t\tupdateresource.clientoptions = resource.clientoptions;\n\t\tupdateresource.clientconfiguration = resource.clientconfiguration;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.ssocredential = resource.ssocredential;\n\t\tupdateresource.windowsautologon = resource.windowsautologon;\n\t\tupdateresource.usemip = resource.usemip;\n\t\tupdateresource.useiip = resource.useiip;\n\t\tupdateresource.clientdebug = resource.clientdebug;\n\t\tupdateresource.loginscript = resource.loginscript;\n\t\tupdateresource.logoutscript = resource.logoutscript;\n\t\tupdateresource.homepage = resource.homepage;\n\t\tupdateresource.icaproxy = resource.icaproxy;\n\t\tupdateresource.wihome = resource.wihome;\n\t\tupdateresource.citrixreceiverhome = resource.citrixreceiverhome;\n\t\tupdateresource.wiportalmode = resource.wiportalmode;\n\t\tupdateresource.clientchoices = resource.clientchoices;\n\t\tupdateresource.epaclienttype = resource.epaclienttype;\n\t\tupdateresource.iipdnssuffix = resource.iipdnssuffix;\n\t\tupdateresource.forcedtimeout = resource.forcedtimeout;\n\t\tupdateresource.forcedtimeoutwarning = resource.forcedtimeoutwarning;\n\t\tupdateresource.ntdomain = resource.ntdomain;\n\t\tupdateresource.clientlessvpnmode = resource.clientlessvpnmode;\n\t\tupdateresource.emailhome = resource.emailhome;\n\t\tupdateresource.clientlessmodeurlencoding = resource.clientlessmodeurlencoding;\n\t\tupdateresource.clientlesspersistentcookie = resource.clientlesspersistentcookie;\n\t\tupdateresource.allowedlogingroups = resource.allowedlogingroups;\n\t\tupdateresource.securebrowse = resource.securebrowse;\n\t\tupdateresource.storefronturl = resource.storefronturl;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "public static JmsDestinationType getTypeFromClass(String aClass)\n {\n if (StringUtils.equals(aClass, \"javax.jms.Queue\") || StringUtils.equals(aClass, \"javax.jms.QueueConnectionFactory\"))\n {\n return JmsDestinationType.QUEUE;\n }\n else if (StringUtils.equals(aClass, \"javax.jms.Topic\") || StringUtils.equals(aClass, \"javax.jms.TopicConnectionFactory\"))\n {\n return JmsDestinationType.TOPIC;\n }\n else\n {\n return null;\n }\n }", "public Module generateBuildInfoModule(Run build, TaskListener listener, ArtifactoryConfigurator config, String buildName, String buildNumber, String timestamp) throws IOException {\n if (artifactsProps == null) {\n artifactsProps = ArrayListMultimap.create();\n }\n artifactsProps.put(\"build.name\", buildName);\n artifactsProps.put(\"build.number\", buildNumber);\n artifactsProps.put(\"build.timestamp\", timestamp);\n String artifactsPropsStr = ExtractorUtils.buildPropertiesString(artifactsProps);\n\n Properties buildInfoItemsProps = new Properties();\n buildInfoItemsProps.setProperty(\"build.name\", buildName);\n buildInfoItemsProps.setProperty(\"build.number\", buildNumber);\n buildInfoItemsProps.setProperty(\"build.timestamp\", timestamp);\n\n ArtifactoryServer server = config.getArtifactoryServer();\n CredentialsConfig preferredResolver = server.getDeployerCredentialsConfig();\n ArtifactoryDependenciesClient dependenciesClient = null;\n ArtifactoryBuildInfoClient propertyChangeClient = null;\n\n try {\n dependenciesClient = server.createArtifactoryDependenciesClient(\n preferredResolver.provideUsername(build.getParent()), preferredResolver.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy), listener);\n\n CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(config, server);\n propertyChangeClient = server.createArtifactoryClient(\n preferredDeployer.provideUsername(build.getParent()), preferredDeployer.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy));\n\n Module buildInfoModule = new Module();\n buildInfoModule.setId(imageTag.substring(imageTag.indexOf(\"/\") + 1));\n\n // If manifest and imagePath not found, return.\n if ((StringUtils.isEmpty(manifest) || StringUtils.isEmpty(imagePath)) && !findAndSetManifestFromArtifactory(server, dependenciesClient, listener)) {\n return buildInfoModule;\n }\n\n listener.getLogger().println(\"Fetching details of published docker layers from Artifactory...\");\n boolean includeVirtualReposSupported = propertyChangeClient.getArtifactoryVersion().isAtLeast(VIRTUAL_REPOS_SUPPORTED_VERSION);\n DockerLayers layers = createLayers(dependenciesClient, includeVirtualReposSupported);\n\n listener.getLogger().println(\"Tagging published docker layers with build properties in Artifactory...\");\n setDependenciesAndArtifacts(buildInfoModule, layers, artifactsPropsStr, buildInfoItemsProps,\n dependenciesClient, propertyChangeClient, server);\n setBuildInfoModuleProps(buildInfoModule);\n return buildInfoModule;\n } finally {\n if (dependenciesClient != null) {\n dependenciesClient.close();\n }\n if (propertyChangeClient != null) {\n propertyChangeClient.close();\n }\n }\n }", "public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}", "static String guessEntityTypeFromId(String id) {\n\t\tif(id.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"Entity ids should not be empty.\");\n\t\t}\n\t\tswitch (id.charAt(0)) {\n\t\t\tcase 'L':\n\t\t\t\tif(id.contains(\"-F\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_FORM;\n\t\t\t\t} else if(id.contains(\"-S\")) {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_SENSE;\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON_ENTITY_TYPE_LEXEME;\n\t\t\t\t}\n\t\t\tcase 'P':\n\t\t\t\treturn JSON_ENTITY_TYPE_PROPERTY;\n\t\t\tcase 'Q':\n\t\t\t\treturn JSON_ENTITY_TYPE_ITEM;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}", "public void merge(GVRSkeleton newSkel)\n {\n int numBones = getNumBones();\n List<Integer> parentBoneIds = new ArrayList<Integer>(numBones + newSkel.getNumBones());\n List<String> newBoneNames = new ArrayList<String>(newSkel.getNumBones());\n List<Matrix4f> newMatrices = new ArrayList<Matrix4f>(newSkel.getNumBones());\n GVRPose oldBindPose = getBindPose();\n GVRPose curPose = getPose();\n\n for (int i = 0; i < numBones; ++i)\n {\n parentBoneIds.add(mParentBones[i]);\n }\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n String boneName = newSkel.getBoneName(j);\n int boneId = getBoneIndex(boneName);\n if (boneId < 0)\n {\n int parentId = newSkel.getParentBoneIndex(j);\n Matrix4f m = new Matrix4f();\n\n newSkel.getBindPose().getLocalMatrix(j, m);\n newMatrices.add(m);\n newBoneNames.add(boneName);\n if (parentId >= 0)\n {\n boneName = newSkel.getBoneName(parentId);\n parentId = getBoneIndex(boneName);\n }\n parentBoneIds.add(parentId);\n }\n }\n if (parentBoneIds.size() == numBones)\n {\n return;\n }\n int n = numBones + parentBoneIds.size();\n int[] parentIds = Arrays.copyOf(mParentBones, n);\n int[] boneOptions = Arrays.copyOf(mBoneOptions, n);\n String[] boneNames = Arrays.copyOf(mBoneNames, n);\n\n mBones = Arrays.copyOf(mBones, n);\n mPoseMatrices = new float[n * 16];\n for (int i = 0; i < parentBoneIds.size(); ++i)\n {\n n = numBones + i;\n parentIds[n] = parentBoneIds.get(i);\n boneNames[n] = newBoneNames.get(i);\n boneOptions[n] = BONE_ANIMATE;\n }\n mBoneOptions = boneOptions;\n mBoneNames = boneNames;\n mParentBones = parentIds;\n mPose = new GVRPose(this);\n mBindPose = new GVRPose(this);\n mBindPose.copy(oldBindPose);\n mPose.copy(curPose);\n mBindPose.sync();\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n mBindPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n mPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n }\n setBindPose(mBindPose);\n mPose.sync();\n updateBonePose();\n }", "public static base_response disable(nitro_service client, String name) throws Exception {\n\t\tvserver disableresource = new vserver();\n\t\tdisableresource.name = name;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "private byte[] createErrorImage(int width, int height, Exception e) throws IOException {\n\t\tString error = e.getMessage();\n\t\tif (null == error) {\n\t\t\tWriter result = new StringWriter();\n\t\t\tPrintWriter printWriter = new PrintWriter(result);\n\t\t\te.printStackTrace(printWriter);\n\t\t\terror = result.toString();\n\t\t}\n\n\t\tBufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);\n\t\tGraphics2D g = (Graphics2D) image.getGraphics();\n\n\t\tg.setColor(Color.RED);\n\t\tg.drawString(error, ERROR_MESSAGE_X, height / 2);\n\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\tImageIO.write(image, \"PNG\", out);\n\t\tout.flush();\n\t\tbyte[] result = out.toByteArray();\n\t\tout.close();\n\n\t\treturn result;\n\t}", "public static Set<String> listDeployments(Resource deploymentRootResource, Set<String> runtimeNames) {\n Set<Pattern> set = new HashSet<>();\n for (String wildcardExpr : runtimeNames) {\n Pattern pattern = DeploymentOverlayIndex.getPattern(wildcardExpr);\n set.add(pattern);\n }\n return listDeploymentNames(deploymentRootResource, set);\n }", "public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\n }" ]
Use this API to fetch authenticationradiusaction resource of given name .
[ "public static authenticationradiusaction get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tobj.set_name(name);\n\t\tauthenticationradiusaction response = (authenticationradiusaction) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public static lbvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_auditnslogpolicy_binding obj = new lbvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_auditnslogpolicy_binding response[] = (lbvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public int getPrivacy() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PRIVACY);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element personElement = response.getPayload();\r\n return Integer.parseInt(personElement.getAttribute(\"privacy\"));\r\n }", "public SerialMessage getMessage(AlarmType alarmType) {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) SENSOR_ALARM_GET,\r\n\t\t\t\t\t\t\t\t(byte) alarmType.getKey() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}", "protected Boolean getIgnoreQuery() {\n\n Boolean isIgnoreQuery = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_QUERY);\n return (null == isIgnoreQuery) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreQueryParam())\n : isIgnoreQuery;\n }", "public static synchronized void unregister(final String serviceName,\n final Callable<Class< ? >> factory) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null ) {\n l.remove( factory );\n }\n }\n }", "private void readProjectProperties(Settings phoenixSettings, Storepoint storepoint)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(phoenixSettings.getTitle());\n mpxjProperties.setDefaultDurationUnits(phoenixSettings.getBaseunit());\n mpxjProperties.setStatusDate(storepoint.getDataDate());\n }", "private void populateRelationList(Task task, TaskField field, String data)\n {\n DeferredRelationship dr = new DeferredRelationship();\n dr.setTask(task);\n dr.setField(field);\n dr.setData(data);\n m_deferredRelationships.add(dr);\n }", "public float getSphereBound(float[] sphere)\n {\n if ((sphere == null) || (sphere.length != 4) ||\n ((NativeVertexBuffer.getBoundingVolume(getNative(), sphere)) < 0))\n {\n throw new IllegalArgumentException(\"Cannot copy sphere bound into array provided\");\n }\n return sphere[0];\n }", "public void close() throws IOException {\n final ManagedBinding binding = this.socketBindingManager.getNamedRegistry().getManagedBinding(this.name);\n if (binding == null) {\n return;\n }\n binding.close();\n }" ]
Loads the given class, respecting the given classloader. @param clazz class to load @return Loaded class @throws ClassNotFoundException
[ "protected Class<?> loadClass(String clazz) throws ClassNotFoundException {\n\t\tif (this.classLoader == null){\n\t\t\treturn Class.forName(clazz);\n\t\t}\n\n\t\treturn Class.forName(clazz, true, this.classLoader);\n\n\t}" ]
[ "public static String[] tokenizeUnquoted(String s) {\r\n List tokens = new LinkedList();\r\n int first = 0;\r\n while (first < s.length()) {\r\n first = skipWhitespace(s, first);\r\n int last = scanToken(s, first);\r\n if (first < last) {\r\n tokens.add(s.substring(first, last));\r\n }\r\n first = last;\r\n }\r\n return (String[])tokens.toArray(new String[tokens.size()]);\r\n }", "protected void runImportScript(CmsObject cms, CmsModule module) {\n\n LOG.info(\"Executing import script for module \" + module.getName());\n m_report.println(\n org.opencms.module.Messages.get().container(org.opencms.module.Messages.RPT_IMPORT_SCRIPT_HEADER_0),\n I_CmsReport.FORMAT_HEADLINE);\n String importScript = \"echo on\\n\" + module.getImportScript();\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n PrintStream out = new PrintStream(buffer);\n CmsShell shell = new CmsShell(cms, \"${user}@${project}:${siteroot}|${uri}>\", null, out, out);\n shell.execute(importScript);\n String outputString = buffer.toString();\n LOG.info(\"Shell output for import script was: \\n\" + outputString);\n m_report.println(\n org.opencms.module.Messages.get().container(\n org.opencms.module.Messages.RPT_IMPORT_SCRIPT_OUTPUT_1,\n outputString));\n }", "public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = _table.getColumn((String)objA).getProperty(\"id\");\r\n String idBStr = _table.getColumn((String)objB).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex) {\r\n return 1;\r\n }\r\n try {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex) {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }", "private void checkDuplicateStdOutOutput(DumpProcessingAction newAction) {\n\t\tif (newAction.useStdOut()) {\n\t\t\tif (this.quiet) {\n\t\t\t\tlogger.warn(\"Multiple actions are using stdout as output destination.\");\n\t\t\t}\n\t\t\tthis.quiet = true;\n\t\t}\n\t}", "public RandomVariable[]\tgetParameter() {\n\t\tdouble[] parameterAsDouble = this.getParameterAsDouble();\n\t\tRandomVariable[] parameter = new RandomVariable[parameterAsDouble.length];\n\t\tfor(int i=0; i<parameter.length; i++) {\n\t\t\tparameter[i] = new Scalar(parameterAsDouble[i]);\n\t\t}\n\t\treturn parameter;\n\t}", "public void stop()\n {\n if (mAudioListener != null)\n {\n Log.d(\"SOUND\", \"stopping audio source %d %s\", getSourceId(), getSoundFile());\n mAudioListener.getAudioEngine().stopSound(getSourceId());\n }\n }", "public List<Method> getMethodsFromGroupId(int groupId, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.OVERRIDE_GROUP_ID + \" = ?\"\n );\n statement.setInt(1, groupId);\n results = statement.executeQuery();\n while (results.next()) {\n Method method = PathOverrideService.getInstance().getMethodForOverrideId(results.getInt(\"id\"));\n if (method == null) {\n continue;\n }\n\n // decide whether or not to add this method based on the filters\n boolean add = true;\n if (filters != null) {\n add = false;\n for (String filter : filters) {\n if (method.getMethodType().endsWith(filter)) {\n add = true;\n break;\n }\n }\n }\n\n if (add && !methods.contains(method)) {\n methods.add(method);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return methods;\n }", "okhttp3.Response get(String url, Map<String, Object> params)\n throws RequestException, LocalOperationException {\n\n String fullUrl = getFullUrl(url);\n okhttp3.Request request = new okhttp3.Request.Builder()\n .url(addUrlParams(fullUrl, toPayload(params)))\n .addHeader(\"Transloadit-Client\", version)\n .build();\n\n try {\n return httpClient.newCall(request).execute();\n } catch (IOException e) {\n throw new RequestException(e);\n }\n }", "public static JqmClient getClient(String name, Properties p, boolean cached)\n {\n Properties p2 = null;\n if (binder == null)\n {\n bind();\n }\n if (p == null)\n {\n p2 = props;\n }\n else\n {\n p2 = new Properties(props);\n p2.putAll(p);\n }\n return binder.getClientFactory().getClient(name, p2, cached);\n }" ]
Logs the time taken by this rule, and attaches this to the total for the RuleProvider
[ "private void logTimeTakenByRuleProvider(GraphContext graphContext, Context context, int ruleIndex, int timeTaken)\n {\n AbstractRuleProvider ruleProvider = (AbstractRuleProvider) context.get(RuleMetadataType.RULE_PROVIDER);\n if (ruleProvider == null)\n return;\n\n if (!timeTakenByProvider.containsKey(ruleProvider))\n {\n RuleProviderExecutionStatisticsModel model = new RuleProviderExecutionStatisticsService(graphContext)\n .create();\n model.setRuleIndex(ruleIndex);\n model.setRuleProviderID(ruleProvider.getMetadata().getID());\n model.setTimeTaken(timeTaken);\n\n timeTakenByProvider.put(ruleProvider, model.getElement().id());\n }\n else\n {\n RuleProviderExecutionStatisticsService service = new RuleProviderExecutionStatisticsService(graphContext);\n RuleProviderExecutionStatisticsModel model = service.getById(timeTakenByProvider.get(ruleProvider));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n logTimeTakenByPhase(graphContext, ruleProvider.getMetadata().getPhase(), timeTaken);\n }" ]
[ "protected void parseOperationsLR(Symbol ops[], TokenList tokens, Sequence sequence) {\n\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n if( token.getType() != Type.VARIABLE )\n throw new ParseError(\"The first token in an equation needs to be a variable and not \"+token);\n\n boolean hasLeft = false;\n while( token != null ) {\n if( token.getType() == Type.FUNCTION ) {\n throw new ParseError(\"Function encountered with no parentheses\");\n } else if( token.getType() == Type.VARIABLE ) {\n if( hasLeft ) {\n if( isTargetOp(token.previous,ops)) {\n token = createOp(token.previous.previous,token.previous,token,tokens,sequence);\n }\n } else {\n hasLeft = true;\n }\n } else {\n if( token.previous.getType() == Type.SYMBOL ) {\n throw new ParseError(\"Two symbols next to each other. \"+token.previous+\" and \"+token);\n }\n }\n token = token.next;\n }\n }", "public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {\n final CopyOption[] options;\n if (overwrite) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};\n } else {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.walkFileTree(source, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n Files.copy(dir, target.resolve(source.relativize(dir)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.copy(file, target.resolve(source.relativize(file)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }", "private List<StyleFilter> initStyleFilters(List<FeatureStyleInfo> styleDefinitions) throws GeomajasException {\n\t\tList<StyleFilter> styleFilters = new ArrayList<StyleFilter>();\n\t\tif (styleDefinitions == null || styleDefinitions.size() == 0) {\n\t\t\tstyleFilters.add(new StyleFilterImpl()); // use default.\n\t\t} else {\n\t\t\tfor (FeatureStyleInfo styleDef : styleDefinitions) {\n\t\t\t\tStyleFilterImpl styleFilterImpl = null;\n\t\t\t\tString formula = styleDef.getFormula();\n\t\t\t\tif (null != formula && formula.length() > 0) {\n\t\t\t\t\tstyleFilterImpl = new StyleFilterImpl(filterService.parseFilter(formula), styleDef);\n\t\t\t\t} else {\n\t\t\t\t\tstyleFilterImpl = new StyleFilterImpl(Filter.INCLUDE, styleDef);\n\t\t\t\t}\n\t\t\t\tstyleFilters.add(styleFilterImpl);\n\t\t\t}\n\t\t}\n\t\treturn styleFilters;\n\t}", "public static int lookupShaper(String name) {\r\n if (name == null) {\r\n return NOWORDSHAPE;\r\n } else if (name.equalsIgnoreCase(\"dan1\")) {\r\n return WORDSHAPEDAN1;\r\n } else if (name.equalsIgnoreCase(\"chris1\")) {\r\n return WORDSHAPECHRIS1;\r\n } else if (name.equalsIgnoreCase(\"dan2\")) {\r\n return WORDSHAPEDAN2;\r\n } else if (name.equalsIgnoreCase(\"dan2useLC\")) {\r\n return WORDSHAPEDAN2USELC;\r\n } else if (name.equalsIgnoreCase(\"dan2bio\")) {\r\n return WORDSHAPEDAN2BIO;\r\n } else if (name.equalsIgnoreCase(\"dan2bioUseLC\")) {\r\n return WORDSHAPEDAN2BIOUSELC;\r\n } else if (name.equalsIgnoreCase(\"jenny1\")) {\r\n return WORDSHAPEJENNY1;\r\n } else if (name.equalsIgnoreCase(\"jenny1useLC\")) {\r\n return WORDSHAPEJENNY1USELC;\r\n } else if (name.equalsIgnoreCase(\"chris2\")) {\r\n return WORDSHAPECHRIS2;\r\n } else if (name.equalsIgnoreCase(\"chris2useLC\")) {\r\n return WORDSHAPECHRIS2USELC;\r\n } else if (name.equalsIgnoreCase(\"chris3\")) {\r\n return WORDSHAPECHRIS3;\r\n } else if (name.equalsIgnoreCase(\"chris3useLC\")) {\r\n return WORDSHAPECHRIS3USELC;\r\n } else if (name.equalsIgnoreCase(\"chris4\")) {\r\n return WORDSHAPECHRIS4;\r\n } else if (name.equalsIgnoreCase(\"digits\")) {\r\n return WORDSHAPEDIGITS;\r\n } else {\r\n return NOWORDSHAPE;\r\n }\r\n }", "public void readTags(InputStream tagsXML)\n {\n SAXParserFactory factory = SAXParserFactory.newInstance();\n try\n {\n SAXParser saxParser = factory.newSAXParser();\n saxParser.parse(tagsXML, new TagsSaxHandler(this));\n }\n catch (ParserConfigurationException | SAXException | IOException ex)\n {\n throw new RuntimeException(\"Failed parsing the tags definition: \" + ex.getMessage(), ex);\n }\n }", "public void setSlideDrawable(Drawable drawable) {\n mSlideDrawable = new SlideDrawable(drawable);\n mSlideDrawable.setIsRtl(ViewHelper.getLayoutDirection(this) == LAYOUT_DIRECTION_RTL);\n\n if (mActionBarHelper != null) {\n mActionBarHelper.setDisplayShowHomeAsUpEnabled(true);\n\n if (mDrawerIndicatorEnabled) {\n mActionBarHelper.setActionBarUpIndicator(mSlideDrawable,\n isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc);\n }\n }\n }", "public static boolean sameLists(String list1, String list2)\r\n {\r\n return new CommaListIterator(list1).equals(new CommaListIterator(list2));\r\n }", "public Object remove(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null != bean) {\n\t\t\tbeans.remove(name);\n\t\t\tbean.destructionCallback.run();\n\t\t\treturn bean.object;\n\t\t}\n\t\treturn null;\n\t}", "protected synchronized Object materializeSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tTemporaryBrokerWrapper tmp = getBroker();\r\n try\r\n\t\t{\r\n\t\t\tObject realSubject = tmp.broker.getObjectByIdentity(_id);\r\n\t\t\tif (realSubject == null)\r\n\t\t\t{\r\n\t\t\t\tLoggerFactory.getLogger(IndirectionHandler.class).warn(\r\n\t\t\t\t\t\t\"Can not materialize object for Identity \" + _id + \" - using PBKey \" + getBrokerKey());\r\n\t\t\t}\r\n\t\t\treturn realSubject;\r\n\t\t} catch (Exception ex)\r\n\t\t{\r\n\t\t\tthrow new PersistenceBrokerException(ex);\r\n\t\t} finally\r\n\t\t{\r\n\t\t\ttmp.close();\r\n\t\t}\r\n\t}" ]
This is the main entry point used to convert the internal representation of timephased cost into an external form which can be displayed to the user. @param projectCalendar calendar used by the resource assignment @param cost timephased resource assignment data @param rangeUnits timescale units @param dateList timescale date ranges @return list of durations, one per timescale date range
[ "public ArrayList<Double> segmentCost(ProjectCalendar projectCalendar, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n ArrayList<Double> result = new ArrayList<Double>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, cost, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(NumberHelper.DOUBLE_ZERO);\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeCost(projectCalendar, rangeUnits, range, cost, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }" ]
[ "public final void fatal(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.FATAL, pObject, null);\r\n\t}", "public void append(float[] newValue) {\n if ( (newValue.length % 2) == 0) {\n for (int i = 0; i < (newValue.length/2); i++) {\n value.add( new SFVec2f(newValue[i*2], newValue[i*2+1]) );\n }\n }\n else {\n Log.e(TAG, \"X3D MFVec3f append set with array length not divisible by 2\");\n }\n }", "public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() {\n\n if (null == m_resourceCategories) {\n m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object resourceName) {\n\n try {\n CmsResource resource = m_cms.readResource(\n getRequestContext().removeSiteRoot((String)resourceName));\n return new CmsJspCategoryAccessBean(m_cms, resource);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n });\n }\n return m_resourceCategories;\n }", "public float get(int row, int col) {\n if (row < 0 || row > 3) {\n throw new IndexOutOfBoundsException(\"Index: \" + row + \", Size: 4\");\n }\n if (col < 0 || col > 3) {\n throw new IndexOutOfBoundsException(\"Index: \" + col + \", Size: 4\");\n }\n\n return m_data[row * 4 + col];\n }", "private double sumSquaredDiffs()\n { \n double mean = getArithmeticMean();\n double squaredDiffs = 0;\n for (int i = 0; i < getSize(); i++)\n {\n double diff = mean - dataSet[i];\n squaredDiffs += (diff * diff);\n }\n return squaredDiffs;\n }", "public static appflowpolicylabel[] get(nitro_service service) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tappflowpolicylabel[] response = (appflowpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static Set<String> commaDelimitedListToSet(String str) {\n Set<String> set = new TreeSet<String>();\n String[] tokens = commaDelimitedListToStringArray(str);\n Collections.addAll(set, tokens);\n return set;\n }", "@Override\n public void setJobQueue(int jobId, Queue queue)\n {\n JqmClientFactory.getClient().setJobQueue(jobId, queue);\n }", "public static Type boxedType(Type type) {\n if (type instanceof Class<?>) {\n return boxedClass((Class<?>) type);\n } else {\n return type;\n }\n }" ]
Closes off this connection @param connection to close
[ "protected void closeConnection(ConnectionHandle connection) {\r\n\t\tif (connection != null) {\r\n\t\t\ttry {\r\n\t\t\t\tconnection.internalClose();\r\n\t\t\t} catch (Throwable t) {\r\n\t\t\t\tlogger.error(\"Destroy connection exception\", t);\r\n\t\t\t} finally {\r\n\t\t\t\tthis.pool.postDestroyConnection(connection);\r\n\t\t\t}\r\n\t\t}\r\n}" ]
[ "private static List<Path> expandMultiAppInputDirs(List<Path> input)\n {\n List<Path> expanded = new LinkedList<>();\n for (Path path : input)\n {\n if (Files.isRegularFile(path))\n {\n expanded.add(path);\n continue;\n }\n if (!Files.isDirectory(path))\n {\n String pathString = (path == null) ? \"\" : path.toString(); \n log.warning(\"Neither a file or directory found in input: \" + pathString);\n continue;\n }\n\n try\n {\n try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path))\n {\n for (Path subpath : directoryStream)\n {\n\n if (isJavaArchive(subpath))\n {\n expanded.add(subpath);\n }\n }\n }\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to read directory contents of: \" + path);\n }\n }\n return expanded;\n }", "public Map<DeckReference, AlbumArt> getLoadedArt() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, AlbumArt>(hotCache));\n }", "@Override public void setUniqueID(Integer uniqueID)\n {\n ProjectFile parent = getParentFile();\n\n if (m_uniqueID != null)\n {\n parent.getCalendars().unmapUniqueID(m_uniqueID);\n }\n\n parent.getCalendars().mapUniqueID(uniqueID, this);\n\n m_uniqueID = uniqueID;\n }", "public static String encodeAuthority(String authority, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(authority, encoding, HierarchicalUriComponents.Type.AUTHORITY);\n\t}", "public long removeRangeByScore(final ScoreRange scoreRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zremrangeByScore(getKey(), scoreRange.from(), scoreRange.to());\n }\n });\n }", "public int getPathId(String pathName, int profileId) {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n // first get the pathId for the pathName/profileId\n int pathId = -1;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_PATH\n + \" WHERE \" + Constants.PATH_PROFILE_PATHNAME + \"= ? \"\n + \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n queryStatement.setString(1, pathName);\n queryStatement.setInt(2, profileId);\n results = queryStatement.executeQuery();\n if (results.next()) {\n pathId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return pathId;\n }", "private void initFieldFactories() {\n\n if (m_model.hasMasterMode()) {\n TranslateTableFieldFactory masterFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER));\n masterFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.MASTER, masterFieldFactory);\n }\n TranslateTableFieldFactory defaultFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT));\n defaultFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, defaultFieldFactory);\n\n }", "public static boolean isConstructorCall(Expression expression, List<String> classNames) {\r\n return expression instanceof ConstructorCallExpression && classNames.contains(expression.getType().getName());\r\n }", "public void recordCheckoutQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutQueueLength(null, queueLength);\n recordCheckoutQueueLength(null, queueLength);\n } else {\n this.checkoutQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }" ]
Non-blocking call that will throw any Exceptions in the traditional manner on access @param key @param value @return
[ "public Eval<UploadResult> putAsync(String key, Object value) {\n return Eval.later(() -> put(key, value))\n .map(t -> t.orElse(null))\n .map(FluentFunctions.ofChecked(up -> up.waitForUploadResult()));\n\n }" ]
[ "public V internalNonBlockingGet(K key) throws Exception {\n Pool<V> resourcePool = getResourcePoolForKey(key);\n return attemptNonBlockingCheckout(key, resourcePool);\n }", "public static tunneltrafficpolicy get(nitro_service service, String name) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\tobj.set_name(name);\n\t\ttunneltrafficpolicy response = (tunneltrafficpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "private String parseRssFeed(String feed) {\n String[] result = feed.split(\"<br />\");\n String[] result2 = result[2].split(\"<BR />\");\n\n return result2[0];\n }", "public static final Duration parseDuration(String value)\n {\n Duration result = null;\n if (value != null)\n {\n int split = value.indexOf(' ');\n if (split != -1)\n {\n double durationValue = Double.parseDouble(value.substring(0, split));\n TimeUnit durationUnits = parseTimeUnits(value.substring(split + 1));\n\n result = Duration.getInstance(durationValue, durationUnits);\n\n }\n }\n return result;\n }", "public void setWeekDay(String dayString) {\n\n final WeekDay day = WeekDay.valueOf(dayString);\n if (m_model.getWeekDay() != day) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(day);\n onValueChange();\n }\n });\n }\n\n }", "void start(String monitoredDirectory, Long pollingTime) {\n this.monitoredDirectory = monitoredDirectory;\n String deployerKlassName;\n if (klass.equals(ImportDeclaration.class)) {\n deployerKlassName = ImporterDeployer.class.getName();\n } else if (klass.equals(ExportDeclaration.class)) {\n deployerKlassName = ExporterDeployer.class.getName();\n } else {\n throw new IllegalStateException(\"\");\n }\n\n this.dm = new DirectoryMonitor(monitoredDirectory, pollingTime, deployerKlassName);\n try {\n dm.start(getBundleContext());\n } catch (DirectoryMonitoringException e) {\n LOG.error(\"Failed to start \" + DirectoryMonitor.class.getName() + \" for the directory \" + monitoredDirectory + \" and polling time \" + pollingTime.toString(), e);\n }\n }", "public void setPrefix(String prefix) {\n if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_PREFIX()))) {\n log(\"Ignoring prefix attribute because it is overridden by user properties.\", Project.MSG_WARN);\n } else {\n SysGlobals.initializeWith(prefix);\n }\n }", "private static String getBindingId(Server server) {\n Endpoint ep = server.getEndpoint();\n BindingInfo bi = ep.getBinding().getBindingInfo();\n return bi.getBindingId();\n }", "public final PJsonArray toJSON() {\n JSONArray jsonArray = new JSONArray();\n final int size = this.array.size();\n for (int i = 0; i < size; i++) {\n final Object o = get(i);\n if (o instanceof PYamlObject) {\n PYamlObject pYamlObject = (PYamlObject) o;\n jsonArray.put(pYamlObject.toJSON().getInternalObj());\n } else if (o instanceof PYamlArray) {\n PYamlArray pYamlArray = (PYamlArray) o;\n jsonArray.put(pYamlArray.toJSON().getInternalArray());\n } else {\n jsonArray.put(o);\n }\n\n }\n return new PJsonArray(null, jsonArray, getContextName());\n }" ]
This method extracts project properties from a Phoenix file. @param phoenixSettings Phoenix settings @param storepoint Current storepoint
[ "private void readProjectProperties(Settings phoenixSettings, Storepoint storepoint)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(phoenixSettings.getTitle());\n mpxjProperties.setDefaultDurationUnits(phoenixSettings.getBaseunit());\n mpxjProperties.setStatusDate(storepoint.getDataDate());\n }" ]
[ "public static ipset_nsip_binding[] get(nitro_service service, String name) throws Exception{\n\t\tipset_nsip_binding obj = new ipset_nsip_binding();\n\t\tobj.set_name(name);\n\t\tipset_nsip_binding response[] = (ipset_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void diffUpdate(List<T> newList) {\n if (getCollection().size() == 0) {\n addAll(newList);\n notifyDataSetChanged();\n } else {\n DiffCallback diffCallback = new DiffCallback(collection, newList);\n DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);\n clear();\n addAll(newList);\n diffResult.dispatchUpdatesTo(this);\n }\n }", "@Override\n public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public void convertToDense() {\n switch ( mat.getType() ) {\n case DSCC: {\n DMatrix m = new DMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrix) mat, m);\n setMatrix(m);\n } break;\n case FSCC: {\n FMatrix m = new FMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrix) mat, m);\n setMatrix(m);\n } break;\n case DDRM:\n case FDRM:\n case ZDRM:\n case CDRM:\n break;\n default:\n throw new RuntimeException(\"Not a sparse matrix!\");\n }\n }", "public void addOrderedChildResourceTypes(PathAddress resourceAddress, Resource resource) {\n Set<String> orderedChildTypes = resource.getOrderedChildTypes();\n if (orderedChildTypes.size() > 0) {\n orderedChildren.put(resourceAddress, resource.getOrderedChildTypes());\n }\n }", "public static base_response update(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup updateresource = new cachecontentgroup();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\tupdateresource.heurexpiryparam = resource.heurexpiryparam;\n\t\tupdateresource.relexpiry = resource.relexpiry;\n\t\tupdateresource.relexpirymillisec = resource.relexpirymillisec;\n\t\tupdateresource.absexpiry = resource.absexpiry;\n\t\tupdateresource.absexpirygmt = resource.absexpirygmt;\n\t\tupdateresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\tupdateresource.hitparams = resource.hitparams;\n\t\tupdateresource.invalparams = resource.invalparams;\n\t\tupdateresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\tupdateresource.matchcookies = resource.matchcookies;\n\t\tupdateresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\tupdateresource.polleverytime = resource.polleverytime;\n\t\tupdateresource.ignorereloadreq = resource.ignorereloadreq;\n\t\tupdateresource.removecookies = resource.removecookies;\n\t\tupdateresource.prefetch = resource.prefetch;\n\t\tupdateresource.prefetchperiod = resource.prefetchperiod;\n\t\tupdateresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\tupdateresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\tupdateresource.flashcache = resource.flashcache;\n\t\tupdateresource.expireatlastbyte = resource.expireatlastbyte;\n\t\tupdateresource.insertvia = resource.insertvia;\n\t\tupdateresource.insertage = resource.insertage;\n\t\tupdateresource.insertetag = resource.insertetag;\n\t\tupdateresource.cachecontrol = resource.cachecontrol;\n\t\tupdateresource.quickabortsize = resource.quickabortsize;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.maxressize = resource.maxressize;\n\t\tupdateresource.memlimit = resource.memlimit;\n\t\tupdateresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\tupdateresource.minhits = resource.minhits;\n\t\tupdateresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\tupdateresource.persist = resource.persist;\n\t\tupdateresource.pinned = resource.pinned;\n\t\tupdateresource.lazydnsresolve = resource.lazydnsresolve;\n\t\tupdateresource.hitselector = resource.hitselector;\n\t\tupdateresource.invalselector = resource.invalselector;\n\t\treturn updateresource.update_resource(client);\n\t}", "public Number getMinutesPerYear()\n {\n return Integer.valueOf(NumberHelper.getInt(getMinutesPerDay()) * NumberHelper.getInt(getDaysPerMonth()) * 12);\n }", "private Resource readResource(net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource phoenixResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n TimeUnit rateUnits = phoenixResource.getMonetarybase();\n if (rateUnits == null)\n {\n rateUnits = TimeUnit.HOURS;\n }\n\n // phoenixResource.getMaximum()\n mpxjResource.setCostPerUse(phoenixResource.getMonetarycostperuse());\n mpxjResource.setStandardRate(new Rate(phoenixResource.getMonetaryrate(), rateUnits));\n mpxjResource.setStandardRateUnits(rateUnits);\n mpxjResource.setName(phoenixResource.getName());\n mpxjResource.setType(phoenixResource.getType());\n mpxjResource.setMaterialLabel(phoenixResource.getUnitslabel());\n //phoenixResource.getUnitsperbase()\n mpxjResource.setGUID(phoenixResource.getUuid());\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n\n return mpxjResource;\n }", "private Client getClientFromResultSet(ResultSet result) throws Exception {\n Client client = new Client();\n client.setId(result.getInt(Constants.GENERIC_ID));\n client.setUUID(result.getString(Constants.CLIENT_CLIENT_UUID));\n client.setFriendlyName(result.getString(Constants.CLIENT_FRIENDLY_NAME));\n client.setProfile(ProfileService.getInstance().findProfile(result.getInt(Constants.GENERIC_PROFILE_ID)));\n client.setIsActive(result.getBoolean(Constants.CLIENT_IS_ACTIVE));\n client.setActiveServerGroup(result.getInt(Constants.CLIENT_ACTIVESERVERGROUP));\n return client;\n }" ]
used for encoding queries or form data
[ "public static String encode(String value) throws UnsupportedEncodingException {\n if (isNullOrEmpty(value)) return value;\n return URLEncoder.encode(value, URL_ENCODING);\n }" ]
[ "protected void propagateOnTouch(GVRPickedObject hit)\n {\n if (mEventOptions.contains(EventOptions.SEND_TOUCH_EVENTS))\n {\n GVREventManager eventManager = getGVRContext().getEventManager();\n GVRSceneObject hitObject = hit.getHitObject();\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n eventManager.sendEvent(this, ITouchEvents.class, \"onTouchStart\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_HIT_OBJECT))\n {\n eventManager.sendEvent(hitObject, ITouchEvents.class, \"onTouchStart\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n eventManager.sendEvent(mScene, ITouchEvents.class, \"onTouchStart\", hitObject, hit);\n }\n }\n }", "public void setCurrencyDigits(Integer currDigs)\n {\n if (currDigs == null)\n {\n currDigs = DEFAULT_CURRENCY_DIGITS;\n }\n set(ProjectField.CURRENCY_DIGITS, currDigs);\n }", "public Enumeration getPKEnumerationByQuery(Class primaryKeyClass, Query query) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled()) logger.debug(\"getPKEnumerationByQuery \" + query);\n\n query.setFetchSize(1);\n ClassDescriptor cld = getClassDescriptor(query.getSearchClass());\n return new PkEnumeration(query, cld, primaryKeyClass, this);\n }", "public static base_responses Import(nitro_service client, sslfipskey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslfipskey Importresources[] = new sslfipskey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tImportresources[i] = new sslfipskey();\n\t\t\t\tImportresources[i].fipskeyname = resources[i].fipskeyname;\n\t\t\t\tImportresources[i].key = resources[i].key;\n\t\t\t\tImportresources[i].inform = resources[i].inform;\n\t\t\t\tImportresources[i].wrapkeyname = resources[i].wrapkeyname;\n\t\t\t\tImportresources[i].iv = resources[i].iv;\n\t\t\t\tImportresources[i].exponent = resources[i].exponent;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, Importresources,\"Import\");\n\t\t}\n\t\treturn result;\n\t}", "public static boolean applyTo(ImageHolder imageHolder, ImageView imageView, String tag) {\n if (imageHolder != null && imageView != null) {\n return imageHolder.applyTo(imageView, tag);\n }\n return false;\n }", "public static base_response clear(nitro_service client, bridgetable resource) throws Exception {\n\t\tbridgetable clearresource = new bridgetable();\n\t\tclearresource.vlan = resource.vlan;\n\t\tclearresource.ifnum = resource.ifnum;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public float getTangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_tangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }", "private static double threePointsAngle(Point vertex, Point A, Point B) {\n double b = pointsDistance(vertex, A);\n double c = pointsDistance(A, B);\n double a = pointsDistance(B, vertex);\n\n return Math.toDegrees(Math.acos((a * a + b * b - c * c) / (2 * a * b)));\n\n }", "public static int Minimum(ImageSource fastBitmap, int startX, int startY, int width, int height) {\r\n int min = 255;\r\n if (fastBitmap.isGrayscale()) {\r\n for (int i = startX; i < height; i++) {\r\n for (int j = startY; j < width; j++) {\r\n int gray = fastBitmap.getRGB(j, i);\r\n if (gray < min) {\r\n min = gray;\r\n }\r\n }\r\n }\r\n } else {\r\n for (int i = startX; i < height; i++) {\r\n for (int j = startY; j < width; j++) {\r\n int gray = fastBitmap.getG(j, i);\r\n if (gray < min) {\r\n min = gray;\r\n }\r\n }\r\n }\r\n }\r\n return min;\r\n }" ]
Combines weighted crf with this crf @param crf @param weight
[ "public void combine(CRFClassifier<IN> crf, double weight) {\r\n Timing timer = new Timing();\r\n\r\n // Check the CRFClassifiers are compatible\r\n if (!this.pad.equals(crf.pad)) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: pad does not match\");\r\n }\r\n if (this.windowSize != crf.windowSize) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: windowSize does not match\");\r\n }\r\n if (this.labelIndices.length != crf.labelIndices.length) {\r\n // Should match since this should be same as the windowSize\r\n throw new RuntimeException(\"Incompatible CRFClassifier: labelIndices length does not match\");\r\n }\r\n this.classIndex.addAll(crf.classIndex.objectsList());\r\n\r\n // Combine weights of the other classifier with this classifier,\r\n // weighing the other classifier's weights by weight\r\n // First merge the feature indicies\r\n int oldNumFeatures1 = this.featureIndex.size();\r\n int oldNumFeatures2 = crf.featureIndex.size();\r\n int oldNumWeights1 = this.getNumWeights();\r\n int oldNumWeights2 = crf.getNumWeights();\r\n this.featureIndex.addAll(crf.featureIndex.objectsList());\r\n this.knownLCWords.addAll(crf.knownLCWords);\r\n assert (weights.length == oldNumFeatures1);\r\n\r\n // Combine weights of this classifier with other classifier\r\n for (int i = 0; i < labelIndices.length; i++) {\r\n this.labelIndices[i].addAll(crf.labelIndices[i].objectsList());\r\n }\r\n System.err.println(\"Combining weights: will automatically match labelIndices\");\r\n combineWeights(crf, weight);\r\n\r\n int numFeatures = featureIndex.size();\r\n int numWeights = getNumWeights();\r\n long elapsedMs = timer.stop();\r\n System.err.println(\"numFeatures: orig1=\" + oldNumFeatures1 + \", orig2=\" + oldNumFeatures2 + \", combined=\"\r\n + numFeatures);\r\n System.err\r\n .println(\"numWeights: orig1=\" + oldNumWeights1 + \", orig2=\" + oldNumWeights2 + \", combined=\" + numWeights);\r\n System.err.println(\"Time to combine CRFClassifier: \" + Timing.toSecondsString(elapsedMs) + \" seconds\");\r\n }" ]
[ "public SyntaxException getSyntaxError(int index) {\n SyntaxException exception = null;\n\n Message message = getError(index);\n if (message != null && message instanceof SyntaxErrorMessage) {\n exception = ((SyntaxErrorMessage) message).getCause();\n }\n return exception;\n }", "public static Enum<?> findMatchingEnumVal(Field field, String unknownEnumName) {\n\t\tif (unknownEnumName == null || unknownEnumName.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tfor (Enum<?> enumVal : (Enum<?>[]) field.getType().getEnumConstants()) {\n\t\t\tif (enumVal.name().equals(unknownEnumName)) {\n\t\t\t\treturn enumVal;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unknwown enum unknown name \" + unknownEnumName + \" for field \" + field);\n\t}", "public static base_response delete(nitro_service client, appfwlearningdata resource) throws Exception {\n\t\tappfwlearningdata deleteresource = new appfwlearningdata();\n\t\tdeleteresource.profilename = resource.profilename;\n\t\tdeleteresource.starturl = resource.starturl;\n\t\tdeleteresource.cookieconsistency = resource.cookieconsistency;\n\t\tdeleteresource.fieldconsistency = resource.fieldconsistency;\n\t\tdeleteresource.formactionurl_ffc = resource.formactionurl_ffc;\n\t\tdeleteresource.crosssitescripting = resource.crosssitescripting;\n\t\tdeleteresource.formactionurl_xss = resource.formactionurl_xss;\n\t\tdeleteresource.sqlinjection = resource.sqlinjection;\n\t\tdeleteresource.formactionurl_sql = resource.formactionurl_sql;\n\t\tdeleteresource.fieldformat = resource.fieldformat;\n\t\tdeleteresource.formactionurl_ff = resource.formactionurl_ff;\n\t\tdeleteresource.csrftag = resource.csrftag;\n\t\tdeleteresource.csrfformoriginurl = resource.csrfformoriginurl;\n\t\tdeleteresource.xmldoscheck = resource.xmldoscheck;\n\t\tdeleteresource.xmlwsicheck = resource.xmlwsicheck;\n\t\tdeleteresource.xmlattachmentcheck = resource.xmlattachmentcheck;\n\t\tdeleteresource.totalxmlrequests = resource.totalxmlrequests;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static boolean isTypesProxyable(Iterable<? extends Type> types, ServiceRegistry services) {\n return getUnproxyableTypesException(types, services) == null;\n }", "private void processActivityCodes(Storepoint storepoint)\n {\n for (Code code : storepoint.getActivityCodes().getCode())\n {\n int sequence = 0;\n for (Value value : code.getValue())\n {\n UUID uuid = getUUID(value.getUuid(), value.getName());\n m_activityCodeValues.put(uuid, value.getName());\n m_activityCodeSequence.put(uuid, Integer.valueOf(++sequence));\n }\n }\n }", "protected static Map<String, List<Statement>> removeStatements(Set<String> statementIds, Map<String, List<Statement>> claims) {\n\t\tMap<String, List<Statement>> newClaims = new HashMap<>(claims.size());\n\t\tfor(Entry<String, List<Statement>> entry : claims.entrySet()) {\n\t\t\tList<Statement> filteredStatements = new ArrayList<>();\n\t\t\tfor(Statement s : entry.getValue()) {\n\t\t\t\tif(!statementIds.contains(s.getStatementId())) {\n\t\t\t\t\tfilteredStatements.add(s);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!filteredStatements.isEmpty()) {\n\t\t\t\tnewClaims.put(entry.getKey(),\n\t\t\t\t\tfilteredStatements);\n\t\t\t}\n\t\t}\n\t\treturn newClaims;\n\t}", "public ParallelTask execute(ParallecResponseHandler handler) {\n\n ParallelTask task = new ParallelTask();\n\n try {\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n final ParallelTask taskReal = new ParallelTask(requestProtocol,\n concurrency, httpMeta, targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta,\n handler, responseContext, \n replacementVarMapNodeSpecific, replacementVarMap,\n requestReplacementType, \n config);\n\n task = taskReal;\n\n logger.info(\"***********START_PARALLEL_HTTP_TASK_\"\n + task.getTaskId() + \"***********\");\n\n // throws ParallelTaskInvalidException\n task.validateWithFillDefault();\n\n task.setSubmitTime(System.currentTimeMillis());\n\n if (task.getConfig().isEnableCapacityAwareTaskScheduler()) {\n\n //late initialize the task scheduler\n ParallelTaskManager.getInstance().initTaskSchedulerIfNot();\n // add task to the wait queue\n ParallelTaskManager.getInstance().getWaitQ().add(task);\n\n logger.info(\"Enabled CapacityAwareTaskScheduler. Submitted task to waitQ in builder.. \"\n + task.getTaskId());\n\n } else {\n\n logger.info(\n \"Disabled CapacityAwareTaskScheduler. Immediately execute task {} \",\n task.getTaskId());\n\n Runnable director = new Runnable() {\n\n public void run() {\n ParallelTaskManager.getInstance()\n .generateUpdateExecuteTask(taskReal);\n }\n };\n new Thread(director).start();\n }\n\n if (this.getMode() == TaskRunMode.SYNC) {\n logger.info(\"Executing task {} in SYNC mode... \",\n task.getTaskId());\n\n while (task != null && !task.isCompleted()) {\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n logger.error(\"InterruptedException \" + e);\n }\n }\n }\n } catch (ParallelTaskInvalidException ex) {\n\n logger.info(\"Request is invalid with missing parts. Details: \"\n + ex.getMessage() + \" Cannot execute at this time. \"\n + \" Please review your request and try again.\\nCommand:\"\n + httpMeta.toString());\n\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.VALIDATION_ERROR,\n \"validation eror\"));\n\n } catch (Exception t) {\n logger.error(\"fail task builder. Unknown error: \" + t, t);\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.UNKNOWN, \"unknown eror\",\n t));\n }\n\n logger.info(\"***********FINISH_PARALLEL_HTTP_TASK_\" + task.getTaskId()\n + \"***********\");\n return task;\n\n }", "@Override\r\n public void close() {\r\n // Use monitor to avoid race between external close and handler thread run()\r\n synchronized (closeMonitor) {\r\n // Close and clear streams, sockets etc.\r\n if (socket != null) {\r\n try {\r\n // Terminates thread blocking on socket read\r\n // and automatically closed depending streams\r\n socket.close();\r\n } catch (IOException e) {\r\n log.warn(\"Can not close socket\", e);\r\n } finally {\r\n socket = null;\r\n }\r\n }\r\n\r\n // Clear user data\r\n session = null;\r\n response = null;\r\n }\r\n }", "private void processPredecessors()\n {\n for (Map.Entry<Task, List<MapRow>> entry : m_predecessorMap.entrySet())\n {\n Task task = entry.getKey();\n List<MapRow> predecessors = entry.getValue();\n for (MapRow predecessor : predecessors)\n {\n processPredecessor(task, predecessor);\n }\n }\n }" ]
Generates a full list of all parents and their children, in order. @param parentList A list of the parents from the {@link ExpandableRecyclerAdapter} @return A list of all parents and their children, expanded
[ "private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded());\n }\n\n return flatItemList;\n }" ]
[ "private long recover() throws IOException {\n checkMutable();\n long len = channel.size();\n ByteBuffer buffer = ByteBuffer.allocate(4);\n long validUpTo = 0;\n long next = 0L;\n do {\n next = validateMessage(channel, validUpTo, len, buffer);\n if (next >= 0) validUpTo = next;\n } while (next >= 0);\n channel.truncate(validUpTo);\n setSize.set(validUpTo);\n setHighWaterMark.set(validUpTo);\n logger.info(\"recover high water mark:\" + highWaterMark());\n /* This should not be necessary, but fixes bug 6191269 on some OSs. */\n channel.position(validUpTo);\n needRecover.set(false);\n return len - validUpTo;\n }", "public void setConnectTimeout(int connectTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}", "public static void count() {\n long duration = SystemClock.uptimeMillis() - startTime;\n float avgFPS = sumFrames / (duration / 1000f);\n\n Log.v(\"FPSCounter\",\n \"total frames = %d, total elapsed time = %d ms, average fps = %f\",\n sumFrames, duration, avgFPS);\n }", "public synchronized Response doCommandFullResponse(String command) throws CommandFormatException, IOException {\n ModelNode request = cmdCtx.buildRequest(command);\n boolean replacedBytes = replaceFilePathsWithBytes(request);\n OperationResponse response = execute(request, isSlowCommand(command) || replacedBytes);\n return new Response(command, request, response);\n }", "public static Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2) {\n\t\tif (clazz1 == null) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tif (clazz2 == null) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz1.isAssignableFrom(clazz2)) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz2.isAssignableFrom(clazz1)) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tClass<?> ancestor = clazz1;\n\t\tdo {\n\t\t\tancestor = ancestor.getSuperclass();\n\t\t\tif (ancestor == null || Object.class.equals(ancestor)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\twhile (!ancestor.isAssignableFrom(clazz2));\n\t\treturn ancestor;\n\t}", "public CollectionValuedMap<K, V> deltaClone() {\r\n CollectionValuedMap<K, V> result = new CollectionValuedMap<K, V>(null, cf, true);\r\n result.map = new DeltaMap<K, Collection<V>>(this.map);\r\n return result;\r\n }", "String decodeCString(ByteBuf buffer) throws IOException {\n int length = buffer.bytesBefore(BsonConstants.STRING_TERMINATION);\n if (length < 0)\n throw new IOException(\"string termination not found\");\n\n String result = buffer.toString(buffer.readerIndex(), length, StandardCharsets.UTF_8);\n buffer.skipBytes(length + 1);\n return result;\n }", "private HiveShellContainer createHiveServerContainer(final List<? extends Script> scripts, final Object testCase, TemporaryFolder baseDir) \n throws IOException {\n\n HiveServerContext context = new StandaloneHiveServerContext(baseDir, config);\n\n final HiveServerContainer hiveTestHarness = new HiveServerContainer(context);\n\n HiveShellBuilder hiveShellBuilder = new HiveShellBuilder();\n hiveShellBuilder.setCommandShellEmulation(config.getCommandShellEmulator());\n\n HiveShellField shellSetter = loadScriptUnderTest(testCase, hiveShellBuilder);\n if (scripts != null) {\n hiveShellBuilder.overrideScriptsUnderTest(scripts);\n }\n\n hiveShellBuilder.setHiveServerContainer(hiveTestHarness);\n\n loadAnnotatedResources(testCase, hiveShellBuilder);\n\n loadAnnotatedProperties(testCase, hiveShellBuilder);\n\n loadAnnotatedSetupScripts(testCase, hiveShellBuilder);\n\n // Build shell\n final HiveShellContainer shell = hiveShellBuilder.buildShell();\n\n // Set shell\n shellSetter.setShell(shell);\n\n if (shellSetter.isAutoStart()) {\n shell.start();\n }\n\n return shell;\n }", "public void close() throws IOException {\n for (CloseableHttpClient c : cachedClients.values()) {\n c.close();\n }\n cachedClients.clear();\n }" ]
Main method to run the bot. @param args @throws LoginFailedException @throws IOException @throws MediaWikiApiErrorException
[ "public static void main(String[] args) throws LoginFailedException,\n\t\t\tIOException, MediaWikiApiErrorException {\n\t\tExampleHelpers.configureLogging();\n\t\tprintDocumentation();\n\n\t\tSetLabelsForNumbersBot bot = new SetLabelsForNumbersBot();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(bot);\n\t\tbot.finish();\n\n\t\tSystem.out.println(\"*** Done.\");\n\t}" ]
[ "private static String stripExtraLineEnd(String text, boolean formalRTF)\n {\n if (formalRTF && text.endsWith(\"\\n\"))\n {\n text = text.substring(0, text.length() - 1);\n }\n return text;\n }", "public static base_responses export(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata exportresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texportresources[i] = new appfwlearningdata();\n\t\t\t\texportresources[i].profilename = resources[i].profilename;\n\t\t\t\texportresources[i].securitycheck = resources[i].securitycheck;\n\t\t\t\texportresources[i].target = resources[i].target;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, exportresources,\"export\");\n\t\t}\n\t\treturn result;\n\t}", "private String getSite(CmsObject cms, CmsFavoriteEntry entry) {\n\n CmsSite site = OpenCms.getSiteManager().getSiteForRootPath(entry.getSiteRoot());\n Item item = m_sitesContainer.getItem(entry.getSiteRoot());\n if (item != null) {\n return (String)(item.getItemProperty(\"caption\").getValue());\n }\n String result = entry.getSiteRoot();\n if (site != null) {\n if (!CmsStringUtil.isEmpty(site.getTitle())) {\n result = site.getTitle();\n }\n }\n return result;\n }", "public HttpConnection execute(HttpConnection connection) {\n\n //set our HttpUrlFactory on the connection\n connection.connectionFactory = factory;\n\n // all CouchClient requests want to receive application/json responses\n connection.requestProperties.put(\"Accept\", \"application/json\");\n connection.responseInterceptors.addAll(this.responseInterceptors);\n connection.requestInterceptors.addAll(this.requestInterceptors);\n InputStream es = null; // error stream - response from server for a 500 etc\n\n // first try to execute our request and get the input stream with the server's response\n // we want to catch IOException because HttpUrlConnection throws these for non-success\n // responses (eg 404 throws a FileNotFoundException) but we need to map to our own\n // specific exceptions\n try {\n try {\n connection = connection.execute();\n } catch (HttpConnectionInterceptorException e) {\n CouchDbException exception = new CouchDbException(connection.getConnection()\n .getResponseMessage(), connection.getConnection().getResponseCode());\n if (e.deserialize) {\n try {\n JsonObject errorResponse = new Gson().fromJson(e.error, JsonObject\n .class);\n exception.error = getAsString(errorResponse, \"error\");\n exception.reason = getAsString(errorResponse, \"reason\");\n } catch (JsonParseException jpe) {\n exception.error = e.error;\n }\n } else {\n exception.error = e.error;\n exception.reason = e.reason;\n }\n throw exception;\n }\n int code = connection.getConnection().getResponseCode();\n String response = connection.getConnection().getResponseMessage();\n // everything ok? return the stream\n if (code / 100 == 2) { // success [200,299]\n return connection;\n } else {\n final CouchDbException ex;\n switch (code) {\n case HttpURLConnection.HTTP_NOT_FOUND: //404\n ex = new NoDocumentException(response);\n break;\n case HttpURLConnection.HTTP_CONFLICT: //409\n ex = new DocumentConflictException(response);\n break;\n case HttpURLConnection.HTTP_PRECON_FAILED: //412\n ex = new PreconditionFailedException(response);\n break;\n case 429:\n // If a Replay429Interceptor is present it will check for 429 and retry at\n // intervals. If the retries do not succeed or no 429 replay was configured\n // we end up here and throw a TooManyRequestsException.\n ex = new TooManyRequestsException(response);\n break;\n default:\n ex = new CouchDbException(response, code);\n break;\n }\n es = connection.getConnection().getErrorStream();\n //if there is an error stream try to deserialize into the typed exception\n if (es != null) {\n try {\n //read the error stream into memory\n byte[] errorResponse = IOUtils.toByteArray(es);\n\n Class<? extends CouchDbException> exceptionClass = ex.getClass();\n //treat the error as JSON and try to deserialize\n try {\n // Register an InstanceCreator that returns the existing exception so\n // we can just populate the fields, but not ignore the constructor.\n // Uses a new Gson so we don't accidentally recycle an exception.\n Gson g = new GsonBuilder().registerTypeAdapter(exceptionClass, new\n CouchDbExceptionInstanceCreator(ex)).create();\n // Now populate the exception with the error/reason other info from JSON\n g.fromJson(new InputStreamReader(new ByteArrayInputStream\n (errorResponse),\n \"UTF-8\"), exceptionClass);\n } catch (JsonParseException e) {\n // The error stream was not JSON so just set the string content as the\n // error field on ex before we throw it\n ex.error = new String(errorResponse, \"UTF-8\");\n }\n } finally {\n close(es);\n }\n }\n ex.setUrl(connection.url.toString());\n throw ex;\n }\n } catch (IOException ioe) {\n CouchDbException ex = new CouchDbException(\"Error retrieving server response\", ioe);\n ex.setUrl(connection.url.toString());\n throw ex;\n }\n }", "public static Type[] getActualTypeArguments(Type type) {\n Type resolvedType = Types.getCanonicalType(type);\n if (resolvedType instanceof ParameterizedType) {\n return ((ParameterizedType) resolvedType).getActualTypeArguments();\n } else {\n return EMPTY_TYPES;\n }\n }", "private Project.Calendars.Calendar writeCalendar(ProjectCalendar bc)\n {\n //\n // Create a calendar\n //\n Project.Calendars.Calendar calendar = m_factory.createProjectCalendarsCalendar();\n calendar.setUID(NumberHelper.getBigInteger(bc.getUniqueID()));\n calendar.setIsBaseCalendar(Boolean.valueOf(!bc.isDerived()));\n\n ProjectCalendar base = bc.getParent();\n // SF-329: null default required to keep Powerproject happy when importing MSPDI files\n calendar.setBaseCalendarUID(base == null ? NULL_CALENDAR_ID : NumberHelper.getBigInteger(base.getUniqueID()));\n calendar.setName(bc.getName());\n\n //\n // Create a list of normal days\n //\n Project.Calendars.Calendar.WeekDays days = m_factory.createProjectCalendarsCalendarWeekDays();\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time;\n ProjectCalendarHours bch;\n\n List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList = days.getWeekDay();\n\n for (int loop = 1; loop < 8; loop++)\n {\n DayType workingFlag = bc.getWorkingDay(Day.getInstance(loop));\n\n if (workingFlag != DayType.DEFAULT)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay();\n dayList.add(day);\n day.setDayType(BigInteger.valueOf(loop));\n day.setDayWorking(Boolean.valueOf(workingFlag == DayType.WORKING));\n\n if (workingFlag == DayType.WORKING)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes();\n day.setWorkingTimes(times);\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n bch = bc.getCalendarHours(Day.getInstance(loop));\n if (bch != null)\n {\n for (DateRange range : bch)\n {\n if (range != null)\n {\n time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }\n }\n }\n\n //\n // Create a list of exceptions\n //\n // A quirk of MS Project is that these exceptions must be\n // in date order in the file, otherwise they are ignored\n //\n List<ProjectCalendarException> exceptions = new ArrayList<ProjectCalendarException>(bc.getCalendarExceptions());\n if (!exceptions.isEmpty())\n {\n Collections.sort(exceptions);\n writeExceptions(calendar, dayList, exceptions);\n }\n\n //\n // Do not add a weekdays tag to the calendar unless it\n // has valid entries.\n // Fixes SourceForge bug 1854747: MPXJ and MSP 2007 XML formats\n //\n if (!dayList.isEmpty())\n {\n calendar.setWeekDays(days);\n }\n\n writeWorkWeeks(calendar, bc);\n\n m_eventManager.fireCalendarWrittenEvent(bc);\n\n return (calendar);\n }", "public void addAll(@NonNull final Collection<T> collection) {\n final int length = collection.size();\n if (length == 0) {\n return;\n }\n synchronized (mLock) {\n final int position = getItemCount();\n mObjects.addAll(collection);\n notifyItemRangeInserted(position, length);\n }\n }", "public double getAccruedInterest(double time, AnalyticModel model) {\n\t\tLocalDate date= FloatingpointDate.getDateFromFloatingPointDate(schedule.getReferenceDate(), time);\n\t\treturn getAccruedInterest(date, model);\n\t}", "public Response remove(DesignDocument designDocument) {\r\n assertNotEmpty(designDocument, \"DesignDocument\");\r\n ensureDesignPrefixObject(designDocument);\r\n return db.remove(designDocument);\r\n }" ]
Load a cube map texture asynchronously. This is the implementation of {@link GVRAssetLoader#loadCubemapTexture(GVRAndroidResource)} - it will usually be more convenient (and more efficient) to call that directly. @param gvrContext The GVRF context @param textureCache Texture cache - may be {@code null} @param resource A steam containing a zip file which contains six bitmaps. The six bitmaps correspond to +x, -x, +y, -y, +z, and -z faces of the cube map texture respectively. The default names of the six images are "posx.png", "negx.png", "posy.png", "negx.png", "posz.png", and "negz.png", which can be changed by calling {@link GVRCubemapImage#setFaceNames(String[])}. @param priority This request's priority. Please see the notes on asynchronous priorities in the <a href="package-summary.html#async">package description</a>. @return A {@link Future} that you can pass to methods like {@link GVRShaderData#setMainTexture(Future)}
[ "public static GVRTexture loadFutureCubemapTexture(\n GVRContext gvrContext, ResourceCache<GVRImage> textureCache,\n GVRAndroidResource resource, int priority,\n Map<String, Integer> faceIndexMap) {\n GVRTexture tex = new GVRTexture(gvrContext);\n GVRImage cached = textureCache.get(resource);\n if (cached != null)\n {\n Log.v(\"ASSET\", \"Future Texture: %s loaded from cache\", cached.getFileName());\n tex.setImage(cached);\n }\n else\n {\n AsyncCubemapTexture.get().loadTexture(gvrContext,\n CancelableCallbackWrapper.wrap(GVRCubemapImage.class, tex),\n resource, priority, faceIndexMap);\n\n }\n return tex;\n }" ]
[ "public static Set<String> getStoreNamesSet(List<StoreDefinition> storeDefList) {\n HashSet<String> storeSet = new HashSet<String>();\n for(StoreDefinition def: storeDefList) {\n storeSet.add(def.getName());\n }\n return storeSet;\n }", "public void delete(boolean notifyUser, boolean force) {\n String queryString = new QueryStringBuilder()\n .appendParam(\"notify\", String.valueOf(notifyUser))\n .appendParam(\"force\", String.valueOf(force))\n .toString();\n\n URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public static Map<String, Object> findFreeMarkerContextVariables(Variables variables, String... varNames)\n {\n Map<String, Object> results = new HashMap<>();\n\n for (String varName : varNames)\n {\n WindupVertexFrame payload = null;\n try\n {\n payload = Iteration.getCurrentPayload(variables, null, varName);\n }\n catch (IllegalStateException | IllegalArgumentException e)\n {\n // oh well\n }\n\n if (payload != null)\n {\n results.put(varName, payload);\n }\n else\n {\n Iterable<? extends WindupVertexFrame> var = variables.findVariable(varName);\n if (var != null)\n {\n results.put(varName, var);\n }\n }\n }\n return results;\n }", "public void setBundleActivator(String bundleActivator) {\n\t\tString old = mainAttributes.get(BUNDLE_ACTIVATOR);\n\t\tif (!bundleActivator.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_ACTIVATOR, bundleActivator);\n\t\t\tthis.modified = true;\n\t\t\tthis.bundleActivator = bundleActivator;\n\t\t}\n\t}", "@Override public RendererViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {\n rendererBuilder.withParent(viewGroup);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(viewGroup.getContext()));\n rendererBuilder.withViewType(viewType);\n RendererViewHolder viewHolder = rendererBuilder.buildRendererViewHolder();\n if (viewHolder == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null viewHolder\");\n }\n return viewHolder;\n }", "public DocumentReaderAndWriter<IN> makePlainTextReaderAndWriter() {\r\n String readerClassName = flags.plainTextDocumentReaderAndWriter;\r\n // We set this default here if needed because there may be models\r\n // which don't have the reader flag set\r\n if (readerClassName == null) {\r\n readerClassName = SeqClassifierFlags.DEFAULT_PLAIN_TEXT_READER;\r\n }\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>) Class.forName(readerClassName).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.plainTextDocumentReaderAndWriter: '%s'\", flags.plainTextDocumentReaderAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }", "public static route6[] get(nitro_service service) throws Exception{\n\t\troute6 obj = new route6();\n\t\troute6[] response = (route6[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void replace( Token original , Token target ) {\n if( first == original )\n first = target;\n if( last == original )\n last = target;\n\n target.next = original.next;\n target.previous = original.previous;\n\n if( original.next != null )\n original.next.previous = target;\n if( original.previous != null )\n original.previous.next = target;\n\n original.next = original.previous = null;\n }", "private boolean isRedeployAfterRemoval(ModelNode operation) {\n return operation.hasDefined(DEPLOYMENT_OVERLAY_LINK_REMOVAL) &&\n operation.get(DEPLOYMENT_OVERLAY_LINK_REMOVAL).asBoolean();\n }" ]
Count the number of queued resource requests for a specific pool. @param key The key @return The count of queued resource requests. Returns 0 if no queue exists for given key.
[ "public int getRegisteredResourceRequestCount(K key) {\n if(requestQueueMap.containsKey(key)) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForExistingKey(key);\n // FYI: .size() is not constant time in the next call. ;)\n if(requestQueue != null) {\n return requestQueue.size();\n }\n }\n return 0;\n }" ]
[ "public static <T> void addAll(Collection<T> collection, Iterable<? extends T> items) {\r\n for (T item : items) {\r\n collection.add(item);\r\n }\r\n }", "private static Constraint loadConstraint(Annotation context) {\n Constraint constraint = null;\n final ServiceLoader<Constraint> constraints = ServiceLoader.load(Constraint.class);\n\n for (Constraint aConstraint : constraints) {\n try {\n aConstraint.getClass().getDeclaredMethod(\"check\", context.annotationType());\n constraint = aConstraint;\n break;\n } catch (NoSuchMethodException e) {\n // Look for next implementation if method not found with required signature.\n }\n }\n\n if (constraint == null) {\n throw new IllegalStateException(\"Couldn't found any implementation of \" + Constraint.class.getName());\n }\n return constraint;\n }", "private long doMemoryManagementAndPerFrameCallbacks() {\n long currentTime = GVRTime.getCurrentTime();\n mFrameTime = (currentTime - mPreviousTimeNanos) / 1e9f;\n mPreviousTimeNanos = currentTime;\n\n /*\n * Without the sensor data, can't draw a scene properly.\n */\n if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) {\n Runnable runnable;\n while ((runnable = mRunnables.poll()) != null) {\n try {\n runnable.run();\n } catch (final Exception exc) {\n Log.e(TAG, \"Runnable-on-GL %s threw %s\", runnable, exc.toString());\n exc.printStackTrace();\n }\n }\n\n final List<GVRDrawFrameListener> frameListeners = mFrameListeners;\n for (GVRDrawFrameListener listener : frameListeners) {\n try {\n listener.onDrawFrame(mFrameTime);\n } catch (final Exception exc) {\n Log.e(TAG, \"DrawFrameListener %s threw %s\", listener, exc.toString());\n exc.printStackTrace();\n }\n }\n }\n\n return currentTime;\n }", "protected boolean isZero( int index ) {\n double bottom = Math.abs(diag[index])+Math.abs(diag[index+1]);\n\n return( Math.abs(off[index]) <= bottom*UtilEjml.EPS);\n }", "public OAuth1RequestToken getRequestToken(String callbackUrl) {\r\n String callback = (callbackUrl != null) ? callbackUrl : OUT_OF_BOUND_AUTH_METHOD;\r\n\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .callback(callback)\r\n .build(FlickrApi.instance());\r\n\r\n try {\r\n return service.getRequestToken();\r\n } catch (IOException | InterruptedException | ExecutionException e) {\r\n throw new FlickrRuntimeException(e);\r\n }\r\n }", "public String getNamefromId(int id) {\n return (String) sqlService.getFromTable(\n Constants.PROFILE_PROFILE_NAME, Constants.GENERIC_ID,\n id, Constants.DB_TABLE_PROFILE);\n }", "@Override\n\tpublic IPAddress toAddress() throws UnknownHostException, HostNameException {\n\t\tIPAddress addr = resolvedAddress;\n\t\tif(addr == null && !resolvedIsNull) {\n\t\t\t//note that validation handles empty address resolution\n\t\t\tvalidate();\n\t\t\tsynchronized(this) {\n\t\t\t\taddr = resolvedAddress;\n\t\t\t\tif(addr == null && !resolvedIsNull) {\n\t\t\t\t\tif(parsedHost.isAddressString()) {\n\t\t\t\t\t\taddr = parsedHost.asAddress();\n\t\t\t\t\t\tresolvedIsNull = (addr == null);\n\t\t\t\t\t\t//note there is no need to apply prefix or mask here, it would have been applied to the address already\n\t\t\t\t\t} else {\n\t\t\t\t\t\tString strHost = parsedHost.getHost();\n\t\t\t\t\t\tif(strHost.length() == 0 && !validationOptions.emptyIsLoopback) {\n\t\t\t\t\t\t\taddr = null;\n\t\t\t\t\t\t\tresolvedIsNull = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//Note we do not set resolvedIsNull, so we will attempt to resolve again if the previous attempt threw an exception\n\t\t\t\t\t\t\tInetAddress inetAddress = InetAddress.getByName(strHost);\n\t\t\t\t\t\t\tbyte bytes[] = inetAddress.getAddress();\n\t\t\t\t\t\t\tInteger networkPrefixLength = parsedHost.getNetworkPrefixLength();\n\t\t\t\t\t\t\tif(networkPrefixLength == null) {\n\t\t\t\t\t\t\t\tIPAddress mask = parsedHost.getMask();\n\t\t\t\t\t\t\t\tif(mask != null) {\n\t\t\t\t\t\t\t\t\tbyte maskBytes[] = mask.getBytes();\n\t\t\t\t\t\t\t\t\tif(maskBytes.length != bytes.length) {\n\t\t\t\t\t\t\t\t\t\tthrow new HostNameException(host, \"ipaddress.error.ipMismatch\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tfor(int i = 0; i < bytes.length; i++) {\n\t\t\t\t\t\t\t\t\t\tbytes[i] &= maskBytes[i];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tnetworkPrefixLength = mask.getBlockMaskPrefixLength(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tIPAddressStringParameters addressParams = validationOptions.addressOptions;\n\t\t\t\t\t\t\tif(bytes.length == IPv6Address.BYTE_COUNT) {\n\t\t\t\t\t\t\t\tIPv6AddressCreator creator = addressParams.getIPv6Parameters().getNetwork().getAddressCreator();\n\t\t\t\t\t\t\t\taddr = creator.createAddressInternal(bytes, networkPrefixLength, null, this); /* address creation */\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tIPv4AddressCreator creator = addressParams.getIPv4Parameters().getNetwork().getAddressCreator();\n\t\t\t\t\t\t\t\taddr = creator.createAddressInternal(bytes, networkPrefixLength, this); /* address creation */\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tresolvedAddress = addr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn addr;\n\t}", "public final void notifyHeaderItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newHeaderItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (newHeaderItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart, itemCount);\n }", "public static DMatrixRMaj stripReal(ZMatrixD1 input , DMatrixRMaj output ) {\n if( output == null ) {\n output = new DMatrixRMaj(input.numRows,input.numCols);\n } else if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n final int length = input.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i/2] = input.data[i];\n }\n return output;\n }" ]
Use this API to fetch all the dnspolicylabel resources that are configured on netscaler.
[ "public static dnspolicylabel[] get(nitro_service service) throws Exception{\n\t\tdnspolicylabel obj = new dnspolicylabel();\n\t\tdnspolicylabel[] response = (dnspolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public BoxFile.Info restoreFile(String fileID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFile restoredFile = new BoxFile(this.api, responseJSON.get(\"id\").asString());\n return restoredFile.new Info(responseJSON);\n }", "public <T> T getNodeMetaData(Object key) {\n if (metaDataMap == null) {\n return (T) null;\n }\n return (T) metaDataMap.get(key);\n }", "private void performDownload(HttpResponse response, File destFile)\n throws IOException {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n return;\n }\n \n //get content length\n long contentLength = entity.getContentLength();\n if (contentLength >= 0) {\n size = toLengthText(contentLength);\n }\n \n processedBytes = 0;\n loggedKb = 0;\n \n //open stream and start downloading\n InputStream is = entity.getContent();\n streamAndMove(is, destFile);\n }", "private void handleUpdate(final CdjStatus update) {\n // First see if any metadata caches need evicting or mount sets need updating.\n if (update.isLocalUsbEmpty()) {\n final SlotReference slot = SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.USB_SLOT);\n detachMetadataCache(slot);\n flushHotCacheSlot(slot);\n removeMount(slot);\n } else if (update.isLocalUsbLoaded()) {\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.USB_SLOT));\n }\n\n if (update.isLocalSdEmpty()) {\n final SlotReference slot = SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.SD_SLOT);\n detachMetadataCache(slot);\n flushHotCacheSlot(slot);\n removeMount(slot);\n } else if (update.isLocalSdLoaded()){\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.SD_SLOT));\n }\n\n if (update.isDiscSlotEmpty()) {\n removeMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.CD_SLOT));\n } else {\n recordMount(SlotReference.getSlotReference(update.getDeviceNumber(), CdjStatus.TrackSourceSlot.CD_SLOT));\n }\n\n // Now see if a track has changed that needs new metadata.\n if (update.getTrackType() == CdjStatus.TrackType.UNKNOWN ||\n update.getTrackType() == CdjStatus.TrackType.NO_TRACK ||\n update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK ||\n update.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.UNKNOWN ||\n update.getRekordboxId() == 0) { // We no longer have metadata for this device.\n clearDeck(update);\n } else { // We can offer metadata for this device; check if we already looked up this track.\n final TrackMetadata lastMetadata = hotCache.get(DeckReference.getDeckReference(update.getDeviceNumber(), 0));\n final DataReference trackReference = new DataReference(update.getTrackSourcePlayer(),\n update.getTrackSourceSlot(), update.getRekordboxId());\n if (lastMetadata == null || !lastMetadata.trackReference.equals(trackReference)) { // We have something new!\n // First see if we can find the new track in the hot cache as a hot cue\n for (TrackMetadata cached : hotCache.values()) {\n if (cached.trackReference.equals(trackReference)) { // Found a hot cue hit, use it.\n updateMetadata(update, cached);\n return;\n }\n }\n\n // Not in the hot cache so try actually retrieving it.\n if (activeRequests.add(update.getTrackSourcePlayer())) {\n // We had to make sure we were not already asking for this track.\n clearDeck(update); // We won't know what it is until our request completes.\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n TrackMetadata data = requestMetadataInternal(trackReference, update.getTrackType(), true);\n if (data != null) {\n updateMetadata(update, data);\n }\n } catch (Exception e) {\n logger.warn(\"Problem requesting track metadata from update\" + update, e);\n } finally {\n activeRequests.remove(update.getTrackSourcePlayer());\n }\n }\n }, \"MetadataFinder metadata request\").start();\n }\n }\n }\n }", "public AddonChange removeAddon(String appName, String addonName) {\n return connection.execute(new AddonRemove(appName, addonName), apiKey);\n }", "public void configure(@Observes(precedence = -10) ArquillianDescriptor arquillianDescriptor) {\n Map<String, String> config = arquillianDescriptor.extension(EXTENSION_NAME).getExtensionProperties();\n CubeConfiguration cubeConfiguration = CubeConfiguration.fromMap(config);\n configurationProducer.set(cubeConfiguration);\n }", "@Override\n protected boolean changeDirection(int currentIndex, int centerIndex, boolean inBounds) {\n boolean changed = false;\n if (getGravityInternal() == Gravity.CENTER &&\n currentIndex <= centerIndex &&\n currentIndex == 0 || !inBounds) {\n\n changed = true;\n }\n return changed;\n }", "private void verityLicenseIsConflictFree(final DbLicense newComer) {\n if(newComer.getRegexp() == null || newComer.getRegexp().isEmpty()) {\n return;\n }\n\n final DbLicense existing = repoHandler.getLicense(newComer.getName());\n final List<DbLicense> licenses = repoHandler.getAllLicenses();\n\n if(null == existing) {\n licenses.add(newComer);\n } else {\n existing.setRegexp(newComer.getRegexp());\n }\n\n\n final Optional<Report> reportOp = ReportsRegistry.findById(MULTIPLE_LICENSE_MATCHING_STRINGS);\n if (reportOp.isPresent()) {\n final Report reportDef = reportOp.get();\n ReportRequest reportRequest = new ReportRequest();\n reportRequest.setReportId(reportDef.getId());\n\n Map<String, String> params = new HashMap<>();\n\n //\n // TODO: Make the organization come as an external parameter from the client side.\n // This may have impact on the UI, as when the user will update a license he will\n // have to specify which organization he's editing the license for (in case there\n // are more organizations defined in the collection).\n //\n params.put(\"organization\", \"Axway\");\n reportRequest.setParamValues(params);\n\n final RepositoryHandler wrapped = wrapperBuilder\n .start(repoHandler)\n .replaceGetMethod(\"getAllLicenses\", licenses)\n .build();\n\n final ReportExecution execution = reportDef.execute(wrapped, reportRequest);\n\n List<String[]> data = execution.getData();\n\n final Optional<String[]> first = data\n .stream()\n .filter(strings -> strings[2].contains(newComer.getName()))\n .findFirst();\n\n if(first.isPresent()) {\n final String[] strings = first.get();\n final String message = String.format(\n \"Pattern conflict for string entry %s matching multiple licenses: %s\",\n strings[1], strings[2]);\n LOG.info(message);\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(message)\n .build());\n } else {\n if(!data.isEmpty() && !data.get(0)[2].isEmpty()) {\n LOG.info(\"There are remote conflicts between existing licenses and artifact strings\");\n }\n }\n } else {\n if(LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"Cannot find report by id %s\", MULTIPLE_LICENSE_MATCHING_STRINGS));\n }\n }\n }", "private static JsonNode findNestedNode(JsonNode jsonNode, String composedKey) {\n String[] jsonNodeKeys = splitKeyByFlatteningDots(composedKey);\n for (String jsonNodeKey : jsonNodeKeys) {\n jsonNode = jsonNode.get(unescapeEscapedDots(jsonNodeKey));\n if (jsonNode == null) {\n return null;\n }\n }\n return jsonNode;\n }" ]
Organises the data from Asta into a hierarchy and converts this into tasks. @param bars bar data @param expandedTasks expanded task data @param tasks task data @param milestones milestone data
[ "public void processTasks(List<Row> bars, List<Row> expandedTasks, List<Row> tasks, List<Row> milestones)\n {\n List<Row> parentBars = buildRowHierarchy(bars, expandedTasks, tasks, milestones);\n createTasks(m_project, \"\", parentBars);\n deriveProjectCalendar();\n updateStructure();\n }" ]
[ "boolean resumeSyncForDocument(\n final MongoNamespace namespace,\n final BsonValue documentId\n ) {\n if (namespace == null || documentId == null) {\n return false;\n }\n\n final NamespaceSynchronizationConfig namespaceSynchronizationConfig;\n final CoreDocumentSynchronizationConfig config;\n\n if ((namespaceSynchronizationConfig = syncConfig.getNamespaceConfig(namespace)) == null\n || (config = namespaceSynchronizationConfig.getSynchronizedDocument(documentId)) == null) {\n return false;\n }\n\n config.setPaused(false);\n return !config.isPaused();\n }", "static void i(String message){\n if (getStaticDebugLevel() >= CleverTapAPI.LogLevel.INFO.intValue()){\n Log.i(Constants.CLEVERTAP_LOG_TAG,message);\n }\n }", "public static void deleteSilentlyRecursively(final Path path) {\n if (path != null) {\n try {\n deleteRecursively(path);\n } catch (IOException ioex) {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(ioex, path);\n }\n }\n }", "private void deliverMountUpdate(SlotReference slot, boolean mounted) {\n if (mounted) {\n logger.info(\"Reporting media mounted in \" + slot);\n\n } else {\n logger.info(\"Reporting media removed from \" + slot);\n }\n for (final MountListener listener : getMountListeners()) {\n try {\n if (mounted) {\n listener.mediaMounted(slot);\n } else {\n listener.mediaUnmounted(slot);\n }\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering mount update to listener\", t);\n }\n }\n if (mounted) {\n MetadataCache.tryAutoAttaching(slot);\n }\n }", "protected String escapeApostrophes(String text) {\r\n\t\tString resultString;\r\n\t\tif (text.contains(\"'\")) {\r\n\t\t\tStringBuilder stringBuilder = new StringBuilder();\r\n\t\t\tstringBuilder.append(\"concat('\");\r\n\t\t\tstringBuilder.append(text.replace(\"'\", \"',\\\"'\\\",'\"));\r\n\t\t\tstringBuilder.append(\"')\");\r\n\t\t\tresultString = stringBuilder.toString();\r\n\t\t} else {\r\n\t\t\tresultString = \"'\" + text + \"'\";\r\n\t\t}\r\n\t\treturn resultString;\r\n\t}", "public void removePrefetchingListeners()\r\n {\r\n if (prefetchingListeners != null)\r\n {\r\n for (Iterator it = prefetchingListeners.iterator(); it.hasNext(); )\r\n {\r\n PBPrefetchingListener listener = (PBPrefetchingListener) it.next();\r\n listener.removeThisListener();\r\n }\r\n prefetchingListeners.clear();\r\n }\r\n }", "private void appendLikeCriteria(TableAlias alias, PathInfo pathInfo, LikeCriteria c, StringBuffer buf)\r\n {\r\n appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);\r\n buf.append(c.getClause());\r\n appendParameter(c.getValue(), buf);\r\n\r\n buf.append(m_platform.getEscapeClause(c));\r\n }", "private void updateCursorsInScene(GVRScene scene, boolean add) {\n synchronized (mCursors) {\n for (Cursor cursor : mCursors) {\n if (cursor.isActive()) {\n if (add) {\n addCursorToScene(cursor);\n } else {\n removeCursorFromScene(cursor);\n }\n }\n }\n }\n }", "public final void setWeeksOfMonth(SortedSet<WeekOfMonth> weeksOfMonth) {\n\n m_weeksOfMonth.clear();\n if (null != weeksOfMonth) {\n m_weeksOfMonth.addAll(weeksOfMonth);\n }\n\n }" ]
Constraint that ensures that the field has a conversion if the java type requires it. Also checks the conversion class. @param fieldDef The field descriptor @param checkLevel The current check level (this constraint is checked in basic (partly) and strict) @exception ConstraintException If the conversion class is invalid
[ "private void ensureConversion(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n // we issue a warning if we encounter a field with a java.util.Date java type without a conversion\r\n if (\"java.util.Date\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE)) &&\r\n !fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_CONVERSION))\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureConversion\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\r\n \" of type java.util.Date is directly mapped to jdbc-type \"+\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)+\r\n \". However, most JDBC drivers can't handle java.util.Date directly so you might want to \"+\r\n \" use a conversion for converting it to a JDBC datatype like TIMESTAMP.\");\r\n }\r\n\r\n String conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_CONVERSION);\r\n\r\n if (((conversionClass == null) || (conversionClass.length() == 0)) &&\r\n fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION) &&\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE).equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)))\r\n {\r\n conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_CONVERSION, conversionClass);\r\n }\r\n // now checking\r\n if (CHECKLEVEL_STRICT.equals(checkLevel) && (conversionClass != null) && (conversionClass.length() > 0))\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(conversionClass, CONVERSION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" does not implement the necessary interface \"+CONVERSION_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+ex.getMessage()+\" hasn't been found on the classpath while checking the conversion class specified for field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName());\r\n }\r\n }\r\n}" ]
[ "@GET\n @Produces(MediaType.APPLICATION_JSON)\n @Path(\"/graph/{name}/{version}\")\n public Response getModuleGraph(@PathParam(\"name\") final String moduleName,\n @PathParam(\"version\") final String moduleVersion,\n @Context final UriInfo uriInfo){\n\n LOG.info(\"Dependency Checker got a get module graph export request.\");\n\n if(moduleName == null || moduleVersion == null){\n return Response.serverError().status(HttpStatus.NOT_ACCEPTABLE_406).build();\n }\n\n final FiltersHolder filters = new FiltersHolder();\n filters.init(uriInfo.getQueryParameters());\n\n final String moduleId = DbModule.generateID(moduleName, moduleVersion);\n final AbstractGraph moduleGraph = getGraphsHandler(filters).getModuleGraph(moduleId);\n\n return Response.ok(moduleGraph).build();\n }", "public static Collection<MonetaryAmountFactory<?>> getAmountFactories(MonetaryAmountFactoryQuery query) {\n return Optional.ofNullable(monetaryAmountsSingletonQuerySpi()).orElseThrow(() -> new MonetaryException(\n \"No MonetaryAmountsSingletonQuerySpi loaded, query functionality is not available.\"))\n .getAmountFactories(query);\n }", "public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() {\n\n if (null == m_resourceCategories) {\n m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object resourceName) {\n\n try {\n CmsResource resource = m_cms.readResource(\n getRequestContext().removeSiteRoot((String)resourceName));\n return new CmsJspCategoryAccessBean(m_cms, resource);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n });\n }\n return m_resourceCategories;\n }", "private void sendAnnouncement(InetAddress broadcastAddress) {\n try {\n DatagramPacket announcement = new DatagramPacket(announcementBytes, announcementBytes.length,\n broadcastAddress, DeviceFinder.ANNOUNCEMENT_PORT);\n socket.get().send(announcement);\n Thread.sleep(getAnnounceInterval());\n } catch (Throwable t) {\n logger.warn(\"Unable to send announcement packet, shutting down\", t);\n stop();\n }\n }", "public void setIntVec(int[] data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 4)\n {\n throw new UnsupportedOperationException(\"Cannot update short indices with int array\");\n }\n if (!NativeIndexBuffer.setIntArray(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }", "public static void fire(I_CmsHasDateBoxEventHandlers source, Date date, boolean isTyping) {\n\n if (TYPE != null) {\n CmsDateBoxEvent event = new CmsDateBoxEvent(date, isTyping);\n source.fireEvent(event);\n }\n }", "public static double[] getTileLayerSize(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble div = Math.pow(2, code.getTileLevel());\n\t\tdouble tileWidth = Math.ceil((scale * maxExtent.getWidth()) / div) / scale;\n\t\tdouble tileHeight = Math.ceil((scale * maxExtent.getHeight()) / div) / scale;\n\t\treturn new double[] { tileWidth, tileHeight };\n\t}", "@Override\n\tpublic void write(final char[] cbuf, final int off, final int len) throws IOException {\n\t\tint offset = off;\n\t\tint length = len;\n\t\twhile (suppressLineCount > 0 && length > 0) {\n\t\t\tlength = -1;\n\t\t\tfor (int i = 0; i < len && suppressLineCount > 0; i++) {\n\t\t\t\tif (cbuf[off + i] == '\\n') {\n\t\t\t\t\toffset = off + i + 1;\n\t\t\t\t\tlength = len - i - 1;\n\t\t\t\t\tsuppressLineCount--;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (length <= 0)\n\t\t\t\treturn;\n\t\t}\n\t\tdelegate.write(cbuf, offset, length);\n\t}", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<InternationalFixedDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<InternationalFixedDate>) super.zonedDateTime(temporal);\n }" ]
Convert a field value to something suitable to be stored in the database.
[ "public Object convertJavaFieldToSqlArgValue(Object fieldVal) throws SQLException {\n\t\t/*\n\t\t * Limitation here. Some people may want to override the null with their own value in the converter but we\n\t\t * currently don't allow that. Specifying a default value I guess is a better mechanism.\n\t\t */\n\t\tif (fieldVal == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.javaToSqlArg(this, fieldVal);\n\t\t}\n\t}" ]
[ "public static boolean deleteDatabase(final StitchAppClientInfo appInfo,\n final String serviceName,\n final EmbeddedMongoClientFactory clientFactory,\n final String userId) {\n final String dataDir = appInfo.getDataDirectory();\n if (dataDir == null) {\n throw new IllegalArgumentException(\"StitchAppClient not configured with a data directory\");\n }\n\n final String instanceKey = String.format(\n \"%s-%s_sync_%s_%s\", appInfo.getClientAppId(), dataDir, serviceName, userId);\n final String dbPath = String.format(\n \"%s/%s/sync_mongodb_%s/%s/0/\", dataDir, appInfo.getClientAppId(), serviceName, userId);\n final MongoClient client =\n clientFactory.getClient(instanceKey, dbPath, appInfo.getCodecRegistry());\n\n for (final String listDatabaseName : client.listDatabaseNames()) {\n try {\n client.getDatabase(listDatabaseName).drop();\n } catch (Exception e) {\n // do nothing\n }\n }\n\n client.close();\n clientFactory.removeClient(instanceKey);\n\n return new File(dbPath).delete();\n }", "private void prepare() throws IOException, DocumentException, PrintingException {\n\t\tif (baos == null) {\n\t\t\tbaos = new ByteArrayOutputStream(); // let it grow as much as needed\n\t\t}\n\t\tbaos.reset();\n\t\tboolean resize = false;\n\t\tif (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {\n\t\t\tresize = true;\n\t\t}\n\t\t// Create a document in the requested ISO scale.\n\t\tDocument document = new Document(page.getBounds(), 0, 0, 0, 0);\n\t\tPdfWriter writer;\n\t\twriter = PdfWriter.getInstance(document, baos);\n\n\t\t// Render in correct colors for transparent rasters\n\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t// The mapView is not scaled to the document, we assume the mapView\n\t\t// has the right ratio.\n\n\t\t// Write document title and metadata\n\t\tdocument.open();\n\t\tPdfContext context = new PdfContext(writer);\n\t\tcontext.initSize(page.getBounds());\n\t\t// first pass of all children to calculate size\n\t\tpage.calculateSize(context);\n\t\tif (resize) {\n\t\t\t// we now know the bounds of the document\n\t\t\t// round 'm up and restart with a new document\n\t\t\tint width = (int) Math.ceil(page.getBounds().getWidth());\n\t\t\tint height = (int) Math.ceil(page.getBounds().getHeight());\n\t\t\tpage.getConstraint().setWidth(width);\n\t\t\tpage.getConstraint().setHeight(height);\n\n\t\t\tdocument = new Document(new Rectangle(width, height), 0, 0, 0, 0);\n\t\t\twriter = PdfWriter.getInstance(document, baos);\n\t\t\t// Render in correct colors for transparent rasters\n\t\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t\tdocument.open();\n\t\t\tbaos.reset();\n\t\t\tcontext = new PdfContext(writer);\n\t\t\tcontext.initSize(page.getBounds());\n\t\t}\n\t\t// int compressionLevel = writer.getCompressionLevel(); // For testing\n\t\t// writer.setCompressionLevel(0);\n\n\t\t// Actual drawing\n\t\tdocument.addTitle(\"Geomajas\");\n\t\t// second pass to layout\n\t\tpage.layout(context);\n\t\t// finally render (uses baos)\n\t\tpage.render(context);\n\n\t\tdocument.add(context.getImage());\n\t\t// Now close the document\n\t\tdocument.close();\n\t}", "public RandomVariable getImpliedBachelierATMOptionVolatility(RandomVariable optionValue, double optionMaturity, double swapAnnuity){\n\t\treturn optionValue.average().mult(Math.sqrt(2.0 * Math.PI / optionMaturity) / swapAnnuity);\n\t}", "public void filterUnsafeOrUnnecessaryRequest(\n Map<String, NodeReqResponse> nodeDataMapValidSource,\n Map<String, NodeReqResponse> nodeDataMapValidSafe) {\n\n for (Entry<String, NodeReqResponse> entry : nodeDataMapValidSource\n .entrySet()) {\n\n String hostName = entry.getKey();\n NodeReqResponse nrr = entry.getValue();\n\n Map<String, String> map = nrr.getRequestParameters();\n\n /**\n * 20130507: will generally apply to all requests: if have this\n * field and this field is false\n */\n if (map.containsKey(PcConstants.NODE_REQUEST_WILL_EXECUTE)) {\n Boolean willExecute = Boolean.parseBoolean(map\n .get(PcConstants.NODE_REQUEST_WILL_EXECUTE));\n\n if (!willExecute) {\n logger.info(\"NOT_EXECUTE_COMMAND \" + \" on target: \"\n + hostName + \" at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n continue;\n }\n }\n\n // now safely to add this node in.\n nodeDataMapValidSafe.put(hostName, nrr);\n }// end for loop\n\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushNotificationViewedEvent(Bundle extras){\n\n if (extras == null || extras.isEmpty() || extras.get(Constants.NOTIFICATION_TAG) == null) {\n getConfigLogger().debug(getAccountId(), \"Push notification: \" + (extras == null ? \"NULL\" : extras.toString()) + \" not from CleverTap - will not process Notification Viewed event.\");\n return;\n }\n\n if (!extras.containsKey(Constants.NOTIFICATION_ID_TAG) || (extras.getString(Constants.NOTIFICATION_ID_TAG) == null)) {\n getConfigLogger().debug(getAccountId(), \"Push notification ID Tag is null, not processing Notification Viewed event for: \" + extras.toString());\n return;\n }\n\n // Check for dupe notification views; if same notficationdId within specified time interval (2 secs) don't process\n boolean isDuplicate = checkDuplicateNotificationIds(extras, notificationViewedIdTagMap, Constants.NOTIFICATION_VIEWED_ID_TAG_INTERVAL);\n if (isDuplicate) {\n getConfigLogger().debug(getAccountId(), \"Already processed Notification Viewed event for \" + extras.toString() + \", dropping duplicate.\");\n return;\n }\n\n JSONObject event = new JSONObject();\n try {\n JSONObject notif = getWzrkFields(extras);\n event.put(\"evtName\", Constants.NOTIFICATION_VIEWED_EVENT_NAME);\n event.put(\"evtData\", notif);\n } catch (Throwable ignored) {\n //no-op\n }\n queueEvent(context, event, Constants.RAISED_EVENT);\n }", "public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() {\n\n if (null == m_resourceCategories) {\n m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object resourceName) {\n\n try {\n CmsResource resource = m_cms.readResource(\n getRequestContext().removeSiteRoot((String)resourceName));\n return new CmsJspCategoryAccessBean(m_cms, resource);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n });\n }\n return m_resourceCategories;\n }", "private void writeProjectProperties()\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n\n m_plannerProject.setCompany(properties.getCompany());\n m_plannerProject.setManager(properties.getManager());\n m_plannerProject.setName(getString(properties.getName()));\n m_plannerProject.setProjectStart(getDateTime(properties.getStartDate()));\n m_plannerProject.setCalendar(getIntegerString(m_projectFile.getDefaultCalendar().getUniqueID()));\n m_plannerProject.setMrprojectVersion(\"2\");\n }", "protected void removeSequence(String sequenceName)\r\n {\r\n // lookup the sequence map for calling DB\r\n Map mapForDB = (Map) sequencesDBMap.get(getBrokerForClass()\r\n .serviceConnectionManager().getConnectionDescriptor().getJcdAlias());\r\n if(mapForDB != null)\r\n {\r\n synchronized(SequenceManagerHighLowImpl.class)\r\n {\r\n mapForDB.remove(sequenceName);\r\n }\r\n }\r\n }", "public String getCanonicalTypeName(Object object) {\n ensureNotNull(\"object\", object);\n\n for (TypeDetector typeDetector : typeDetectors) {\n if (typeDetector.canHandle(object)) {\n return typeDetector.detectType(object);\n }\n }\n\n throw LOG.unableToDetectCanonicalType(object);\n }" ]
Get all field attributes in an unmodifiable Map, or null if no attributes have been added @return all field attributes, or <code>NULL</code> if none exist
[ "public Map<String, String> getAttributes() {\n if (attributes == null) {\n return null;\n } else {\n return Collections.unmodifiableMap(attributes);\n }\n }" ]
[ "public static Command newGetGlobal(String identifier,\n String outIdentifier) {\n return getCommandFactoryProvider().newGetGlobal( identifier,\n outIdentifier );\n }", "public static MarvinImage binaryToRgb(MarvinImage img) {\n MarvinImage resultImage = new MarvinImage(img.getWidth(), img.getHeight(), MarvinImage.COLOR_MODEL_RGB);\n\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n if (img.getBinaryColor(x, y)) {\n resultImage.setIntColor(x, y, 0, 0, 0);\n } else {\n resultImage.setIntColor(x, y, 255, 255, 255);\n }\n }\n }\n return resultImage;\n }", "protected final void setDefaultValue() {\n\n m_start = null;\n m_end = null;\n m_patterntype = PatternType.NONE;\n m_dayOfMonth = 0;\n m_exceptions.clear();\n m_individualDates.clear();\n m_interval = 0;\n m_isEveryWorkingDay = false;\n m_isWholeDay = false;\n m_month = Month.JANUARY;\n m_seriesEndDate = null;\n m_seriesOccurrences = 0;\n m_weekDays.clear();\n m_weeksOfMonth.clear();\n m_endType = EndType.SINGLE;\n m_parentSeriesId = null;\n }", "public CollectionRequest<ProjectStatus> findByProject(String project) {\n\n String path = String.format(\"/projects/%s/project_statuses\", project);\n return new CollectionRequest<ProjectStatus>(this, ProjectStatus.class, path, \"GET\");\n }", "protected CompletableFuture<JsonObjectBuilder> makeBuilder(int instanceId) {\n CompletableFuture<T> futureValue = getValue();\n\n if (futureValue == null) {\n logger.error(\"Could not retrieve value \" + this.getClass().getName());\n return null;\n }\n\n return futureValue\n .exceptionally(\n t -> {\n logger.error(\"Could not retrieve value \" + this.getClass().getName(), t);\n return null;\n })\n .thenApply(\n value -> {\n JsonArrayBuilder perms = Json.createArrayBuilder();\n if (isWritable) {\n perms.add(\"pw\");\n }\n if (isReadable) {\n perms.add(\"pr\");\n }\n if (isEventable) {\n perms.add(\"ev\");\n }\n JsonObjectBuilder builder =\n Json.createObjectBuilder()\n .add(\"iid\", instanceId)\n .add(\"type\", shortType)\n .add(\"perms\", perms.build())\n .add(\"format\", format)\n .add(\"ev\", false)\n .add(\"description\", description);\n setJsonValue(builder, value);\n return builder;\n });\n }", "public static String get(MessageKey key) {\n return data.getProperty(key.toString(), key.toString());\n }", "private double getExpectedProbability(double x)\n {\n double y = 1 / (standardDeviation * Math.sqrt(Math.PI * 2));\n double z = -(Math.pow(x - mean, 2) / (2 * Math.pow(standardDeviation, 2)));\n return y * Math.exp(z);\n }", "public String getRealm() {\n if (UNDEFINED.equals(realm)) {\n Principal principal = securityIdentity.getPrincipal();\n String realm = null;\n if (principal instanceof RealmPrincipal) {\n realm = ((RealmPrincipal)principal).getRealm();\n }\n this.realm = realm;\n\n }\n\n return this.realm;\n }", "public static void main(String[] args) {\n CmdLine cmd = new CmdLine();\n Configuration conf = new Configuration();\n int res = 0;\n try {\n res = ToolRunner.run(conf, cmd, args);\n } catch (Exception e) {\n System.err.println(\"Error while running MR job\");\n e.printStackTrace();\n }\n System.exit(res);\n }" ]
Returns the default privacy level preference for the user. @see com.flickr4java.flickr.Flickr#PRIVACY_LEVEL_NO_FILTER @see com.flickr4java.flickr.Flickr#PRIVACY_LEVEL_PUBLIC @see com.flickr4java.flickr.Flickr#PRIVACY_LEVEL_FRIENDS @see com.flickr4java.flickr.Flickr#PRIVACY_LEVEL_FRIENDS_FAMILY @see com.flickr4java.flickr.Flickr#PRIVACY_LEVEL_FAMILY @see com.flickr4java.flickr.Flickr#PRIVACY_LEVEL_FRIENDS @throws FlickrException @return privacyLevel
[ "public int getPrivacy() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PRIVACY);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element personElement = response.getPayload();\r\n return Integer.parseInt(personElement.getAttribute(\"privacy\"));\r\n }" ]
[ "private void processAnalytics() throws SQLException\n {\n allocateConnection();\n\n try\n {\n DatabaseMetaData meta = m_connection.getMetaData();\n String productName = meta.getDatabaseProductName();\n if (productName == null || productName.isEmpty())\n {\n productName = \"DATABASE\";\n }\n else\n {\n productName = productName.toUpperCase();\n }\n\n ProjectProperties properties = m_reader.getProject().getProjectProperties();\n properties.setFileApplication(\"Primavera\");\n properties.setFileType(productName);\n }\n\n finally\n {\n releaseConnection();\n }\n }", "private Date getTime(String value) throws MPXJException\n {\n try\n {\n Number hours = m_twoDigitFormat.parse(value.substring(0, 2));\n Number minutes = m_twoDigitFormat.parse(value.substring(2, 4));\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hours.intValue());\n cal.set(Calendar.MINUTE, minutes.intValue());\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n Date result = cal.getTime();\n DateHelper.pushCalendar(cal);\n \n return result;\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse time \" + value, ex);\n }\n }", "public AT_Row setPaddingBottom(int paddingBottom) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>\n getDonorsAndStealersForBalance(final Cluster nextCandidateCluster,\n Map<Integer, List<Integer>> numPartitionsPerNodePerZone) {\n HashMap<Node, Integer> donorNodes = Maps.newHashMap();\n HashMap<Node, Integer> stealerNodes = Maps.newHashMap();\n\n HashMap<Integer, Integer> numNodesAssignedInZone = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n numNodesAssignedInZone.put(zoneId, 0);\n }\n for(Node node: nextCandidateCluster.getNodes()) {\n int zoneId = node.getZoneId();\n\n int offset = numNodesAssignedInZone.get(zoneId);\n numNodesAssignedInZone.put(zoneId, offset + 1);\n\n int numPartitions = numPartitionsPerNodePerZone.get(zoneId).get(offset);\n\n if(numPartitions < node.getNumberOfPartitions()) {\n donorNodes.put(node, numPartitions);\n } else if(numPartitions > node.getNumberOfPartitions()) {\n stealerNodes.put(node, numPartitions);\n }\n }\n\n // Print out donor/stealer information\n for(Node node: donorNodes.keySet()) {\n System.out.println(\"Donor Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + donorNodes.get(node));\n }\n for(Node node: stealerNodes.keySet()) {\n System.out.println(\"Stealer Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + stealerNodes.get(node));\n }\n\n return new Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>(donorNodes, stealerNodes);\n }", "public static java.sql.Date rollYears(java.util.Date startDate, int years) {\n return rollDate(startDate, Calendar.YEAR, years);\n }", "public void setIndirectionHandlerClass(Class indirectionHandlerClass)\r\n {\r\n if(indirectionHandlerClass == null)\r\n {\r\n //throw new MetadataException(\"No IndirectionHandlerClass specified.\");\r\n /**\r\n * andrew.clute\r\n * Allow the default IndirectionHandler for the given ProxyFactory implementation\r\n * when the parameter is not given\r\n */\r\n indirectionHandlerClass = getDefaultIndirectionHandlerClass();\r\n }\r\n if(indirectionHandlerClass.isInterface()\r\n || Modifier.isAbstract(indirectionHandlerClass.getModifiers())\r\n || !getIndirectionHandlerBaseClass().isAssignableFrom(indirectionHandlerClass))\r\n {\r\n throw new MetadataException(\"Illegal class \"\r\n + indirectionHandlerClass.getName()\r\n + \" specified for IndirectionHandlerClass. Must be a concrete subclass of \"\r\n + getIndirectionHandlerBaseClass().getName());\r\n }\r\n _indirectionHandlerClass = indirectionHandlerClass;\r\n }", "void forcedUndeployScan() {\n\n if (acquireScanLock()) {\n try {\n ROOT_LOGGER.tracef(\"Performing a post-boot forced undeploy scan for scan directory %s\", deploymentDir.getAbsolutePath());\n ScanContext scanContext = new ScanContext(deploymentOperations);\n\n // Add remove actions to the plan for anything we count as\n // deployed that we didn't find on the scan\n for (Map.Entry<String, DeploymentMarker> missing : scanContext.toRemove.entrySet()) {\n // remove successful deployment and left will be removed\n if (scanContext.registeredDeployments.containsKey(missing.getKey())) {\n scanContext.registeredDeployments.remove(missing.getKey());\n }\n }\n Set<String> scannedDeployments = new HashSet<String>(scanContext.registeredDeployments.keySet());\n scannedDeployments.removeAll(scanContext.persistentDeployments);\n\n List<ScannerTask> scannerTasks = scanContext.scannerTasks;\n for (String toUndeploy : scannedDeployments) {\n scannerTasks.add(new UndeployTask(toUndeploy, deploymentDir, scanContext.scanStartTime, true));\n }\n try {\n executeScannerTasks(scannerTasks, deploymentOperations, true);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n\n ROOT_LOGGER.tracef(\"Forced undeploy scan complete\");\n } catch (Exception e) {\n ROOT_LOGGER.scanException(e, deploymentDir.getAbsolutePath());\n } finally {\n releaseScanLock();\n }\n }\n }", "void sendError(HttpResponseStatus status, Throwable ex) {\n String msg;\n\n if (ex instanceof InvocationTargetException) {\n msg = String.format(\"Exception Encountered while processing request : %s\", ex.getCause().getMessage());\n } else {\n msg = String.format(\"Exception Encountered while processing request: %s\", ex.getMessage());\n }\n\n // Send the status and message, followed by closing of the connection.\n responder.sendString(status, msg, new DefaultHttpHeaders().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE));\n if (bodyConsumer != null) {\n bodyConsumerError(ex);\n }\n }", "public static appfwglobal_auditnslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tappfwglobal_auditnslogpolicy_binding obj = new appfwglobal_auditnslogpolicy_binding();\n\t\tappfwglobal_auditnslogpolicy_binding response[] = (appfwglobal_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Specifies the list of enrichers that will be used to enrich the container object. @param enrichers list of enrichers that will be used to enrich the container object @return the current builder instance
[ "public DockerContainerObjectBuilder<T> withEnrichers(Collection<TestEnricher> enrichers) {\n if (enrichers == null) {\n throw new IllegalArgumentException(\"enrichers cannot be null\");\n }\n this.enrichers = enrichers;\n return this;\n }" ]
[ "public static final String printDuration(Duration value)\n {\n return value == null ? null : Double.toString(value.getDuration());\n }", "public float getColorR(int vertex, int colorset) {\n if (!hasColors(colorset)) {\n throw new IllegalStateException(\"mesh has no colorset \" + colorset);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for colorset are done by java for us */\n \n return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT);\n }", "public static vpnvserver_aaapreauthenticationpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_aaapreauthenticationpolicy_binding response[] = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public WebSocketContext sendToPeers(String message, boolean excludeSelf) {\n return sendToConnections(message, url, manager.urlRegistry(), excludeSelf);\n }", "public static boolean readBooleanAttributeElement(final XMLExtendedStreamReader reader, final String attributeName)\n throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n final boolean value = Boolean.parseBoolean(reader.getAttributeValue(0));\n requireNoContent(reader);\n return value;\n }", "private void updateSession(Session newSession) {\n if (this.currentSession == null) {\n this.currentSession = newSession;\n } else {\n synchronized (this.currentSession) {\n this.currentSession = newSession;\n }\n }\n }", "public static appfwglobal_auditnslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tappfwglobal_auditnslogpolicy_binding obj = new appfwglobal_auditnslogpolicy_binding();\n\t\tappfwglobal_auditnslogpolicy_binding response[] = (appfwglobal_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "void writeBestRankTriples() {\n\t\tfor (Resource resource : this.rankBuffer.getBestRankedStatements()) {\n\t\t\ttry {\n\t\t\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\t\t\tRdfWriter.RDF_TYPE, RdfWriter.WB_BEST_RANK.toString());\n\t\t\t} catch (RDFHandlerException e) {\n\t\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t\tthis.rankBuffer.clear();\n\t}", "public static <E> Collection<E> collectify(ObjectMapper mapper, Object source, Class<? extends Collection> targetCollectionType, Class<E> targetElementType) {\n CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(targetCollectionType, targetElementType);\n return objectify(mapper, convertToCollection(source), collectionType);\n }" ]
Handles the response of the SerialAPIGetCapabilities request. @param incomingMessage the response message to process.
[ "private void handleSerialAPIGetCapabilitiesResponse(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Serial API Get Capabilities\");\n\n\t\tthis.serialAPIVersion = String.format(\"%d.%d\", incomingMessage.getMessagePayloadByte(0), incomingMessage.getMessagePayloadByte(1));\n\t\tthis.manufactureId = ((incomingMessage.getMessagePayloadByte(2)) << 8) | (incomingMessage.getMessagePayloadByte(3));\n\t\tthis.deviceType = ((incomingMessage.getMessagePayloadByte(4)) << 8) | (incomingMessage.getMessagePayloadByte(5));\n\t\tthis.deviceId = (((incomingMessage.getMessagePayloadByte(6)) << 8) | (incomingMessage.getMessagePayloadByte(7)));\n\t\t\n\t\tlogger.debug(String.format(\"API Version = %s\", this.getSerialAPIVersion()));\n\t\tlogger.debug(String.format(\"Manufacture ID = 0x%x\", this.getManufactureId()));\n\t\tlogger.debug(String.format(\"Device Type = 0x%x\", this.getDeviceType()));\n\t\tlogger.debug(String.format(\"Device ID = 0x%x\", this.getDeviceId()));\n\t\t\n\t\t// Ready to get information on Serial API\t\t\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessagePriority.High));\n\t}" ]
[ "public static <T> T notNull(T argument, String argumentName) {\n if (argument == null) {\n throw new IllegalArgumentException(\"Argument \" + argumentName + \" must not be null.\");\n }\n return argument;\n }", "public static dospolicy get(nitro_service service, String name) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tobj.set_name(name);\n\t\tdospolicy response = (dospolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "public double getDegrees() {\n double kms = getValue(GeoDistanceUnit.KILOMETRES);\n return DistanceUtils.dist2Degrees(kms, DistanceUtils.EARTH_MEAN_RADIUS_KM);\n }", "public static byte[] getBytes(String string, String encoding) {\n try {\n return string.getBytes(encoding);\n } catch(UnsupportedEncodingException e) {\n throw new IllegalArgumentException(encoding + \" is not a known encoding name.\", e);\n }\n }", "public static boolean intArrayContains(int[] array, int numToCheck) {\n for (int i = 0; i < array.length; i++) {\n if (array[i] == numToCheck) {\n return true;\n }\n }\n return false;\n }", "protected synchronized void setStream(InputStream s)\n {\n if (stream != null)\n {\n throw new UnsupportedOperationException(\"Cannot set the stream of an open resource\");\n }\n stream = s;\n streamState = StreamStates.OPEN;\n }", "ArgumentsBuilder param(String param, String value) {\n if (value != null) {\n args.add(param);\n args.add(value);\n }\n return this;\n }", "public void seekToSeasonYear(String seasonString, String yearString) {\n Season season = Season.valueOf(seasonString);\n assert(season != null);\n \n seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary());\n }", "private boolean isTileVisible(final ReferencedEnvelope tileBounds) {\n if (FloatingPointUtil.equals(this.transformer.getRotation(), 0.0)) {\n return true;\n }\n\n final GeometryFactory gfac = new GeometryFactory();\n final Optional<Geometry> rotatedMapBounds = getRotatedMapBounds(gfac);\n\n if (rotatedMapBounds.isPresent()) {\n return rotatedMapBounds.get().intersects(gfac.toGeometry(tileBounds));\n } else {\n // in case of an error, we simply load the tile\n return true;\n }\n }" ]
get the TypeSignature corresponding to given class with given type arguments @param clazz @param typeArgs @return
[ "public static FullTypeSignature getTypeSignature(Class<?> clazz, Class<?>[] typeArgs) {\n\t\tClassTypeSignature rawClassTypeSignature = (ClassTypeSignature) javaTypeToTypeSignature\n\t\t\t\t.getTypeSignature(clazz);\n\t\tTypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArgs.length];\n\t\tfor (int i = 0; i < typeArgs.length; i++) {\n\t\t\ttypeArgSignatures[i] = new TypeArgSignature(\n\t\t\t\t\tTypeArgSignature.NO_WILDCARD,\n\t\t\t\t\t(FieldTypeSignature) javaTypeToTypeSignature\n\t\t\t\t\t\t\t.getTypeSignature(typeArgs[i]));\n\t\t}\n\t\tClassTypeSignature classTypeSignature = new ClassTypeSignature(\n\t\t\t\trawClassTypeSignature.getBinaryName(), typeArgSignatures,\n\t\t\t\trawClassTypeSignature.getOwnerTypeSignature());\n\n\t\treturn classTypeSignature;\n\t}" ]
[ "public static String determineFieldName(@Nonnull final String methodName) {\n\t\tCheck.notEmpty(methodName, \"methodName\");\n\t\tfinal Matcher m = PATTERN.matcher(methodName);\n\t\tCheck.stateIsTrue(m.find(), \"passed method name '%s' is not applicable\", methodName);\n\t\treturn m.group(2).substring(0, 1).toLowerCase() + m.group(2).substring(1);\n\t}", "public void bind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service);\n updateSortedServices();\n }\n }", "@Override\r\n public V remove(Object key) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n V result = temp.remove(key);\r\n map = temp;\r\n return (result);\r\n }\r\n } else {\r\n synchronized (map) {\r\n return (map.remove(key));\r\n }\r\n }\r\n }", "public static systemcore[] get(nitro_service service, systemcore_args args) throws Exception{\n\t\tsystemcore obj = new systemcore();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsystemcore[] response = (systemcore[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public static base_response update(nitro_service client, nstimeout resource) throws Exception {\n\t\tnstimeout updateresource = new nstimeout();\n\t\tupdateresource.zombie = resource.zombie;\n\t\tupdateresource.client = resource.client;\n\t\tupdateresource.server = resource.server;\n\t\tupdateresource.httpclient = resource.httpclient;\n\t\tupdateresource.httpserver = resource.httpserver;\n\t\tupdateresource.tcpclient = resource.tcpclient;\n\t\tupdateresource.tcpserver = resource.tcpserver;\n\t\tupdateresource.anyclient = resource.anyclient;\n\t\tupdateresource.anyserver = resource.anyserver;\n\t\tupdateresource.halfclose = resource.halfclose;\n\t\tupdateresource.nontcpzombie = resource.nontcpzombie;\n\t\tupdateresource.reducedfintimeout = resource.reducedfintimeout;\n\t\tupdateresource.newconnidletimeout = resource.newconnidletimeout;\n\t\treturn updateresource.update_resource(client);\n\t}", "public Schedule generateSchedule(LocalDate referenceDate, LocalDate startDate, LocalDate endDate) {\r\n\t\treturn ScheduleGenerator.createScheduleFromConventions(referenceDate, startDate, endDate, getFrequency(), getDaycountConvention(),\r\n\t\t\t\tgetShortPeriodConvention(), getDateRollConvention(), getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());\r\n\t}", "@UiHandler(\"m_seriesCheckBox\")\n void onSeriesChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setIsSeries(event.getValue());\n }\n }", "public void merge(GVRSkeleton newSkel)\n {\n int numBones = getNumBones();\n List<Integer> parentBoneIds = new ArrayList<Integer>(numBones + newSkel.getNumBones());\n List<String> newBoneNames = new ArrayList<String>(newSkel.getNumBones());\n List<Matrix4f> newMatrices = new ArrayList<Matrix4f>(newSkel.getNumBones());\n GVRPose oldBindPose = getBindPose();\n GVRPose curPose = getPose();\n\n for (int i = 0; i < numBones; ++i)\n {\n parentBoneIds.add(mParentBones[i]);\n }\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n String boneName = newSkel.getBoneName(j);\n int boneId = getBoneIndex(boneName);\n if (boneId < 0)\n {\n int parentId = newSkel.getParentBoneIndex(j);\n Matrix4f m = new Matrix4f();\n\n newSkel.getBindPose().getLocalMatrix(j, m);\n newMatrices.add(m);\n newBoneNames.add(boneName);\n if (parentId >= 0)\n {\n boneName = newSkel.getBoneName(parentId);\n parentId = getBoneIndex(boneName);\n }\n parentBoneIds.add(parentId);\n }\n }\n if (parentBoneIds.size() == numBones)\n {\n return;\n }\n int n = numBones + parentBoneIds.size();\n int[] parentIds = Arrays.copyOf(mParentBones, n);\n int[] boneOptions = Arrays.copyOf(mBoneOptions, n);\n String[] boneNames = Arrays.copyOf(mBoneNames, n);\n\n mBones = Arrays.copyOf(mBones, n);\n mPoseMatrices = new float[n * 16];\n for (int i = 0; i < parentBoneIds.size(); ++i)\n {\n n = numBones + i;\n parentIds[n] = parentBoneIds.get(i);\n boneNames[n] = newBoneNames.get(i);\n boneOptions[n] = BONE_ANIMATE;\n }\n mBoneOptions = boneOptions;\n mBoneNames = boneNames;\n mParentBones = parentIds;\n mPose = new GVRPose(this);\n mBindPose = new GVRPose(this);\n mBindPose.copy(oldBindPose);\n mPose.copy(curPose);\n mBindPose.sync();\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n mBindPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n mPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n }\n setBindPose(mBindPose);\n mPose.sync();\n updateBonePose();\n }", "private String getCacheFormatEntry() throws IOException {\n ZipEntry zipEntry = zipFile.getEntry(CACHE_FORMAT_ENTRY);\n InputStream is = zipFile.getInputStream(zipEntry);\n try {\n Scanner s = new Scanner(is, \"UTF-8\").useDelimiter(\"\\\\A\");\n String tag = null;\n if (s.hasNext()) tag = s.next();\n return tag;\n } finally {\n is.close();\n }\n }" ]
Read multiple columns from a block. @param startIndex start of the block @param blockLength length of the block
[ "private void readColumnBlock(int startIndex, int blockLength) throws Exception\n {\n int endIndex = startIndex + blockLength;\n List<Integer> blocks = new ArrayList<Integer>();\n for (int index = startIndex; index < endIndex - 11; index++)\n {\n if (matchChildBlock(index))\n {\n int childBlockStart = index - 2;\n blocks.add(Integer.valueOf(childBlockStart));\n }\n }\n blocks.add(Integer.valueOf(endIndex));\n\n int childBlockStart = -1;\n for (int childBlockEnd : blocks)\n {\n if (childBlockStart != -1)\n {\n int childblockLength = childBlockEnd - childBlockStart;\n try\n {\n readColumn(childBlockStart, childblockLength);\n }\n catch (UnexpectedStructureException ex)\n {\n logUnexpectedStructure();\n }\n }\n childBlockStart = childBlockEnd;\n }\n }" ]
[ "protected String escapeApostrophes(String text) {\r\n\t\tString resultString;\r\n\t\tif (text.contains(\"'\")) {\r\n\t\t\tStringBuilder stringBuilder = new StringBuilder();\r\n\t\t\tstringBuilder.append(\"concat('\");\r\n\t\t\tstringBuilder.append(text.replace(\"'\", \"',\\\"'\\\",'\"));\r\n\t\t\tstringBuilder.append(\"')\");\r\n\t\t\tresultString = stringBuilder.toString();\r\n\t\t} else {\r\n\t\t\tresultString = \"'\" + text + \"'\";\r\n\t\t}\r\n\t\treturn resultString;\r\n\t}", "public void verifyMessageSize(int maxMessageSize) {\n Iterator<MessageAndOffset> shallowIter = internalIterator(true);\n while(shallowIter.hasNext()) {\n MessageAndOffset messageAndOffset = shallowIter.next();\n int payloadSize = messageAndOffset.message.payloadSize();\n if(payloadSize > maxMessageSize) {\n throw new MessageSizeTooLargeException(\"payload size of \" + payloadSize + \" larger than \" + maxMessageSize);\n }\n }\n }", "public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }", "public String toMixedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.mixedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.mixedString = result = toNormalizedString(IPv6StringCache.mixedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toMixedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}", "protected <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) {\r\n\r\n return ensureHandlers().addHandlerToSource(type, this, handler);\r\n }", "public static File createTempDirectory(String prefix) {\n\tFile temp = null;\n\t\n\ttry {\n\t temp = File.createTempFile(prefix != null ? prefix : \"temp\", Long.toString(System.nanoTime()));\n\t\n\t if (!(temp.delete())) {\n\t throw new IOException(\"Could not delete temp file: \"\n\t\t + temp.getAbsolutePath());\n\t }\n\t\n\t if (!(temp.mkdir())) {\n\t throw new IOException(\"Could not create temp directory: \"\n\t + temp.getAbsolutePath());\n\t }\n\t} catch (IOException e) {\n\t throw new DukeException(\"Unable to create temporary directory with prefix \" + prefix, e);\n\t}\n\t\n\treturn temp;\n }", "public void startAnimation()\n {\n Date time = new Date();\n this.beginAnimation = time.getTime();\n this.endAnimation = beginAnimation + (long) (animationTime * 1000);\n this.animate = true;\n }", "public int getFixedDataOffset(FieldType type)\n {\n int result;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFixedDataOffset();\n }\n else\n {\n result = -1;\n }\n return result;\n }", "public static final UUID getUUID(InputStream is) throws IOException\n {\n byte[] data = new byte[16];\n is.read(data);\n\n long long1 = 0;\n long1 |= ((long) (data[3] & 0xFF)) << 56;\n long1 |= ((long) (data[2] & 0xFF)) << 48;\n long1 |= ((long) (data[1] & 0xFF)) << 40;\n long1 |= ((long) (data[0] & 0xFF)) << 32;\n long1 |= ((long) (data[5] & 0xFF)) << 24;\n long1 |= ((long) (data[4] & 0xFF)) << 16;\n long1 |= ((long) (data[7] & 0xFF)) << 8;\n long1 |= ((long) (data[6] & 0xFF)) << 0;\n\n long long2 = 0;\n long2 |= ((long) (data[8] & 0xFF)) << 56;\n long2 |= ((long) (data[9] & 0xFF)) << 48;\n long2 |= ((long) (data[10] & 0xFF)) << 40;\n long2 |= ((long) (data[11] & 0xFF)) << 32;\n long2 |= ((long) (data[12] & 0xFF)) << 24;\n long2 |= ((long) (data[13] & 0xFF)) << 16;\n long2 |= ((long) (data[14] & 0xFF)) << 8;\n long2 |= ((long) (data[15] & 0xFF)) << 0;\n\n return new UUID(long1, long2);\n }" ]
Use this API to add clusternodegroup resources.
[ "public static base_responses add(nitro_service client, clusternodegroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusternodegroup addresources[] = new clusternodegroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new clusternodegroup();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].strict = resources[i].strict;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "private static double arcAngle(Point center, Point a, Point b, Rect area, int radius) {\n double angle = threePointsAngle(center, a, b);\n Point innerPoint = findMidnormalPoint(center, a, b, area, radius);\n Point midInsectPoint = new Point((a.x + b.x) / 2, (a.y + b.y) / 2);\n double distance = pointsDistance(midInsectPoint, innerPoint);\n if (distance > radius) {\n return 360 - angle;\n }\n return angle;\n }", "public static String encodeScheme(String scheme, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(scheme, encoding, HierarchicalUriComponents.Type.SCHEME);\n\t}", "public VectorClock incremented(int nodeId, long time) {\n VectorClock copyClock = this.clone();\n copyClock.incrementVersion(nodeId, time);\n return copyClock;\n }", "protected FieldDescriptor getFieldDescriptor(TableAlias aTableAlias, PathInfo aPathInfo)\r\n {\r\n FieldDescriptor fld = null;\r\n String colName = aPathInfo.column;\r\n\r\n if (aTableAlias != null)\r\n {\r\n fld = aTableAlias.cld.getFieldDescriptorByName(colName);\r\n if (fld == null)\r\n {\r\n ObjectReferenceDescriptor ord = aTableAlias.cld.getObjectReferenceDescriptorByName(colName);\r\n if (ord != null)\r\n {\r\n fld = getFldFromReference(aTableAlias, ord);\r\n }\r\n else\r\n {\r\n fld = getFldFromJoin(aTableAlias, colName);\r\n }\r\n }\r\n }\r\n\r\n return fld;\r\n }", "private void applyAliases()\n {\n CustomFieldContainer fields = m_projectFile.getCustomFields();\n for (Map.Entry<FieldType, String> entry : ALIASES.entrySet())\n {\n fields.getCustomField(entry.getKey()).setAlias(entry.getValue());\n }\n }", "public void setRefreshing(boolean refreshing) {\n if (refreshing && mRefreshing != refreshing) {\n // scale and show\n mRefreshing = refreshing;\n int endTarget = 0;\n if (!mUsingCustomStart) {\n switch (mDirection) {\n case BOTTOM:\n endTarget = getMeasuredHeight() - (int) (mSpinnerFinalOffset);\n break;\n case TOP:\n default:\n endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));\n break;\n }\n } else {\n endTarget = (int) mSpinnerFinalOffset;\n }\n setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop,\n true /* requires update */);\n mNotify = false;\n startScaleUpAnimation(mRefreshListener);\n } else {\n setRefreshing(refreshing, false /* notify */);\n }\n }", "public DynamicReportBuilder setQuery(String text, String language) {\n this.report.setQuery(new DJQuery(text, language));\n return this;\n }", "private void readResourceCustomFields(net.sf.mpxj.ganttproject.schema.Resource gpResource, Resource mpxjResource)\n {\n //\n // Populate custom field default values\n //\n Map<FieldType, Object> customFields = new HashMap<FieldType, Object>();\n for (Pair<FieldType, String> definition : m_resourcePropertyDefinitions.values())\n {\n customFields.put(definition.getFirst(), definition.getSecond());\n }\n\n //\n // Update with custom field actual values\n //\n for (CustomResourceProperty property : gpResource.getCustomProperty())\n {\n Pair<FieldType, String> definition = m_resourcePropertyDefinitions.get(property.getDefinitionId());\n if (definition != null)\n {\n //\n // Retrieve the value. If it is empty, use the default.\n //\n String value = property.getValueAttribute();\n if (value.isEmpty())\n {\n value = null;\n }\n\n //\n // If we have a value,convert it to the correct type\n //\n if (value != null)\n {\n Object result;\n\n switch (definition.getFirst().getDataType())\n {\n case NUMERIC:\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n result = Double.valueOf(value);\n }\n break;\n }\n\n case DATE:\n {\n try\n {\n result = m_localeDateFormat.parse(value);\n }\n catch (ParseException ex)\n {\n result = null;\n }\n break;\n }\n\n case BOOLEAN:\n {\n result = Boolean.valueOf(value.equals(\"true\"));\n break;\n }\n\n default:\n {\n result = value;\n break;\n }\n }\n\n if (result != null)\n {\n customFields.put(definition.getFirst(), result);\n }\n }\n }\n }\n\n for (Map.Entry<FieldType, Object> item : customFields.entrySet())\n {\n if (item.getValue() != null)\n {\n mpxjResource.set(item.getKey(), item.getValue());\n }\n }\n }", "private void showSettingsMenu(final Cursor cursor) {\n Log.d(TAG, \"showSettingsMenu\");\n enableSettingsCursor(cursor);\n context.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n new SettingsView(context, scene, CursorManager.this,\n settingsCursor.getIoDevice().getCursorControllerId(), cursor, new\n SettingsChangeListener() {\n @Override\n public void onBack(boolean cascading) {\n disableSettingsCursor();\n }\n\n @Override\n public int onDeviceChanged(IoDevice device) {\n // we are changing the io device on the settings cursor\n removeCursorFromScene(settingsCursor);\n IoDevice clickedDevice = getAvailableIoDevice(device);\n settingsCursor.setIoDevice(clickedDevice);\n addCursorToScene(settingsCursor);\n return device.getCursorControllerId();\n }\n });\n }\n });\n }" ]