query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Returns new boolean matrix with true or false values selected with equal probability.
@param numRow Number of rows in the new matrix.
@param numCol Number of columns in the new matrix.
@param rand Random number generator used to fill the matrix.
@return The randomly generated matrix. | [
"public static BMatrixRMaj randomBinary(int numRow , int numCol , Random rand ) {\n BMatrixRMaj mat = new BMatrixRMaj(numRow,numCol);\n\n setRandomB(mat, rand);\n\n return mat;\n }"
] | [
"public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {\n assertNumericArgument(corePoolSize, true);\n assertNumericArgument(maximumPoolSize, true);\n assertNumericArgument(corePoolSize + maximumPoolSize, false);\n assertNumericArgument(keepAliveTime, true);\n this.corePoolSize = corePoolSize;\n this.maximumPoolSize = maximumPoolSize;\n this.keepAliveTime = unit.toMillis(keepAliveTime);\n return this;\n }",
"public boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }",
"private void processProperties(XMLStreamWriter writer, Set<Method> methodSet, Class<?> aClass) throws IntrospectionException, XMLStreamException\n {\n BeanInfo beanInfo = Introspector.getBeanInfo(aClass, aClass.getSuperclass());\n PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();\n\n for (int i = 0; i < propertyDescriptors.length; i++)\n {\n PropertyDescriptor propertyDescriptor = propertyDescriptors[i];\n if (propertyDescriptor.getPropertyType() != null)\n {\n String name = propertyDescriptor.getName();\n Method readMethod = propertyDescriptor.getReadMethod();\n Method writeMethod = propertyDescriptor.getWriteMethod();\n\n String readMethodName = readMethod == null ? null : readMethod.getName();\n String writeMethodName = writeMethod == null ? null : writeMethod.getName();\n addProperty(writer, name, propertyDescriptor.getPropertyType(), readMethodName, writeMethodName);\n\n if (readMethod != null)\n {\n methodSet.add(readMethod);\n }\n\n if (writeMethod != null)\n {\n methodSet.add(writeMethod);\n }\n }\n else\n {\n processAmbiguousProperty(writer, methodSet, aClass, propertyDescriptor);\n }\n }\n }",
"@Override\n public void process() {\n if (client.isDone() || executorService.isTerminated()) {\n throw new IllegalStateException(\"Client is already stopped\");\n }\n Runnable runner = new Runnable() {\n @Override\n public void run() {\n try {\n while (!client.isDone()) {\n String msg = messageQueue.take();\n try {\n parseMessage(msg);\n } catch (Exception e) {\n logger.warn(\"Exception thrown during parsing msg \" + msg, e);\n onException(e);\n }\n }\n } catch (Exception e) {\n onException(e);\n }\n }\n };\n\n executorService.execute(runner);\n }",
"protected void load()\r\n {\r\n properties = new Properties();\r\n\r\n String filename = getFilename();\r\n \r\n try\r\n {\r\n URL url = ClassHelper.getResource(filename);\r\n\r\n if (url == null)\r\n {\r\n url = (new File(filename)).toURL();\r\n }\r\n\r\n logger.info(\"Loading OJB's properties: \" + url);\r\n\r\n URLConnection conn = url.openConnection();\r\n conn.setUseCaches(false);\r\n conn.connect();\r\n InputStream strIn = conn.getInputStream();\r\n properties.load(strIn);\r\n strIn.close();\r\n }\r\n catch (FileNotFoundException ex)\r\n {\r\n // [tomdz] If the filename is explicitly reset (null or empty string) then we'll\r\n // output an info message because the user did this on purpose\r\n // Otherwise, we'll output a warning\r\n if ((filename == null) || (filename.length() == 0))\r\n {\r\n logger.info(\"Starting OJB without a properties file. OJB is using default settings instead.\");\r\n }\r\n else\r\n {\r\n logger.warn(\"Could not load properties file '\"+filename+\"'. Using default settings!\", ex);\r\n }\r\n // [tomdz] There seems to be no use of this setting ?\r\n //properties.put(\"valid\", \"false\");\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new MetadataException(\"An error happend while loading the properties file '\"+filename+\"'\", ex);\r\n }\r\n }",
"public static spilloverpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy_stats response = (spilloverpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public boolean process( int sideLength,\n double diag[] ,\n double off[] ,\n double eigenvalues[] ) {\n if( diag != null )\n helper.init(diag,off,sideLength);\n if( Q == null )\n Q = CommonOps_DDRM.identity(helper.N);\n helper.setQ(Q);\n\n this.followingScript = true;\n this.eigenvalues = eigenvalues;\n this.fastEigenvalues = false;\n\n return _process();\n }",
"private CompiledStatement assignStatementArguments(CompiledStatement stmt) throws SQLException {\n\t\tboolean ok = false;\n\t\ttry {\n\t\t\tif (limit != null) {\n\t\t\t\t// we use this if SQL statement LIMITs are not supported by this database type\n\t\t\t\tstmt.setMaxRows(limit.intValue());\n\t\t\t}\n\t\t\t// set any arguments if we are logging our object\n\t\t\tObject[] argValues = null;\n\t\t\tif (logger.isLevelEnabled(Level.TRACE) && argHolders.length > 0) {\n\t\t\t\targValues = new Object[argHolders.length];\n\t\t\t}\n\t\t\tfor (int i = 0; i < argHolders.length; i++) {\n\t\t\t\tObject argValue = argHolders[i].getSqlArgValue();\n\t\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\t\tSqlType sqlType;\n\t\t\t\tif (fieldType == null) {\n\t\t\t\t\tsqlType = argHolders[i].getSqlType();\n\t\t\t\t} else {\n\t\t\t\t\tsqlType = fieldType.getSqlType();\n\t\t\t\t}\n\t\t\t\tstmt.setObject(i, argValue, sqlType);\n\t\t\t\tif (argValues != null) {\n\t\t\t\t\targValues[i] = argValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"prepared statement '{}' with {} args\", statement, argHolders.length);\n\t\t\tif (argValues != null) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"prepared statement arguments: {}\", (Object) argValues);\n\t\t\t}\n\t\t\tok = true;\n\t\t\treturn stmt;\n\t\t} finally {\n\t\t\tif (!ok) {\n\t\t\t\tIOUtils.closeThrowSqlException(stmt, \"statement\");\n\t\t\t}\n\t\t}\n\t}",
"private String toRfsName(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(m_cache.getRepositoryPath(), \"\" + name.hashCode()) + size.getSuffix();\n }"
] |
Retrieves the formatted parent WBS value.
@return formatted parent WBS value | [
"public String getFormattedParentValue()\n {\n String result = null;\n if (m_elements.size() > 2)\n {\n result = joinElements(m_elements.size() - 2);\n }\n return result;\n }"
] | [
"public static ComponentsMultiThread getComponentsMultiThread() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.componentsMultiThread;\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}",
"@Override\n public final long getLong(final String key) {\n Long result = optLong(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"private void logShort(CharSequence message, boolean trim) throws IOException {\n int length = message.length();\n if (trim) {\n while (length > 0 && Character.isWhitespace(message.charAt(length - 1))) {\n length--;\n }\n }\n\n char [] chars = new char [length + 1];\n for (int i = 0; i < length; i++) {\n chars[i] = message.charAt(i);\n }\n chars[length] = '\\n';\n\n output.write(chars);\n }",
"@SuppressWarnings({ \"unchecked\" })\n public static <T> T[] readArrayAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n final List<T> list = readListAttributeElement(reader, attributeName, type);\n return list.toArray((T[]) Array.newInstance(type, list.size()));\n }",
"public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) {\n checkArgument(!variableName.isEmpty());\n return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine));\n }",
"protected void addStatement(Statement statement, boolean isNew) {\n\t\tPropertyIdValue pid = statement.getMainSnak().getPropertyId();\n\n\t\t// This code maintains the following properties:\n\t\t// (1) the toKeep structure does not contain two statements with the\n\t\t// same statement id\n\t\t// (2) the toKeep structure does not contain two statements that can\n\t\t// be merged\n\t\tif (this.toKeep.containsKey(pid)) {\n\t\t\tList<StatementWithUpdate> statements = this.toKeep.get(pid);\n\t\t\tfor (int i = 0; i < statements.size(); i++) {\n\t\t\t\tStatement currentStatement = statements.get(i).statement;\n\t\t\t\tboolean currentIsNew = statements.get(i).write;\n\n\t\t\t\tif (!\"\".equals(currentStatement.getStatementId())\n\t\t\t\t\t\t&& currentStatement.getStatementId().equals(\n\t\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t// Same, non-empty id: ignore existing statement as if\n\t\t\t\t\t// deleted\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tStatement newStatement = mergeStatements(statement,\n\t\t\t\t\t\tcurrentStatement);\n\t\t\t\tif (newStatement != null) {\n\t\t\t\t\tboolean writeNewStatement = (isNew || !newStatement\n\t\t\t\t\t\t\t.equals(statement))\n\t\t\t\t\t\t\t&& (currentIsNew || !newStatement\n\t\t\t\t\t\t\t\t\t.equals(currentStatement));\n\t\t\t\t\t// noWrite: (newS == statement && !isNew)\n\t\t\t\t\t// || (newS == cur && !curIsNew)\n\t\t\t\t\t// Write: (newS != statement || isNew )\n\t\t\t\t\t// && (newS != cur || curIsNew)\n\n\t\t\t\t\tstatements.set(i, new StatementWithUpdate(newStatement,\n\t\t\t\t\t\t\twriteNewStatement));\n\n\t\t\t\t\t// Impossible with default merge code:\n\t\t\t\t\t// Kept here for future extensions that may choose to not\n\t\t\t\t\t// reuse this id.\n\t\t\t\t\tif (!\"\".equals(statement.getStatementId())\n\t\t\t\t\t\t\t&& !newStatement.getStatementId().equals(\n\t\t\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t\tthis.toDelete.add(statement.getStatementId());\n\t\t\t\t\t}\n\t\t\t\t\tif (!\"\".equals(currentStatement.getStatementId())\n\t\t\t\t\t\t\t&& !newStatement.getStatementId().equals(\n\t\t\t\t\t\t\t\t\tcurrentStatement.getStatementId())) {\n\t\t\t\t\t\tthis.toDelete.add(currentStatement.getStatementId());\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatements.add(new StatementWithUpdate(statement, isNew));\n\t\t} else {\n\t\t\tList<StatementWithUpdate> statements = new ArrayList<>();\n\t\t\tstatements.add(new StatementWithUpdate(statement, isNew));\n\t\t\tthis.toKeep.put(pid, statements);\n\t\t}\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 }",
"public static String common() {\n String common = SysProps.get(KEY_COMMON_CONF_TAG);\n if (S.blank(common)) {\n common = \"common\";\n }\n return common;\n }"
] |
Creates a spin wrapper for a data input. The data format of the
input is assumed to be XML.
@param input the input to wrap
@return the spin wrapper for the input
@throws IllegalArgumentException in case an argument of illegal type is provided (such as 'null') | [
"public static SpinXmlElement XML(Object input) {\n return SpinFactory.INSTANCE.createSpin(input, DataFormats.xml());\n }"
] | [
"private static final double printDurationFractionsOfMinutes(Duration duration, int factor)\n {\n double result = 0;\n\n if (duration != null)\n {\n result = duration.getDuration();\n\n switch (duration.getUnits())\n {\n case HOURS:\n case ELAPSED_HOURS:\n {\n result *= 60;\n break;\n }\n\n case DAYS:\n {\n result *= (60 * 8);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n result *= (60 * 24);\n break;\n }\n\n case WEEKS:\n {\n result *= (60 * 8 * 5);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n result *= (60 * 24 * 7);\n break;\n }\n\n case MONTHS:\n {\n result *= (60 * 8 * 5 * 4);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n result *= (60 * 24 * 30);\n break;\n }\n\n case YEARS:\n {\n result *= (60 * 8 * 5 * 52);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n result *= (60 * 24 * 365);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n result *= factor;\n\n return (result);\n }",
"private int countHours(Integer hours)\n {\n int value = hours.intValue();\n int hoursPerDay = 0;\n int hour = 0;\n while (value > 0)\n {\n // Move forward until we find a working hour\n while (hour < 24)\n {\n if ((value & 0x1) != 0)\n {\n ++hoursPerDay;\n }\n value = value >> 1;\n ++hour;\n }\n }\n return hoursPerDay;\n }",
"public FailureDetectorConfig setCluster(Cluster cluster) {\n Utils.notNull(cluster);\n this.cluster = cluster;\n /*\n * FIXME: this is the hacky way to refresh the admin connection\n * verifier, but it'll just work. The clean way to do so is to have a\n * centralized metadata management, and all references of cluster object\n * point to that.\n */\n if(this.connectionVerifier instanceof AdminConnectionVerifier) {\n ((AdminConnectionVerifier) connectionVerifier).setCluster(cluster);\n }\n return this;\n }",
"public static rsskeytype get(nitro_service service) throws Exception{\n\t\trsskeytype obj = new rsskeytype();\n\t\trsskeytype[] response = (rsskeytype[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public List<MapRow> readTableConditional(Class<? extends TableReader> readerClass) throws IOException\n {\n List<MapRow> result;\n if (DatatypeConverter.getBoolean(m_stream))\n {\n result = readTable(readerClass);\n }\n else\n {\n result = Collections.emptyList();\n }\n return result;\n }",
"public static void withInstance(String url, Closure c) throws SQLException {\n Sql sql = null;\n try {\n sql = newInstance(url);\n c.call(sql);\n } finally {\n if (sql != null) sql.close();\n }\n }",
"public Collection<Group> search(String text, int perPage, int page) throws FlickrException {\r\n GroupList<Group> groupList = new GroupList<Group>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SEARCH);\r\n\r\n parameters.put(\"text\", text);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\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 Element groupsElement = response.getPayload();\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n groupList.setPage(XMLUtilities.getIntAttribute(groupsElement, \"page\"));\r\n groupList.setPages(XMLUtilities.getIntAttribute(groupsElement, \"pages\"));\r\n groupList.setPerPage(XMLUtilities.getIntAttribute(groupsElement, \"perpage\"));\r\n groupList.setTotal(XMLUtilities.getIntAttribute(groupsElement, \"total\"));\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"nsid\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n groupList.add(group);\r\n }\r\n return groupList;\r\n }",
"public List<Dependency> getModuleDependencies(final String moduleName, final String moduleVersion, final Boolean fullRecursive, final Boolean corporate, final Boolean thirdParty) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactDependencies(moduleName, moduleVersion));\n final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_TEST_PARAM, \"true\")\n .queryParam(ServerAPI.RECURSIVE_PARAM, fullRecursive.toString())\n .queryParam(ServerAPI.SHOW_CORPORATE_PARAM, corporate.toString())\n .queryParam(ServerAPI.SHOW_THIRPARTY_PARAM, thirdParty.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module ancestors \", moduleName, moduleVersion);\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\n return response.getEntity(new GenericType<List<Dependency>>(){});\n }",
"public static String soundex(String str) {\n if (str.length() < 1)\n return \"\"; // no soundex key for the empty string (could use 000)\n \n char[] key = new char[4];\n key[0] = str.charAt(0);\n int pos = 1;\n char prev = '0';\n for (int ix = 1; ix < str.length() && pos < 4; ix++) {\n char ch = str.charAt(ix);\n int charno;\n if (ch >= 'A' && ch <= 'Z')\n charno = ch - 'A';\n else if (ch >= 'a' && ch <= 'z')\n charno = ch - 'a';\n else\n continue;\n\n if (number[charno] != '0' && number[charno] != prev)\n key[pos++] = number[charno];\n prev = number[charno];\n }\n\n for ( ; pos < 4; pos++)\n key[pos] = '0';\n\n return new String(key);\n }"
] |
Creates the parents of nested XML elements if necessary.
@param xmlContent the XML content that is edited.
@param xmlPath the path of the (nested) element, for which the parents should be created
@param l the locale for which the XML content is edited. | [
"protected void createParentXmlElements(CmsXmlContent xmlContent, String xmlPath, Locale l) {\n\n if (CmsXmlUtils.isDeepXpath(xmlPath)) {\n String parentPath = CmsXmlUtils.removeLastXpathElement(xmlPath);\n if (null == xmlContent.getValue(parentPath, l)) {\n createParentXmlElements(xmlContent, parentPath, l);\n xmlContent.addValue(m_cms, parentPath, l, CmsXmlUtils.getXpathIndexInt(parentPath) - 1);\n }\n }\n\n }"
] | [
"public void stopDrag() {\n mPhysicsDragger.stopDrag();\n\n mPhysicsContext.runOnPhysicsThread(new Runnable() {\n @Override\n public void run() {\n if (mRigidBodyDragMe != null) {\n NativePhysics3DWorld.stopDrag(getNative());\n mRigidBodyDragMe = null;\n }\n }\n });\n }",
"public void setIssueTrackerInfo(BuildInfoBuilder builder) {\n Issues issues = new Issues();\n issues.setAggregateBuildIssues(aggregateBuildIssues);\n issues.setAggregationBuildStatus(aggregationBuildStatus);\n issues.setTracker(new IssueTracker(\"JIRA\", issueTrackerVersion));\n Set<Issue> affectedIssuesSet = IssuesTrackerUtils.getAffectedIssuesSet(affectedIssues);\n if (!affectedIssuesSet.isEmpty()) {\n issues.setAffectedIssues(affectedIssuesSet);\n }\n builder.issues(issues);\n }",
"public static int nullity(SingularValueDecomposition_F64 svd , double threshold ) {\n int ret = 0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n int numCol = svd.numCols();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] <= threshold) ret++;\n }\n return ret + numCol-N;\n }",
"public static base_responses update(nitro_service client, nd6ravariables resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnd6ravariables updateresources[] = new nd6ravariables[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nd6ravariables();\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].ceaserouteradv = resources[i].ceaserouteradv;\n\t\t\t\tupdateresources[i].sendrouteradv = resources[i].sendrouteradv;\n\t\t\t\tupdateresources[i].srclinklayeraddroption = resources[i].srclinklayeraddroption;\n\t\t\t\tupdateresources[i].onlyunicastrtadvresponse = resources[i].onlyunicastrtadvresponse;\n\t\t\t\tupdateresources[i].managedaddrconfig = resources[i].managedaddrconfig;\n\t\t\t\tupdateresources[i].otheraddrconfig = resources[i].otheraddrconfig;\n\t\t\t\tupdateresources[i].currhoplimit = resources[i].currhoplimit;\n\t\t\t\tupdateresources[i].maxrtadvinterval = resources[i].maxrtadvinterval;\n\t\t\t\tupdateresources[i].minrtadvinterval = resources[i].minrtadvinterval;\n\t\t\t\tupdateresources[i].linkmtu = resources[i].linkmtu;\n\t\t\t\tupdateresources[i].reachabletime = resources[i].reachabletime;\n\t\t\t\tupdateresources[i].retranstime = resources[i].retranstime;\n\t\t\t\tupdateresources[i].defaultlifetime = resources[i].defaultlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<Symmetry454Date> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<Symmetry454Date>) super.localDateTime(temporal);\n }",
"public static ExtensibleConfigurationPersister createDomainXmlConfigurationPersister(final ConfigurationFile file, ExecutorService executorService, ExtensionRegistry extensionRegistry, final HostControllerEnvironment environment) {\n DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry);\n\n boolean suppressLoad = false;\n ConfigurationFile.InteractionPolicy policy = file.getInteractionPolicy();\n final boolean isReloaded = environment.getRunningModeControl().isReloaded();\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW && (file.getBootFile().exists() && file.getBootFile().length() != 0))) {\n throw HostControllerLogger.ROOT_LOGGER.cannotOverwriteDomainXmlWithEmpty(file.getBootFile().getName());\n }\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW || policy == ConfigurationFile.InteractionPolicy.DISCARD)) {\n suppressLoad = true;\n }\n\n BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), \"domain\"), domainXml, domainXml, suppressLoad);\n for (Namespace namespace : Namespace.domainValues()) {\n if (!namespace.equals(Namespace.CURRENT)) {\n persister.registerAdditionalRootElement(new QName(namespace.getUriString(), \"domain\"), domainXml);\n }\n }\n extensionRegistry.setWriterRegistry(persister);\n return persister;\n }",
"@Override\n public boolean accept(File file) {\n //All directories are added in the least that can be read by the Application\n if (file.isDirectory()&&file.canRead())\n { return true;\n }\n else if(properties.selection_type==DialogConfigs.DIR_SELECT)\n { /* True for files, If the selection type is Directory type, ie.\n * Only directory has to be selected from the list, then all files are\n * ignored.\n */\n return false;\n }\n else\n { /* Check whether name of the file ends with the extension. Added if it\n * does.\n */\n String name = file.getName().toLowerCase(Locale.getDefault());\n for (String ext : validExtensions) {\n if (name.endsWith(ext)) {\n return true;\n }\n }\n }\n return false;\n }",
"protected boolean showMoreEntries(Calendar nextDate, int previousOccurrences) {\n\n switch (getSerialEndType()) {\n case DATE:\n boolean moreByDate = nextDate.getTimeInMillis() < m_endMillis;\n boolean moreByOccurrences = previousOccurrences < CmsSerialDateUtil.getMaxEvents();\n if (moreByDate && !moreByOccurrences) {\n m_hasTooManyOccurrences = Boolean.TRUE;\n }\n return moreByDate && moreByOccurrences;\n case TIMES:\n case SINGLE:\n return previousOccurrences < getOccurrences();\n default:\n throw new IllegalArgumentException();\n }\n }",
"public static tmsessionpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\ttmsessionpolicy_binding obj = new tmsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\ttmsessionpolicy_binding response = (tmsessionpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Use this API to fetch all the dnsnsecrec resources that are configured on netscaler.
This uses dnsnsecrec_args which is a way to provide additional arguments while fetching the resources. | [
"public static dnsnsecrec[] get(nitro_service service, dnsnsecrec_args args) throws Exception{\n\t\tdnsnsecrec obj = new dnsnsecrec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnsnsecrec[] response = (dnsnsecrec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}"
] | [
"private void handleSendDataRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Send Data Request\");\n\t\t\n\t\tint callbackId = incomingMessage.getMessagePayloadByte(0);\n\t\tTransmissionState status = TransmissionState.getTransmissionState(incomingMessage.getMessagePayloadByte(1));\n\t\tSerialMessage originalMessage = this.lastSentMessage;\n\t\t\n\t\tif (status == null) {\n\t\t\tlogger.warn(\"Transmission state not found, ignoring.\");\n\t\t\treturn;\n\t\t}\n\n\t\tlogger.debug(\"CallBack ID = {}\", callbackId);\n\t\tlogger.debug(String.format(\"Status = %s (0x%02x)\", status.getLabel(), status.getKey()));\n\t\t\n\t\tif (originalMessage == null || originalMessage.getCallbackId() != callbackId) {\n\t\t\tlogger.warn(\"Already processed another send data request for this callback Id, ignoring.\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tswitch (status) {\n\t\t\tcase COMPLETE_OK:\n\t\t\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\t\tnode.resetResendCount();\n\t\t\t\t\n\t\t\t\t// in case we received a ping response and the node is alive, we proceed with the next node stage for this node.\n\t\t\t\tif (node != null && node.getNodeStage() == NodeStage.NODEBUILDINFO_PING) {\n\t\t\t\t\tnode.advanceNodeStage();\n\t\t\t\t}\n\t\t\t\tif (incomingMessage.getMessageClass() == originalMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase COMPLETE_NO_ACK:\n\t\t\tcase COMPLETE_FAIL:\n\t\t\tcase COMPLETE_NOT_IDLE:\n\t\t\tcase COMPLETE_NOROUTE:\n\t\t\t\ttry {\n\t\t\t\t\thandleFailedSendDataRequest(originalMessage);\n\t\t\t\t} finally {\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\tdefault:\n\t\t}\n\t}",
"public synchronized void reset() {\n this.authorizerDescription = StandardRBACAuthorizer.AUTHORIZER_DESCRIPTION;\n this.useIdentityRoles = this.nonFacadeMBeansSensitive = false;\n this.roleMappings = new HashMap<String, RoleMappingImpl>();\n RoleMaps oldRoleMaps = this.roleMaps;\n this.roleMaps = new RoleMaps(authorizerDescription.getStandardRoles(), Collections.<String, ScopedRole>emptyMap());\n for (ScopedRole role : oldRoleMaps.scopedRoles.values()) {\n for (ScopedRoleListener listener : scopedRoleListeners) {\n try {\n listener.scopedRoleRemoved(role);\n } catch (Exception ignored) {\n // TODO log an ERROR\n }\n }\n }\n }",
"public AlbumArt requestArtworkFrom(final DataReference artReference, final CdjStatus.TrackType trackType) {\n ensureRunning();\n AlbumArt artwork = findArtInMemoryCaches(artReference); // First check the in-memory artwork caches.\n if (artwork == null) {\n artwork = requestArtworkInternal(artReference, trackType, false);\n }\n return artwork;\n }",
"public static void showBooks(final ListOfBooks booksList){\n \t\n \tif(booksList != null && booksList.getBook() != null && !booksList.getBook().isEmpty()){\n \t\tList<BookType> books = booksList.getBook();\n \t\tSystem.out.println(\"\\nNumber of books: \" + books.size());\n \t\tint cnt = 0;\n \t\tfor (BookType book : books) {\n \t\t\tSystem.out.println(\"\\nBookNum: \" + (cnt++ + 1));\n \t\t\tList<PersonType> authors = book.getAuthor();\n \t\t\tif(authors != null && !authors.isEmpty()){\n \t\t\t\tfor (PersonType author : authors) {\n \t\t\t\t\tSystem.out.println(\"Author: \" + author.getFirstName() + \n \t\t\t\t\t\t\t\t\t\t\" \" + author.getLastName());\n\t\t\t\t\t}\n \t\t\t}\n \t\t\tSystem.out.println(\"Title: \" + book.getTitle());\n \t\t\tSystem.out.println(\"Year: \" + book.getYearPublished());\n \t\t\tif(book.getISBN()!=null){\n \t\t\t\tSystem.out.println(\"ISBN: \" + book.getISBN());\n \t\t\t}\n\t\t\t\t\n\t\t\t}\n \t}else{\n \t\tSystem.out.println(\"List of books is empty\");\n \t}\n \tSystem.out.println(\"\");\n\t}",
"private String escapeText(StringBuilder sb, String text)\n {\n int length = text.length();\n char c;\n\n sb.setLength(0);\n\n for (int loop = 0; loop < length; loop++)\n {\n c = text.charAt(loop);\n\n switch (c)\n {\n case '<':\n {\n sb.append(\"<\");\n break;\n }\n\n case '>':\n {\n sb.append(\">\");\n break;\n }\n\n case '&':\n {\n sb.append(\"&\");\n break;\n }\n\n default:\n {\n if (validXMLCharacter(c))\n {\n if (c > 127)\n {\n sb.append(\"&#\" + (int) c + \";\");\n }\n else\n {\n sb.append(c);\n }\n }\n\n break;\n }\n }\n }\n\n return (sb.toString());\n }",
"@Override public void render() {\n Video video = getContent();\n renderThumbnail(video);\n renderTitle(video);\n renderMarker(video);\n renderLabel();\n }",
"public void refresh() {\n this.getRefreshLock().writeLock().lock();\n\n try {\n this.authenticate();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n this.getRefreshLock().writeLock().unlock();\n throw e;\n }\n\n this.notifyRefresh();\n this.getRefreshLock().writeLock().unlock();\n }",
"private void processCalendarException(ProjectCalendar calendar, Row row)\n {\n Date fromDate = row.getDate(\"CD_FROM_DATE\");\n Date toDate = row.getDate(\"CD_TO_DATE\");\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n if (working)\n {\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME1\"), row.getDate(\"CD_TO_TIME1\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME2\"), row.getDate(\"CD_TO_TIME2\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME3\"), row.getDate(\"CD_TO_TIME3\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME4\"), row.getDate(\"CD_TO_TIME4\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME5\"), row.getDate(\"CD_TO_TIME5\")));\n }\n }",
"public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n //\n // Retrieve the LHS value\n //\n FieldType field = m_leftValue;\n Object lhs;\n\n if (field == null)\n {\n lhs = null;\n }\n else\n {\n lhs = container.getCurrentValue(field);\n switch (field.getDataType())\n {\n case DATE:\n {\n if (lhs != null)\n {\n lhs = DateHelper.getDayStartDate((Date) lhs);\n }\n break;\n }\n\n case DURATION:\n {\n if (lhs != null)\n {\n Duration dur = (Duration) lhs;\n lhs = dur.convertUnits(TimeUnit.HOURS, m_properties);\n }\n else\n {\n lhs = Duration.getInstance(0, TimeUnit.HOURS);\n }\n break;\n }\n\n case STRING:\n {\n lhs = lhs == null ? \"\" : lhs;\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n //\n // Retrieve the RHS values\n //\n Object[] rhs;\n if (m_symbolicValues == true)\n {\n rhs = processSymbolicValues(m_workingRightValues, container, promptValues);\n }\n else\n {\n rhs = m_workingRightValues;\n }\n\n //\n // Evaluate\n //\n boolean result;\n switch (m_operator)\n {\n case AND:\n case OR:\n {\n result = evaluateLogicalOperator(container, promptValues);\n break;\n }\n\n default:\n {\n result = m_operator.evaluate(lhs, rhs);\n break;\n }\n }\n\n return result;\n }"
] |
Creates a real agent in the platform
@param agent_name
The name that the agent is gonna have in the platform
@param path
The path of the description (xml) of the agent | [
"public void createAgent(String agent_name, String path) {\n IComponentIdentifier agent = cmsService.createComponent(agent_name,\n path, null, null).get(new ThreadSuspendable());\n createdAgents.put(agent_name, agent);\n }"
] | [
"public int deleteById(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedDelete == null) {\n\t\t\tmappedDelete = MappedDelete.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedDelete.deleteById(databaseConnection, id, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}",
"public List<String> getPropertyPaths() {\n List<String> result = new ArrayList<String>();\n\n for (String property : this.values.names()) {\n if (!property.startsWith(\"$\")) {\n result.add(this.propertyToPath(property));\n }\n }\n\n return result;\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}",
"private String generateValue() {\r\n\r\n String result = \"\";\r\n for (CmsCheckBox checkbox : m_checkboxes) {\r\n if (checkbox.isChecked()) {\r\n result += checkbox.getInternalValue() + \",\";\r\n }\r\n }\r\n if (result.contains(\",\")) {\r\n result = result.substring(0, result.lastIndexOf(\",\"));\r\n }\r\n return result;\r\n }",
"private void updateDefaultTimeAndSizeRollingAppender(final FoundationFileRollingAppender appender) {\n\n\t\tif (appender.getDatePattern().trim().length() == 0) {\n\t\t\tappender.setDatePattern(FoundationLoggerConstants.DEFAULT_DATE_PATTERN.toString());\n\t\t}\n\t\t\n\t\tString maxFileSizeKey = \"log4j.appender.\"+appender.getName()+\".MaxFileSize\";\n\t\tappender.setMaxFileSize(FoundationLogger.log4jConfigProps.getProperty(maxFileSizeKey, FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString()));\n\n//\t\tif (appender.getMaxFileSize() == null || appender.getMaxFileSize().equals(FoundationLoggerConstants.DEFAULT_FILE_SIZE.toString())) {\n//\t\t\tappender.setMaxFileSize(FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString());\n//\t\t}\n\n\t\tString maxRollCountKey = \"log4j.appender.\"+appender.getName()+\".MaxRollFileCount\";\n\t\tappender.setMaxRollFileCount(Integer.parseInt(FoundationLogger.log4jConfigProps.getProperty(maxRollCountKey,\"100\")));\n\t}",
"public static String getClassName(Class<?> c) {\n String name = c.getName();\n return name.substring(name.lastIndexOf('.') + 1, name.length());\n }",
"private SearchableItem buildSearchableItem(Message menuItem) {\n return new SearchableItem((int) ((NumberField) menuItem.arguments.get(1)).getValue(),\n ((StringField) menuItem.arguments.get(3)).getValue());\n }",
"private boolean setNextIterator()\r\n {\r\n boolean retval = false;\r\n // first, check if the activeIterator is null, and set it.\r\n if (m_activeIterator == null)\r\n {\r\n if (m_rsIterators.size() > 0)\r\n {\r\n m_activeIteratorIndex = 0;\r\n m_currentCursorPosition = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n }\r\n }\r\n else if (!m_activeIterator.hasNext())\r\n {\r\n if (m_rsIterators.size() > (m_activeIteratorIndex + 1))\r\n {\r\n // we still have iterators in the collection, move to the\r\n // next one, increment the counter, and set the active\r\n // iterator.\r\n m_activeIteratorIndex++;\r\n m_currentCursorPosition = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n retval = true;\r\n }\r\n }\r\n\r\n return retval;\r\n }",
"public SpinJsonDataFormatException unableToParseValue(String expectedType, JsonNodeType type) {\n return new SpinJsonDataFormatException(exceptionMessage(\"002\", \"Expected '{}', got '{}'\", expectedType, type.toString()));\n }"
] |
Parses the configuration node and provides a pipeline configuration without any extensions marked for loading.
The configuration node is supposed to conform to the pipeline configuration JSON schema.
<p>The caller is supposed to use the methods from the builder to add/find extension classes that will be used in
the analysis.
<p>Note that the returned pipeline configuration might not contain all the extensions available in
the classloader depending on the include/exclude filters in the configuration.
@param json the configuration node
@return a pipeline configuration parsed from the configuration
@see Builder#build() | [
"public static PipelineConfiguration.Builder parse(ModelNode json) {\n ModelNode analyzerIncludeNode = json.get(\"analyzers\").get(\"include\");\n ModelNode analyzerExcludeNode = json.get(\"analyzers\").get(\"exclude\");\n ModelNode filterIncludeNode = json.get(\"filters\").get(\"include\");\n ModelNode filterExcludeNode = json.get(\"filters\").get(\"exclude\");\n ModelNode transformIncludeNode = json.get(\"transforms\").get(\"include\");\n ModelNode transformExcludeNode = json.get(\"transforms\").get(\"exclude\");\n ModelNode reporterIncludeNode = json.get(\"reporters\").get(\"include\");\n ModelNode reporterExcludeNode = json.get(\"reporters\").get(\"exclude\");\n\n return builder()\n .withTransformationBlocks(json.get(\"transformBlocks\"))\n .withAnalyzerExtensionIdsInclude(asStringList(analyzerIncludeNode))\n .withAnalyzerExtensionIdsExclude(asStringList(analyzerExcludeNode))\n .withFilterExtensionIdsInclude(asStringList(filterIncludeNode))\n .withFilterExtensionIdsExclude(asStringList(filterExcludeNode))\n .withTransformExtensionIdsInclude(asStringList(transformIncludeNode))\n .withTransformExtensionIdsExclude(asStringList(transformExcludeNode))\n .withReporterExtensionIdsInclude(asStringList(reporterIncludeNode))\n .withReporterExtensionIdsExclude(asStringList(reporterExcludeNode));\n }"
] | [
"public static void writeFully(ByteBuffer buffer, WritableByteChannel channel) throws IOException {\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\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 }",
"private void updateMax(MtasRBTreeNode n, MtasRBTreeNode c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n }\n }",
"private void disableTalkBack() {\n GVRSceneObject[] sceneObjects = mGvrContext.getMainScene().getWholeSceneObjects();\n for (GVRSceneObject sceneObject : sceneObjects) {\n if (sceneObject instanceof GVRAccessiblityObject)\n if (((GVRAccessiblityObject) sceneObject).getTalkBack() != null)\n ((GVRAccessiblityObject) sceneObject).getTalkBack().setActive(false);\n\n }\n }",
"public static List getAt(Matcher self, Collection indices) {\n List result = new ArrayList();\n for (Object value : indices) {\n if (value instanceof Range) {\n result.addAll(getAt(self, (Range) value));\n } else {\n int idx = DefaultTypeTransformation.intUnbox(value);\n result.add(getAt(self, idx));\n }\n }\n return result;\n }",
"@POST\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response addCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an add 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 add!\");\n throw new WebApplicationException(Response.serverError().status(HttpStatus.BAD_REQUEST_400)\n .entity(\"CorporateGroupId to add should be in the query content.\").build());\n }\n\n getOrganizationHandler().addCorporateGroupId(organizationId, corporateGroupId);\n return Response.ok().status(HttpStatus.CREATED_201).build();\n }",
"public void putAll(Map<KEY, VALUE> mapDataToPut) {\n int targetSize = maxSize - mapDataToPut.size();\n if (maxSize > 0 && values.size() > targetSize) {\n evictToTargetSize(targetSize);\n }\n Set<Entry<KEY, VALUE>> entries = mapDataToPut.entrySet();\n for (Entry<KEY, VALUE> entry : entries) {\n put(entry.getKey(), entry.getValue());\n }\n }",
"private Object getUdfValue(UDFAssignmentType udf)\n {\n if (udf.getCostValue() != null)\n {\n return udf.getCostValue();\n }\n \n if (udf.getDoubleValue() != null)\n {\n return udf.getDoubleValue();\n }\n \n if (udf.getFinishDateValue() != null)\n {\n return udf.getFinishDateValue();\n }\n \n if (udf.getIndicatorValue() != null)\n {\n return udf.getIndicatorValue();\n }\n \n if (udf.getIntegerValue() != null)\n {\n return udf.getIntegerValue();\n }\n \n if (udf.getStartDateValue() != null)\n {\n return udf.getStartDateValue();\n }\n \n if (udf.getTextValue() != null)\n {\n return udf.getTextValue();\n }\n \n return null;\n }",
"private TypeArgSignature getTypeArgSignature(Type type) {\r\n\t\tif (type instanceof WildcardType) {\r\n\t\t\tWildcardType wildcardType = (WildcardType) type;\r\n\t\t\tType lowerBound = wildcardType.getLowerBounds().length == 0 ? null\r\n\t\t\t\t\t: wildcardType.getLowerBounds()[0];\r\n\t\t\tType upperBound = wildcardType.getUpperBounds().length == 0 ? null\r\n\t\t\t\t\t: wildcardType.getUpperBounds()[0];\r\n\r\n\t\t\tif (lowerBound == null && Object.class.equals(upperBound)) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.UNBOUNDED_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(upperBound));\r\n\t\t\t} else if (lowerBound == null && upperBound != null) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.UPPERBOUND_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(upperBound));\r\n\t\t\t} else if (lowerBound != null) {\r\n\t\t\t\treturn new TypeArgSignature(\r\n\t\t\t\t\t\tTypeArgSignature.LOWERBOUND_WILDCARD,\r\n\t\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(lowerBound));\r\n\t\t\t} else {\r\n\t\t\t\tthrow new RuntimeException(\"Invalid type\");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn new TypeArgSignature(TypeArgSignature.NO_WILDCARD,\r\n\t\t\t\t\t(FieldTypeSignature) getFullTypeSignature(type));\r\n\t\t}\r\n\t}"
] |
Gets the Symmetric Kullback-Leibler distance.
This metric is valid only for real and positive P and Q.
@param p P vector.
@param q Q vector.
@return The Symmetric Kullback Leibler distance between p and q. | [
"public static double SymmetricKullbackLeibler(double[] p, double[] q) {\n double dist = 0;\n for (int i = 0; i < p.length; i++) {\n dist += (p[i] - q[i]) * (Math.log(p[i]) - Math.log(q[i]));\n }\n\n return dist;\n }"
] | [
"public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }",
"public static String toXml(DeploymentDescriptor descriptor) {\n try {\n\n Marshaller marshaller = getContext().createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);\n marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, \"http://www.jboss.org/jbpm deployment-descriptor.xsd\");\n marshaller.setSchema(schema);\n StringWriter stringWriter = new StringWriter();\n\n // clone the object and cleanup transients\n DeploymentDescriptor clone = ((DeploymentDescriptorImpl) descriptor).clearClone();\n\n marshaller.marshal(clone, stringWriter);\n String output = stringWriter.toString();\n\n return output;\n } catch (Exception e) {\n throw new RuntimeException(\"Unable to generate xml from deployment descriptor\", e);\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 static double distance(double lat1, double lon1,\n double lat2, double lon2) {\n double dLat = Math.toRadians(lat2-lat1);\n double dLon = Math.toRadians(lon2-lon1);\n lat1 = Math.toRadians(lat1);\n lat2 = Math.toRadians(lat2);\n\n double a = Math.sin(dLat/2) * Math.sin(dLat/2) +\n Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); \n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n return R * c;\n }",
"public boolean needToSetCategoryFolder() {\n\n if (m_adeModuleVersion == null) {\n return true;\n }\n CmsModuleVersion categoryFolderUpdateVersion = new CmsModuleVersion(\"9.0.0\");\n return (m_adeModuleVersion.compareTo(categoryFolderUpdateVersion) == -1);\n }",
"public void addFkToThisClass(String column)\r\n {\r\n if (fksToThisClass == null)\r\n {\r\n fksToThisClass = new Vector();\r\n }\r\n fksToThisClass.add(column);\r\n fksToThisClassAry = null;\r\n }",
"public void delete(Object element, boolean testForEquality) {\r\n\tint index = indexOfFromTo(element, 0, size-1, testForEquality);\r\n\tif (index>=0) removeFromTo(index,index);\r\n}",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addBooleanFilter(String attribute, Boolean value) {\n booleanFilterMap.put(attribute, value);\n rebuildQueryFacetFilters();\n return this;\n }",
"public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) {\n recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0);\n }"
] |
Use this API to add appfwjsoncontenttype. | [
"public static base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"public static String fill(int color) {\n final String colorCode = Integer.toHexString(color & 0xFFFFFF); // Strip alpha\n return FILTER_FILL + \"(\" + colorCode + \")\";\n }",
"public static FullTypeSignature getTypeSignature(String typeSignatureString,\n\t\t\tboolean useInternalFormFullyQualifiedName) {\n\t\tString key;\n\t\tif (!useInternalFormFullyQualifiedName) {\n\t\t\tkey = typeSignatureString.replace('.', '/')\n\t\t\t\t\t.replace('$', '.');\n\t\t} else {\n\t\t\tkey = typeSignatureString;\n\t\t}\n\n\t\t// we always use the internal form as a key for cache\n\t\tFullTypeSignature typeSignature = typeSignatureCache\n\t\t\t\t.get(key);\n\t\tif (typeSignature == null) {\n\t\t\tClassFileTypeSignatureParser typeSignatureParser = new ClassFileTypeSignatureParser(\n\t\t\t\t\ttypeSignatureString);\n\t\t\ttypeSignatureParser.setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName);\n\t\t\ttypeSignature = typeSignatureParser.parseTypeSignature();\n\t\t\ttypeSignatureCache.put(typeSignatureString, typeSignature);\n\t\t}\n\t\treturn typeSignature;\n\t}",
"private static void logVersionWarnings(String label1, String version1, String label2, String version2) {\n\t\tif (version1 == null) {\n\t\t\tif (version2 != null) {\n\t\t\t\twarning(null, \"Unknown version\", \" for {}, version for {} is '{}'\", new Object[] { label1, label2,\n\t\t\t\t\t\tversion2 });\n\t\t\t}\n\t\t} else {\n\t\t\tif (version2 == null) {\n\t\t\t\twarning(null, \"Unknown version\", \" for {}, version for {} is '{}'\", new Object[] { label2, label1,\n\t\t\t\t\t\tversion1 });\n\t\t\t} else if (!version1.equals(version2)) {\n\t\t\t\twarning(null, \"Mismatched versions\", \": {} is '{}', while {} is '{}'\", new Object[] { label1, version1,\n\t\t\t\t\t\tlabel2, version2 });\n\t\t\t}\n\t\t}\n\t}",
"public static void setPropertySafely(Marshaller marshaller, String name, Object value) {\n try {\n marshaller.setProperty(name, value);\n } catch (PropertyException e) {\n LOGGER.warn(String.format(\"Can't set \\\"%s\\\" property to given marshaller\", name), e);\n }\n }",
"public void beforeCompletion()\r\n {\r\n // avoid redundant calls\r\n if(beforeCompletionCall) return;\r\n\r\n log.info(\"Method beforeCompletion was called\");\r\n int status = Status.STATUS_UNKNOWN;\r\n try\r\n {\r\n JTATxManager mgr = (JTATxManager) getImplementation().getTxManager();\r\n status = mgr.getJTATransaction().getStatus();\r\n // ensure proper work, check all possible status\r\n // normally only check for 'STATUS_MARKED_ROLLBACK' is necessary\r\n if(status == Status.STATUS_MARKED_ROLLBACK\r\n || status == Status.STATUS_ROLLEDBACK\r\n || status == Status.STATUS_ROLLING_BACK\r\n || status == Status.STATUS_UNKNOWN\r\n || status == Status.STATUS_NO_TRANSACTION)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Can't prepare for commit, because tx status was \"\r\n + TxUtil.getStatusString(status) + \". Do internal cleanup only.\");\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Synchronization#beforeCompletion: Prepare for commit\");\r\n }\r\n // write objects to database\r\n prepareCommit();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Error while prepare for commit\", e);\r\n if(e instanceof LockNotGrantedException)\r\n {\r\n throw (LockNotGrantedException) e;\r\n }\r\n else if(e instanceof TransactionAbortedException)\r\n {\r\n throw (TransactionAbortedException) e;\r\n }\r\n else if(e instanceof ODMGRuntimeException)\r\n {\r\n throw (ODMGRuntimeException) e;\r\n }\r\n else\r\n { \r\n throw new ODMGRuntimeException(\"Method beforeCompletion() fails, status of JTA-tx was \"\r\n + TxUtil.getStatusString(status) + \", message: \" + e.getMessage());\r\n }\r\n\r\n }\r\n finally\r\n {\r\n beforeCompletionCall = true;\r\n setInExternTransaction(false);\r\n internalCleanup();\r\n }\r\n }",
"private void populateResourceAssignment(Record record, ResourceAssignment assignment) throws MPXJException\n {\n //\n // Handle malformed MPX files - ensure that we can locate the resource\n // using either the Unique ID attribute or the ID attribute.\n //\n Resource resource = m_projectFile.getResourceByUniqueID(record.getInteger(12));\n if (resource == null)\n {\n resource = m_projectFile.getResourceByID(record.getInteger(0));\n }\n\n assignment.setUnits(record.getUnits(1));\n assignment.setWork(record.getDuration(2));\n assignment.setBaselineWork(record.getDuration(3));\n assignment.setActualWork(record.getDuration(4));\n assignment.setOvertimeWork(record.getDuration(5));\n assignment.setCost(record.getCurrency(6));\n assignment.setBaselineCost(record.getCurrency(7));\n assignment.setActualCost(record.getCurrency(8));\n assignment.setStart(record.getDateTime(9));\n assignment.setFinish(record.getDateTime(10));\n assignment.setDelay(record.getDuration(11));\n\n //\n // Calculate the remaining work\n //\n Duration work = assignment.getWork();\n Duration actualWork = assignment.getActualWork();\n if (work != null && actualWork != null)\n {\n if (work.getUnits() != actualWork.getUnits())\n {\n actualWork = actualWork.convertUnits(work.getUnits(), m_projectFile.getProjectProperties());\n }\n\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }",
"public void removeAccessory(HomekitAccessory accessory) {\n this.registry.remove(accessory);\n logger.info(\"Removed accessory \" + accessory.getLabel());\n if (started) {\n registry.reset();\n webHandler.resetConnections();\n }\n }",
"private Task readTask(ChildTaskContainer parent, Integer id)\n {\n Table a0 = getTable(\"A0TAB\");\n Table a1 = getTable(\"A1TAB\");\n Table a2 = getTable(\"A2TAB\");\n Table a3 = getTable(\"A3TAB\");\n Table a4 = getTable(\"A4TAB\");\n\n Task task = parent.addTask();\n MapRow a1Row = a1.find(id);\n MapRow a2Row = a2.find(id);\n\n setFields(A0TAB_FIELDS, a0.find(id), task);\n setFields(A1TAB_FIELDS, a1Row, task);\n setFields(A2TAB_FIELDS, a2Row, task);\n setFields(A3TAB_FIELDS, a3.find(id), task);\n setFields(A5TAB_FIELDS, a4.find(id), task);\n\n task.setStart(task.getEarlyStart());\n task.setFinish(task.getEarlyFinish());\n if (task.getName() == null)\n {\n task.setName(task.getText(1));\n }\n\n m_eventManager.fireTaskReadEvent(task);\n\n return task;\n }",
"public static <T> Class<T> loadClass(String className, ResourceLoader resourceLoader) {\n try {\n return cast(resourceLoader.classForName(className));\n } catch (ResourceLoadingException e) {\n return null;\n } catch (SecurityException e) {\n return null;\n }\n }"
] |
I promise that this is always a collection of HazeltaskTasks | [
"public Collection<HazeltaskTask<GROUP>> call() throws Exception {\n try {\n if(isShutdownNow)\n return this.getDistributedExecutorService().shutdownNowWithHazeltask();\n else\n this.getDistributedExecutorService().shutdown();\n } catch(IllegalStateException e) {}\n \n return Collections.emptyList();\n }"
] | [
"public void fireRelationReadEvent(Relation relation)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.relationRead(relation);\n }\n }\n }",
"public void setVariable(String name, Object value) {\n if (variables == null)\n variables = new LinkedHashMap();\n variables.put(name, value);\n }",
"@Override\n public DecompilationResult decompileClassFile(Path rootDir, Path classFilePath, Path outputDir)\n throws DecompilationException\n {\n Checks.checkDirectoryToBeRead(rootDir.toFile(), \"Classes root dir\");\n File classFile = classFilePath.toFile();\n Checks.checkFileToBeRead(classFile, \"Class file\");\n Checks.checkDirectoryToBeFilled(outputDir.toFile(), \"Output directory\");\n\n log.info(\"Decompiling .class '\" + classFilePath + \"' to '\" + outputDir + \"' from: '\" + rootDir + \"'\");\n\n String name = classFilePath.normalize().toAbsolutePath().toString().substring(rootDir.toAbsolutePath().toString().length() + 1);\n final String typeName = StringUtils.removeEnd(name, \".class\");// .replace('/', '.');\n\n DecompilationResult result = new DecompilationResult();\n try\n {\n DecompilerSettings settings = getDefaultSettings(outputDir.toFile());\n this.procyonConf.setDecompilerSettings(settings); // TODO: This is horrible mess.\n\n final ITypeLoader typeLoader = new CompositeTypeLoader(new WindupClasspathTypeLoader(rootDir.toString()), new ClasspathTypeLoader());\n WindupMetadataSystem metadataSystem = new WindupMetadataSystem(typeLoader);\n File outputFile = this.decompileType(settings, metadataSystem, typeName);\n result.addDecompiled(Collections.singletonList(classFilePath.toString()), outputFile.getAbsolutePath());\n }\n catch (Throwable e)\n {\n DecompilationFailure failure = new DecompilationFailure(\"Error during decompilation of \"\n + classFilePath.toString() + \":\\n \" + e.getMessage(), Collections.singletonList(name), e);\n log.severe(failure.getMessage());\n result.addFailure(failure);\n }\n\n return result;\n }",
"private boolean interpolationsDisagree(TrackPositionUpdate lastUpdate, TrackPositionUpdate currentUpdate) {\n long now = System.nanoTime();\n return Math.abs(interpolateTimeSinceUpdate(lastUpdate, now) - interpolateTimeSinceUpdate(currentUpdate, now)) >\n slack.get();\n }",
"public void initialize() {\n\t\tif (dataClass == null) {\n\t\t\tthrow new IllegalStateException(\"dataClass was never set on \" + getClass().getSimpleName());\n\t\t}\n\t\tif (tableName == null) {\n\t\t\ttableName = extractTableName(databaseType, dataClass);\n\t\t}\n\t}",
"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 void appointTempoMaster(int deviceNumber) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n appointTempoMaster(update);\n }",
"@Override\n public boolean decompose(DMatrixRMaj orig) {\n if( orig.numCols != orig.numRows )\n throw new IllegalArgumentException(\"Matrix must be square.\");\n if( orig.numCols <= 0 )\n return false;\n\n int N = orig.numRows;\n\n // compute a similar tridiagonal matrix\n if( !decomp.decompose(orig) )\n return false;\n\n if( diag == null || diag.length < N) {\n diag = new double[N];\n off = new double[N-1];\n }\n decomp.getDiagonal(diag,off);\n\n // Tell the helper to work with this matrix\n helper.init(diag,off,N);\n\n if( computeVectors ) {\n if( computeVectorsWithValues ) {\n return extractTogether();\n } else {\n return extractSeparate(N);\n }\n } else {\n return computeEigenValues();\n }\n }",
"public static ServiceName deploymentUnitName(String name, Phase phase) {\n return JBOSS_DEPLOYMENT_UNIT.append(name, phase.name());\n }"
] |
Save the current file as the given type.
@param file target file
@param type file type | [
"public void saveFile(File file, String type)\n {\n try\n {\n Class<? extends ProjectWriter> fileClass = WRITER_MAP.get(type);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot write files of type: \" + type);\n }\n\n ProjectWriter writer = fileClass.newInstance();\n writer.write(m_projectFile, file);\n }\n\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n }"
] | [
"public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }",
"@GwtIncompatible(\"Class.getDeclaredFields\")\n\tpublic ToStringBuilder addDeclaredFields() {\n\t\tField[] fields = instance.getClass().getDeclaredFields();\n\t\tfor(Field field : fields) {\n\t\t\taddField(field);\n\t\t}\n\t\treturn this;\n\t}",
"public void addClass(ClassDescriptorDef classDef)\r\n {\r\n classDef.setOwner(this);\r\n // Regardless of the format of the class name, we're using the fully qualified format\r\n // This is safe because of the package & class naming constraints of the Java language\r\n _classDefs.put(classDef.getQualifiedName(), classDef);\r\n }",
"public void setTimeWarp(String l) {\n\n long warp = CmsContextInfo.CURRENT_TIME;\n try {\n warp = Long.parseLong(l);\n } catch (NumberFormatException e) {\n // if parsing the time warp fails, it will be set to -1 (i.e. disabled)\n }\n m_settings.setTimeWarp(warp);\n }",
"public static crvserver_policymap_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcrvserver_policymap_binding obj = new crvserver_policymap_binding();\n\t\tobj.set_name(name);\n\t\tcrvserver_policymap_binding response[] = (crvserver_policymap_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public ParallelTaskBuilder prepareHttpPost(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.POST);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\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 void setSpeed(float newValue) {\n if (newValue < 0) newValue = 0;\n this.pitch.setValue( newValue );\n this.speed.setValue( newValue );\n }",
"public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, JRDataSource ds, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n\n JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, layoutManager, _parameters);\n jp = JasperFillManager.fillReport(jr, _parameters, ds);\n\n return jp;\n }"
] |
Support the range subscript operator for GString
@param text a GString
@param range a Range
@return the String of characters corresponding to the provided range
@since 2.3.7 | [
"public static String getAt(GString text, Range range) {\n return getAt(text.toString(), range);\n }"
] | [
"public void loadClass(String className) throws Exception {\n ClassInformation classInfo = classInformation.get(className);\n\n logger.info(\"Loading plugin.: {}, {}\", className, classInfo.pluginPath);\n\n // get URL for proxylib\n // need to load this also otherwise the annotations cannot be found later on\n File libFile = new File(proxyLibPath);\n URL libUrl = libFile.toURI().toURL();\n\n // store the last modified time of the plugin\n File pluginDirectoryFile = new File(classInfo.pluginPath);\n classInfo.lastModified = pluginDirectoryFile.lastModified();\n\n // load the plugin directory\n URL classURL = new File(classInfo.pluginPath).toURI().toURL();\n\n URL[] urls = new URL[] {classURL};\n URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader());\n\n // load the class\n Class<?> cls = child.loadClass(className);\n\n // put loaded class into classInfo\n classInfo.loadedClass = cls;\n classInfo.loaded = true;\n\n classInformation.put(className, classInfo);\n\n logger.info(\"Loaded plugin: {}, {} method(s)\", cls.toString(), cls.getDeclaredMethods().length);\n }",
"private void setNsid() throws FlickrException {\n\n if (username != null && !username.equals(\"\")) {\n Auth auth = null;\n if (authStore != null) {\n auth = authStore.retrieve(username); // assuming FileAuthStore is enhanced else need to\n // keep in user-level files.\n\n if (auth != null) {\n nsid = auth.getUser().getId();\n }\n }\n if (auth != null)\n return;\n\n Auth[] allAuths = authStore.retrieveAll();\n for (int i = 0; i < allAuths.length; i++) {\n if (username.equals(allAuths[i].getUser().getUsername())) {\n nsid = allAuths[i].getUser().getId();\n return;\n }\n }\n\n // For this to work: REST.java or PeopleInterface needs to change to pass apiKey\n // as the parameter to the call which is not authenticated.\n\n // Get nsid using flickr.people.findByUsername\n PeopleInterface peopleInterf = flickr.getPeopleInterface();\n User u = peopleInterf.findByUsername(username);\n if (u != null) {\n nsid = u.getId();\n }\n }\n }",
"private void loadResourceFile(URL configurationResourceUrl, Properties hotRodConfiguration) {\n\t\tif ( configurationResourceUrl != null ) {\n\t\t\ttry ( InputStream openStream = configurationResourceUrl.openStream() ) {\n\t\t\t\thotRodConfiguration.load( openStream );\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow log.failedLoadingHotRodConfigurationProperties( e );\n\t\t\t}\n\t\t}\n\t}",
"protected static Map<String, List<Statement>> addStatementToGroups(Statement statement, Map<String, List<Statement>> claims) {\n\t\tMap<String, List<Statement>> newGroups = new HashMap<>(claims);\n\t\tString pid = statement.getMainSnak().getPropertyId().getId();\n\t\tif(newGroups.containsKey(pid)) {\n\t\t\tList<Statement> newGroup = new ArrayList<>(newGroups.get(pid).size());\n\t\t\tboolean statementReplaced = false;\n\t\t\tfor(Statement existingStatement : newGroups.get(pid)) {\n\t\t\t\tif(existingStatement.getStatementId().equals(statement.getStatementId()) &&\n\t\t\t\t\t\t!existingStatement.getStatementId().isEmpty()) {\n\t\t\t\t\tstatementReplaced = true;\n\t\t\t\t\tnewGroup.add(statement);\n\t\t\t\t} else {\n\t\t\t\t\tnewGroup.add(existingStatement);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!statementReplaced) {\n\t\t\t\tnewGroup.add(statement);\n\t\t\t}\n\t\t\tnewGroups.put(pid, newGroup);\n\t\t} else {\n\t\t\tnewGroups.put(pid, Collections.singletonList(statement));\n\t\t}\n\t\treturn newGroups;\n\t}",
"private String parseAddress(String address) {\r\n try {\r\n StringBuilder buf = new StringBuilder();\r\n InternetAddress[] netAddrs = InternetAddress.parseHeader(address, false);\r\n for (InternetAddress netAddr : netAddrs) {\r\n if (buf.length() > 0) {\r\n buf.append(SP);\r\n }\r\n\r\n buf.append(LB);\r\n\r\n String personal = netAddr.getPersonal();\r\n if (personal != null && (personal.length() != 0)) {\r\n buf.append(Q).append(personal).append(Q);\r\n } else {\r\n buf.append(NIL);\r\n }\r\n buf.append(SP);\r\n buf.append(NIL); // should add route-addr\r\n buf.append(SP);\r\n try {\r\n // Remove quotes to avoid double quoting\r\n MailAddress mailAddr = new MailAddress(netAddr.getAddress().replaceAll(\"\\\"\", \"\\\\\\\\\\\"\"));\r\n buf.append(Q).append(mailAddr.getUser()).append(Q);\r\n buf.append(SP);\r\n buf.append(Q).append(mailAddr.getHost()).append(Q);\r\n } catch (Exception pe) {\r\n buf.append(NIL + SP + NIL);\r\n }\r\n buf.append(RB);\r\n }\r\n\r\n return buf.toString();\r\n } catch (AddressException e) {\r\n throw new RuntimeException(\"Failed to parse address: \" + address, e);\r\n }\r\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 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}",
"static Property getProperty(String propName, ModelNode attrs) {\n String[] arr = propName.split(\"\\\\.\");\n ModelNode attrDescr = attrs;\n for (String item : arr) {\n // Remove list part.\n if (item.endsWith(\"]\")) {\n int i = item.indexOf(\"[\");\n if (i < 0) {\n return null;\n }\n item = item.substring(0, i);\n }\n ModelNode descr = attrDescr.get(item);\n if (!descr.isDefined()) {\n if (attrDescr.has(Util.VALUE_TYPE)) {\n ModelNode vt = attrDescr.get(Util.VALUE_TYPE);\n if (vt.has(item)) {\n attrDescr = vt.get(item);\n continue;\n }\n }\n return null;\n }\n attrDescr = descr;\n }\n return new Property(propName, attrDescr);\n }",
"public static void inner_reorder_lower(DMatrix1Row A , DMatrix1Row B )\n {\n final int cols = A.numCols;\n B.reshape(cols,cols);\n\n Arrays.fill(B.data,0);\n for (int i = 0; i <cols; i++) {\n for (int j = 0; j <=i; j++) {\n B.data[i*cols+j] += A.data[i]*A.data[j];\n }\n\n for (int k = 1; k < A.numRows; k++) {\n int indexRow = k*cols;\n double valI = A.data[i+indexRow];\n int indexB = i*cols;\n for (int j = 0; j <= i; j++) {\n B.data[indexB++] += valI*A.data[indexRow++];\n }\n }\n }\n }"
] |
This looks at the servlet attributes to get the list of response headers to remove while the response object gets created by the servlet | [
"@Override\n public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {\n final ServletRequest r1 = request;\n chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {\n @SuppressWarnings(\"unchecked\")\n public void setHeader(String name, String value) {\n ArrayList<String> headersToRemove = new ArrayList<String>();\n \n if (r1.getAttribute(\"com.groupon.odo.removeHeaders\") != null)\n headersToRemove = (ArrayList<String>) r1.getAttribute(\"com.groupon.odo.removeHeaders\");\n\n boolean removeHeader = false;\n // need to loop through removeHeaders to make things case insensitive\n for (String headerToRemove : headersToRemove) {\n if (headerToRemove.toLowerCase().equals(name.toLowerCase())) {\n removeHeader = true;\n break;\n }\n }\n\n if (! removeHeader) {\n super.setHeader(name, value);\n }\n }\n });\n }"
] | [
"public static final MVCArray buildArcPoints(LatLong center, double startBearing, double endBearing, double radius) {\n int points = DEFAULT_ARC_POINTS;\n\n MVCArray res = new MVCArray();\n\n if (startBearing > endBearing) {\n endBearing += 360.0;\n }\n double deltaBearing = endBearing - startBearing;\n deltaBearing = deltaBearing / points;\n for (int i = 0; (i < points + 1); i++) {\n res.push(center.getDestinationPoint(startBearing + i * deltaBearing, radius));\n }\n\n return res;\n\n }",
"public synchronized Object next() throws NoSuchElementException\r\n {\r\n try\r\n {\r\n if (!isHasCalledCheck())\r\n {\r\n hasNext();\r\n }\r\n setHasCalledCheck(false);\r\n if (getHasNext())\r\n {\r\n Object obj = getObjectFromResultSet();\r\n m_current_row++;\r\n\r\n // Invoke events on PersistenceBrokerAware instances and listeners\r\n // set target object\r\n if (!disableLifeCycleEvents)\r\n {\r\n getAfterLookupEvent().setTarget(obj);\r\n getBroker().fireBrokerEvent(getAfterLookupEvent());\r\n getAfterLookupEvent().setTarget(null);\r\n } \r\n return obj;\r\n }\r\n else\r\n {\r\n throw new NoSuchElementException(\"inner hasNext was false\");\r\n }\r\n }\r\n catch (ResourceClosedException ex)\r\n {\r\n autoReleaseDbResources();\r\n throw ex;\r\n }\r\n catch (NoSuchElementException ex)\r\n {\r\n autoReleaseDbResources();\r\n logger.error(\"Error while iterate ResultSet for query \" + m_queryObject, ex);\r\n throw new NoSuchElementException(\"Could not obtain next object: \" + ex.getMessage());\r\n }\r\n }",
"public static List<DockerImage> getDockerImagesFromAgents(final int buildInfoId, TaskListener listener) throws IOException, InterruptedException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n\n // Collect images from the master:\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n\n // Collect images from all the agents:\n List<Node> nodes = Jenkins.getInstance().getNodes();\n for (Node node : nodes) {\n if (node == null || node.getChannel() == null) {\n continue;\n }\n try {\n List<DockerImage> partialDockerImages = node.getChannel().call(new MasterToSlaveCallable<List<DockerImage>, IOException>() {\n public List<DockerImage> call() throws IOException {\n List<DockerImage> dockerImages = new ArrayList<DockerImage>();\n dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));\n return dockerImages;\n }\n });\n dockerImages.addAll(partialDockerImages);\n } catch (Exception e) {\n listener.getLogger().println(\"Could not collect docker images from Jenkins node '\" + node.getDisplayName() + \"' due to: \" + e.getMessage());\n }\n }\n return dockerImages;\n }",
"public static appfwprofile_cookieconsistency_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_cookieconsistency_binding obj = new appfwprofile_cookieconsistency_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_cookieconsistency_binding response[] = (appfwprofile_cookieconsistency_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 }",
"private void loadCadidateString() {\n volumeUp = mGvrContext.getActivity().getResources().getString(R.string.volume_up);\n volumeDown = mGvrContext.getActivity().getResources().getString(R.string.volume_down);\n zoomIn = mGvrContext.getActivity().getResources().getString(R.string.zoom_in);\n zoomOut = mGvrContext.getActivity().getResources().getString(R.string.zoom_out);\n invertedColors = mGvrContext.getActivity().getResources().getString(R.string.inverted_colors);\n talkBack = mGvrContext.getActivity().getResources().getString(R.string.talk_back);\n disableTalkBack = mGvrContext.getActivity().getResources().getString(R.string.disable_talk_back);\n }",
"public static IntRange GetRange( int[] values, double percent ){\n int total = 0, n = values.length;\n\n // for all values\n for ( int i = 0; i < n; i++ )\n {\n // accumalate total\n total += values[i];\n }\n\n int min, max, hits;\n int h = (int) ( total * ( percent + ( 1 - percent ) / 2 ) );\n\n // get range min value\n for ( min = 0, hits = total; min < n; min++ )\n {\n hits -= values[min];\n if ( hits < h )\n break;\n }\n // get range max value\n for ( max = n - 1, hits = total; max >= 0; max-- )\n {\n hits -= values[max];\n if ( hits < h )\n break;\n }\n return new IntRange( min, max );\n }",
"public static double Bhattacharyya(double[] histogram1, double[] histogram2) {\n int bins = histogram1.length; // histogram bins\n double b = 0; // Bhattacharyya's coefficient\n\n for (int i = 0; i < bins; i++)\n b += Math.sqrt(histogram1[i]) * Math.sqrt(histogram2[i]);\n\n // Bhattacharyya distance between the two distributions\n return Math.sqrt(1.0 - b);\n }",
"public RedwoodConfiguration loggingClass(final String classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces); } });\r\n return this;\r\n }"
] |
Gets an iterable of all the collections for the given user.
@param api the API connection to be used when retrieving the collections.
@return an iterable containing info about all the collections. | [
"public static Iterable<BoxCollection.Info> getAllCollections(final BoxAPIConnection api) {\n return new Iterable<BoxCollection.Info>() {\n public Iterator<BoxCollection.Info> iterator() {\n URL url = GET_COLLECTIONS_URL_TEMPLATE.build(api.getBaseURL());\n return new BoxCollectionIterator(api, url);\n }\n };\n }"
] | [
"public static OgmCollectionPersister getInverseCollectionPersister(OgmCollectionPersister mainSidePersister) {\n\t\tif ( mainSidePersister.isInverse() || !mainSidePersister.isManyToMany() || !mainSidePersister.getElementType().isEntityType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tEntityPersister inverseSidePersister = mainSidePersister.getElementPersister();\n\n\t\t// process collection-typed properties of inverse side and try to find association back to main side\n\t\tfor ( Type type : inverseSidePersister.getPropertyTypes() ) {\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( mainSidePersister.getFactory(), (CollectionType) type );\n\t\t\t\tif ( isCollectionMatching( mainSidePersister, inverseCollectionPersister ) ) {\n\t\t\t\t\treturn inverseCollectionPersister;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"@Override\n public final Boolean optBool(final String key) {\n if (this.obj.optString(key, null) == null) {\n return null;\n } else {\n return this.obj.optBoolean(key);\n }\n }",
"public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\ttry {\n\t\t\tClassLoader target = clazz.getClassLoader();\n\t\t\tif (target == null) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tClassLoader cur = classLoader;\n\t\t\tif (cur == target) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\twhile (cur != null) {\n\t\t\t\tcur = cur.getParent();\n\t\t\t\tif (cur == target) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tcatch (SecurityException ex) {\n\t\t\t// Probably from the system ClassLoader - let's consider it safe.\n\t\t\treturn true;\n\t\t}\n\t}",
"public int[] indices(Collection<E> elems) {\r\n int[] indices = new int[elems.size()];\r\n int i = 0;\r\n for (E elem : elems) {\r\n indices[i++] = indexOf(elem);\r\n }\r\n return indices;\r\n }",
"public T execute(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException {\n\t\tif (objectCache != null) {\n\t\t\tT result = objectCache.get(clazz, id);\n\t\t\tif (result != null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\tObject[] args = new Object[] { convertIdToFieldObject(id) };\n\t\t// @SuppressWarnings(\"unchecked\")\n\t\tObject result = databaseConnection.queryForOne(statement, args, argFieldTypes, this, objectCache);\n\t\tif (result == null) {\n\t\t\tlogger.debug(\"{} using '{}' and {} args, got no results\", label, statement, args.length);\n\t\t} else if (result == DatabaseConnection.MORE_THAN_ONE) {\n\t\t\tlogger.error(\"{} using '{}' and {} args, got >1 results\", label, statement, args.length);\n\t\t\tlogArgs(args);\n\t\t\tthrow new SQLException(label + \" got more than 1 result: \" + statement);\n\t\t} else {\n\t\t\tlogger.debug(\"{} using '{}' and {} args, got 1 result\", label, statement, args.length);\n\t\t}\n\t\tlogArgs(args);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT castResult = (T) result;\n\t\treturn castResult;\n\t}",
"private static JsonArray getJsonArray(List<String> keys) {\n JsonArray array = new JsonArray();\n for (String key : keys) {\n array.add(key);\n }\n\n return array;\n }",
"public static void addOperation(final OperationContext context) {\n RbacSanityCheckOperation added = context.getAttachment(KEY);\n if (added == null) {\n // TODO support managed domain\n if (!context.isNormalServer()) return;\n context.addStep(createOperation(), INSTANCE, Stage.MODEL);\n context.attach(KEY, INSTANCE);\n }\n }",
"public static void acceptsPartition(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_P, OPT_PARTITION), \"partition id list\")\n .withRequiredArg()\n .describedAs(\"partition-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\n }",
"public double getAccruedInterest(LocalDate date, AnalyticModel model) {\n\t\tint periodIndex=schedule.getPeriodIndex(date);\n\t\tPeriod period=schedule.getPeriod(periodIndex);\n\t\tDayCountConvention dcc= schedule.getDaycountconvention();\n\t\tdouble accruedInterest=getCouponPayment(periodIndex,model)*(dcc.getDaycountFraction(period.getPeriodStart(), date))/schedule.getPeriodLength(periodIndex);\n\t\treturn accruedInterest;\n\t}"
] |
Gets the addresses of the child resources under the given resource.
@param context the operation context
@param registry registry entry representing the resource
@param resource the current resource
@param validChildType a single child type to which the results should be limited. If {@code null} the result
should include all child types
@return map where the keys are the child types and the values are a set of child names associated with a type | [
"static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) {\n\n Map<String, Set<String>> result = new HashMap<>();\n Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType);\n\n if (resource != null) {\n for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) {\n if (validChildTypeFilter.test(childType)) {\n List<String> list = new ArrayList<>();\n for (String child : resource.getChildrenNames(childType)) {\n if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) {\n list.add(child);\n }\n }\n result.put(childType, new LinkedHashSet<>(list));\n }\n }\n }\n\n Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);\n for (PathElement path : paths) {\n String childType = path.getKey();\n if (validChildTypeFilter.test(childType)) {\n Set<String> children = result.get(childType);\n if (children == null) {\n // WFLY-3306 Ensure we have an entry for any valid child type\n children = new LinkedHashSet<>();\n result.put(childType, children);\n }\n ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path));\n if (childRegistration != null) {\n AliasEntry aliasEntry = childRegistration.getAliasEntry();\n if (aliasEntry != null) {\n PathAddress childAddr = addr.append(path);\n PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context));\n assert !childAddr.equals(target) : \"Alias was not translated\";\n PathAddress targetParent = target.getParent();\n Resource parentResource = context.readResourceFromRoot(targetParent, false);\n if (parentResource != null) {\n PathElement targetElement = target.getLastElement();\n if (targetElement.isWildcard()) {\n children.addAll(parentResource.getChildrenNames(targetElement.getKey()));\n } else if (parentResource.hasChild(targetElement)) {\n children.add(path.getValue());\n }\n }\n }\n if (!path.isWildcard() && childRegistration.isRemote()) {\n children.add(path.getValue());\n }\n }\n }\n }\n\n return result;\n }"
] | [
"@SuppressWarnings(\"unused\")\n\t@XmlID\n @XmlAttribute(name = \"id\")\n private String getXmlID(){\n return String.format(\"%s-%s\", this.getClass().getSimpleName(), Long.valueOf(id));\n }",
"public Object get(String name, ObjectFactory<?> factory) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\n\t\tObject result = context.getBean(name);\n\t\tif (null == result) {\n\t\t\tresult = factory.getObject();\n\t\t\tcontext.setBean(name, result);\n\t\t}\n\t\treturn result;\n\t}",
"public static IndexedContainer getPrincipalContainer(\n CmsObject cms,\n List<? extends I_CmsPrincipal> list,\n String captionID,\n String descID,\n String iconID,\n String ouID,\n String icon,\n List<FontIcon> iconList) {\n\n IndexedContainer res = new IndexedContainer();\n\n res.addContainerProperty(captionID, String.class, \"\");\n res.addContainerProperty(ouID, String.class, \"\");\n res.addContainerProperty(iconID, FontIcon.class, new CmsCssIcon(icon));\n if (descID != null) {\n res.addContainerProperty(descID, String.class, \"\");\n }\n\n for (I_CmsPrincipal group : list) {\n\n Item item = res.addItem(group);\n item.getItemProperty(captionID).setValue(group.getSimpleName());\n item.getItemProperty(ouID).setValue(group.getOuFqn());\n if (descID != null) {\n item.getItemProperty(descID).setValue(group.getDescription(A_CmsUI.get().getLocale()));\n }\n }\n\n for (int i = 0; i < iconList.size(); i++) {\n res.getItem(res.getIdByIndex(i)).getItemProperty(iconID).setValue(iconList.get(i));\n }\n\n return res;\n }",
"public static Timespan create(Timespan... timespans) {\n if (timespans == null) {\n return null;\n }\n\n if (timespans.length == 0) {\n return ZERO_MILLISECONDS;\n }\n\n Timespan res = timespans[0];\n\n for (int i = 1; i < timespans.length; i++) {\n Timespan timespan = timespans[i];\n res = res.add(timespan);\n }\n\n return res;\n }",
"public static service_stats[] get(nitro_service service) throws Exception{\n\t\tservice_stats obj = new service_stats();\n\t\tservice_stats[] response = (service_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"protected List<TransformationDescription> buildChildren() {\n if(children.isEmpty()) {\n return Collections.emptyList();\n }\n final List<TransformationDescription> children = new ArrayList<TransformationDescription>();\n for(final TransformationDescriptionBuilder builder : this.children) {\n children.add(builder.build());\n }\n return children;\n }",
"public final static int readUntil(final StringBuilder out, final String in, final int start, final char end)\n {\n int pos = start;\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 if (ch == end)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }",
"public GVRShader getTemplate(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate;\n }",
"public static float[][] toFloat(int[][] array) {\n float[][] n = new float[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (float) array[i][j];\n }\n }\n return n;\n }"
] |
defines the KEY in the parent report parameters map where to get the subreport parameters map.
@param path where to get the parameter map for the subrerpot.
@return | [
"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 <Result, Param extends Resource> Result execWithTemporaryCaching(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\tIgnoreValuesMemento memento = cacheAdapter.ignoreNewValues();\n\t\ttry {\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tmemento.done();\n\t\t}\n\t}",
"public static DataPersister lookupForField(Field field) {\n\n\t\t// see if the any of the registered persisters are valid first\n\t\tif (registeredPersisters != null) {\n\t\t\tfor (DataPersister persister : registeredPersisters) {\n\t\t\t\tif (persister.isValidForField(field)) {\n\t\t\t\t\treturn persister;\n\t\t\t\t}\n\t\t\t\t// check the classes instead\n\t\t\t\tfor (Class<?> clazz : persister.getAssociatedClasses()) {\n\t\t\t\t\tif (field.getType() == clazz) {\n\t\t\t\t\t\treturn persister;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// look it up in our built-in map by class\n\t\tDataPersister dataPersister = builtInMap.get(field.getType().getName());\n\t\tif (dataPersister != null) {\n\t\t\treturn dataPersister;\n\t\t}\n\n\t\t/*\n\t\t * Special case for enum types. We can't put this in the registered persisters because we want people to be able\n\t\t * to override it.\n\t\t */\n\t\tif (field.getType().isEnum()) {\n\t\t\treturn DEFAULT_ENUM_PERSISTER;\n\t\t} else {\n\t\t\t/*\n\t\t\t * Serializable classes return null here because we don't want them to be automatically configured for\n\t\t\t * forwards compatibility with future field types that happen to be Serializable.\n\t\t\t */\n\t\t\treturn null;\n\t\t}\n\t}",
"protected GVRPickedObject findCollider(GVRPickedObject[] pickList, GVRCollider findme)\n {\n if (pickList == null)\n {\n return null;\n }\n for (GVRPickedObject hit : pickList)\n {\n if ((hit != null) && (hit.hitCollider == findme))\n {\n return hit;\n }\n }\n return null;\n }",
"@NonNull\n public static File[] listAllFiles(File directory) {\n if (directory == null) {\n return new File[0];\n }\n File[] files = directory.listFiles();\n return files != null ? files : new File[0];\n }",
"public String getCsv() {\n\n StringWriter writer = new StringWriter();\n try (CSVWriter csv = new CSVWriter(writer)) {\n List<String> headers = new ArrayList<>();\n for (String col : m_columns) {\n headers.add(col);\n }\n csv.writeNext(headers.toArray(new String[] {}));\n for (List<Object> row : m_data) {\n List<String> colCsv = new ArrayList<>();\n for (Object col : row) {\n colCsv.add(String.valueOf(col));\n }\n csv.writeNext(colCsv.toArray(new String[] {}));\n }\n return writer.toString();\n } catch (IOException e) {\n return null;\n }\n }",
"public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration(Properties properties,\n ClassLoader... classLoaders) {\n return FactoryServiceHolder.factoryService.newKnowledgeBuilderConfiguration( properties, classLoaders );\n }",
"public static void validateCurrentFinalCluster(final Cluster currentCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(currentCluster, finalCluster);\n validateClusterNodeState(currentCluster, finalCluster);\n\n return;\n }",
"@UiHandler(\"m_currentTillEndCheckBox\")\n void onCurrentTillEndChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setCurrentTillEnd(event.getValue());\n }\n }",
"public static Artifact createArtifact(final String groupId, final String artifactId, final String version, final String classifier, final String type, final String extension, final String origin){\n\t\tfinal Artifact artifact = new Artifact();\n\n\t\tartifact.setGroupId(groupId);\n\t\tartifact.setArtifactId(artifactId);\n\t\tartifact.setVersion(version);\n\n\t\tif(classifier != null){\n\t\t\tartifact.setClassifier(classifier);\n\t\t}\n\n\t\tif(type != null){\n\t\t\tartifact.setType(type);\n\t\t}\n\n\t\tif(extension != null){\n\t\t\tartifact.setExtension(extension);\n\t\t}\n\n\t\tartifact.setOrigin(origin == null ? \"maven\" : origin);\n\n\t\treturn artifact;\n\t}"
] |
Serializes Number value and writes it into specified buffer. | [
"private static void writeNumber(Class<?> numberClass, Number value, CharBuf buffer) {\n if (numberClass == Integer.class) {\n buffer.addInt((Integer) value);\n } else if (numberClass == Long.class) {\n buffer.addLong((Long) value);\n } else if (numberClass == BigInteger.class) {\n buffer.addBigInteger((BigInteger) value);\n } else if (numberClass == BigDecimal.class) {\n buffer.addBigDecimal((BigDecimal) value);\n } else if (numberClass == Double.class) {\n Double doubleValue = (Double) value;\n if (doubleValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (doubleValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addDouble(doubleValue);\n } else if (numberClass == Float.class) {\n Float floatValue = (Float) value;\n if (floatValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (floatValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addFloat(floatValue);\n } else if (numberClass == Byte.class) {\n buffer.addByte((Byte) value);\n } else if (numberClass == Short.class) {\n buffer.addShort((Short) value);\n } else { // Handle other Number implementations\n buffer.addString(value.toString());\n }\n }"
] | [
"MACAddressSegment[] toEUISegments(boolean extended) {\n\t\tIPv6AddressSegment seg0, seg1, seg2, seg3;\n\t\tint start = addressSegmentIndex;\n\t\tint segmentCount = getSegmentCount();\n\t\tint segmentIndex;\n\t\tif(start < 4) {\n\t\t\tstart = 0;\n\t\t\tsegmentIndex = 4 - start;\n\t\t} else {\n\t\t\tstart -= 4;\n\t\t\tsegmentIndex = 0;\n\t\t}\n\t\tint originalSegmentIndex = segmentIndex;\n\t\tseg0 = (start == 0 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg1 = (start <= 1 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg2 = (start <= 2 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg3 = (start <= 3 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tint macSegCount = (segmentIndex - originalSegmentIndex) << 1;\n\t\tif(!extended) {\n\t\t\tmacSegCount -= 2;\n\t\t}\n\t\tif((seg1 != null && !seg1.matchesWithMask(0xff, 0xff)) || (seg2 != null && !seg2.matchesWithMask(0xfe00, 0xff00)) || macSegCount == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tMACAddressCreator creator = getMACNetwork().getAddressCreator();\n\t\tMACAddressSegment ZERO_SEGMENT = creator.createSegment(0);\n\t\tMACAddressSegment newSegs[] = creator.createSegmentArray(macSegCount);\n\t\tint macStartIndex = 0;\n\t\tif(seg0 != null) {\n\t\t\tseg0.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t//toggle the u/l bit\n\t\t\tMACAddressSegment macSegment0 = newSegs[0];\n\t\t\tint lower0 = macSegment0.getSegmentValue();\n\t\t\tint upper0 = macSegment0.getUpperSegmentValue();\n\t\t\tint mask2ndBit = 0x2;\n\t\t\tif(!macSegment0.matchesWithMask(mask2ndBit & lower0, mask2ndBit)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t//you can use matches with mask\n\t\t\tlower0 ^= mask2ndBit;//flip the universal/local bit\n\t\t\tupper0 ^= mask2ndBit;\n\t\t\tnewSegs[0] = creator.createSegment(lower0, upper0, null);\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg1 != null) {\n\t\t\tseg1.getSplitSegments(newSegs, macStartIndex, creator); //a ff fe b\n\t\t\tif(!extended) {\n\t\t\t\tnewSegs[macStartIndex + 1] = ZERO_SEGMENT;\n\t\t\t}\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg2 != null) {\n\t\t\tif(!extended) {\n\t\t\t\tif(seg1 != null) {\n\t\t\t\t\tmacStartIndex -= 2;\n\t\t\t\t\tMACAddressSegment first = newSegs[macStartIndex];\n\t\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t\t\tnewSegs[macStartIndex] = first;\n\t\t\t\t} else {\n\t\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t\t\tnewSegs[macStartIndex] = ZERO_SEGMENT;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t}\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg3 != null) {\n\t\t\tseg3.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t}\n\t\treturn newSegs;\n\t}",
"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 void validateSegments(List<LogSegment> segments) {\n synchronized (lock) {\n for (int i = 0; i < segments.size() - 1; i++) {\n LogSegment curr = segments.get(i);\n LogSegment next = segments.get(i + 1);\n if (curr.start() + curr.size() != next.start()) {\n throw new IllegalStateException(\"The following segments don't validate: \" + curr.getFile()\n .getAbsolutePath() + \", \" + next.getFile().getAbsolutePath());\n }\n }\n }\n }",
"public static appfwlearningsettings get(nitro_service service, String profilename) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\tobj.set_profilename(profilename);\n\t\tappfwlearningsettings response = (appfwlearningsettings) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public ThumborUrlBuilder align(VerticalAlign valign, HorizontalAlign halign) {\n return align(valign).align(halign);\n }",
"public String updateClassification(String classificationType) {\n Metadata metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.add(\"/Box__Security__Classification__Key\", classificationType);\n Metadata classification = this.updateMetadata(metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }",
"public void setEmptyDefault(String iso) {\n if (iso == null || iso.isEmpty()) {\n iso = DEFAULT_COUNTRY;\n }\n int defaultIdx = mCountries.indexOfIso(iso);\n mSelectedCountry = mCountries.get(defaultIdx);\n mCountrySpinner.setSelection(defaultIdx);\n }",
"public static nsrollbackcmd[] get(nitro_service service, nsrollbackcmd_args args) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<AccountingDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<AccountingDate>) super.zonedDateTime(temporal);\n }"
] |
Calculate the determinant.
@return Determinant. | [
"public double determinant() {\n if (m != n) {\n throw new IllegalArgumentException(\"Matrix must be square.\");\n }\n double d = (double) pivsign;\n for (int j = 0; j < n; j++) {\n d *= LU[j][j];\n }\n return d;\n }"
] | [
"public static String getXPathExpression(Node node) {\n\t\tObject xpathCache = node.getUserData(FULL_XPATH_CACHE);\n\t\tif (xpathCache != null) {\n\t\t\treturn xpathCache.toString();\n\t\t}\n\t\tNode parent = node.getParentNode();\n\n\t\tif ((parent == null) || parent.getNodeName().contains(\"#document\")) {\n\t\t\tString xPath = \"/\" + node.getNodeName() + \"[1]\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tif (node.hasAttributes() && node.getAttributes().getNamedItem(\"id\") != null) {\n\t\t\tString xPath = \"//\" + node.getNodeName() + \"[@id = '\"\n\t\t\t\t\t+ node.getAttributes().getNamedItem(\"id\").getNodeValue() + \"']\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tStringBuffer buffer = new StringBuffer();\n\n\t\tif (parent != node) {\n\t\t\tbuffer.append(getXPathExpression(parent));\n\t\t\tbuffer.append(\"/\");\n\t\t}\n\n\t\tbuffer.append(node.getNodeName());\n\n\t\tList<Node> mySiblings = getSiblings(parent, node);\n\n\t\tfor (int i = 0; i < mySiblings.size(); i++) {\n\t\t\tNode el = mySiblings.get(i);\n\n\t\t\tif (el.equals(node)) {\n\t\t\t\tbuffer.append('[').append(Integer.toString(i + 1)).append(']');\n\t\t\t\t// Found so break;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tString xPath = buffer.toString();\n\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\treturn xPath;\n\t}",
"public void stopListenting() {\n if (channel != null) {\n log.info(\"closing server channel\");\n channel.close().syncUninterruptibly();\n channel = null;\n }\n }",
"private Duration getAssignmentWork(ProjectCalendar calendar, TimephasedWork assignment)\n {\n Date assignmentStart = assignment.getStart();\n\n Date splitStart = assignmentStart;\n Date splitFinishTime = calendar.getFinishTime(splitStart);\n Date splitFinish = DateHelper.setTime(splitStart, splitFinishTime);\n\n Duration calendarSplitWork = calendar.getWork(splitStart, splitFinish, TimeUnit.MINUTES);\n Duration assignmentWorkPerDay = assignment.getAmountPerDay();\n Duration splitWork;\n\n double splitMinutes = assignmentWorkPerDay.getDuration();\n splitMinutes *= calendarSplitWork.getDuration();\n splitMinutes /= (8 * 60); // this appears to be a fixed value\n splitWork = Duration.getInstance(splitMinutes, TimeUnit.MINUTES);\n return splitWork;\n }",
"public static <T> Set<T> toSet(Iterator<? extends T> iterator) {\n\t\treturn Sets.newLinkedHashSet(toIterable(iterator));\n\t}",
"public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource,\n\t\t\tDatabaseTableConfig<T> tableConfig) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tTableConfigConnectionSource key = new TableConfigConnectionSource(connectionSource, tableConfig);\n\t\tDao<?, ?> dao = lookupDao(key);\n\t\tif (dao == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tD castDao = (D) dao;\n\t\t\treturn castDao;\n\t\t}\n\t}",
"public void append(LogSegment segment) {\n while (true) {\n List<LogSegment> curr = contents.get();\n List<LogSegment> updated = new ArrayList<LogSegment>(curr);\n updated.add(segment);\n if (contents.compareAndSet(curr, updated)) {\n return;\n }\n }\n }",
"private Set<T> findMatching(R resolvable) {\n Set<T> result = new HashSet<T>();\n for (T bean : getAllBeans(resolvable)) {\n if (matches(resolvable, bean)) {\n result.add(bean);\n }\n }\n return result;\n }",
"protected Object getFieldData(Integer id, FieldType type, byte[][] fixedData, Var2Data varData)\n {\n Object result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.read(id, fixedData, varData);\n }\n\n return result;\n }",
"public T findById(Object id) throws RowNotFoundException, TooManyRowsException {\n return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult();\n }"
] |
Adds labels to the item
@param labels
the labels to add | [
"protected void processLabels(List<MonolingualTextValue> labels) {\n for(MonolingualTextValue label : labels) {\n \tString lang = label.getLanguageCode();\n \tNameWithUpdate currentValue = newLabels.get(lang);\n \tif (currentValue == null || !currentValue.value.equals(label)) {\n\t newLabels.put(lang,\n\t new NameWithUpdate(label, true));\n\t \n\t // Delete any alias that matches the new label\n\t AliasesWithUpdate currentAliases = newAliases.get(lang);\n\t if (currentAliases != null && currentAliases.aliases.contains(label)) {\n\t \tdeleteAlias(label);\n\t }\n \t}\n }\n \n }"
] | [
"private void modifyBeliefCount(int count){\n introspector.setBeliefValue(getLocalName(), Definitions.RECEIVED_MESSAGE_COUNT, getBeliefCount()+count, null);\n }",
"public static BoxCollaborationWhitelist.Info create(final BoxAPIConnection api, String domain,\n WhitelistDirection direction) {\n\n URL url = COLLABORATION_WHITELIST_ENTRIES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"domain\", domain)\n .add(\"direction\", direction.toString());\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxCollaborationWhitelist domainWhitelist =\n new BoxCollaborationWhitelist(api, responseJSON.get(\"id\").asString());\n\n return domainWhitelist.new Info(responseJSON);\n }",
"public static void registerParams(DynamicJasperDesign jd, Map _parameters) {\n for (Object key : _parameters.keySet()) {\n if (key instanceof String) {\n try {\n Object value = _parameters.get(key);\n if (jd.getParametersMap().get(key) != null) {\n log.warn(\"Parameter \\\"\" + key + \"\\\" already registered, skipping this one: \" + value);\n continue;\n }\n\n JRDesignParameter parameter = new JRDesignParameter();\n\n if (value == null) //There are some Map implementations that allows nulls values, just go on\n continue;\n\n//\t\t\t\t\tparameter.setValueClassName(value.getClass().getCanonicalName());\n Class clazz = value.getClass().getComponentType();\n if (clazz == null)\n clazz = value.getClass();\n parameter.setValueClass(clazz); //NOTE this is very strange\n //when using an array as subreport-data-source, I must pass the parameter class name like this: value.getClass().getComponentType()\n parameter.setName((String) key);\n jd.addParameter(parameter);\n } catch (JRException e) {\n //nothing to do\n }\n }\n\n }\n\n }",
"public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }",
"private <T> T getBeanOrNull(String name, Class<T> requiredType) {\n\t\tif (name == null || !applicationContext.containsBean(name)) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\treturn applicationContext.getBean(name, requiredType);\n\t\t\t} catch (BeansException be) {\n\t\t\t\tlog.error(\"Error during getBeanOrNull, not rethrown, \" + be.getMessage(), be);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t}",
"private JSONArray getApplicablePathNames (String requestUrl, Integer requestType) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n List<EndpointOverride> applicablePaths;\n JSONArray pathNames = new JSONArray();\n // Get all paths that match the request\n applicablePaths = PathOverrideService.getInstance().getSelectedPaths(Constants.OVERRIDE_TYPE_REQUEST, requestInfo.client,\n requestInfo.profile,\n requestUrl + \"?\" + requestInfo.originalRequestInfo.getQueryString(),\n requestType, true);\n // Extract just the path name from each path\n for (EndpointOverride path : applicablePaths) {\n JSONObject pathName = new JSONObject();\n pathName.put(\"name\", path.getPathName());\n pathNames.put(pathName);\n }\n\n return pathNames;\n }",
"protected final void setParentNode(final DiffNode parentNode)\n\t{\n\t\tif (this.parentNode != null && this.parentNode != parentNode)\n\t\t{\n\t\t\tthrow new IllegalStateException(\"The parent of a node cannot be changed, once it's set.\");\n\t\t}\n\t\tthis.parentNode = parentNode;\n\t}",
"public static base_responses update(nitro_service client, nd6ravariables resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnd6ravariables updateresources[] = new nd6ravariables[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nd6ravariables();\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].ceaserouteradv = resources[i].ceaserouteradv;\n\t\t\t\tupdateresources[i].sendrouteradv = resources[i].sendrouteradv;\n\t\t\t\tupdateresources[i].srclinklayeraddroption = resources[i].srclinklayeraddroption;\n\t\t\t\tupdateresources[i].onlyunicastrtadvresponse = resources[i].onlyunicastrtadvresponse;\n\t\t\t\tupdateresources[i].managedaddrconfig = resources[i].managedaddrconfig;\n\t\t\t\tupdateresources[i].otheraddrconfig = resources[i].otheraddrconfig;\n\t\t\t\tupdateresources[i].currhoplimit = resources[i].currhoplimit;\n\t\t\t\tupdateresources[i].maxrtadvinterval = resources[i].maxrtadvinterval;\n\t\t\t\tupdateresources[i].minrtadvinterval = resources[i].minrtadvinterval;\n\t\t\t\tupdateresources[i].linkmtu = resources[i].linkmtu;\n\t\t\t\tupdateresources[i].reachabletime = resources[i].reachabletime;\n\t\t\t\tupdateresources[i].retranstime = resources[i].retranstime;\n\t\t\t\tupdateresources[i].defaultlifetime = resources[i].defaultlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public boolean matchesWithMask(IPAddressSection other, IPAddressSection mask) {\n\t\tcheckMaskSectionCount(mask);\n\t\tcheckSectionCount(other);\n\t\tint divCount = getSegmentCount();\n\t\tfor(int i = 0; i < divCount; i++) {\n\t\t\tIPAddressSegment div = getSegment(i);\n\t\t\tIPAddressSegment maskSegment = mask.getSegment(i);\n\t\t\tIPAddressSegment otherSegment = other.getSegment(i);\n\t\t\tif(!div.matchesWithMask(\n\t\t\t\t\totherSegment.getSegmentValue(), \n\t\t\t\t\totherSegment.getUpperSegmentValue(), \n\t\t\t\t\tmaskSegment.getSegmentValue())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}"
] |
Handle http Request.
@param request HttpRequest to be handled.
@param responder HttpResponder to write the response.
@param groupValues Values needed for the invocation. | [
"@SuppressWarnings(\"unchecked\")\n public HttpMethodInfo handle(HttpRequest request,\n HttpResponder responder, Map<String, String> groupValues) throws Exception {\n //TODO: Refactor group values.\n try {\n if (httpMethods.contains(request.method())) {\n //Setup args for reflection call\n Object [] args = new Object[paramsInfo.size()];\n\n int idx = 0;\n for (Map<Class<? extends Annotation>, ParameterInfo<?>> info : paramsInfo) {\n if (info.containsKey(PathParam.class)) {\n args[idx] = getPathParamValue(info, groupValues);\n }\n if (info.containsKey(QueryParam.class)) {\n args[idx] = getQueryParamValue(info, request.uri());\n }\n if (info.containsKey(HeaderParam.class)) {\n args[idx] = getHeaderParamValue(info, request);\n }\n idx++;\n }\n\n return new HttpMethodInfo(method, handler, responder, args, exceptionHandler);\n } else {\n //Found a matching resource but could not find the right HttpMethod so return 405\n throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, String.format\n (\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n }\n } catch (Throwable e) {\n throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Error in executing request: %s %s\", request.method(),\n request.uri()), e);\n }\n }"
] | [
"@Override\n public Optional<String> hash(final Optional<URL> url) throws IOException {\n if (!url.isPresent()) {\n return Optional.absent();\n }\n logger.debug(\"Calculating md5 hash, url:{}\", url);\n if (isHotReloadModeOff()) {\n final String md5 = cache.getIfPresent(url.get());\n\n logger.debug(\"md5 hash:{}\", md5);\n\n if (md5 != null) {\n return Optional.of(md5);\n }\n }\n\n final InputStream is = url.get().openStream();\n final String md5 = getMD5Checksum(is);\n\n if (isHotReloadModeOff()) {\n logger.debug(\"caching url:{} with hash:{}\", url, md5);\n\n cache.put(url.get(), md5);\n }\n\n return Optional.fromNullable(md5);\n }",
"public static sslfipskey get(nitro_service service, String fipskeyname) throws Exception{\n\t\tsslfipskey obj = new sslfipskey();\n\t\tobj.set_fipskeyname(fipskeyname);\n\t\tsslfipskey response = (sslfipskey) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static String getDateCreatedTimeRangeFilterQuery(String searchField, long startTime, long endTime) {\n\n String sStartTime = null;\n String sEndTime = null;\n\n // Convert startTime to ISO 8601 format\n if ((startTime > Long.MIN_VALUE) && (startTime < Long.MAX_VALUE)) {\n sStartTime = CmsSearchUtil.getDateAsIso8601(new Date(startTime));\n }\n\n // Convert endTime to ISO 8601 format\n if ((endTime > Long.MIN_VALUE) && (endTime < Long.MAX_VALUE)) {\n sEndTime = CmsSearchUtil.getDateAsIso8601(new Date(endTime));\n }\n\n // Build Solr range string\n final String rangeString = CmsSearchUtil.getSolrRangeString(sStartTime, sEndTime);\n\n // Build Solr filter string\n return String.format(\"%s:%s\", searchField, rangeString);\n }",
"public void initialize() {\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessagePriority.High));\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessagePriority.High));\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessagePriority.High));\n\t}",
"public static void addItemsHandled(String handledItemsType, int handledItemsNumber) {\n \tJobLogger jobLogger = (JobLogger) getInstance();\n if (jobLogger == null) {\n return;\n }\n\n jobLogger.addItemsHandledInstance(handledItemsType, handledItemsNumber);\n }",
"public void setCapacity(int capacity) {\n if (capacity <= 0) {\n throw new IllegalArgumentException(\"capacity must be greater than 0\");\n }\n\n synchronized (queue) {\n // If the capacity was reduced, we remove oldest elements until the\n // queue fits inside the specified capacity\n if (capacity < this.capacity) {\n while (queue.size() > capacity) {\n queue.removeFirst();\n }\n }\n }\n\n this.capacity = capacity;\n }",
"private void allClustersEqual(final List<String> clusterUrls) {\n Validate.notEmpty(clusterUrls, \"clusterUrls cannot be null\");\n // If only one clusterUrl return immediately\n if (clusterUrls.size() == 1)\n return;\n AdminClient adminClientLhs = adminClientPerCluster.get(clusterUrls.get(0));\n Cluster clusterLhs = adminClientLhs.getAdminClientCluster();\n for (int index = 1; index < clusterUrls.size(); index++) {\n AdminClient adminClientRhs = adminClientPerCluster.get(clusterUrls.get(index));\n Cluster clusterRhs = adminClientRhs.getAdminClientCluster();\n if (!areTwoClustersEqual(clusterLhs, clusterRhs))\n throw new VoldemortException(\"Cluster \" + clusterLhs.getName()\n + \" is not the same as \" + clusterRhs.getName());\n }\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 Object copy(final Object obj, final PersistenceBroker broker)\r\n {\r\n return clone(obj, IdentityMapFactory.getIdentityMap(), broker);\r\n }"
] |
Concatenates the trajectory a and b
@param a The end of this trajectory will be connected to the start of trajectory b
@param b The start of this trajectory will be connected to the end of trajectory a
@return Concatenated trajectory | [
"public static Trajectory concactTrajectorie(Trajectory a, Trajectory b){\n\t\tif(a.getDimension()!=b.getDimension()){\n\t\t\tthrow new IllegalArgumentException(\"Combination not possible: The trajectorys does not have the same dimension\");\n\t\t}\n\t\tTrajectory c = new Trajectory(a.getDimension());\n\t\t\n\t\tfor(int i = 0 ; i < a.size(); i++){\n\t\t\tPoint3d pos = new Point3d(a.get(i).x, \n\t\t\t\t\ta.get(i).y, \n\t\t\t\t\ta.get(i).z);\n\t\t\tc.add(pos);\n\t\t}\n\t\t\n\t\tdouble dx = a.get(a.size()-1).x - b.get(0).x;\n\t\tdouble dy = a.get(a.size()-1).y - b.get(0).y;\n\t\tdouble dz = a.get(a.size()-1).z - b.get(0).z;\n\t\t\n\t\tfor(int i = 1 ; i < b.size(); i++){\n\t\t\tPoint3d pos = new Point3d(b.get(i).x+dx, \n\t\t\t\t\tb.get(i).y+dy, \n\t\t\t\t\tb.get(i).z+dz);\n\t\t\tc.add(pos);\n\t\t}\n\t\t\n\t\treturn c;\n\t\t\n\t}"
] | [
"private String extractAndConvertTaskType(Task task)\n {\n String activityType = (String) task.getCachedValue(m_activityTypeField);\n if (activityType == null)\n {\n activityType = \"Resource Dependent\";\n }\n else\n {\n if (ACTIVITY_TYPE_MAP.containsKey(activityType))\n {\n activityType = ACTIVITY_TYPE_MAP.get(activityType);\n }\n }\n return activityType;\n }",
"private static <T> void writeConfig(BufferedWriter writer, DatabaseTableConfig<T> config) throws IOException,\n\t\t\tSQLException {\n\t\twriter.append(CONFIG_FILE_START_MARKER);\n\t\twriter.newLine();\n\t\tif (config.getDataClass() != null) {\n\t\t\twriter.append(FIELD_NAME_DATA_CLASS).append('=').append(config.getDataClass().getName());\n\t\t\twriter.newLine();\n\t\t}\n\t\tif (config.getTableName() != null) {\n\t\t\twriter.append(FIELD_NAME_TABLE_NAME).append('=').append(config.getTableName());\n\t\t\twriter.newLine();\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_START);\n\t\twriter.newLine();\n\t\tif (config.getFieldConfigs() != null) {\n\t\t\tfor (DatabaseFieldConfig field : config.getFieldConfigs()) {\n\t\t\t\tDatabaseFieldConfigLoader.write(writer, field, config.getTableName());\n\t\t\t}\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_END);\n\t\twriter.newLine();\n\t\twriter.append(CONFIG_FILE_END_MARKER);\n\t\twriter.newLine();\n\t}",
"protected void updateRotator(DMatrixRMaj Q , int m, int n, double c, double s) {\n int rowA = m*Q.numCols;\n int rowB = n*Q.numCols;\n\n// for( int i = 0; i < Q.numCols; i++ ) {\n// double a = Q.get(rowA+i);\n// double b = Q.get(rowB+i);\n// Q.set( rowA+i, c*a + s*b);\n// Q.set( rowB+i, -s*a + c*b);\n// }\n// System.out.println(\"------ AFter Update Rotator \"+m+\" \"+n);\n// Q.print();\n// System.out.println();\n int endA = rowA + Q.numCols;\n for( ; rowA != endA; rowA++ , rowB++ ) {\n double a = Q.get(rowA);\n double b = Q.get(rowB);\n Q.set(rowA, c*a + s*b);\n Q.set(rowB, -s*a + c*b);\n }\n }",
"public static boolean isInverse(DMatrixRMaj a , DMatrixRMaj b , double tol ) {\n if( a.numRows != b.numRows || a.numCols != b.numCols ) {\n return false;\n }\n\n int numRows = a.numRows;\n int numCols = a.numCols;\n\n for( int i = 0; i < numRows; i++ ) {\n for( int j = 0; j < numCols; j++ ) {\n double total = 0;\n for( int k = 0; k < numCols; k++ ) {\n total += a.get(i,k)*b.get(k,j);\n }\n\n if( i == j ) {\n if( !(Math.abs(total-1) <= tol) )\n return false;\n } else if( !(Math.abs(total) <= tol) )\n return false;\n }\n }\n\n return true;\n }",
"private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueTag tag) {\n for (RekordboxAnlz.CueEntry cueEntry : tag.cues()) { // TODO: Need to figure out how to identify deleted entries to ignore.\n if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) {\n entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()),\n Util.timeToHalfFrame(cueEntry.loopTime())));\n } else {\n entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time())));\n }\n }\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 }",
"public static CmsSearchConfigurationSorting create(\n final String sortParam,\n final List<I_CmsSearchConfigurationSortOption> options,\n final I_CmsSearchConfigurationSortOption defaultOption) {\n\n return (null != sortParam) || ((null != options) && !options.isEmpty()) || (null != defaultOption)\n ? new CmsSearchConfigurationSorting(sortParam, options, defaultOption)\n : null;\n }",
"protected String createName() {\n final StringBuilder buf = new StringBuilder(128);\n try {\n buf.append(InetAddress.getLocalHost().getHostName()).append(COLON)\n .append(ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]) // PID\n .append('-').append(this.workerId).append(COLON).append(JAVA_DYNAMIC_QUEUES);\n for (final String queueName : this.queueNames) {\n buf.append(',').append(queueName);\n }\n } catch (UnknownHostException uhe) {\n throw new RuntimeException(uhe);\n }\n return buf.toString();\n }",
"public Shard getShard(String docId) {\n assertNotEmpty(docId, \"docId\");\n return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path(\"_shards\")\n .path(docId).build(),\n Shard.class);\n }"
] |
Clear tmpData in subtree rooted in this node. | [
"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}"
] | [
"public static void extract( DMatrix src,\n int srcY0, int srcY1,\n int srcX0, int srcX1,\n DMatrix dst ) {\n ((ReshapeMatrix)dst).reshape(srcY1-srcY0,srcX1-srcX0);\n extract(src,srcY0,srcY1,srcX0,srcX1,dst,0,0);\n }",
"private void applyAliases(Map<FieldType, String> aliases)\n {\n CustomFieldContainer fields = m_project.getCustomFields();\n for (Map.Entry<FieldType, String> entry : aliases.entrySet())\n {\n fields.getCustomField(entry.getKey()).setAlias(entry.getValue());\n }\n }",
"void countNonZeroInV( int []parent ) {\n int []w = gwork.data;\n findMinElementIndexInRows(leftmost);\n createRowElementLinkedLists(leftmost,w);\n countNonZeroUsingLinkedList(parent,w);\n }",
"protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }",
"public float getNormalZ(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }",
"@Override\n\tpublic void Invoke(final String method, JSONArray args,\n\t\t\tHubInvokeCallback callback) {\n\n\t\tif (method == null)\n {\n throw new IllegalArgumentException(\"method\");\n }\n\n if (args == null)\n {\n throw new IllegalArgumentException(\"args\");\n }\n\n final String callbackId = mConnection.RegisterCallback(callback);\n\n HubInvocation hubData = new HubInvocation(mHubName, method, args, callbackId);\n\n String value = hubData.Serialize();\n\n mConnection.Send(value, new SendCallback() \n {\n\t\t\t@Override\n\t\t\tpublic void OnSent(CharSequence messageSent) {\n\t\t\t\tLog.v(TAG, \"Invoke of \" + method + \"sent to \" + mHubName);\n\t\t\t\t// callback.OnSent() ??!?!?\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void OnError(Exception ex) {\n\t\t\t\t// TODO Cancel the callback\n\t\t\t\tLog.e(TAG, \"Failed to invoke \" + method + \"on \" + mHubName);\n\t\t\t\tmConnection.RemoveCallback(callbackId);\n\t\t\t\t// callback.OnError() ?!?!?\n\t\t\t}\n });\n }",
"public boolean setUpCameraForVrMode(final int fpsMode) {\n\n cameraSetUpStatus = false;\n this.fpsMode = fpsMode;\n\n if (!isCameraOpen) {\n Log.e(TAG, \"Camera is not open\");\n return false;\n }\n if (fpsMode < 0 || fpsMode > 2) {\n Log.e(TAG,\n \"Invalid fpsMode: %d. It can only take values 0, 1, or 2.\", fpsMode);\n } else {\n Parameters params = camera.getParameters();\n\n // check if the device supports vr mode preview\n if (\"true\".equalsIgnoreCase(params.get(\"vrmode-supported\"))) {\n\n Log.v(TAG, \"VR Mode supported!\");\n\n // set vr mode\n params.set(\"vrmode\", 1);\n\n // true if the apps intend to record videos using\n // MediaRecorder\n params.setRecordingHint(true);\n\n // set preview size\n // params.setPreviewSize(640, 480);\n\n // set fast-fps-mode: 0 for 30fps, 1 for 60 fps,\n // 2 for 120 fps\n params.set(\"fast-fps-mode\", fpsMode);\n\n switch (fpsMode) {\n case 0: // 30 fps\n params.setPreviewFpsRange(30000, 30000);\n break;\n case 1: // 60 fps\n params.setPreviewFpsRange(60000, 60000);\n break;\n case 2: // 120 fps\n params.setPreviewFpsRange(120000, 120000);\n break;\n default:\n }\n\n // for auto focus\n params.set(\"focus-mode\", \"continuous-video\");\n\n params.setVideoStabilization(false);\n if (\"true\".equalsIgnoreCase(params.get(\"ois-supported\"))) {\n params.set(\"ois\", \"center\");\n }\n\n camera.setParameters(params);\n cameraSetUpStatus = true;\n }\n }\n\n return cameraSetUpStatus;\n }",
"public LuaScript endScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }",
"private String parsePropertyName(String orgPropertyName, Object userData) {\n\t\t// try to assure the correct separator is used\n\t\tString propertyName = orgPropertyName.replace(HibernateLayerUtil.XPATH_SEPARATOR, HibernateLayerUtil.SEPARATOR);\n\n\t\t// split the path (separator is defined in the HibernateLayerUtil)\n\t\tString[] props = propertyName.split(HibernateLayerUtil.SEPARATOR_REGEXP);\n\t\tString finalName;\n\t\tif (props.length > 1 && userData instanceof Criteria) {\n\t\t\t// the criteria API requires an alias for each join table !!!\n\t\t\tString prevAlias = null;\n\t\t\tfor (int i = 0; i < props.length - 1; i++) {\n\t\t\t\tString alias = props[i] + \"_alias\";\n\t\t\t\tif (!aliases.contains(alias)) {\n\t\t\t\t\tCriteria criteria = (Criteria) userData;\n\t\t\t\t\tif (i == 0) {\n\t\t\t\t\t\tcriteria.createAlias(props[0], alias);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcriteria.createAlias(prevAlias + \".\" + props[i], alias);\n\t\t\t\t\t}\n\t\t\t\t\taliases.add(alias);\n\t\t\t\t}\n\t\t\t\tprevAlias = alias;\n\t\t\t}\n\t\t\tfinalName = prevAlias + \".\" + props[props.length - 1];\n\t\t} else {\n\t\t\tfinalName = propertyName;\n\t\t}\n\t\treturn finalName;\n\t}"
] |
Set some initial values. | [
"private void init()\r\n {\r\n jdbcProperties = new Properties();\r\n dbcpProperties = new Properties();\r\n setFetchSize(0);\r\n this.setTestOnBorrow(true);\r\n this.setTestOnReturn(false);\r\n this.setTestWhileIdle(false);\r\n this.setLogAbandoned(false);\r\n this.setRemoveAbandoned(false);\r\n }"
] | [
"private String getResourceType(Resource resource)\n {\n String result;\n net.sf.mpxj.ResourceType type = resource.getType();\n if (type == null)\n {\n type = net.sf.mpxj.ResourceType.WORK;\n }\n\n switch (type)\n {\n case MATERIAL:\n {\n result = \"Material\";\n break;\n }\n\n case COST:\n {\n result = \"Nonlabor\";\n break;\n }\n\n default:\n {\n result = \"Labor\";\n break;\n }\n }\n\n return result;\n }",
"public static List<KoreanPhraseExtractor.KoreanPhrase> extractPhrases(Seq<KoreanToken> tokens, boolean filterSpam, boolean includeHashtags) {\n return JavaConversions.seqAsJavaList(\n TwitterKoreanProcessor.extractPhrases(tokens, filterSpam, includeHashtags)\n );\n }",
"public ColumnBuilder addFieldProperty(String propertyName, String value) {\n\t\tfieldProperties.put(propertyName, value);\n\t\treturn this;\n\t}",
"protected void applyBanners() {\n DynamicReportOptions options = getReport().getOptions();\n if (options.getFirstPageImageBanners().isEmpty() && options.getImageBanners().isEmpty()){\n return;\n }\n\n\t\t/*\n\t\t First create image banners for the first page only\n\t\t */\n\t\tJRDesignBand title = (JRDesignBand) getDesign().getTitle();\n\t\t//if there is no title band, but there are banner images for the first page, we create a title band\n\t\tif (title == null && !options.getFirstPageImageBanners().isEmpty()){\n\t\t\ttitle = new JRDesignBand();\n\t\t\tgetDesign().setTitle(title);\n\t\t}\n\t\tapplyImageBannersToBand(title, options.getFirstPageImageBanners().values(), null, true);\n\n\t\t/*\n\t\t Now create image banner for the rest of the pages\n\t\t */\n\t\tJRDesignBand pageHeader = (JRDesignBand) getDesign().getPageHeader();\n\t\t//if there is no title band, but there are banner images for the first page, we create a title band\n\t\tif (pageHeader == null && !options.getImageBanners().isEmpty()){\n\t\t\tpageHeader = new JRDesignBand();\n\t\t\tgetDesign().setPageHeader(pageHeader);\n\t\t}\n\t\tJRDesignExpression printWhenExpression = null;\n\t\tif (!options.getFirstPageImageBanners().isEmpty()){\n\t\t\tprintWhenExpression = new JRDesignExpression();\n\t\t\tprintWhenExpression.setValueClass(Boolean.class);\n\t\t\tprintWhenExpression.setText(EXPRESSION_TRUE_WHEN_NOT_FIRST_PAGE);\n\t\t}\n\t\tapplyImageBannersToBand(pageHeader, options.getImageBanners().values(),printWhenExpression, true);\n\n\n\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 static URL codeLocationFromClass(Class<?> codeLocationClass) {\n String pathOfClass = codeLocationClass.getName().replace(\".\", \"/\") + \".class\";\n URL classResource = codeLocationClass.getClassLoader().getResource(pathOfClass);\n String codeLocationPath = removeEnd(getPathFromURL(classResource), pathOfClass);\n if(codeLocationPath.endsWith(\".jar!/\")) {\n codeLocationPath=removeEnd(codeLocationPath,\"!/\");\n }\n return codeLocationFromPath(codeLocationPath);\n }",
"public void addRow(String primaryKeyColumnName, Map<String, Object> map)\n {\n Integer rowNumber = Integer.valueOf(m_rowNumber++);\n map.put(\"ROW_NUMBER\", rowNumber);\n Object primaryKey = null;\n if (primaryKeyColumnName != null)\n {\n primaryKey = map.get(primaryKeyColumnName);\n }\n\n if (primaryKey == null)\n {\n primaryKey = rowNumber;\n }\n\n MapRow newRow = new MapRow(map);\n MapRow oldRow = m_rows.get(primaryKey);\n if (oldRow == null)\n {\n m_rows.put(primaryKey, newRow);\n }\n else\n {\n int oldVersion = oldRow.getInteger(\"ROW_VERSION\").intValue();\n int newVersion = newRow.getInteger(\"ROW_VERSION\").intValue();\n if (newVersion > oldVersion)\n {\n m_rows.put(primaryKey, newRow);\n }\n }\n }",
"private String readLine(boolean trim) throws IOException {\n boolean done = false;\n boolean sawCarriage = false;\n // bytes to trim (the \\r and the \\n)\n int removalBytes = 0;\n while (!done) {\n if (isReadBufferEmpty()) {\n offset = 0;\n end = 0;\n int bytesRead = inputStream.read(buffer, end, Math.min(DEFAULT_READ_COUNT, buffer.length - end));\n if (bytesRead < 0) {\n // we failed to read anything more...\n throw new IOException(\"Reached the end of the stream\");\n } else {\n end += bytesRead;\n }\n }\n\n int originalOffset = offset;\n for (; !done && offset < end; offset++) {\n if (buffer[offset] == LF) {\n int cpLength = offset - originalOffset + 1;\n if (trim) {\n int length = 0;\n if (buffer[offset] == LF) {\n length ++;\n if (sawCarriage) {\n length++;\n }\n }\n cpLength -= length;\n }\n\n if (cpLength > 0) {\n copyToStrBuffer(buffer, originalOffset, cpLength);\n } else {\n // negative length means we need to trim a \\r from strBuffer\n removalBytes = cpLength;\n }\n done = true;\n } else {\n // did not see newline:\n sawCarriage = buffer[offset] == CR;\n }\n }\n\n if (!done) {\n copyToStrBuffer(buffer, originalOffset, end - originalOffset);\n offset = end;\n }\n }\n int strLength = strBufferIndex + removalBytes;\n strBufferIndex = 0;\n return new String(strBuffer, 0, strLength, charset);\n }",
"public AirMapViewBuilder builder(AirMapViewTypes mapType) {\n switch (mapType) {\n case NATIVE:\n if (isNativeMapSupported) {\n return new NativeAirMapViewBuilder();\n }\n break;\n case WEB:\n return getWebMapViewBuilder();\n }\n throw new UnsupportedOperationException(\"Requested map type is not supported\");\n }"
] |
When creating image columns
@return | [
"protected AbstractColumn buildSimpleImageColumn() {\n\t\tImageColumn column = new ImageColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tpopulateExpressionAttributes(column);\n\t\t\n\t\tcolumn.setExpression(customExpression);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setExpressionForCalculation(customExpressionForCalculation);\n\t\t\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\treturn column;\n\t}"
] | [
"public QueryBuilder<T, ID> orderBy(String columnName, boolean ascending) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't orderBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddOrderBy(new OrderBy(columnName, ascending));\n\t\treturn this;\n\t}",
"protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) {\n if (value == null) {\n return \"\";\n }\n else {\n // midnight GMT\n Date date = new Date(0);\n // offset by timezone and value\n date.setTime(UTCDateBox.timezoneOffsetMillis(date) + value.longValue());\n // format it\n return fmt.format(date);\n }\n }",
"public static Map<String, String> getContentMap(File file, String separator) throws IOException {\n List<String> content = getContentLines(file);\n Map<String, String> map = new LinkedHashMap<String, String>();\n \n for (String line : content) {\n String[] spl = line.split(separator);\n if (line.trim().length() > 0) {\n map.put(spl[0], (spl.length > 1 ? spl[1] : \"\"));\n }\n }\n \n return map;\n }",
"public <CT> CT callBatchTasks(ConnectionSource connectionSource, Callable<CT> callable) throws SQLException {\n\t\tif (connectionSource.isSingleConnection(tableInfo.getTableName())) {\n\t\t\tsynchronized (this) {\n\t\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t\t}\n\t\t} else {\n\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t}\n\t}",
"public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CRFClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CRFClassifier<CoreLabel> crf = new CRFClassifier<CoreLabel>(props);\r\n String testFile = crf.flags.testFile;\r\n String textFile = crf.flags.textFile;\r\n String loadPath = crf.flags.loadClassifier;\r\n String loadTextPath = crf.flags.loadTextClassifier;\r\n String serializeTo = crf.flags.serializeTo;\r\n String serializeToText = crf.flags.serializeToText;\r\n\r\n if (loadPath != null) {\r\n crf.loadClassifierNoExceptions(loadPath, props);\r\n } else if (loadTextPath != null) {\r\n System.err.println(\"Warning: this is now only tested for Chinese Segmenter\");\r\n System.err.println(\"(Sun Dec 23 00:59:39 2007) (pichuan)\");\r\n try {\r\n crf.loadTextClassifier(loadTextPath, props);\r\n // System.err.println(\"DEBUG: out from crf.loadTextClassifier\");\r\n } catch (Exception e) {\r\n throw new RuntimeException(\"error loading \" + loadTextPath, e);\r\n }\r\n } else if (crf.flags.loadJarClassifier != null) {\r\n crf.loadJarClassifier(crf.flags.loadJarClassifier, props);\r\n } else if (crf.flags.trainFile != null || crf.flags.trainFileList != null) {\r\n crf.train();\r\n } else {\r\n crf.loadDefaultClassifier();\r\n }\r\n\r\n // System.err.println(\"Using \" + crf.flags.featureFactory);\r\n // System.err.println(\"Using \" +\r\n // StringUtils.getShortClassName(crf.readerAndWriter));\r\n\r\n if (serializeTo != null) {\r\n crf.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (serializeToText != null) {\r\n crf.serializeTextClassifier(serializeToText);\r\n }\r\n\r\n if (testFile != null) {\r\n DocumentReaderAndWriter<CoreLabel> readerAndWriter = crf.makeReaderAndWriter();\r\n if (crf.flags.searchGraphPrefix != null) {\r\n crf.classifyAndWriteViterbiSearchGraph(testFile, crf.flags.searchGraphPrefix, crf.makeReaderAndWriter());\r\n } else if (crf.flags.printFirstOrderProbs) {\r\n crf.printFirstOrderProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.printProbs) {\r\n crf.printProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.useKBest) {\r\n int k = crf.flags.kBest;\r\n crf.classifyAndWriteAnswersKBest(testFile, k, readerAndWriter);\r\n } else if (crf.flags.printLabelValue) {\r\n crf.printLabelInformation(testFile, readerAndWriter);\r\n } else {\r\n crf.classifyAndWriteAnswers(testFile, readerAndWriter);\r\n }\r\n }\r\n\r\n if (textFile != null) {\r\n crf.classifyAndWriteAnswers(textFile);\r\n }\r\n\r\n if (crf.flags.readStdin) {\r\n crf.classifyStdin();\r\n }\r\n }",
"public void removeLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (declaration.getStatus().getServiceReferencesBounded().contains(declarationBinderRef)) {\n linkerManagement.unlink(declaration, declarationBinderRef);\n }\n }\n }",
"public Results analyze(RuleSet ruleSet) {\r\n long startTime = System.currentTimeMillis();\r\n DirectoryResults reportResults = new DirectoryResults();\r\n\r\n int numThreads = Runtime.getRuntime().availableProcessors() - 1;\r\n numThreads = numThreads > 0 ? numThreads : 1;\r\n\r\n ExecutorService pool = Executors.newFixedThreadPool(numThreads);\r\n\r\n for (FileSet fileSet : fileSets) {\r\n processFileSet(fileSet, ruleSet, pool);\r\n }\r\n\r\n pool.shutdown();\r\n\r\n try {\r\n boolean completed = pool.awaitTermination(POOL_TIMEOUT_SECONDS, TimeUnit.SECONDS);\r\n if (!completed) {\r\n throw new IllegalStateException(\"Thread Pool terminated before comp<FileResults>letion\");\r\n }\r\n } catch (InterruptedException e) {\r\n throw new IllegalStateException(\"Thread Pool interrupted before completion\");\r\n }\r\n\r\n addDirectoryResults(reportResults);\r\n LOG.info(\"Analysis time=\" + (System.currentTimeMillis() - startTime) + \"ms\");\r\n return reportResults;\r\n }",
"public static spilloverpolicy[] get(nitro_service service, options option) throws Exception{\n\t\tspilloverpolicy obj = new spilloverpolicy();\n\t\tspilloverpolicy[] response = (spilloverpolicy[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"public List<TimephasedCost> getTimephasedBaselineCost(int index)\n {\n return m_timephasedBaselineCost[index] == null ? null : m_timephasedBaselineCost[index].getData();\n }"
] |
Read leaf tasks attached to the WBS.
@param id initial WBS ID | [
"private void readTasks(Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"WBSTAB\");\n\n while (currentID.intValue() != 0)\n {\n MapRow row = table.find(currentID);\n Task task = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID\"));\n readLeafTasks(task, row.getInteger(\"FIRST_CHILD_TASK_ID\"));\n Integer childID = row.getInteger(\"CHILD_ID\");\n if (childID.intValue() != 0)\n {\n readTasks(childID);\n }\n currentID = row.getInteger(\"NEXT_ID\");\n }\n }"
] | [
"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 static TxInfo getTransactionInfo(Environment env, Bytes prow, Column pcol, long startTs) {\n // TODO ensure primary is visible\n\n IteratorSetting is = new IteratorSetting(10, RollbackCheckIterator.class);\n RollbackCheckIterator.setLocktime(is, startTs);\n\n Entry<Key, Value> entry = ColumnUtil.checkColumn(env, is, prow, pcol);\n\n TxInfo txInfo = new TxInfo();\n\n if (entry == null) {\n txInfo.status = TxStatus.UNKNOWN;\n return txInfo;\n }\n\n ColumnType colType = ColumnType.from(entry.getKey());\n long ts = entry.getKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK;\n\n switch (colType) {\n case LOCK: {\n if (ts == startTs) {\n txInfo.status = TxStatus.LOCKED;\n txInfo.lockValue = entry.getValue().get();\n } else {\n txInfo.status = TxStatus.UNKNOWN; // locked by another tx\n }\n break;\n }\n case DEL_LOCK: {\n DelLockValue dlv = new DelLockValue(entry.getValue().get());\n\n if (ts != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(prow + \" \" + pcol + \" (\" + ts + \" != \" + startTs + \") \");\n }\n\n if (dlv.isRollback()) {\n txInfo.status = TxStatus.ROLLED_BACK;\n } else {\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = dlv.getCommitTimestamp();\n }\n break;\n }\n case WRITE: {\n long timePtr = WriteValue.getTimestamp(entry.getValue().get());\n\n if (timePtr != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(\n prow + \" \" + pcol + \" (\" + timePtr + \" != \" + startTs + \") \");\n }\n\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = ts;\n break;\n }\n default:\n throw new IllegalStateException(\"unexpected col type returned \" + colType);\n }\n\n return txInfo;\n }",
"@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n // Calculate summaries.\n summaryListener.suiteSummary(e);\n\n Description suiteDescription = e.getDescription();\n String displayName = suiteDescription.getDisplayName();\n if (displayName.trim().isEmpty()) {\n junit4.log(\"Could not emit XML report for suite (null description).\", \n Project.MSG_WARN);\n return;\n }\n\n if (!suiteCounts.containsKey(displayName)) {\n suiteCounts.put(displayName, 1);\n } else {\n int newCount = suiteCounts.get(displayName) + 1;\n suiteCounts.put(displayName, newCount);\n if (!ignoreDuplicateSuites && newCount == 2) {\n junit4.log(\"Duplicate suite name used with XML reports: \"\n + displayName + \". This may confuse tools that process XML reports. \"\n + \"Set 'ignoreDuplicateSuites' to true to skip this message.\", Project.MSG_WARN);\n }\n displayName = displayName + \"-\" + newCount;\n }\n \n try {\n File reportFile = new File(dir, \"TEST-\" + displayName + \".xml\");\n RegistryMatcher rm = new RegistryMatcher();\n rm.bind(String.class, new XmlStringTransformer());\n Persister persister = new Persister(rm);\n persister.write(buildModel(e), reportFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize report for suite \"\n + displayName + \": \" + x.toString(), x, Project.MSG_WARN);\n }\n }",
"public void delete(Object obj, boolean ignoreReferences) throws PersistenceBrokerException\n {\n if(isTxCheck() && !isInTransaction())\n {\n if(logger.isEnabledFor(Logger.ERROR))\n {\n String msg = \"No running PB-tx found. Please, only delete objects in context of a PB-transaction\" +\n \" to avoid side-effects - e.g. when rollback of complex objects.\";\n try\n {\n throw new Exception(\"** Delete object without active PersistenceBroker transaction **\");\n }\n catch(Exception e)\n {\n logger.error(msg, e);\n }\n }\n }\n try\n {\n doDelete(obj, ignoreReferences);\n }\n finally\n {\n markedForDelete.clear();\n }\n }",
"public static Cluster swapGreedyRandomPartitions(final Cluster nextCandidateCluster,\n final List<Integer> nodeIds,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<StoreDefinition> storeDefs) {\n\n System.out.println(\"GreedyRandom : nodeIds:\" + nodeIds);\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n int nodeIdA = -1;\n int nodeIdB = -1;\n int partitionIdA = -1;\n int partitionIdB = -1;\n\n for(int nodeIdAPrime: nodeIds) {\n System.out.println(\"GreedyRandom : processing nodeId:\" + nodeIdAPrime);\n List<Integer> partitionIdsAPrime = new ArrayList<Integer>();\n partitionIdsAPrime.addAll(returnCluster.getNodeById(nodeIdAPrime).getPartitionIds());\n Collections.shuffle(partitionIdsAPrime);\n\n int maxPartitionsInAPrime = Math.min(greedySwapMaxPartitionsPerNode,\n partitionIdsAPrime.size());\n\n for(int offsetAPrime = 0; offsetAPrime < maxPartitionsInAPrime; offsetAPrime++) {\n Integer partitionIdAPrime = partitionIdsAPrime.get(offsetAPrime);\n List<Pair<Integer, Integer>> partitionIdsZone = new ArrayList<Pair<Integer, Integer>>();\n for(int nodeIdBPrime: nodeIds) {\n if(nodeIdBPrime == nodeIdAPrime)\n continue;\n for(Integer partitionIdBPrime: returnCluster.getNodeById(nodeIdBPrime)\n .getPartitionIds()) {\n partitionIdsZone.add(new Pair<Integer, Integer>(nodeIdBPrime,\n partitionIdBPrime));\n }\n }\n\n Collections.shuffle(partitionIdsZone);\n int maxPartitionsInZone = Math.min(greedySwapMaxPartitionsPerZone,\n partitionIdsZone.size());\n for(int offsetZone = 0; offsetZone < maxPartitionsInZone; offsetZone++) {\n Integer nodeIdBPrime = partitionIdsZone.get(offsetZone).getFirst();\n Integer partitionIdBPrime = partitionIdsZone.get(offsetZone).getSecond();\n Cluster swapResult = swapPartitions(returnCluster,\n nodeIdAPrime,\n partitionIdAPrime,\n nodeIdBPrime,\n partitionIdBPrime);\n double swapUtility = new PartitionBalance(swapResult, storeDefs).getUtility();\n if(swapUtility < currentUtility) {\n currentUtility = swapUtility;\n System.out.println(\" -> \" + currentUtility);\n nodeIdA = nodeIdAPrime;\n partitionIdA = partitionIdAPrime;\n nodeIdB = nodeIdBPrime;\n partitionIdB = partitionIdBPrime;\n }\n }\n }\n }\n\n if(nodeIdA == -1) {\n return returnCluster;\n }\n return swapPartitions(returnCluster, nodeIdA, partitionIdA, nodeIdB, partitionIdB);\n }",
"public static String formatConnectionEstablishmentMessage(final String connectionName, final String host, final String connectionReason) {\n\t\treturn CON_ESTABLISHMENT_FORMAT.format(new Object[] { connectionName, host, connectionReason });\n\t}",
"public static List<? extends Expression> getMethodArguments(ASTNode methodCall) {\r\n if (methodCall instanceof ConstructorCallExpression) {\r\n return extractExpressions(((ConstructorCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof MethodCallExpression) {\r\n return extractExpressions(((MethodCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof StaticMethodCallExpression) {\r\n return extractExpressions(((StaticMethodCallExpression) methodCall).getArguments());\r\n } else if (respondsTo(methodCall, \"getArguments\")) {\r\n throw new RuntimeException(); // TODO: remove, should never happen\r\n }\r\n return new ArrayList<Expression>();\r\n }",
"@Override\n\tpublic void processItemDocument(ItemDocument itemDocument) {\n\t\tthis.countItems++;\n\n\t\t// Do some printing for demonstration/debugging.\n\t\t// Only print at most 50 items (or it would get too slow).\n\t\tif (this.countItems < 10) {\n\t\t\tSystem.out.println(itemDocument);\n\t\t} else if (this.countItems == 10) {\n\t\t\tSystem.out.println(\"*** I won't print any further items.\\n\"\n\t\t\t\t\t+ \"*** We will never finish if we print all the items.\\n\"\n\t\t\t\t\t+ \"*** Maybe remove this debug output altogether.\");\n\t\t}\n\t}",
"private void writeCustomInfo(Event event) {\n // insert customInfo (key/value) into DB\n for (Map.Entry<String, String> customInfo : event.getCustomInfo().entrySet()) {\n long cust_id = dbDialect.getIncrementer().nextLongValue();\n getJdbcTemplate()\n .update(\"insert into EVENTS_CUSTOMINFO (ID, EVENT_ID, CUST_KEY, CUST_VALUE)\"\n + \" values (?,?,?,?)\",\n cust_id, event.getPersistedId(), customInfo.getKey(), customInfo.getValue());\n }\n }"
] |
Gets the explorer file entry options.
@return the explorer file entry options | [
"@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 static XMLGregorianCalendar convertDate(Date date) {\n if (date == null) {\n return null;\n }\n\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTimeInMillis(date.getTime());\n\n try {\n return getDatatypeFactory().newXMLGregorianCalendar(gc);\r\n } catch (DatatypeConfigurationException ex) {\n return null;\n }\n }",
"private boolean isForGerritHost(HttpRequest request) {\n if (!(request instanceof HttpRequestWrapper)) return false;\n HttpRequest originalRequest = ((HttpRequestWrapper) request).getOriginal();\n if (!(originalRequest instanceof HttpRequestBase)) return false;\n URI uri = ((HttpRequestBase) originalRequest).getURI();\n URI authDataUri = URI.create(authData.getHost());\n if (uri == null || uri.getHost() == null) return false;\n boolean hostEquals = uri.getHost().equals(authDataUri.getHost());\n boolean portEquals = uri.getPort() == authDataUri.getPort();\n return hostEquals && portEquals;\n }",
"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 search(String query) {\n final Query newQuery = searcher.getQuery().setQuery(query);\n searcher.setQuery(newQuery).search();\n }",
"protected final boolean isValidEndTypeForPattern() {\n\n if (getEndType() == null) {\n return false;\n }\n switch (getPatternType()) {\n case DAILY:\n case WEEKLY:\n case MONTHLY:\n case YEARLY:\n return (getEndType().equals(EndType.DATE) || getEndType().equals(EndType.TIMES));\n case INDIVIDUAL:\n case NONE:\n return getEndType().equals(EndType.SINGLE);\n default:\n return false;\n }\n }",
"protected int readByte(InputStream is) throws IOException\n {\n byte[] data = new byte[1];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getByte(data, 0));\n }",
"public static int NextPowerOf2(int x) {\r\n --x;\r\n x |= x >> 1;\r\n x |= x >> 2;\r\n x |= x >> 4;\r\n x |= x >> 8;\r\n x |= x >> 16;\r\n return ++x;\r\n }",
"private void verifyApplicationName(String name) {\n if (name == null) {\n throw new IllegalArgumentException(\"Application name cannot be null\");\n }\n if (name.isEmpty()) {\n throw new IllegalArgumentException(\"Application name length must be > 0\");\n }\n String reason = null;\n char[] chars = name.toCharArray();\n char c;\n for (int i = 0; i < chars.length; i++) {\n c = chars[i];\n if (c == 0) {\n reason = \"null character not allowed @\" + i;\n break;\n } else if (c == '/' || c == '.' || c == ':') {\n reason = \"invalid character '\" + c + \"'\";\n break;\n } else if (c > '\\u0000' && c <= '\\u001f' || c >= '\\u007f' && c <= '\\u009F'\n || c >= '\\ud800' && c <= '\\uf8ff' || c >= '\\ufff0' && c <= '\\uffff') {\n reason = \"invalid character @\" + i;\n break;\n }\n }\n if (reason != null) {\n throw new IllegalArgumentException(\n \"Invalid application name \\\"\" + name + \"\\\" caused by \" + reason);\n }\n }",
"public static List<? extends Expression> getMethodArguments(ASTNode methodCall) {\r\n if (methodCall instanceof ConstructorCallExpression) {\r\n return extractExpressions(((ConstructorCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof MethodCallExpression) {\r\n return extractExpressions(((MethodCallExpression) methodCall).getArguments());\r\n } else if (methodCall instanceof StaticMethodCallExpression) {\r\n return extractExpressions(((StaticMethodCallExpression) methodCall).getArguments());\r\n } else if (respondsTo(methodCall, \"getArguments\")) {\r\n throw new RuntimeException(); // TODO: remove, should never happen\r\n }\r\n return new ArrayList<Expression>();\r\n }"
] |
Remove pairs with the given keys from the map.
@param <K> type of the map keys.
@param <V> type of the map values.
@param map the map to update.
@param keysToRemove the keys of the pairs to remove.
@since 2.15 | [
"public static <K, V> void operator_remove(Map<K, V> map, Iterable<? super K> keysToRemove) {\n\t\tfor (final Object key : keysToRemove) {\n\t\t\tmap.remove(key);\n\t\t}\n\t}"
] | [
"private boolean isOrdinal(int paramType) {\n\t\tswitch ( paramType ) {\n\t\t\tcase Types.INTEGER:\n\t\t\tcase Types.NUMERIC:\n\t\t\tcase Types.SMALLINT:\n\t\t\tcase Types.TINYINT:\n\t\t\tcase Types.BIGINT:\n\t\t\tcase Types.DECIMAL: //for Oracle Driver\n\t\t\tcase Types.DOUBLE: //for Oracle Driver\n\t\t\tcase Types.FLOAT: //for Oracle Driver\n\t\t\t\treturn true;\n\t\t\tcase Types.CHAR:\n\t\t\tcase Types.LONGVARCHAR:\n\t\t\tcase Types.VARCHAR:\n\t\t\t\treturn false;\n\t\t\tdefault:\n\t\t\t\tthrow new HibernateException( \"Unable to persist an Enum in a column of SQL Type: \" + paramType );\n\t\t}\n\t}",
"public static String plus(CharSequence left, Object value) {\n return left + DefaultGroovyMethods.toString(value);\n }",
"@Override\r\n public String upload(File file, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(file);\r\n return sendUploadRequest(metaData, payload);\r\n }",
"protected void removeWatermark(URLTemplate itemUrl) {\n URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID());\n URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"synchronized ArrayList<CTMessageDAO> getMessages(String userId){\n final String tName = Table.INBOX_MESSAGES.getName();\n Cursor cursor;\n ArrayList<CTMessageDAO> messageDAOArrayList = new ArrayList<>();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n cursor= db.rawQuery(\"SELECT * FROM \"+tName+\" WHERE \" + USER_ID + \" = ? ORDER BY \" + KEY_CREATED_AT+ \" DESC\", new String[]{userId});\n if(cursor != null) {\n while(cursor.moveToNext()){\n CTMessageDAO ctMessageDAO = new CTMessageDAO();\n ctMessageDAO.setId(cursor.getString(cursor.getColumnIndex(_ID)));\n ctMessageDAO.setJsonData(new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA))));\n ctMessageDAO.setWzrkParams(new JSONObject(cursor.getString(cursor.getColumnIndex(WZRKPARAMS))));\n ctMessageDAO.setDate(cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT)));\n ctMessageDAO.setExpires(cursor.getLong(cursor.getColumnIndex(EXPIRES)));\n ctMessageDAO.setRead(cursor.getInt(cursor.getColumnIndex(IS_READ)));\n ctMessageDAO.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));\n ctMessageDAO.setTags(cursor.getString(cursor.getColumnIndex(TAGS)));\n ctMessageDAO.setCampaignId(cursor.getString(cursor.getColumnIndex(CAMPAIGN)));\n messageDAOArrayList.add(ctMessageDAO);\n }\n cursor.close();\n }\n return messageDAOArrayList;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e);\n return null;\n } catch (JSONException e) {\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e.getMessage());\n return null;\n } finally {\n dbHelper.close();\n }\n }",
"private void ensureLength(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_LENGTH))\r\n {\r\n String defaultLength = JdbcTypeHelper.getDefaultLengthFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultLength != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no length setting though its jdbc type requires it (in most databases); using default length of \"+defaultLength);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_LENGTH, defaultLength);\r\n }\r\n }\r\n }",
"void processSiteRow(String siteRow) {\n\t\tString[] row = getSiteRowFields(siteRow);\n\n\t\tString filePath = \"\";\n\t\tString pagePath = \"\";\n\n\t\tString dataArray = row[8].substring(row[8].indexOf('{'),\n\t\t\t\trow[8].length() - 2);\n\n\t\t// Explanation for the regular expression below:\n\t\t// \"'{' or ';'\" followed by either\n\t\t// \"NOT: ';', '{', or '}'\" repeated one or more times; or\n\t\t// \"a single '}'\"\n\t\t// The first case matches \";s:5:\\\"paths\\\"\"\n\t\t// but also \";a:2:\" in \"{s:5:\\\"paths\\\";a:2:{s:9:\\ ...\".\n\t\t// The second case matches \";}\" which terminates (sub)arrays.\n\t\tMatcher matcher = Pattern.compile(\"[{;](([^;}{][^;}{]*)|[}])\").matcher(\n\t\t\t\tdataArray);\n\t\tString prevString = \"\";\n\t\tString curString = \"\";\n\t\tString path = \"\";\n\t\tboolean valuePosition = false;\n\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group().substring(1);\n\t\t\tif (match.length() == 0) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (match.charAt(0) == 's') {\n\t\t\t\tvaluePosition = !valuePosition && !\"\".equals(prevString);\n\t\t\t\tcurString = match.substring(match.indexOf('\"') + 1,\n\t\t\t\t\t\tmatch.length() - 2);\n\t\t\t} else if (match.charAt(0) == 'a') {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path + \"/\" + prevString;\n\t\t\t} else if (\"}\".equals(match)) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path.substring(0, path.lastIndexOf('/'));\n\t\t\t}\n\n\t\t\tif (valuePosition && \"file_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tfilePath = curString;\n\t\t\t} else if (valuePosition && \"page_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tpagePath = curString;\n\t\t\t}\n\n\t\t\tprevString = curString;\n\t\t\tcurString = \"\";\n\t\t}\n\n\t\tMwSitesDumpFileProcessor.logger.debug(\"Found site data \\\"\" + row[1]\n\t\t\t\t+ \"\\\" (group \\\"\" + row[3] + \"\\\", language \\\"\" + row[5]\n\t\t\t\t+ \"\\\", type \\\"\" + row[2] + \"\\\")\");\n\t\tthis.sites.setSiteInformation(row[1], row[3], row[5], row[2], filePath,\n\t\t\t\tpagePath);\n\t}",
"private static DumpContentType guessDumpContentType(String fileName) {\n\t\tString lcDumpName = fileName.toLowerCase();\n\t\tif (lcDumpName.contains(\".json.gz\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".json.bz2\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".sql.gz\")) {\n\t\t\treturn DumpContentType.SITES;\n\t\t} else if (lcDumpName.contains(\".xml.bz2\")) {\n\t\t\tif (lcDumpName.contains(\"daily\")) {\n\t\t\t\treturn DumpContentType.DAILY;\n\t\t\t} else if (lcDumpName.contains(\"current\")) {\n\t\t\t\treturn DumpContentType.CURRENT;\n\t\t\t} else {\n\t\t\t\treturn DumpContentType.FULL;\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.warn(\"Could not guess type of the dump file \\\"\" + fileName\n\t\t\t\t\t+ \"\\\". Defaulting to json.gz.\");\n\t\t\treturn DumpContentType.JSON;\n\t\t}\n\t}",
"public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException {\n\t\tlog.debug(\"clipTile before {}\", tile);\n\t\tList<InternalFeature> orgFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tGeometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping.\n\t\tfor (InternalFeature feature : orgFeatures) {\n\t\t\t// clip feature if necessary\n\t\t\tif (exceedsScreenDimensions(feature, scale)) {\n\t\t\t\tlog.debug(\"feature {} exceeds screen dimensions\", feature);\n\t\t\t\tInternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone();\n\t\t\t\ttile.setClipped(true);\n\t\t\t\tvectorFeature.setClipped(true);\n\t\t\t\tif (null == maxScreenBbox) {\n\t\t\t\t\tmaxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin));\n\t\t\t\t}\n\t\t\t\tGeometry clipped = maxScreenBbox.intersection(feature.getGeometry());\n\t\t\t\tvectorFeature.setClippedGeometry(clipped);\n\t\t\t\ttile.addFeature(vectorFeature);\n\t\t\t} else {\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t\tlog.debug(\"clipTile after {}\", tile);\n\t}"
] |
Rotate root widget to make it facing to the front of the scene | [
"public void rotateToFront() {\n GVRTransform transform = mSceneRootObject.getTransform();\n transform.setRotation(1, 0, 0, 0);\n transform.rotateByAxisWithPivot(-frontFacingRotation + 180, 0, 1, 0, 0, 0, 0);\n }"
] | [
"public StochasticPathwiseLevenbergMarquardt getCloneWithModifiedTargetValues(List<RandomVariable> newTargetVaues, List<RandomVariable> newWeights, boolean isUseBestParametersAsInitialParameters) throws CloneNotSupportedException {\n\t\tStochasticPathwiseLevenbergMarquardt clonedOptimizer = clone();\n\t\tclonedOptimizer.targetValues = numberListToDoubleArray(newTargetVaues);\n\t\tclonedOptimizer.weights = numberListToDoubleArray(newWeights);\n\n\t\tif(isUseBestParametersAsInitialParameters && this.done()) {\n\t\t\tclonedOptimizer.initialParameters = this.getBestFitParameters();\n\t\t}\n\n\t\treturn clonedOptimizer;\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 ViewGroup getContentContainer() {\n if (mDragMode == MENU_DRAG_CONTENT) {\n return mContentContainer;\n } else {\n return (ViewGroup) findViewById(android.R.id.content);\n }\n }",
"protected void copyStream(File outputDirectory,\n InputStream stream,\n String targetFileName) throws IOException\n {\n File resourceFile = new File(outputDirectory, targetFileName);\n BufferedReader reader = null;\n Writer writer = null;\n try\n {\n reader = new BufferedReader(new InputStreamReader(stream, ENCODING));\n writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resourceFile), ENCODING));\n\n String line = reader.readLine();\n while (line != null)\n {\n writer.write(line);\n writer.write('\\n');\n line = reader.readLine();\n }\n writer.flush();\n }\n finally\n {\n if (reader != null)\n {\n reader.close();\n }\n if (writer != null)\n {\n writer.close();\n }\n }\n }",
"public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) {\n assertNumericArgument(timeout, true);\n this.requestTimeout = unit.toMillis(timeout);\n return this;\n }",
"private boolean addType(TypeDefinition type) {\n\n if (type == null) {\n return false;\n }\n\n if (type.getBaseTypeId() == null) {\n return false;\n }\n\n // find base type\n TypeDefinition baseType = null;\n if (type.getBaseTypeId() == BaseTypeId.CMIS_DOCUMENT) {\n baseType = copyTypeDefintion(m_types.get(DOCUMENT_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_FOLDER) {\n baseType = copyTypeDefintion(m_types.get(FOLDER_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_RELATIONSHIP) {\n baseType = copyTypeDefintion(m_types.get(RELATIONSHIP_TYPE_ID).getTypeDefinition());\n } else if (type.getBaseTypeId() == BaseTypeId.CMIS_POLICY) {\n baseType = copyTypeDefintion(m_types.get(POLICY_TYPE_ID).getTypeDefinition());\n } else {\n return false;\n }\n\n AbstractTypeDefinition newType = (AbstractTypeDefinition)copyTypeDefintion(type);\n\n // copy property definition\n for (PropertyDefinition<?> propDef : baseType.getPropertyDefinitions().values()) {\n ((AbstractPropertyDefinition<?>)propDef).setIsInherited(Boolean.TRUE);\n newType.addPropertyDefinition(propDef);\n }\n\n // add it\n addTypeInternal(newType);\n return true;\n }",
"public static base_response add(nitro_service client, route6 resource) throws Exception {\n\t\troute6 addresource = new route6();\n\t\taddresource.network = resource.network;\n\t\taddresource.gateway = resource.gateway;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.weight = resource.weight;\n\t\taddresource.distance = resource.distance;\n\t\taddresource.cost = resource.cost;\n\t\taddresource.advertise = resource.advertise;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}",
"@Override\n public final Job queueIn(final Job job, final long millis) {\n return pushAt(job, System.currentTimeMillis() + millis);\n }",
"@JmxOperation(description = \"swapFiles changes this store to use the new data directory\")\n public void swapFiles(String newStoreDirectory) {\n logger.info(\"Swapping files for store '\" + getName() + \"' to \" + newStoreDirectory);\n File newVersionDir = new File(newStoreDirectory);\n\n if(!newVersionDir.exists())\n throw new VoldemortException(\"File \" + newVersionDir.getAbsolutePath()\n + \" does not exist.\");\n\n if(!(newVersionDir.getParentFile().compareTo(storeDir.getAbsoluteFile()) == 0 && ReadOnlyUtils.checkVersionDirName(newVersionDir)))\n throw new VoldemortException(\"Invalid version folder name '\"\n + newVersionDir\n + \"'. Either parent directory is incorrect or format(version-n) is incorrect\");\n\n // retrieve previous version for (a) check if last write is winning\n // (b) if failure, rollback use\n File previousVersionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n if(previousVersionDir == null)\n throw new VoldemortException(\"Could not find any latest directory to swap with in store '\"\n + getName() + \"'\");\n\n long newVersionId = ReadOnlyUtils.getVersionId(newVersionDir);\n long previousVersionId = ReadOnlyUtils.getVersionId(previousVersionDir);\n if(newVersionId == -1 || previousVersionId == -1)\n throw new VoldemortException(\"Unable to parse folder names (\" + newVersionDir.getName()\n + \",\" + previousVersionDir.getName()\n + \") since format(version-n) is incorrect\");\n\n // check if we're greater than latest since we want last write to win\n if(previousVersionId > newVersionId) {\n logger.info(\"No swap required since current latest version \" + previousVersionId\n + \" is greater than swap version \" + newVersionId);\n deleteBackups();\n return;\n }\n\n logger.info(\"Acquiring write lock on '\" + getName() + \"':\");\n fileModificationLock.writeLock().lock();\n boolean success = false;\n try {\n close();\n logger.info(\"Opening primary files for store '\" + getName() + \"' at \"\n + newStoreDirectory);\n\n // open the latest store\n open(newVersionDir);\n success = true;\n } finally {\n try {\n // we failed to do the swap, attempt a rollback to last version\n if(!success)\n rollback(previousVersionDir);\n\n } finally {\n fileModificationLock.writeLock().unlock();\n if(success)\n logger.info(\"Swap operation completed successfully on store \" + getName()\n + \", releasing lock.\");\n else\n logger.error(\"Swap operation failed.\");\n }\n }\n\n // okay we have released the lock and the store is now open again, it is\n // safe to do a potentially slow delete if we have one too many backups\n deleteBackups();\n }"
] |
Record the resource request queue length
@param dest Destination of the socket for which resource request is
enqueued. Will actually record if null. Otherwise will call this
on self and corresponding child with this param null.
@param queueLength The number of entries in the "asynchronous" resource
request queue. | [
"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 java.sql.Time rollTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.sql.Time(gc.getTime().getTime());\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 setSpeed(float newValue) {\n if (newValue < 0) newValue = 0;\n this.pitch.setValue( newValue );\n this.speed.setValue( newValue );\n }",
"public void stop(int waitMillis) throws InterruptedException {\n try {\n if (!isDone()) {\n setExitStatus(new Event(EventType.STOPPED_BY_USER, String.format(\"Stopped by user: waiting for %d ms\", waitMillis)));\n }\n if (!waitForFinish(waitMillis)) {\n logger.warn(\"{} Client thread failed to finish in {} millis\", name, waitMillis);\n }\n } finally {\n rateTracker.shutdown();\n }\n }",
"public Story storyOfPath(Configuration configuration, String storyPath) {\n String storyAsText = configuration.storyLoader().loadStoryAsText(storyPath);\n return configuration.storyParser().parseStory(storyAsText, storyPath);\n }",
"protected List<I_CmsFacetQueryItem> parseFacetQueryItems(JSONObject queryFacetObject) throws JSONException {\n\n JSONArray items = queryFacetObject.getJSONArray(JSON_KEY_QUERY_FACET_QUERY);\n List<I_CmsFacetQueryItem> result = new ArrayList<I_CmsFacetQueryItem>(items.length());\n for (int i = 0; i < items.length(); i++) {\n I_CmsFacetQueryItem item = parseFacetQueryItem(items.getJSONObject(i));\n if (item != null) {\n result.add(item);\n }\n }\n return result;\n }",
"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 }",
"public void setCastShadow(boolean enableFlag)\n {\n GVRSceneObject owner = getOwnerObject();\n\n if (owner != null)\n {\n GVRShadowMap shadowMap = (GVRShadowMap) getComponent(GVRRenderTarget.getComponentType());\n if (enableFlag)\n {\n if (shadowMap != null)\n {\n shadowMap.setEnable(true);\n }\n else\n {\n float angle = (float) Math.acos(getFloat(\"outer_cone_angle\")) * 2.0f;\n GVRCamera shadowCam = GVRShadowMap.makePerspShadowCamera(getGVRContext().getMainScene().getMainCameraRig().getCenterCamera(), angle);\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n mChanged.set(true);\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\n }",
"private static void deleteOldAndEmptyFiles() {\n File dir = LOG_FILE_DIR;\n if (dir.exists()) {\n File[] files = dir.listFiles();\n\n for (File f : files) {\n if (f.length() == 0 ||\n f.lastModified() + MAXFILEAGE < System.currentTimeMillis()) {\n f.delete();\n }\n }\n }\n }"
] |
Convert element to another object given a parameterized type signature
@param context
@param destinationType
the destination type
@param source
the source object
@return the converted object
@throws ConverterException
if conversion failed | [
"@SuppressWarnings(\"unchecked\")\r\n\tpublic <T> T convertElement(ConversionContext context, Object source,\r\n\t\t\tTypeReference<T> destinationType) throws ConverterException {\r\n\t\treturn (T) elementConverter.convert(context, source, destinationType);\r\n\t}"
] | [
"public void setEveryWorkingDay(final boolean isEveryWorkingDay) {\n\n if (m_model.isEveryWorkingDay() != isEveryWorkingDay) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay));\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }",
"private void checkCollectionForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef classDef;\r\n CollectionDescriptorDef collDef;\r\n\r\n for (Iterator it = modelDef.getClasses(); it.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)it.next();\r\n for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)\r\n {\r\n collDef = (CollectionDescriptorDef)collIt.next();\r\n if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))\r\n {\r\n checkIndirectionTable(modelDef, collDef);\r\n }\r\n else\r\n { \r\n checkCollectionForeignkeys(modelDef, collDef);\r\n }\r\n }\r\n }\r\n }\r\n }",
"private static void writeNumber(Class<?> numberClass, Number value, CharBuf buffer) {\n if (numberClass == Integer.class) {\n buffer.addInt((Integer) value);\n } else if (numberClass == Long.class) {\n buffer.addLong((Long) value);\n } else if (numberClass == BigInteger.class) {\n buffer.addBigInteger((BigInteger) value);\n } else if (numberClass == BigDecimal.class) {\n buffer.addBigDecimal((BigDecimal) value);\n } else if (numberClass == Double.class) {\n Double doubleValue = (Double) value;\n if (doubleValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (doubleValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addDouble(doubleValue);\n } else if (numberClass == Float.class) {\n Float floatValue = (Float) value;\n if (floatValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (floatValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addFloat(floatValue);\n } else if (numberClass == Byte.class) {\n buffer.addByte((Byte) value);\n } else if (numberClass == Short.class) {\n buffer.addShort((Short) value);\n } else { // Handle other Number implementations\n buffer.addString(value.toString());\n }\n }",
"private void allClustersEqual(final List<String> clusterUrls) {\n Validate.notEmpty(clusterUrls, \"clusterUrls cannot be null\");\n // If only one clusterUrl return immediately\n if (clusterUrls.size() == 1)\n return;\n AdminClient adminClientLhs = adminClientPerCluster.get(clusterUrls.get(0));\n Cluster clusterLhs = adminClientLhs.getAdminClientCluster();\n for (int index = 1; index < clusterUrls.size(); index++) {\n AdminClient adminClientRhs = adminClientPerCluster.get(clusterUrls.get(index));\n Cluster clusterRhs = adminClientRhs.getAdminClientCluster();\n if (!areTwoClustersEqual(clusterLhs, clusterRhs))\n throw new VoldemortException(\"Cluster \" + clusterLhs.getName()\n + \" is not the same as \" + clusterRhs.getName());\n }\n }",
"private static void close(Closeable closeable) {\n\t\tif (closeable != null) {\n\t\t\ttry {\n\t\t\t\tcloseable.close();\n\t\t\t} catch (IOException ignored) {\n\t\t\t\tlogger.error(\"Failed to close output stream: \"\n\t\t\t\t\t\t+ ignored.getMessage());\n\t\t\t}\n\t\t}\n\t}",
"public static Span exact(CharSequence row) {\n Objects.requireNonNull(row);\n return exact(Bytes.of(row));\n }",
"public static void main(final String[] args) throws IOException\n {\n // This is just a _hack_ ...\n BufferedReader reader = null;\n if (args.length == 0)\n {\n System.err.println(\"No input file specified.\");\n System.exit(-1);\n }\n if (args.length > 1)\n {\n reader = new BufferedReader(new InputStreamReader(new FileInputStream(args[1]), \"UTF-8\"));\n String line = reader.readLine();\n while (line != null && !line.startsWith(\"<!-- ###\"))\n {\n System.out.println(line);\n line = reader.readLine();\n }\n }\n System.out.println(Processor.process(new File(args[0])));\n if (args.length > 1 && reader != null)\n {\n String line = reader.readLine();\n while (line != null)\n {\n System.out.println(line);\n line = reader.readLine();\n }\n reader.close();\n }\n }",
"private void writeAssignmentBaselines(Project.Assignments.Assignment xml, ResourceAssignment mpxj)\n {\n Project.Assignments.Assignment.Baseline baseline = m_factory.createProjectAssignmentsAssignmentBaseline();\n boolean populated = false;\n\n Number cost = mpxj.getBaselineCost();\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printExtendedAttributeCurrency(cost));\n }\n\n Date date = mpxj.getBaselineFinish();\n if (date != null)\n {\n populated = true;\n baseline.setFinish(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n date = mpxj.getBaselineStart();\n if (date != null)\n {\n populated = true;\n baseline.setStart(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n Duration duration = mpxj.getBaselineWork();\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, duration));\n }\n\n if (populated)\n {\n baseline.setNumber(\"0\");\n xml.getBaseline().add(baseline);\n }\n\n for (int loop = 1; loop <= 10; loop++)\n {\n baseline = m_factory.createProjectAssignmentsAssignmentBaseline();\n populated = false;\n\n cost = mpxj.getBaselineCost(loop);\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printExtendedAttributeCurrency(cost));\n }\n\n date = mpxj.getBaselineFinish(loop);\n if (date != null)\n {\n populated = true;\n baseline.setFinish(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n date = mpxj.getBaselineStart(loop);\n if (date != null)\n {\n populated = true;\n baseline.setStart(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n duration = mpxj.getBaselineWork(loop);\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, duration));\n }\n\n if (populated)\n {\n baseline.setNumber(Integer.toString(loop));\n xml.getBaseline().add(baseline);\n }\n }\n }",
"public String getScopes() {\n final StringBuilder sb = new StringBuilder();\n for (final Scope scope : Scope.values()) {\n sb.append(scope);\n sb.append(\", \");\n }\n final String scopes = sb.toString().trim();\n return scopes.substring(0, scopes.length() - 1);\n }"
] |
Performs a Bulk Documents insert request.
@param objects The {@link List} of objects.
@param allOrNothing Indicates whether the request has <tt>all-or-nothing</tt> semantics.
@return {@code List<Response>} Containing the resulted entries. | [
"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 }"
] | [
"@Nullable\n public static LocationEngineResult extractResult(Intent intent) {\n LocationEngineResult result = null;\n if (isOnClasspath(GOOGLE_PLAY_LOCATION_RESULT)) {\n result = extractGooglePlayResult(intent);\n }\n return result == null ? extractAndroidResult(intent) : result;\n }",
"protected boolean hasVectorClock(boolean isVectorClockOptional) {\n boolean result = false;\n\n String vectorClockHeader = this.request.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK);\n if(vectorClockHeader != null) {\n ObjectMapper mapper = new ObjectMapper();\n try {\n VectorClockWrapper vcWrapper = mapper.readValue(vectorClockHeader,\n VectorClockWrapper.class);\n this.parsedVectorClock = new VectorClock(vcWrapper.getVersions(),\n vcWrapper.getTimestamp());\n result = true;\n } catch(Exception e) {\n logger.error(\"Exception while parsing and constructing vector clock\", e);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Invalid Vector Clock\");\n }\n } else if(!isVectorClockOptional) {\n logger.error(\"Error when validating request. Missing Vector Clock\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Vector Clock\");\n } else {\n result = true;\n }\n\n return result;\n }",
"public static void registerMbean(MBeanServer server, ModelMBean mbean, ObjectName name) {\n try {\n synchronized(LOCK) {\n if(server.isRegistered(name))\n JmxUtils.unregisterMbean(server, name);\n server.registerMBean(mbean, name);\n }\n } catch(Exception e) {\n logger.error(\"Error registering mbean:\", e);\n }\n }",
"public static PredicateExpression all(Object... rhs) {\n PredicateExpression ex = new PredicateExpression( \"$all\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n running.set(false);\n pendingUpdates.clear();\n queueHandler.interrupt();\n queueHandler = null;\n\n // Report the loss of our previews, on the proper thread, and outside our lock.\n final Set<DeckReference> dyingCache = new HashSet<DeckReference>(hotCache.keySet());\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingCache) {\n if (deck.hotCue == 0) {\n deliverBeatGridUpdate(deck.player, null);\n }\n }\n }\n });\n hotCache.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }",
"public void processAnonymousField(Properties attributes) throws XDocletException\r\n {\r\n if (!attributes.containsKey(ATTRIBUTE_NAME))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.PARAMETER_IS_REQUIRED,\r\n new String[]{ATTRIBUTE_NAME}));\r\n }\r\n\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n FieldDescriptorDef fieldDef = _curClassDef.getField(name);\r\n String attrName;\r\n\r\n if (fieldDef == null)\r\n {\r\n fieldDef = new FieldDescriptorDef(name);\r\n _curClassDef.addField(fieldDef);\r\n }\r\n fieldDef.setAnonymous();\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processAnonymousField\", \" Processing anonymous field \"+fieldDef.getName());\r\n\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n fieldDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_ACCESS, \"anonymous\");\r\n }",
"public final static int readMdLinkId(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 boolean endReached = false;\n switch (ch)\n {\n case '\\n':\n out.append(' ');\n break;\n case '[':\n counter++;\n out.append(ch);\n break;\n case ']':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n else\n {\n out.append(ch);\n }\n break;\n default:\n out.append(ch);\n break;\n }\n if (endReached)\n {\n break;\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }",
"public void postPhoto(Photo photo, String blogId, String blogPassword) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_POST_PHOTO);\r\n\r\n parameters.put(\"blog_id\", blogId);\r\n parameters.put(\"photo_id\", photo.getId());\r\n parameters.put(\"title\", photo.getTitle());\r\n parameters.put(\"description\", photo.getDescription());\r\n if (blogPassword != null) {\r\n parameters.put(\"blog_password\", blogPassword);\r\n }\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 }",
"public static List<Versioned<byte[]>> pruneNonReplicaEntries(List<Versioned<byte[]>> vals,\n List<Integer> keyReplicas,\n MutableBoolean didPrune) {\n List<Versioned<byte[]>> prunedVals = new ArrayList<Versioned<byte[]>>(vals.size());\n for(Versioned<byte[]> val: vals) {\n VectorClock clock = (VectorClock) val.getVersion();\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>();\n for(ClockEntry clockEntry: clock.getEntries()) {\n if(keyReplicas.contains((int) clockEntry.getNodeId())) {\n clockEntries.add(clockEntry);\n } else {\n didPrune.setValue(true);\n }\n }\n prunedVals.add(new Versioned<byte[]>(val.getValue(),\n new VectorClock(clockEntries, clock.getTimestamp())));\n }\n return prunedVals;\n }"
] |
Convert a Java date into a Planner date.
20070222
@param value Java Date instance
@return Planner date | [
"private String getDateString(Date value)\n {\n Calendar cal = DateHelper.popCalendar(value);\n int year = cal.get(Calendar.YEAR);\n int month = cal.get(Calendar.MONTH) + 1;\n int day = cal.get(Calendar.DAY_OF_MONTH);\n DateHelper.pushCalendar(cal);\n \n StringBuilder sb = new StringBuilder(8);\n sb.append(m_fourDigitFormat.format(year));\n sb.append(m_twoDigitFormat.format(month));\n sb.append(m_twoDigitFormat.format(day));\n\n return (sb.toString());\n }"
] | [
"public void clear() {\n\t\tfor (Bean bean : beans.values()) {\n\t\t\tif (null != bean.destructionCallback) {\n\t\t\t\tbean.destructionCallback.run();\n\t\t\t}\n\t\t}\n\t\tbeans.clear();\n\t}",
"private void addChildrenForGroupsNode(I_CmsOuTreeType type, String ouItem) {\n\n try {\n // Cut of type-specific prefix from ouItem with substring()\n List<CmsGroup> groups = m_app.readGroupsForOu(m_cms, ouItem.substring(1), type, false);\n for (CmsGroup group : groups) {\n Pair<String, CmsUUID> key = Pair.of(type.getId(), group.getId());\n Item groupItem = m_treeContainer.addItem(key);\n if (groupItem == null) {\n groupItem = getItem(key);\n }\n groupItem.getItemProperty(PROP_SID).setValue(group.getId());\n groupItem.getItemProperty(PROP_NAME).setValue(getIconCaptionHTML(group, CmsOuTreeType.GROUP));\n groupItem.getItemProperty(PROP_TYPE).setValue(type);\n setChildrenAllowed(key, false);\n m_treeContainer.setParent(key, ouItem);\n }\n } catch (CmsException e) {\n LOG.error(\"Can not read group\", e);\n }\n }",
"public void setOnQueryTextListener(@NonNull final SearchView.OnQueryTextListener listener) {\n if (searchView != null) {\n searchView.setOnQueryTextListener(listener);\n } else if (supportView != null) {\n supportView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {\n @Override public boolean onQueryTextSubmit(String query) {\n return listener.onQueryTextSubmit(query);\n }\n\n @Override public boolean onQueryTextChange(String newText) {\n return listener.onQueryTextChange(newText);\n }\n });\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }",
"@Override\n public DiscordianDate date(int prolepticYear, int month, int dayOfMonth) {\n return DiscordianDate.of(prolepticYear, month, dayOfMonth);\n }",
"public static int allParametersAndArgumentsMatch(Parameter[] params, ClassNode[] args) {\n if (params==null) {\n params = Parameter.EMPTY_ARRAY;\n }\n int dist = 0;\n if (args.length<params.length) return -1;\n // we already know the lengths are equal\n for (int i = 0; i < params.length; i++) {\n ClassNode paramType = params[i].getType();\n ClassNode argType = args[i];\n if (!isAssignableTo(argType, paramType)) return -1;\n else {\n if (!paramType.equals(argType)) dist+=getDistance(argType, paramType);\n }\n }\n return dist;\n }",
"private void checkTexRange(AiTextureType type, int index) {\n if (index < 0 || index > m_numTextures.get(type)) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Size: \" +\n m_numTextures.get(type));\n }\n }",
"public static autoscaleprofile[] get(nitro_service service) throws Exception{\n\t\tautoscaleprofile obj = new autoscaleprofile();\n\t\tautoscaleprofile[] response = (autoscaleprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public <T> Observable<T> delayedEmitAsync(T event, int milliseconds) {\n return Observable.just(event).delay(milliseconds, TimeUnit.MILLISECONDS, Schedulers.immediate());\n }",
"public static Iterable<BoxUser.Info> getAppUsersByExternalAppUserID(final BoxAPIConnection api,\n final String externalAppUserId, final String... fields) {\n return getUsersInfoForType(api, null, null, externalAppUserId, fields);\n }"
] |
Checks if the object with the given identity has been deleted
within the transaction.
@param id The identity
@return true if the object has been deleted
@throws PersistenceBrokerException | [
"public boolean isDeleted(Identity id)\r\n {\r\n ObjectEnvelope envelope = buffer.getByIdentity(id);\r\n\r\n return (envelope != null && envelope.needsDelete());\r\n }"
] | [
"public static File guessKeyRingFile() throws FileNotFoundException {\n final Collection<String> possibleLocations = getKnownPGPSecureRingLocations();\n for (final String location : possibleLocations) {\n final File candidate = new File(location);\n if (candidate.exists()) {\n return candidate;\n }\n }\n final StringBuilder message = new StringBuilder(\"Could not locate secure keyring, locations tried: \");\n final Iterator<String> it = possibleLocations.iterator();\n while (it.hasNext()) {\n message.append(it.next());\n if (it.hasNext()) {\n message.append(\", \");\n }\n }\n throw new FileNotFoundException(message.toString());\n }",
"public void trace(String msg) {\n\t\tlogIfEnabled(Level.TRACE, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}",
"protected NodeData createPageStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"relative\")));\n\t\tret.push(createDeclaration(\"border-width\", tf.createLength(1f, Unit.px)));\n\t\tret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n\t\tret.push(createDeclaration(\"border-color\", tf.createColor(0, 0, 255)));\n\t\tret.push(createDeclaration(\"margin\", tf.createLength(0.5f, Unit.em)));\n\t\t\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n ret.push(createDeclaration(\"width\", tf.createLength(w, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(h, unit)));\n }\n else\n log.warn(\"No media box found\");\n \n return ret;\n }",
"public static authenticationvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_auditnslogpolicy_binding obj = new authenticationvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_auditnslogpolicy_binding response[] = (authenticationvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public boolean matchesWithMask(IPAddress other, IPAddress mask) {\n\t\treturn getSection().matchesWithMask(other.getSection(), mask.getSection());\n\t}",
"public static String getHeaders(HttpServletResponse response) {\n String headerString = \"\";\n Collection<String> headerNames = response.getHeaderNames();\n for (String headerName : headerNames) {\n // there may be multiple headers per header name\n for (String headerValue : response.getHeaders(headerName)) {\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += headerName + \": \" + headerValue;\n }\n }\n\n return headerString;\n }",
"protected void updateStep(int stepNo) {\n\n if ((0 <= stepNo) && (stepNo < m_steps.size())) {\n Class<? extends A_CmsSetupStep> cls = m_steps.get(stepNo);\n A_CmsSetupStep step;\n try {\n step = cls.getConstructor(I_SetupUiContext.class).newInstance(this);\n showStep(step);\n m_stepNo = stepNo; // Only update step number if no exceptions\n } catch (Exception e) {\n CmsSetupErrorDialog.showErrorDialog(e);\n }\n\n }\n }",
"public static String readDesignerVersion(ServletContext context) {\n String retStr = \"\";\n BufferedReader br = null;\n try {\n InputStream inputStream = context.getResourceAsStream(\"/META-INF/MANIFEST.MF\");\n br = new BufferedReader(new InputStreamReader(inputStream,\n \"UTF-8\"));\n String line;\n while ((line = br.readLine()) != null) {\n if (line.startsWith(BUNDLE_VERSION)) {\n retStr = line.substring(BUNDLE_VERSION.length() + 1);\n retStr = retStr.trim();\n }\n }\n inputStream.close();\n } catch (Exception e) {\n logger.error(e.getMessage(),\n e);\n } finally {\n if (br != null) {\n IOUtils.closeQuietly(br);\n }\n }\n return retStr;\n }",
"public static int skipToNextMatchingShort(byte[] buffer, int offset, int value)\n {\n int nextOffset = offset;\n while (getShort(buffer, nextOffset) != value)\n {\n ++nextOffset;\n }\n nextOffset += 2;\n\n return nextOffset;\n }"
] |
Use this API to change sslcertkey resources. | [
"public static base_responses change(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey updateresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslcertkey();\n\t\t\t\tupdateresources[i].certkey = resources[i].certkey;\n\t\t\t\tupdateresources[i].cert = resources[i].cert;\n\t\t\t\tupdateresources[i].key = resources[i].key;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].fipskey = resources[i].fipskey;\n\t\t\t\tupdateresources[i].inform = resources[i].inform;\n\t\t\t\tupdateresources[i].passplain = resources[i].passplain;\n\t\t\t\tupdateresources[i].nodomaincheck = resources[i].nodomaincheck;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, updateresources,\"update\");\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public GVRAnimation setOnFinish(GVROnFinish callback) {\n mOnFinish = callback;\n\n // Do the instance-of test at set-time, not at use-time\n mOnRepeat = callback instanceof GVROnRepeat ? (GVROnRepeat) callback\n : null;\n if (mOnRepeat != null) {\n mRepeatCount = -1; // loop until iterate() returns false\n }\n return this;\n }",
"public static Collection<String> getFormatProviderNames() {\n Collection<String> providers = Optional.ofNullable(getMonetaryFormatsSpi()).orElseThrow(\n () -> new MonetaryException(\n \"No MonetaryFormatsSingletonSpi loaded, query functionality is not available.\"))\n .getProviderNames();\n if (Objects.isNull(providers)) {\n Logger.getLogger(MonetaryFormats.class.getName()).warning(\n \"No supported rate/conversion providers returned by SPI: \" +\n getMonetaryFormatsSpi().getClass().getName());\n return Collections.emptySet();\n }\n return providers;\n }",
"public int[] sampleBatchWithReplacement() {\n // Sample the indices with replacement.\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n batch[i] = Prng.nextInt(numExamples);\n }\n return batch;\n }",
"public DbOrganization getOrganization(final DbArtifact dbArtifact) {\n final DbModule module = getModule(dbArtifact);\n\n if(module == null || module.getOrganization() == null){\n return null;\n }\n\n return repositoryHandler.getOrganization(module.getOrganization());\n }",
"static Style get(final GridParam params) {\n final StyleBuilder builder = new StyleBuilder();\n\n final Symbolizer pointSymbolizer = crossSymbolizer(\"shape://plus\", builder, CROSS_SIZE,\n params.gridColor);\n final Style style = builder.createStyle(pointSymbolizer);\n final List<Symbolizer> symbolizers = style.featureTypeStyles().get(0).rules().get(0).symbolizers();\n\n if (params.haloRadius > 0.0) {\n Symbolizer halo = crossSymbolizer(\"cross\", builder, CROSS_SIZE + params.haloRadius * 2.0,\n params.haloColor);\n symbolizers.add(0, halo);\n }\n\n return style;\n }",
"private void readCollectionElement(\n\t\tfinal Object optionalOwner,\n\t\tfinal Serializable optionalKey,\n\t\tfinal CollectionPersister persister,\n\t\tfinal CollectionAliases descriptor,\n\t\tfinal ResultSet rs,\n\t\tfinal SharedSessionContractImplementor session)\n\t\t\t\tthrows HibernateException, SQLException {\n\n\t\tfinal PersistenceContext persistenceContext = session.getPersistenceContext();\n\n\t\t//implement persister.readKey using the grid type (later)\n\t\tfinal Serializable collectionRowKey = (Serializable) persister.readKey(\n\t\t\t\trs,\n\t\t\t\tdescriptor.getSuffixedKeyAliases(),\n\t\t\t\tsession\n\t\t);\n\n\t\tif ( collectionRowKey != null ) {\n\t\t\t// we found a collection element in the result set\n\n\t\t\tif ( log.isDebugEnabled() ) {\n\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"found row of collection: \" +\n\t\t\t\t\t\tMessageHelper.collectionInfoString( persister, collectionRowKey, getFactory() )\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tObject owner = optionalOwner;\n\t\t\tif ( owner == null ) {\n\t\t\t\towner = persistenceContext.getCollectionOwner( collectionRowKey, persister );\n\t\t\t\tif ( owner == null ) {\n\t\t\t\t\t//TODO: This is assertion is disabled because there is a bug that means the\n\t\t\t\t\t//\t original owner of a transient, uninitialized collection is not known\n\t\t\t\t\t//\t if the collection is re-referenced by a different object associated\n\t\t\t\t\t//\t with the current Session\n\t\t\t\t\t//throw new AssertionFailure(\"bug loading unowned collection\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tPersistentCollection rowCollection = persistenceContext.getLoadContexts()\n\t\t\t\t\t.getCollectionLoadContext( rs )\n\t\t\t\t\t.getLoadingCollection( persister, collectionRowKey );\n\n\t\t\tif ( rowCollection != null ) {\n\t\t\t\thydrateRowCollection( persister, descriptor, rs, owner, rowCollection );\n\t\t\t}\n\n\t\t}\n\t\telse if ( optionalKey != null ) {\n\t\t\t// we did not find a collection element in the result set, so we\n\t\t\t// ensure that a collection is created with the owner's identifier,\n\t\t\t// since what we have is an empty collection\n\n\t\t\tif ( log.isDebugEnabled() ) {\n\t\t\t\tlog.debug(\n\t\t\t\t\t\t\"result set contains (possibly empty) collection: \" +\n\t\t\t\t\t\tMessageHelper.collectionInfoString( persister, optionalKey, getFactory() )\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tpersistenceContext.getLoadContexts()\n\t\t\t\t\t.getCollectionLoadContext( rs )\n\t\t\t\t\t.getLoadingCollection( persister, optionalKey ); // handle empty collection\n\n\t\t}\n\n\t\t// else no collection element, but also no owner\n\n\t}",
"@Override\n public void setJobQueue(int jobId, Queue queue)\n {\n JqmClientFactory.getClient().setJobQueue(jobId, queue);\n }",
"public void insert(Platform platform, Database model, int batchSize) throws SQLException\r\n {\r\n if (batchSize <= 1)\r\n {\r\n for (Iterator it = _beans.iterator(); it.hasNext();)\r\n {\r\n platform.insert(model, (DynaBean)it.next());\r\n }\r\n }\r\n else\r\n {\r\n for (int startIdx = 0; startIdx < _beans.size(); startIdx += batchSize)\r\n {\r\n platform.insert(model, _beans.subList(startIdx, startIdx + batchSize));\r\n }\r\n }\r\n }",
"public static boolean canParseColor(final String colorString) {\n try {\n return ColorParser.toColor(colorString) != null;\n } catch (Exception exc) {\n return false;\n }\n }"
] |
Parses the comma delimited address into model nodes.
@param profileName the profile name for the domain or {@code null} if not a domain
@param inputAddress the address.
@return a collection of the address nodes. | [
"private ModelNode parseAddress(final String profileName, final String inputAddress) {\n final ModelNode result = new ModelNode();\n if (profileName != null) {\n result.add(ServerOperations.PROFILE, profileName);\n }\n String[] parts = inputAddress.split(\",\");\n for (String part : parts) {\n String[] address = part.split(\"=\");\n if (address.length != 2) {\n throw new RuntimeException(part + \" is not a valid address segment\");\n }\n result.add(address[0], address[1]);\n }\n return result;\n }"
] | [
"public static void main(String[] args) {\n try {\n new StartMain(args).go();\n } catch(Throwable t) {\n WeldSELogger.LOG.error(\"Application exited with an exception\", t);\n System.exit(1);\n }\n }",
"public static base_responses delete(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = resources[i].serverip;\n\t\t\t\tdeleteresources[i].servername = resources[i].servername;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void storeToDb(Object obj, ClassDescriptor cld, Identity oid, boolean insert, boolean ignoreReferences)\n {\n // 1. link and store 1:1 references\n storeReferences(obj, cld, insert, ignoreReferences);\n\n Object[] pkValues = oid.getPrimaryKeyValues();\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n // BRJ: fk values may be part of pk, but the are not known during\n // creation of Identity. so we have to get them here\n pkValues = serviceBrokerHelper().getKeyValues(cld, obj);\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n String append = insert ? \" on insert\" : \" on update\" ;\n throw new PersistenceBrokerException(\"assertValidPkFields failed for Object of type: \" + cld.getClassNameOfObject() + append);\n }\n }\n\n // get super class cld then store it with the object\n /*\n now for multiple table inheritance\n 1. store super classes, topmost parent first\n 2. go down through heirarchy until current class\n 3. todo: store to full extent?\n\n// arminw: TODO: The extend-attribute feature dosn't work, should we remove this stuff?\n This if-clause will go up the inheritance heirarchy to store all the super classes.\n The id for the top most super class will be the id for all the subclasses too\n */\n if(cld.getSuperClass() != null)\n {\n\n ClassDescriptor superCld = getDescriptorRepository().getDescriptorFor(cld.getSuperClass());\n storeToDb(obj, superCld, oid, insert);\n // arminw: why this?? I comment out this section\n // storeCollections(obj, cld.getCollectionDescriptors(), insert);\n }\n\n // 2. store primitive typed attributes (Or is THIS step 3 ?)\n // if obj not present in db use INSERT\n if (insert)\n {\n dbAccess.executeInsert(cld, obj);\n if(oid.isTransient())\n {\n // Create a new Identity based on the current set of primary key values.\n oid = serviceIdentity().buildIdentity(cld, obj);\n }\n }\n // else use UPDATE\n else\n {\n try\n {\n dbAccess.executeUpdate(cld, obj);\n }\n catch(OptimisticLockException e)\n {\n // ensure that the outdated object be removed from cache\n objectCache.remove(oid);\n throw e;\n }\n }\n // cache object for symmetry with getObjectByXXX()\n // Add the object to the cache.\n objectCache.doInternalCache(oid, obj, ObjectCacheInternal.TYPE_WRITE);\n // 3. store 1:n and m:n associations\n if(!ignoreReferences) storeCollections(obj, cld, insert);\n }",
"public ParallelTaskBuilder prepareHttpOptions(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.OPTIONS);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n\n }",
"public void addProducer(Broker broker) {\n Properties props = new Properties();\n props.put(\"host\", broker.host);\n props.put(\"port\", \"\" + broker.port);\n props.putAll(config.getProperties());\n if (sync) {\n SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));\n logger.info(\"Creating sync producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n syncProducers.put(broker.id, producer);\n } else {\n AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//\n new SyncProducer(new SyncProducerConfig(props)),//\n serializer,//\n eventHandler,//\n config.getEventHandlerProperties(),//\n this.callbackHandler, //\n config.getCbkHandlerProperties());\n producer.start();\n logger.info(\"Creating async producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n asyncProducers.put(broker.id, producer);\n }\n }",
"public static int[] Argsort(final float[] array, final boolean ascending) {\n Integer[] indexes = new Integer[array.length];\n for (int i = 0; i < indexes.length; i++) {\n indexes[i] = i;\n }\n Arrays.sort(indexes, new Comparator<Integer>() {\n @Override\n public int compare(final Integer i1, final Integer i2) {\n return (ascending ? 1 : -1) * Float.compare(array[i1], array[i2]);\n }\n });\n return asArray(indexes);\n }",
"private void setRawDirection(SwipyRefreshLayoutDirection direction) {\n if (mDirection == direction) {\n return;\n }\n\n mDirection = direction;\n switch (mDirection) {\n case BOTTOM:\n mCurrentTargetOffsetTop = mOriginalOffsetTop = getMeasuredHeight();\n break;\n case TOP:\n default:\n mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();\n break;\n }\n }",
"public static String getOjbClassName(ResultSet rs)\r\n {\r\n try\r\n {\r\n return rs.getString(OJB_CLASS_COLUMN);\r\n }\r\n catch (SQLException e)\r\n {\r\n return null;\r\n }\r\n }",
"public Indexable taskResult(String taskId) {\n TaskGroupEntry<TaskItem> taskGroupEntry = super.getNode(taskId);\n if (taskGroupEntry != null) {\n return taskGroupEntry.taskResult();\n }\n if (!this.proxyTaskGroupWrapper.isActive()) {\n throw new IllegalArgumentException(\"A dependency task with id '\" + taskId + \"' is not found\");\n }\n taskGroupEntry = this.proxyTaskGroupWrapper.proxyTaskGroup.getNode(taskId);\n if (taskGroupEntry != null) {\n return taskGroupEntry.taskResult();\n }\n throw new IllegalArgumentException(\"A dependency task or 'post-run' dependent task with with id '\" + taskId + \"' not found\");\n }"
] |
caching is not supported for this method | [
"@Override\n public List<Revision> getMatrixHistory(final int start, final int limit) throws StoreException {\n return delegate.getMatrixHistory(start, limit);\n }"
] | [
"private static BundleCapability getExportedPackage(BundleContext context, String packageName) {\n List<BundleCapability> packages = new ArrayList<BundleCapability>();\n for (Bundle bundle : context.getBundles()) {\n BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);\n for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) {\n String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);\n if (pName.equalsIgnoreCase(packageName)) {\n packages.add(packageCapability);\n }\n }\n }\n\n Version max = Version.emptyVersion;\n BundleCapability maxVersion = null;\n for (BundleCapability aPackage : packages) {\n Version version = (Version) aPackage.getAttributes().get(\"version\");\n if (max.compareTo(version) <= 0) {\n max = version;\n maxVersion = aPackage;\n }\n }\n\n return maxVersion;\n }",
"public ClassDescriptor getSuperClassDescriptor()\r\n {\r\n if (!m_superCldSet)\r\n {\r\n if(getBaseClass() != null)\r\n {\r\n m_superCld = getRepository().getDescriptorFor(getBaseClass());\r\n if(m_superCld.isAbstract() || m_superCld.isInterface())\r\n {\r\n throw new MetadataException(\"Super class mapping only work for real class, but declared super class\" +\r\n \" is an interface or is abstract. Declared class: \" + m_superCld.getClassNameOfObject());\r\n }\r\n }\r\n m_superCldSet = true;\r\n }\r\n\r\n return m_superCld;\r\n }",
"public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) {\n\t\tif(referenceDate == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn referenceDate.plusDays((int)Math.round(floatingPointDate*365.0));\n\t}",
"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}",
"static void writeCertificates(final ModelNode result, final Certificate[] certificates) throws CertificateEncodingException, NoSuchAlgorithmException {\n if (certificates != null) {\n for (Certificate current : certificates) {\n ModelNode certificate = new ModelNode();\n writeCertificate(certificate, current);\n result.add(certificate);\n }\n }\n }",
"public void addStoreDefinition(StoreDefinition storeDef) {\n // acquire write lock\n writeLock.lock();\n\n try {\n // Check if store already exists\n if(this.storeNames.contains(storeDef.getName())) {\n throw new VoldemortException(\"Store already exists !\");\n }\n\n // Check for backwards compatibility\n StoreDefinitionUtils.validateSchemaAsNeeded(storeDef);\n\n // Otherwise add to the STORES directory\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr);\n this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, null);\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(), new Versioned<Object>(storeDefStr));\n\n // Re-initialize the store definitions. This is primarily required\n // to re-create the value for key: 'stores.xml'. This is necessary\n // for backwards compatibility.\n initStoreDefinitions(null);\n\n updateRoutingStrategies(getCluster(), getStoreDefList());\n } finally {\n writeLock.unlock();\n }\n }",
"protected void checkScopeAllowed() {\n if (ejbDescriptor.isStateless() && !isDependent()) {\n throw BeanLogger.LOG.scopeNotAllowedOnStatelessSessionBean(getScope(), getType());\n }\n if (ejbDescriptor.isSingleton() && !(isDependent() || getScope().equals(ApplicationScoped.class))) {\n throw BeanLogger.LOG.scopeNotAllowedOnSingletonBean(getScope(), getType());\n }\n }",
"public static int cudnnRestoreDropoutDescriptor(\n cudnnDropoutDescriptor dropoutDesc, \n cudnnHandle handle, \n float dropout, \n Pointer states, \n long stateSizeInBytes, \n long seed)\n {\n return checkResult(cudnnRestoreDropoutDescriptorNative(dropoutDesc, handle, dropout, states, stateSizeInBytes, seed));\n }",
"public static wisite_binding[] get(nitro_service service, String sitepath[]) throws Exception{\n\t\tif (sitepath !=null && sitepath.length>0) {\n\t\t\twisite_binding response[] = new wisite_binding[sitepath.length];\n\t\t\twisite_binding obj[] = new wisite_binding[sitepath.length];\n\t\t\tfor (int i=0;i<sitepath.length;i++) {\n\t\t\t\tobj[i] = new wisite_binding();\n\t\t\t\tobj[i].set_sitepath(sitepath[i]);\n\t\t\t\tresponse[i] = (wisite_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}"
] |
Make sure that the Identity objects of garbage collected cached
objects are removed too. | [
"private void processQueue()\r\n {\r\n CacheEntry sv;\r\n while((sv = (CacheEntry) queue.poll()) != null)\r\n {\r\n sessionCache.remove(sv.oid);\r\n }\r\n }"
] | [
"protected boolean appendWhereStatement(StringBuilder sb, List<ArgumentHolder> argList, WhereOperation operation)\n\t\t\tthrows SQLException {\n\t\tif (where == null) {\n\t\t\treturn operation == WhereOperation.FIRST;\n\t\t}\n\t\toperation.appendBefore(sb);\n\t\twhere.appendSql((addTableName ? getTableName() : null), sb, argList);\n\t\toperation.appendAfter(sb);\n\t\treturn false;\n\t}",
"public Duration getBaselineDuration()\n {\n Object result = getCachedValue(TaskField.BASELINE_DURATION);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION);\n }\n\n if (!(result instanceof Duration))\n {\n result = null;\n }\n return (Duration) result;\n }",
"public static <T, A extends Annotation> String getClassAnnotationValue(Class<T> classType, Class<A> annotationType, String attributeName) {\n\t\tString value = null;\n\t\tAnnotation annotation = classType.getAnnotation(annotationType);\n\t\tif (annotation != null) {\n\t\t\ttry {\n\t\t\t\tvalue = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation);\n\t\t\t} catch (Exception ex) {}\n\t\t}\n\t\treturn value;\n\t}",
"public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.sql.Time(gc.getTime().getTime());\n }",
"public AsciiTable setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\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 void createPath(String pathName, String pathValue, String requestType) {\n try {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"pathName\", pathName),\n new BasicNameValuePair(\"path\", pathValue),\n new BasicNameValuePair(\"requestType\", String.valueOf(type)),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH, params));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"public static void d(ISubsystem subsystem, String tag, String pattern, Object... parameters) {\n if (!isEnabled(subsystem)) return;\n d(subsystem, tag, format(pattern, parameters));\n }",
"private void deliverBeatGridUpdate(int player, BeatGrid beatGrid) {\n if (!getBeatGridListeners().isEmpty()) {\n final BeatGridUpdate update = new BeatGridUpdate(player, beatGrid);\n for (final BeatGridListener listener : getBeatGridListeners()) {\n try {\n listener.beatGridChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering beat grid update to listener\", t);\n }\n }\n }\n }"
] |
Searches the variables layers, top to bottom, for given name, and returns if found; null otherwise.
If maxDepth is set to {@link Variables#SEARCH_ALL_LAYERS}, then search all layers. | [
"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 }"
] | [
"public static Attachment fromBinaryBytes( byte[] bytes, MediaType mediaType ) {\n if( !mediaType.isBinary() ) {\n throw new IllegalArgumentException( \"MediaType must be binary\" );\n }\n return new Attachment(BaseEncoding.base64().encode( bytes ), mediaType, null );\n }",
"public double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\n\t}",
"public static String createQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n try {\n Double.parseDouble(str);\n } catch (NumberFormatException nfe) {\n return \"\\\"\" + str + \"\\\"\";\n }\n return str;\n }",
"private void createTasks(ChildTaskContainer parent, String parentName, List<Row> rows)\n {\n for (Row row : rows)\n {\n boolean rowIsBar = (row.getInteger(\"BARID\") != null);\n\n //\n // Don't export hammock tasks.\n //\n if (rowIsBar && row.getChildRows().isEmpty())\n {\n continue;\n }\n\n Task task = parent.addTask();\n\n //\n // Do we have a bar, task, or milestone?\n //\n if (rowIsBar)\n {\n //\n // If the bar only has one child task, we skip it and add the task directly\n //\n if (skipBar(row))\n {\n populateLeaf(row.getString(\"NAMH\"), row.getChildRows().get(0), task);\n }\n else\n {\n populateBar(row, task);\n createTasks(task, task.getName(), row.getChildRows());\n }\n }\n else\n {\n populateLeaf(parentName, row, task);\n }\n\n m_eventManager.fireTaskReadEvent(task);\n }\n }",
"private void writeResources()\n {\n for (Resource resource : m_projectFile.getResources())\n {\n if (resource.getUniqueID().intValue() != 0)\n {\n writeResource(resource);\n }\n }\n }",
"protected void modify(Transaction t) {\n try {\n this.lock.writeLock().lock();\n t.perform();\n } finally {\n this.lock.writeLock().unlock();\n }\n }",
"private void normalizeSelectedCategories() {\r\n\r\n Collection<String> normalizedCategories = new ArrayList<String>(m_selectedCategories.size());\r\n for (CmsTreeItem item : m_categories.values()) {\r\n if (item.getCheckBox().isChecked()) {\r\n normalizedCategories.add(item.getId());\r\n }\r\n }\r\n m_selectedCategories = normalizedCategories;\r\n\r\n }",
"private String extractAndConvertTaskType(Task task)\n {\n String activityType = (String) task.getCachedValue(m_activityTypeField);\n if (activityType == null)\n {\n activityType = \"Resource Dependent\";\n }\n else\n {\n if (ACTIVITY_TYPE_MAP.containsKey(activityType))\n {\n activityType = ACTIVITY_TYPE_MAP.get(activityType);\n }\n }\n return activityType;\n }",
"public void fireEvent(Type eventType, Object event, Annotation... qualifiers) {\n final EventMetadata metadata = new EventMetadataImpl(eventType, null, qualifiers);\n notifier.fireEvent(eventType, event, metadata, qualifiers);\n }"
] |
Returns whether the given host matches this one. For hosts to match, they must represent the same addresses or have the same host names.
Hosts are not resolved when matching. Also, hosts must have the same port and service. They must have the same masks if they are host names.
Even if two hosts are invalid, they match if they have the same invalid string.
@param host
@return | [
"public boolean matches(HostName host) {\n\t\tif(this == host) {\n\t\t\treturn true;\n\t\t}\n\t\tif(isValid()) {\n\t\t\tif(host.isValid()) {\n\t\t\t\tif(isAddressString()) {\n\t\t\t\t\treturn host.isAddressString()\n\t\t\t\t\t\t\t&& asAddressString().equals(host.asAddressString())\n\t\t\t\t\t\t\t&& Objects.equals(getPort(), host.getPort())\n\t\t\t\t\t\t\t&& Objects.equals(getService(), host.getService());\n\t\t\t\t}\n\t\t\t\tif(host.isAddressString()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tString thisHost = parsedHost.getHost();\n\t\t\t\tString otherHost = host.parsedHost.getHost();\n\t\t\t\tif(!thisHost.equals(otherHost)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn Objects.equals(parsedHost.getEquivalentPrefixLength(), host.parsedHost.getEquivalentPrefixLength()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getMask(), host.parsedHost.getMask()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getPort(), host.parsedHost.getPort()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getService(), host.parsedHost.getService());\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\treturn !host.isValid() && toString().equals(host.toString());\n\t}"
] | [
"private static Class<?> extractTypeFromClass(Class<?> clazz, Class<?> source, int typeIndex,\n\t\t\tMap<TypeVariable, Type> typeVariableMap, Map<Integer, Integer> typeIndexesPerLevel,\n\t\t\tint nestingLevel, int currentLevel) {\n\n\t\tif (clazz.getName().startsWith(\"java.util.\")) {\n\t\t\treturn null;\n\t\t}\n\t\tif (clazz.getSuperclass() != null && isIntrospectionCandidate(clazz.getSuperclass())) {\n\t\t\ttry {\n\t\t\t\treturn extractType(clazz.getGenericSuperclass(), source, typeIndex, typeVariableMap,\n\t\t\t\t\t\ttypeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t}\n\t\t\tcatch (MalformedParameterizedTypeException ex) {\n\t\t\t\t// from getGenericSuperclass() - ignore and continue with interface introspection\n\t\t\t}\n\t\t}\n\t\tType[] ifcs = clazz.getGenericInterfaces();\n\t\tif (ifcs != null) {\n\t\t\tfor (Type ifc : ifcs) {\n\t\t\t\tType rawType = ifc;\n\t\t\t\tif (ifc instanceof ParameterizedType) {\n\t\t\t\t\trawType = ((ParameterizedType) ifc).getRawType();\n\t\t\t\t}\n\t\t\t\tif (rawType instanceof Class && isIntrospectionCandidate((Class) rawType)) {\n\t\t\t\t\treturn extractType(ifc, source, typeIndex, typeVariableMap, typeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public void publish() {\n\n CmsDirectPublishDialogAction action = new CmsDirectPublishDialogAction();\n List<CmsResource> resources = getBundleResources();\n I_CmsDialogContext context = new A_CmsDialogContext(\"\", ContextType.appToolbar, resources) {\n\n public void focus(CmsUUID structureId) {\n\n //Nothing to do.\n }\n\n public List<CmsUUID> getAllStructureIdsInView() {\n\n return null;\n }\n\n public void updateUserInfo() {\n\n //Nothing to do.\n }\n };\n action.executeAction(context);\n updateLockInformation();\n\n }",
"public Task<Void> registerWithEmail(@NonNull final String email, @NonNull final String password) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n registerWithEmailInternal(email, password);\n return null;\n }\n });\n }",
"public void set(int i, double value) {\n switch (i) {\n case 0: {\n x = value;\n break;\n }\n case 1: {\n y = value;\n break;\n }\n case 2: {\n z = value;\n break;\n }\n default: {\n throw new ArrayIndexOutOfBoundsException(i);\n }\n }\n }",
"public static Credential getServiceAccountCredential(String serviceAccountId,\n String privateKeyFile, Collection<String> serviceAccountScopes)\n throws GeneralSecurityException, IOException {\n return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes)\n .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFile))\n .build();\n }",
"public void set(final Argument argument) {\n if (argument != null) {\n map.put(argument.getKey(), Collections.singleton(argument));\n }\n }",
"public String getAuthorizationUrl(OAuth1RequestToken oAuthRequestToken, Permission permission) {\r\n\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n String authorizationUrl = service.getAuthorizationUrl(oAuthRequestToken);\r\n return String.format(\"%s&perms=%s\", authorizationUrl, permission.toString());\r\n }",
"public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, Connection con, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n if (_parameters == null)\n _parameters = new HashMap<String, Object>();\n\n visitSubreports(dr, _parameters);\n compileOrLoadSubreports(dr, _parameters, \"r\");\n\n DynamicJasperDesign jd = generateJasperDesign(dr);\n Map<String, Object> params = new HashMap<String, Object>();\n if (!_parameters.isEmpty()) {\n registerParams(jd, _parameters);\n params.putAll(_parameters);\n }\n registerEntities(jd, dr, layoutManager);\n layoutManager.applyLayout(jd, dr);\n JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n //JRProperties.setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n JasperReport jr = JasperCompileManager.compileReport(jd);\n params.putAll(jd.getParametersWithValues());\n jp = JasperFillManager.fillReport(jr, params, con);\n\n return jp;\n }",
"private void populateDefaultSettings(Record record, ProjectProperties properties) throws MPXJException\n {\n properties.setDefaultDurationUnits(record.getTimeUnit(0));\n properties.setDefaultDurationIsFixed(record.getNumericBoolean(1));\n properties.setDefaultWorkUnits(record.getTimeUnit(2));\n properties.setMinutesPerDay(Double.valueOf(NumberHelper.getDouble(record.getFloat(3)) * 60));\n properties.setMinutesPerWeek(Double.valueOf(NumberHelper.getDouble(record.getFloat(4)) * 60));\n properties.setDefaultStandardRate(record.getRate(5));\n properties.setDefaultOvertimeRate(record.getRate(6));\n properties.setUpdatingTaskStatusUpdatesResourceStatus(record.getNumericBoolean(7));\n properties.setSplitInProgressTasks(record.getNumericBoolean(8));\n }"
] |
Use this API to add sslocspresponder resources. | [
"public static base_responses add(nitro_service client, sslocspresponder resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslocspresponder addresources[] = new sslocspresponder[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslocspresponder();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].url = resources[i].url;\n\t\t\t\taddresources[i].cache = resources[i].cache;\n\t\t\t\taddresources[i].cachetimeout = resources[i].cachetimeout;\n\t\t\t\taddresources[i].batchingdepth = resources[i].batchingdepth;\n\t\t\t\taddresources[i].batchingdelay = resources[i].batchingdelay;\n\t\t\t\taddresources[i].resptimeout = resources[i].resptimeout;\n\t\t\t\taddresources[i].respondercert = resources[i].respondercert;\n\t\t\t\taddresources[i].trustresponder = resources[i].trustresponder;\n\t\t\t\taddresources[i].producedattimeskew = resources[i].producedattimeskew;\n\t\t\t\taddresources[i].signingcert = resources[i].signingcert;\n\t\t\t\taddresources[i].usenonce = resources[i].usenonce;\n\t\t\t\taddresources[i].insertclientcert = resources[i].insertclientcert;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public StackTraceElement[] asStackTrace() {\n\t\tint i = 1;\n\t\tStackTraceElement[] list = new StackTraceElement[this.size()];\n\t\tfor (Eventable e : this) {\n\t\t\tlist[this.size() - i] =\n\t\t\t\t\tnew StackTraceElement(e.getEventType().toString(), e.getIdentification()\n\t\t\t\t\t\t\t.toString(), e.getElement().toString(), i);\n\t\t\ti++;\n\t\t}\n\t\treturn list;\n\t}",
"private List<Entity> runQuery(Query query) throws DatastoreException {\n RunQueryRequest.Builder request = RunQueryRequest.newBuilder();\n request.setQuery(query);\n RunQueryResponse response = datastore.runQuery(request.build());\n\n if (response.getBatch().getMoreResults() == QueryResultBatch.MoreResultsType.NOT_FINISHED) {\n System.err.println(\"WARNING: partial results\\n\");\n }\n List<EntityResult> results = response.getBatch().getEntityResultsList();\n List<Entity> entities = new ArrayList<Entity>(results.size());\n for (EntityResult result : results) {\n entities.add(result.getEntity());\n }\n return entities;\n }",
"public Object getRealSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tif (_realSubject == null)\r\n\t\t{\r\n\t\t\tbeforeMaterialization();\r\n\t\t\t_realSubject = materializeSubject();\r\n\t\t\tafterMaterialization();\r\n\t\t}\r\n\t\treturn _realSubject;\r\n\t}",
"public ThumborUrlBuilder buildImage(String image) {\n if (image == null || image.length() == 0) {\n throw new IllegalArgumentException(\"Image must not be blank.\");\n }\n return new ThumborUrlBuilder(host, key, image);\n }",
"public SerialMessage setValueMessage(int level) {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_SET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set);\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) BASIC_SET,\r\n\t\t\t\t\t\t\t\t(byte) level\r\n\t\t\t\t\t\t\t\t};\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"public boolean setOverrideRepeatCount(String pathName, String methodName, Integer ordinal, Integer repeatCount) {\n try {\n String methodId = getOverrideIdForMethodName(methodName).toString();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"profileIdentifier\", this._profileName),\n new BasicNameValuePair(\"ordinal\", ordinal.toString()),\n new BasicNameValuePair(\"repeatNumber\", repeatCount.toString())\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodId, params));\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerFilters(List<AlgoliaFilter> filters) {\n for (final AlgoliaFilter filter : filters) {\n searcher.addFacet(filter.getAttribute());\n }\n }",
"public static base_responses add(nitro_service client, dnsview resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsview addresources[] = new dnsview[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnsview();\n\t\t\t\taddresources[i].viewname = resources[i].viewname;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public IPv4AddressSection mask(IPv4AddressSection mask, boolean retainPrefix) throws IncompatibleAddressException, PrefixLenException, SizeMismatchException {\n\t\tcheckMaskSectionCount(mask);\n\t\treturn getSubnetSegments(\n\t\t\t\tthis,\n\t\t\t\tretainPrefix ? getPrefixLength() : null,\n\t\t\t\tgetAddressCreator(),\n\t\t\t\ttrue,\n\t\t\t\tthis::getSegment,\n\t\t\t\ti -> mask.getSegment(i).getSegmentValue(),\n\t\t\t\tfalse);\n\t}"
] |
Remove all references to a groupId
@param groupIdToRemove ID of group | [
"private void removeGroupIdFromTablePaths(int groupIdToRemove) {\n PreparedStatement queryStatement = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PATH);\n results = queryStatement.executeQuery();\n // this is a hashamp from a pathId to the string of groups\n HashMap<Integer, String> idToGroups = new HashMap<Integer, String>();\n while (results.next()) {\n int pathId = results.getInt(Constants.GENERIC_ID);\n String stringGroupIds = results.getString(Constants.PATH_PROFILE_GROUP_IDS);\n int[] groupIds = Utils.arrayFromStringOfIntegers(stringGroupIds);\n String newGroupIds = \"\";\n for (int i = 0; i < groupIds.length; i++) {\n if (groupIds[i] != groupIdToRemove) {\n newGroupIds += (groupIds[i] + \",\");\n }\n }\n idToGroups.put(pathId, newGroupIds);\n }\n\n // now i want to go though the hashmap and for each pathId, add\n // update the newGroupIds\n for (Map.Entry<Integer, String> entry : idToGroups.entrySet()) {\n Integer pathId = entry.getKey();\n String newGroupIds = entry.getValue();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH\n + \" SET \" + Constants.PATH_PROFILE_GROUP_IDS + \" = ? \"\n + \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newGroupIds);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n }\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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }"
] | [
"public void removeControl(String name) {\n Widget control = findChildByName(name);\n if (control != null) {\n removeChild(control);\n if (mBgResId != -1) {\n updateMesh();\n }\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 String getTexCoordAttr(String texName)\n {\n GVRTexture tex = textures.get(texName);\n if (tex != null)\n {\n return tex.getTexCoordAttr();\n }\n return null;\n }",
"public List<Map<String, String>> pipelinePossibleStates(Assign action, List<Map<String, String>> possibleStateList) {\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n possibleState.put(action.getName(), action.getExpr());\r\n }\n\r\n return possibleStateList;\r\n }",
"private void processColumns()\n {\n int fieldID = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n m_dataOffset = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n FieldType type = FieldTypeHelper.getInstance(fieldID);\n if (type.getDataType() != null)\n {\n processKnownType(type);\n }\n }",
"public SerialMessage setValueMessage(int level) {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_SET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set);\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) BASIC_SET,\r\n\t\t\t\t\t\t\t\t(byte) level\r\n\t\t\t\t\t\t\t\t};\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"public String processNested(Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n XClass type = OjbMemberTagsHandler.getMemberType();\r\n int dim = OjbMemberTagsHandler.getMemberDimension();\r\n NestedDef nestedDef = _curClassDef.getNested(name);\r\n\r\n if (type == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (dim > 0)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.MEMBER_CANNOT_BE_NESTED,\r\n new String[]{name, _curClassDef.getName()}));\r\n }\r\n\r\n ClassDescriptorDef nestedTypeDef = _model.getClass(type.getQualifiedName());\r\n\r\n if (nestedTypeDef == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (nestedDef == null)\r\n {\r\n nestedDef = new NestedDef(name, nestedTypeDef);\r\n _curClassDef.addNested(nestedDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processNested\", \" Processing nested object \"+nestedDef.getName()+\" of type \"+nestedTypeDef.getName());\r\n\r\n String attrName;\r\n \r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n nestedDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }",
"public void process(InputStream is) throws Exception\n {\n readHeader(is);\n readVersion(is);\n readTableData(readTableHeaders(is), is);\n }",
"public void override(HiveRunnerConfig hiveRunnerConfig) {\n config.putAll(hiveRunnerConfig.config);\n hiveConfSystemOverride.putAll(hiveRunnerConfig.hiveConfSystemOverride);\n }"
] |
Returns a new List containing the given objects. | [
"public static <T> List<T> makeList(T... items) {\r\n List<T> s = new ArrayList<T>(items.length);\r\n for (int i = 0; i < items.length; i++) {\r\n s.add(items[i]);\r\n }\r\n return s;\r\n }"
] | [
"protected static void printValuesSorted(String message, Set<String> values)\n {\n System.out.println();\n System.out.println(message + \":\");\n List<String> sorted = new ArrayList<>(values);\n Collections.sort(sorted);\n for (String value : sorted)\n {\n System.out.println(\"\\t\" + value);\n }\n }",
"public void handleChannelClosed(final Channel closed, final IOException e) {\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n if (activeOperation.getChannel() == closed) {\n // Only call cancel, to also interrupt still active threads\n activeOperation.getResultHandler().cancel();\n }\n }\n }",
"public static Bytes toBytes(Text t) {\n return Bytes.of(t.getBytes(), 0, t.getLength());\n }",
"private void processFileType(String token) throws MPXJException\n {\n String version = token.substring(2).split(\" \")[0];\n //System.out.println(version);\n Class<? extends AbstractFileFormat> fileFormatClass = FILE_VERSION_MAP.get(Integer.valueOf(version));\n if (fileFormatClass == null)\n {\n throw new MPXJException(\"Unsupported PP file format version \" + version);\n }\n\n try\n {\n AbstractFileFormat format = fileFormatClass.newInstance();\n m_tableDefinitions = format.tableDefinitions();\n m_epochDateFormat = format.epochDateFormat();\n }\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to configure file format\", ex);\n }\n }",
"private void setMax(MtasRBTreeNode n) {\n n.max = n.right;\n if (n.leftChild != null) {\n n.max = Math.max(n.max, n.leftChild.max);\n }\n if (n.rightChild != null) {\n n.max = Math.max(n.max, n.rightChild.max);\n }\n }",
"private StringBuilder calculateCacheKeyInternal(String sql,\r\n\t\t\tint resultSetType, int resultSetConcurrency) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+20);\r\n\t\ttmp.append(sql);\r\n\r\n\t\ttmp.append(\", T\");\r\n\t\ttmp.append(resultSetType);\r\n\t\ttmp.append(\", C\");\r\n\t\ttmp.append(resultSetConcurrency);\r\n\t\treturn tmp;\r\n\t}",
"@SuppressWarnings(\"serial\")\n private Component createCloseButton() {\n\n Button closeBtn = CmsToolBar.createButton(\n FontOpenCms.CIRCLE_INV_CANCEL,\n m_messages.key(Messages.GUI_BUTTON_CANCEL_0));\n closeBtn.addClickListener(new ClickListener() {\n\n public void buttonClick(ClickEvent event) {\n\n closeAction();\n }\n\n });\n return closeBtn;\n }",
"public static nsacl6[] get(nitro_service service, String acl6name[]) throws Exception{\n\t\tif (acl6name !=null && acl6name.length>0) {\n\t\t\tnsacl6 response[] = new nsacl6[acl6name.length];\n\t\t\tnsacl6 obj[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++) {\n\t\t\t\tobj[i] = new nsacl6();\n\t\t\t\tobj[i].set_acl6name(acl6name[i]);\n\t\t\t\tresponse[i] = (nsacl6) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public static clusterinstance get(nitro_service service, Long clid) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tobj.set_clid(clid);\n\t\tclusterinstance response = (clusterinstance) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Return true if this rule should be applied for the specified ClassNode, based on the
configuration of this rule.
@param classNode - the ClassNode
@return true if this rule should be applied for the specified ClassNode | [
"protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }"
] | [
"public static base_response update(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager updateresource = new snmpmanager();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn updateresource.update_resource(client);\n\t}",
"protected void sendPageBreakToBottom(JRDesignBand band) {\n\t\tJRElement[] elems = band.getElements();\n\t\tJRElement aux = null;\n\t\tfor (JRElement elem : elems) {\n\t\t\tif ((\"\" + elem.getKey()).startsWith(PAGE_BREAK_FOR_)) {\n\t\t\t\taux = elem;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aux != null)\n\t\t\t((JRDesignElement)aux).setY(band.getHeight());\n\t}",
"public static CompressionType getDumpFileCompressionType(String fileName) {\n\t\tif (fileName.endsWith(\".gz\")) {\n\t\t\treturn CompressionType.GZIP;\n\t\t} else if (fileName.endsWith(\".bz2\")) {\n\t\t\treturn CompressionType.BZ2;\n\t\t} else {\n\t\t\treturn CompressionType.NONE;\n\t\t}\n\t}",
"public static Class<?> resolveTypeArgument(Class<?> clazz, Class<?> genericIfc) {\n\t\tClass<?>[] typeArgs = resolveTypeArguments(clazz, genericIfc);\n\t\tif (typeArgs == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (typeArgs.length != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Expected 1 type argument on generic interface [\" +\n\t\t\t\t\tgenericIfc.getName() + \"] but found \" + typeArgs.length);\n\t\t}\n\t\treturn typeArgs[0];\n\t}",
"public void setSegmentReject(String reject) {\n\t\tif (!StringUtils.hasText(reject)) {\n\t\t\treturn;\n\t\t}\n\t\tInteger parsedLimit = null;\n\t\ttry {\n\t\t\tparsedLimit = Integer.parseInt(reject);\n\t\t\tsegmentRejectType = SegmentRejectType.ROWS;\n\t\t} catch (NumberFormatException e) {\n\t\t}\n\t\tif (parsedLimit == null && reject.contains(\"%\")) {\n\t\t\ttry {\n\t\t\t\tparsedLimit = Integer.parseInt(reject.replace(\"%\", \"\").trim());\n\t\t\t\tsegmentRejectType = SegmentRejectType.PERCENT;\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t}\n\t\t}\n\t\tsegmentRejectLimit = parsedLimit;\n\t}",
"public static appfwwsdl get(nitro_service service, String name) throws Exception{\n\t\tappfwwsdl obj = new appfwwsdl();\n\t\tobj.set_name(name);\n\t\tappfwwsdl response = (appfwwsdl) obj.get_resource(service);\n\t\treturn response;\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 }",
"public SpinJsonDataFormatException unableToParseValue(String expectedType, JsonNodeType type) {\n return new SpinJsonDataFormatException(exceptionMessage(\"002\", \"Expected '{}', got '{}'\", expectedType, type.toString()));\n }",
"public static nsacl6[] get(nitro_service service, String acl6name[]) throws Exception{\n\t\tif (acl6name !=null && acl6name.length>0) {\n\t\t\tnsacl6 response[] = new nsacl6[acl6name.length];\n\t\t\tnsacl6 obj[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++) {\n\t\t\t\tobj[i] = new nsacl6();\n\t\t\t\tobj[i].set_acl6name(acl6name[i]);\n\t\t\t\tresponse[i] = (nsacl6) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}"
] |
This method can be called to ensure that the IDs of all
entities are sequential, and start from an
appropriate point. If entities are added to and removed from
this list, then the project is loaded into Microsoft
project, if the ID values have gaps in the sequence, there will
be blank rows shown. | [
"public void renumberIDs()\n {\n if (!isEmpty())\n {\n Collections.sort(this);\n T firstEntity = get(0);\n int id = NumberHelper.getInt(firstEntity.getID());\n if (id != 0)\n {\n id = 1;\n }\n\n for (T entity : this)\n {\n entity.setID(Integer.valueOf(id++));\n }\n }\n }"
] | [
"public static String createQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n try {\n Double.parseDouble(str);\n } catch (NumberFormatException nfe) {\n return \"\\\"\" + str + \"\\\"\";\n }\n return str;\n }",
"public void render(OutputStream outputStream, Format format, int dpi) throws PrintingException {\n\t\ttry {\n\t\t\tif (baos == null) {\n\t\t\t\tprepare();\n\t\t\t}\n\t\t\twriteDocument(outputStream, format, dpi);\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new PrintingException(e, PrintingException.DOCUMENT_RENDER_PROBLEM);\n\t\t}\n\t}",
"public void addExportedPackages(Set<String> exportedPackages) {\n\t\taddExportedPackages(exportedPackages.toArray(new String[exportedPackages.size()]));\n\t}",
"static ChangeEvent<BsonDocument> changeEventForLocalDelete(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.DELETE,\n null,\n namespace,\n new BsonDocument(\"_id\", documentId),\n null,\n writePending);\n }",
"public int[] getIntArray(String attributeName)\n {\n int[] array = NativeVertexBuffer.getIntArray(getNative(), attributeName);\n if (array == null)\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return array;\n }",
"public static Trajectory combineTrajectory(Trajectory a, Trajectory b){\n\t\tif(a.getDimension()!=b.getDimension()){\n\t\t\tthrow new IllegalArgumentException(\"Combination not possible: The trajectorys does not have the same dimension\");\n\t\t}\n\t\tif(a.size()!=b.size()){\n\t\t\tthrow new IllegalArgumentException(\"Combination not possible: The trajectorys does not \"\n\t\t\t\t\t+ \"have the same number of steps a=\"+a.size() + \" b=\"+b.size());\n\t\t}\n\t\tTrajectory c = new Trajectory(a.getDimension());\n\t\t\n\t\tfor(int i = 0 ; i < a.size(); i++){\n\t\t\tPoint3d pos = new Point3d(a.get(i).x+b.get(i).x, \n\t\t\t\t\ta.get(i).y+b.get(i).y, \n\t\t\t\t\ta.get(i).z+b.get(i).z);\n\t\t\tc.add(pos);\n\t\t}\n\t\t\n\t\treturn c;\n\t}",
"public static base_responses add(nitro_service client, dnstxtrec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnstxtrec addresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnstxtrec();\n\t\t\t\taddresources[i].domain = resources[i].domain;\n\t\t\t\taddresources[i].String = resources[i].String;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"protected <T, A> ActiveOperation<T, A> registerActiveOperation(final Integer id, A attachment, ActiveOperation.CompletedCallback<T> callback) {\n lock.lock();\n try {\n // Check that we still allow registration\n // TODO WFCORE-199 distinguish client uses from server uses and limit this check to server uses\n // Using id==null may be one way to do this, but we need to consider ops that involve multiple requests\n // TODO WFCORE-845 consider using an IllegalStateException for this\n //assert ! shutdown;\n final Integer operationId;\n if(id == null) {\n // If we did not get an operationId, create a new one\n operationId = operationIdManager.createBatchId();\n } else {\n // Check that the operationId is not already taken\n if(! operationIdManager.lockBatchId(id)) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(id);\n }\n operationId = id;\n }\n final ActiveOperationImpl<T, A> request = new ActiveOperationImpl<T, A>(operationId, attachment, getCheckedCallback(callback), this);\n final ActiveOperation<?, ?> existing = activeRequests.putIfAbsent(operationId, request);\n if(existing != null) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(operationId);\n }\n ProtocolLogger.ROOT_LOGGER.tracef(\"Registered active operation %d\", operationId);\n activeCount++; // condition.signalAll();\n return request;\n } finally {\n lock.unlock();\n }\n }",
"public static csvserver_appflowpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_appflowpolicy_binding obj = new csvserver_appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_appflowpolicy_binding response[] = (csvserver_appflowpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Use this API to update inat. | [
"public static base_response update(nitro_service client, inat resource) throws Exception {\n\t\tinat updateresource = new inat();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.privateip = resource.privateip;\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.tftp = resource.tftp;\n\t\tupdateresource.usip = resource.usip;\n\t\tupdateresource.usnip = resource.usnip;\n\t\tupdateresource.proxyip = resource.proxyip;\n\t\tupdateresource.mode = resource.mode;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"public String getRecordSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String recSchema = schema.toString();\n return recSchema;\n }",
"public BoxFileUploadSession.Info getStatus() {\n URL statusURL = this.sessionInfo.getSessionEndpoints().getStatusEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), statusURL, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n this.sessionInfo.update(jsonObject);\n\n return this.sessionInfo;\n }",
"public Point measureImage(Resources resources) {\n BitmapFactory.Options justBoundsOptions = new BitmapFactory.Options();\n justBoundsOptions.inJustDecodeBounds = true;\n\n if (bitmap != null) {\n return new Point(bitmap.getWidth(), bitmap.getHeight());\n } else if (resId != null) {\n BitmapFactory.decodeResource(resources, resId, justBoundsOptions);\n float scale = (float) justBoundsOptions.inTargetDensity / justBoundsOptions.inDensity;\n return new Point((int) (justBoundsOptions.outWidth * scale + 0.5f), (int) (justBoundsOptions.outHeight * scale + 0.5f));\n } else if (fileToBitmap != null) {\n BitmapFactory.decodeFile(fileToBitmap.getAbsolutePath(), justBoundsOptions);\n } else if (inputStream != null) {\n BitmapFactory.decodeStream(inputStream, null, justBoundsOptions);\n try {\n inputStream.reset();\n } catch (IOException ignored) {\n }\n } else if (view != null) {\n return new Point(view.getWidth(), view.getHeight());\n }\n return new Point(justBoundsOptions.outWidth, justBoundsOptions.outHeight);\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 }",
"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 ServerGroup addServerGroup(String groupName) {\n ServerGroup group = new ServerGroup();\n\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", groupName),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP, params));\n group = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return group;\n }",
"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 }",
"GcsRestCreationToken handlePutResponse(final GcsRestCreationToken token,\n final boolean isFinalChunk,\n final int length,\n final HTTPRequestInfo reqInfo,\n HTTPResponse resp) throws Error, IOException {\n switch (resp.getResponseCode()) {\n case 200:\n if (!isFinalChunk) {\n throw new RuntimeException(\"Unexpected response code 200 on non-final chunk. Request: \\n\"\n + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n } else {\n return null;\n }\n case 308:\n if (isFinalChunk) {\n throw new RuntimeException(\"Unexpected response code 308 on final chunk: \"\n + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n } else {\n return new GcsRestCreationToken(token.filename, token.uploadId, token.offset + length);\n }\n default:\n throw HttpErrorHandler.error(resp.getResponseCode(),\n URLFetchUtils.describeRequestAndResponse(reqInfo, resp));\n }\n }",
"public PhotoList<Photo> searchInterestingness(SearchParameters params, 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\", METHOD_GET_INTERESTINGNESS);\r\n\r\n parameters.putAll(params.getAsParameters());\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 photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n Photo photo = new Photo();\r\n photo.setId(photoElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photoElement.getAttribute(\"owner\"));\r\n photo.setOwner(owner);\r\n\r\n photo.setSecret(photoElement.getAttribute(\"secret\"));\r\n photo.setServer(photoElement.getAttribute(\"server\"));\r\n photo.setFarm(photoElement.getAttribute(\"farm\"));\r\n photo.setTitle(photoElement.getAttribute(\"title\"));\r\n photo.setPublicFlag(\"1\".equals(photoElement.getAttribute(\"ispublic\")));\r\n photo.setFriendFlag(\"1\".equals(photoElement.getAttribute(\"isfriend\")));\r\n photo.setFamilyFlag(\"1\".equals(photoElement.getAttribute(\"isfamily\")));\r\n photos.add(photo);\r\n }\r\n return photos;\r\n }"
] |
High-accuracy Normal cumulative distribution function.
@param x Value.
@return Result. | [
"public static double HighAccuracyFunction(double x) {\n if (x < -8 || x > 8)\n return 0;\n\n double sum = x;\n double term = 0;\n\n double nextTerm = x;\n double pwr = x * x;\n double i = 1;\n\n // Iterate until adding next terms doesn't produce\n // any change within the current numerical accuracy.\n\n while (sum != term) {\n term = sum;\n\n // Next term\n nextTerm *= pwr / (i += 2);\n\n sum += nextTerm;\n }\n\n return 0.5 + sum * Math.exp(-0.5 * pwr - 0.5 * Constants.Log2PI);\n }"
] | [
"@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n final Set<DeviceAnnouncement> lastDevices = getCurrentDevices();\n socket.get().close();\n socket.set(null);\n devices.clear();\n firstDeviceTime.set(0);\n // Report the loss of all our devices, on the proper thread, outside our lock\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeviceAnnouncement announcement : lastDevices) {\n deliverLostAnnouncement(announcement);\n }\n }\n });\n deliverLifecycleAnnouncement(logger, false);\n }\n }",
"private static void listAssignmentsByResource(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Assignments for resource \" + resource.getName() + \":\");\n\n for (ResourceAssignment assignment : resource.getTaskAssignments())\n {\n Task task = assignment.getTask();\n System.out.println(\" \" + task.getName());\n }\n }\n\n System.out.println();\n }",
"public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name,\n CreateUserParams params) {\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"login\", login);\n requestJSON.add(\"name\", name);\n\n if (params != null) {\n if (params.getRole() != null) {\n requestJSON.add(\"role\", params.getRole().toJSONValue());\n }\n\n if (params.getStatus() != null) {\n requestJSON.add(\"status\", params.getStatus().toJSONValue());\n }\n\n requestJSON.add(\"language\", params.getLanguage());\n requestJSON.add(\"is_sync_enabled\", params.getIsSyncEnabled());\n requestJSON.add(\"job_title\", params.getJobTitle());\n requestJSON.add(\"phone\", params.getPhone());\n requestJSON.add(\"address\", params.getAddress());\n requestJSON.add(\"space_amount\", params.getSpaceAmount());\n requestJSON.add(\"can_see_managed_users\", params.getCanSeeManagedUsers());\n requestJSON.add(\"timezone\", params.getTimezone());\n requestJSON.add(\"is_exempt_from_device_limits\", params.getIsExemptFromDeviceLimits());\n requestJSON.add(\"is_exempt_from_login_verification\", params.getIsExemptFromLoginVerification());\n requestJSON.add(\"is_platform_access_only\", params.getIsPlatformAccessOnly());\n requestJSON.add(\"external_app_user_id\", params.getExternalAppUserId());\n }\n\n URL url = USERS_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxUser createdUser = new BoxUser(api, responseJSON.get(\"id\").asString());\n return createdUser.new Info(responseJSON);\n }",
"void countNonZeroInR( int[] parent ) {\n TriangularSolver_DSCC.postorder(parent,n,post,gwork);\n columnCounts.process(A,parent,post,countsR);\n nz_in_R = 0;\n for (int k = 0; k < n; k++) {\n nz_in_R += countsR[k];\n }\n if( nz_in_R < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in R counts\");\n }",
"public boolean isAssociation(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( pathWithoutAlias.get( 0 ) );\n\t\treturn propertyType.isAssociationType();\n\t}",
"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 void removeChildTask(Task child)\n {\n if (m_children.remove(child))\n {\n child.m_parent = null;\n }\n setSummary(!m_children.isEmpty());\n }",
"public void commandContinuationRequest()\r\n throws ProtocolException {\r\n try {\r\n output.write('+');\r\n output.write(' ');\r\n output.write('O');\r\n output.write('K');\r\n output.write('\\r');\r\n output.write('\\n');\r\n output.flush();\r\n } catch (IOException e) {\r\n throw new ProtocolException(\"Unexpected exception in sending command continuation request.\", e);\r\n }\r\n }",
"public final void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n m_weekDays.clear();\n if (null != weekDays) {\n m_weekDays.addAll(weekDays);\n }\n }"
] |
Add a metadata profile.
@see #loadProfile | [
"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 float getPositionY(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }",
"public void unlock() {\n\n for (Locale l : m_lockedBundleFiles.keySet()) {\n LockedFile f = m_lockedBundleFiles.get(l);\n f.tryUnlock();\n }\n if (null != m_descFile) {\n m_descFile.tryUnlock();\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 static DMatrixSparseCSC rectangle(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n\n nz_total = Math.min(numCols*numRows,nz_total);\n int[] selected = UtilEjml.shuffled(numRows*numCols, nz_total, rand);\n Arrays.sort(selected,0,nz_total);\n\n DMatrixSparseCSC ret = new DMatrixSparseCSC(numRows,numCols,nz_total);\n ret.indicesSorted = true;\n\n // compute the number of elements in each column\n int hist[] = new int[ numCols ];\n for (int i = 0; i < nz_total; i++) {\n hist[selected[i]/numRows]++;\n }\n\n // define col_idx\n ret.histogramToStructure(hist);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]%numRows;\n\n ret.nz_rows[i] = row;\n ret.nz_values[i] = rand.nextDouble()*(max-min)+min;\n }\n\n return ret;\n }",
"public static List<File> extract(File zipFile, File outputFolder) throws IOException {\n List<File> extracted = new ArrayList<File>();\n\n byte[] buffer = new byte[2048];\n\n if (!outputFolder.exists()) {\n outputFolder.mkdir();\n }\n\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));\n\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n\n String neFileNameName = zipEntry.getName();\n File newFile = new File(outputFolder + File.separator + neFileNameName);\n\n newFile.getParentFile().mkdirs();\n\n if (!zipEntry.isDirectory()) {\n FileOutputStream fos = new FileOutputStream(newFile);\n\n int size;\n while ((size = zipInput.read(buffer)) > 0) {\n fos.write(buffer, 0, size);\n }\n\n fos.close();\n extracted.add(newFile);\n }\n\n zipEntry = zipInput.getNextEntry();\n }\n\n zipInput.closeEntry();\n zipInput.close();\n\n return extracted;\n\n }",
"public boolean containsEntryFor(int maturityInMonths, int tenorInMonths, int moneynessBP) {\r\n\t\treturn entryMap.containsKey(new DataKey(maturityInMonths, tenorInMonths, moneynessBP));\r\n\t}",
"protected void watchConnection(ConnectionHandle connectionHandle) {\r\n\t\tString message = captureStackTrace(UNCLOSED_EXCEPTION_MESSAGE);\r\n\t\tthis.closeConnectionExecutor.submit(new CloseThreadMonitor(Thread.currentThread(), connectionHandle, message, this.closeConnectionWatchTimeoutInMs));\r\n\t}",
"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 }",
"public Query getPKQuery(Identity oid)\r\n {\r\n Object[] values = oid.getPrimaryKeyValues();\r\n ClassDescriptor cld = pb.getClassDescriptor(oid.getObjectsTopLevelClass());\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n Criteria criteria = new Criteria();\r\n\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fld = fields[i];\r\n criteria.addEqualTo(fld.getAttributeName(), values[i]);\r\n }\r\n return QueryFactory.newQuery(cld.getClassOfObject(), criteria);\r\n }"
] |
Retrieve and validate the key from the REST request.
@return true if present, false if missing | [
"protected boolean hasKey() {\n boolean result = false;\n String requestURI = this.request.getUri();\n parseKeys(requestURI);\n\n if(this.parsedKeys != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. No key specified.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Error: No key specified !\");\n }\n return result;\n }"
] | [
"public static dnsaaaarec[] get(nitro_service service, dnsaaaarec_args args) throws Exception{\n\t\tdnsaaaarec obj = new dnsaaaarec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnsaaaarec[] response = (dnsaaaarec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"public ItemRequest<Story> delete(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"DELETE\");\n }",
"public boolean equalId(Element otherElement) {\r\n\t\tif (getElementId() == null || otherElement.getElementId() == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn getElementId().equalsIgnoreCase(otherElement.getElementId());\r\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}",
"private void performScriptedStep() {\n double scale = computeBulgeScale();\n if( steps > giveUpOnKnown ) {\n // give up on the script\n followScript = false;\n } else {\n // use previous singular value to step\n double s = values[x2]/scale;\n performImplicitSingleStep(scale,s*s,false);\n }\n }",
"public AT_Row setPaddingRightChar(Character paddingRightChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRightChar(paddingRightChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private void writeResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n Project.Resources.Resource.ExtendedAttribute attrib;\n List<Project.Resources.Resource.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (ResourceField mpxFieldID : getAllResourceExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPResourceField.getID(mpxFieldID) | MPPResourceField.RESOURCE_FIELD_BASE);\n\n attrib = m_factory.createProjectResourcesResourceExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }",
"public void unbind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.remove(ServiceUtil.getComparableForServiceRanking(props));\n updateSortedServices();\n }\n }",
"private void buildTransformers_4_0(ResourceTransformationDescriptionBuilder builder) {\n\n // We need to do custom transformation of the attribute in the root resource\n // related to endpoint configs, as these were moved to the root from a previous child resource\n EndPointWriteTransformer endPointWriteTransformer = new EndPointWriteTransformer();\n builder.getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.ALWAYS, endpointAttrArray)\n .end()\n .addOperationTransformationOverride(\"add\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(new EndPointAddTransformer())\n .end()\n .addOperationTransformationOverride(\"write-attribute\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(endPointWriteTransformer)\n .end()\n .addOperationTransformationOverride(\"undefine-attribute\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(endPointWriteTransformer)\n .end();\n }"
] |
Write a time units field to the JSON file.
@param fieldName field name
@param value field value | [
"private void writeTimeUnitsField(String fieldName, Object value) throws IOException\n {\n TimeUnit val = (TimeUnit) value;\n if (val != m_projectFile.getProjectProperties().getDefaultDurationUnits())\n {\n m_writer.writeNameValuePair(fieldName, val.toString());\n }\n }"
] | [
"public static lbvserver[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tlbvserver[] response = (lbvserver[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"static void restoreFromHistory(final InstallationManager.MutablePatchingTarget target, final String rollbackPatchId,\n final Patch.PatchType patchType, final PatchableTarget.TargetInfo history) throws PatchingException {\n if (patchType == Patch.PatchType.CUMULATIVE) {\n assert history.getCumulativePatchID().equals(rollbackPatchId);\n target.apply(rollbackPatchId, patchType);\n // Restore one off state\n final List<String> oneOffs = new ArrayList<String>(history.getPatchIDs());\n Collections.reverse(oneOffs);\n for (final String oneOff : oneOffs) {\n target.apply(oneOff, Patch.PatchType.ONE_OFF);\n }\n }\n checkState(history, history); // Just check for tests, that rollback should restore the old state\n }",
"protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {\n WeldBeanDeploymentArchive additionalBda = new WeldBeanDeploymentArchive(ADDITIONAL_BDA_ID, Collections.synchronizedSet(new HashSet<String>()), null);\n additionalBda.getServices().addAll(getServices().entrySet());\n beanDeploymentArchives.add(additionalBda);\n setBeanDeploymentArchivesAccessibility();\n return additionalBda;\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 static base_response add(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy addresource = new responderpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.undefaction = resource.undefaction;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\taddresource.appflowaction = resource.appflowaction;\n\t\treturn addresource.add_resource(client);\n\t}",
"public int addServerRedirectToProfile(String region, String srcUrl, String destUrl, String hostHeader,\n int profileId, int clientId) throws Exception {\n int serverId = -1;\n\n try {\n Client client = ClientService.getInstance().getClient(clientId);\n serverId = addServerRedirect(region, srcUrl, destUrl, hostHeader, profileId, client.getActiveServerGroup());\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return serverId;\n }",
"public void setBaseCalendar(String val)\n {\n set(ResourceField.BASE_CALENDAR, val == null || val.length() == 0 ? \"Standard\" : val);\n }",
"public Duration getDuration(int field) throws MPXJException\n {\n Duration result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = DurationUtility.getInstance(m_fields[field], m_formats.getDurationDecimalFormat(), m_locale);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"public static authenticationradiusaction[] get(nitro_service service) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tauthenticationradiusaction[] response = (authenticationradiusaction[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Picks out a File from `thriftFiles` corresponding to a given artifact ID
and file name. Returns null if `artifactId` and `fileName` do not map to a
thrift file path.
@parameter artifactId The artifact ID of which to look up the path
@parameter fileName the name of the thrift file for which to extract a path
@parameter thriftFiles The set of Thrift files in which to lookup the
artifact ID.
@return The path of the directory containing Thrift files for the given
artifact ID. null if artifact ID not found. | [
"private File extractThriftFile(String artifactId, String fileName, Set<File> thriftFiles) {\n for (File thriftFile : thriftFiles) {\n boolean fileFound = false;\n if (fileName.equals(thriftFile.getName())) {\n for (String pathComponent : thriftFile.getPath().split(File.separator)) {\n if (pathComponent.equals(artifactId)) {\n fileFound = true;\n }\n }\n }\n\n if (fileFound) {\n return thriftFile;\n }\n }\n return null;\n }"
] | [
"public int readFrom(byte[] src, int srcOffset, long destOffset, int length) {\n int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length));\n ByteBuffer b = toDirectByteBuffer(destOffset, readLen);\n b.position(0);\n b.put(src, srcOffset, readLen);\n return readLen;\n }",
"private Filter getFilter(String layerFilter, String[] featureIds) throws GeomajasException {\n\t\tFilter filter = null;\n\t\tif (null != layerFilter) {\n\t\t\tfilter = filterService.parseFilter(layerFilter);\n\t\t}\n\t\tif (null != featureIds) {\n\t\t\tFilter fidFilter = filterService.createFidFilter(featureIds);\n\t\t\tif (null == filter) {\n\t\t\t\tfilter = fidFilter;\n\t\t\t} else {\n\t\t\t\tfilter = filterService.createAndFilter(filter, fidFilter);\n\t\t\t}\n\t\t}\n\t\treturn filter;\n\t}",
"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 List getFeedback()\n\t {\n\t List<?> messages = new ArrayList();\n\t for ( ValueSource vs : valueSources )\n\t {\n\t List feedback = vs.getFeedback();\n\t if ( feedback != null && !feedback.isEmpty() )\n\t {\n\t messages.addAll( feedback );\n\t }\n\t }\n\n\t return messages;\n\t }",
"public static void configureProtocolHandler() {\n final String pkgs = System.getProperty(\"java.protocol.handler.pkgs\");\n String newValue = \"org.mapfish.print.url\";\n if (pkgs != null && !pkgs.contains(newValue)) {\n newValue = newValue + \"|\" + pkgs;\n } else if (pkgs != null) {\n newValue = pkgs;\n }\n System.setProperty(\"java.protocol.handler.pkgs\", newValue);\n }",
"private void init() {\n if (initialized.compareAndSet(false, true)) {\n final RowSorter<? extends TableModel> rowSorter = table.getRowSorter();\n rowSorter.toggleSortOrder(1); // sort by date\n rowSorter.toggleSortOrder(1); // descending\n final TableColumnModel columnModel = table.getColumnModel();\n columnModel.getColumn(1).setCellRenderer(dateRenderer);\n columnModel.getColumn(2).setCellRenderer(sizeRenderer);\n }\n }",
"@Inline(value = \"$1.remove($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> boolean operator_remove(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\t//TODO use the JRE 1.8 API: map.remove(entry.getKey(), entry.getValue());\n\t\tfinal K key = entry.getKey();\n\t\tfinal V storedValue = map.get(entry.getKey());\n\t if (!Objects.equal(storedValue, entry.getValue())\n\t\t\t|| (storedValue == null && !map.containsKey(key))) {\n\t return false;\n \t}\n \tmap.remove(key);\n\t return true;\n\t}",
"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}",
"static <T> StitchEvent<T> fromEvent(final Event event,\n final Decoder<T> decoder) {\n return new StitchEvent<>(event.getEventName(), event.getData(), decoder);\n }"
] |
Determines whether the given documentation part contains the specified tag with the given parameter having the
given value.
@param doc The documentation part
@param tagName The tag to be searched for
@param paramName The parameter that the tag is required to have
@param paramValue The value of the parameter
@return boolean Whether the documentation part has the tag and parameter | [
"private boolean checkTagAndParam(XDoc doc, String tagName, String paramName, String paramValue)\r\n {\r\n if (tagName == null) {\r\n return true;\r\n }\r\n if (!doc.hasTag(tagName)) {\r\n return false;\r\n }\r\n if (paramName == null) {\r\n return true;\r\n }\r\n if (!doc.getTag(tagName).getAttributeNames().contains(paramName)) {\r\n return false;\r\n }\r\n return (paramValue == null) || paramValue.equals(doc.getTagAttributeValue(tagName, paramName));\r\n }"
] | [
"public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\n }",
"ServerStatus getState() {\n final InternalState requiredState = this.requiredState;\n final InternalState state = internalState;\n if(requiredState == InternalState.FAILED) {\n return ServerStatus.FAILED;\n }\n switch (state) {\n case STOPPED:\n return ServerStatus.STOPPED;\n case SERVER_STARTED:\n return ServerStatus.STARTED;\n default: {\n if(requiredState == InternalState.SERVER_STARTED) {\n return ServerStatus.STARTING;\n } else {\n return ServerStatus.STOPPING;\n }\n }\n }\n }",
"public static String termPrefix(String term) {\n int i = term.indexOf(MtasToken.DELIMITER);\n String prefix = term;\n if (i >= 0) {\n prefix = term.substring(0, i);\n }\n return prefix.replace(\"\\u0000\", \"\");\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 }",
"private ChildTaskContainer getParentTask(Activity activity)\n {\n //\n // Make a map of activity codes and their values for this activity\n //\n Map<UUID, UUID> map = getActivityCodes(activity);\n\n //\n // Work through the activity codes in sequence\n //\n ChildTaskContainer parent = m_projectFile;\n StringBuilder uniqueIdentifier = new StringBuilder();\n for (UUID activityCode : m_codeSequence)\n {\n UUID activityCodeValue = map.get(activityCode);\n String activityCodeText = m_activityCodeValues.get(activityCodeValue);\n if (activityCodeText != null)\n {\n if (uniqueIdentifier.length() != 0)\n {\n uniqueIdentifier.append('>');\n }\n uniqueIdentifier.append(activityCodeValue.toString());\n UUID uuid = UUID.nameUUIDFromBytes(uniqueIdentifier.toString().getBytes());\n Task newParent = findChildTaskByUUID(parent, uuid);\n if (newParent == null)\n {\n newParent = parent.addTask();\n newParent.setGUID(uuid);\n newParent.setName(activityCodeText);\n }\n parent = newParent;\n }\n }\n return parent;\n }",
"protected void onNewParentObject(GVRSceneObject parent) {\n for (GVRComponent comp : mComponents.values()) {\n comp.onNewOwnersParent(parent);\n }\n }",
"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 }",
"protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException {\n Class c = this.findLoadedClass(name);\n if (c != null) return c;\n c = (Class) customClasses.get(name);\n if (c != null) return c;\n\n try {\n c = oldFindClass(name);\n } catch (ClassNotFoundException cnfe) {\n // IGNORE\n }\n if (c == null) c = super.loadClass(name, resolve);\n\n if (resolve) resolveClass(c);\n\n return c;\n }",
"public <T> T cached(String key) {\n H.Session sess = session();\n if (null != sess) {\n return sess.cached(key);\n } else {\n return app().cache().get(key);\n }\n }"
] |
Returns the current revision. | [
"private Revision uncachedHeadRevision() {\n try (RevWalk revWalk = new RevWalk(jGitRepository)) {\n final ObjectId headRevisionId = jGitRepository.resolve(R_HEADS_MASTER);\n if (headRevisionId != null) {\n final RevCommit revCommit = revWalk.parseCommit(headRevisionId);\n return CommitUtil.extractRevision(revCommit.getFullMessage());\n }\n } catch (CentralDogmaException e) {\n throw e;\n } catch (Exception e) {\n throw new StorageException(\"failed to get the current revision\", e);\n }\n\n throw new StorageException(\"failed to determine the HEAD: \" + jGitRepository.getDirectory());\n }"
] | [
"protected String getArgString(Object arg) {\n //if (arg instanceof LatLong) {\n // return ((LatLong) arg).getVariableName();\n //} else \n if (arg instanceof JavascriptObject) {\n return ((JavascriptObject) arg).getVariableName();\n // return ((JavascriptObject) arg).getPropertiesAsString();\n } else if( arg instanceof JavascriptEnum ) {\n return ((JavascriptEnum) arg).getEnumValue().toString();\n } else {\n return arg.toString();\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 ItemRequest<CustomField> updateEnumOption(String enumOption) {\n \n String path = String.format(\"/enum_options/%s\", enumOption);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"PUT\");\n }",
"public void modified(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n declarationBinders.get(declarationBinderRef).update(declarationBinderRef);\n }",
"public static base_responses delete(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 deleteresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override public void render() {\n Video video = getContent();\n renderThumbnail(video);\n renderTitle(video);\n renderMarker(video);\n renderLabel();\n }",
"public static void replaceBadXmlCharactersBySpace(char[] cbuf, int off, int len) {\n for (int i = off; i < off + len; i++) {\n if (isBadXmlCharacter(cbuf[i])) {\n cbuf[i] = '\\u0020';\n }\n }\n }",
"public static String format(String format) {\n\n if (format == null) {\n format = DEFAULT_FORMAT;\n } else {\n if (format.contains(\"M\")) {\n format = format.replace(\"M\", \"m\");\n }\n\n if (format.contains(\"Y\")) {\n format = format.replace(\"Y\", \"y\");\n }\n\n if (format.contains(\"D\")) {\n format = format.replace(\"D\", \"d\");\n }\n }\n return format;\n }",
"public static void configure(Job conf, SimpleConfiguration props) {\n try {\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n props.save(baos);\n\n conf.getConfiguration().set(PROPS_CONF_KEY,\n new String(baos.toByteArray(), StandardCharsets.UTF_8));\n\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }"
] |
Use this API to fetch wisite_accessmethod_binding resources of given name . | [
"public static wisite_accessmethod_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_accessmethod_binding obj = new wisite_accessmethod_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_accessmethod_binding response[] = (wisite_accessmethod_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public static boolean sameLists(String list1, String list2)\r\n {\r\n return new CommaListIterator(list1).equals(new CommaListIterator(list2));\r\n }",
"protected List<Integer> getPageSizes() {\n\n try {\n return Collections.singletonList(Integer.valueOf(m_configObject.getInt(JSON_KEY_PAGESIZE)));\n } catch (JSONException e) {\n List<Integer> result = null;\n String pageSizesString = null;\n try {\n pageSizesString = m_configObject.getString(JSON_KEY_PAGESIZE);\n String[] pageSizesArray = pageSizesString.split(\"-\");\n if (pageSizesArray.length > 0) {\n result = new ArrayList<>(pageSizesArray.length);\n for (int i = 0; i < pageSizesArray.length; i++) {\n result.add(Integer.valueOf(pageSizesArray[i]));\n }\n }\n return result;\n } catch (NumberFormatException | JSONException e1) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_PARSING_PAGE_SIZES_FAILED_1, pageSizesString), e);\n }\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_PAGESIZE_SPECIFIED_0), e);\n }\n return null;\n } else {\n return m_baseConfig.getPaginationConfig().getPageSizes();\n }\n }\n }",
"private RandomVariable getShortRate(int timeIndex) throws CalculationException {\n\t\tdouble time = getProcess().getTime(timeIndex);\n\t\tdouble timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time;\n\t\tdouble timeNext = getProcess().getTime(timeIndex+1);\n\n\t\tRandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);\n\n\t\tRandomVariable alpha = getDV(0, time);\n\n\t\tRandomVariable value = getProcess().getProcessValue(timeIndex, 0);\n\t\tvalue = value.add(alpha);\n\t\t//\t\tvalue = value.sub(Math.log(value.exp().getAverage()));\n\n\t\tvalue = value.add(zeroRate);\n\n\t\treturn value;\n\t}",
"public AsciiTable setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static gslbsite[] get(nitro_service service, String sitename[]) throws Exception{\n\t\tif (sitename !=null && sitename.length>0) {\n\t\t\tgslbsite response[] = new gslbsite[sitename.length];\n\t\t\tgslbsite obj[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++) {\n\t\t\t\tobj[i] = new gslbsite();\n\t\t\t\tobj[i].set_sitename(sitename[i]);\n\t\t\t\tresponse[i] = (gslbsite) 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 remove(IConverter converter, Object sourceObject,\n\t\t\tTypeReference<?> destinationType) {\n\t\tconvertedObjects.remove(new ConvertedObjectsKey(converter,\n\t\t\t\tsourceObject, destinationType));\n\t}",
"@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Pair<? 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\treturn !Objects.equal(input.getKey(), right.getKey()) || !Objects.equal(input.getValue(), right.getValue());\n\t\t\t}\n\t\t});\n\t}",
"public final void printClientConfig(final JSONWriter json) throws JSONException {\n json.key(\"layouts\");\n json.array();\n final Map<String, Template> accessibleTemplates = getTemplates();\n accessibleTemplates.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))\n .forEach(entry -> {\n json.object();\n json.key(\"name\").value(entry.getKey());\n entry.getValue().printClientConfig(json);\n json.endObject();\n });\n json.endArray();\n json.key(\"smtp\").object();\n json.key(\"enabled\").value(smtp != null);\n if (smtp != null) {\n json.key(\"storage\").object();\n json.key(\"enabled\").value(smtp.getStorage() != null);\n json.endObject();\n }\n json.endObject();\n }",
"protected Object buildOrRefreshObject(Map row, ClassDescriptor targetClassDescriptor, Object targetObject)\r\n {\r\n Object result = targetObject;\r\n FieldDescriptor fmd;\r\n FieldDescriptor[] fields = targetClassDescriptor.getFieldDescriptor(true);\r\n\r\n if(targetObject == null)\r\n {\r\n // 1. create new object instance if needed\r\n result = ClassHelper.buildNewObjectInstance(targetClassDescriptor);\r\n }\r\n\r\n // 2. fill all scalar attributes of the new object\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n fmd = fields[i];\r\n fmd.getPersistentField().set(result, row.get(fmd.getColumnName()));\r\n }\r\n\r\n if(targetObject == null)\r\n {\r\n // 3. for new build objects, invoke the initialization method for the class if one is provided\r\n Method initializationMethod = targetClassDescriptor.getInitializationMethod();\r\n if (initializationMethod != null)\r\n {\r\n try\r\n {\r\n initializationMethod.invoke(result, NO_ARGS);\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(\"Unable to invoke initialization method:\" + initializationMethod.getName() + \" for class:\" + m_cld.getClassOfObject(), ex);\r\n }\r\n }\r\n }\r\n return result;\r\n }"
] |
Tells you if the expression is a predefined constant like TRUE or FALSE.
@param expression
any expression
@return
as described | [
"private static boolean isPredefinedConstant(Expression expression) {\r\n if (expression instanceof PropertyExpression) {\r\n Expression object = ((PropertyExpression) expression).getObjectExpression();\r\n Expression property = ((PropertyExpression) expression).getProperty();\r\n\r\n if (object instanceof VariableExpression) {\r\n List<String> predefinedConstantNames = PREDEFINED_CONSTANTS.get(((VariableExpression) object).getName());\r\n if (predefinedConstantNames != null && predefinedConstantNames.contains(property.getText())) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }"
] | [
"public double distance(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n }",
"private static String getHostname() {\n if (Hostname == null) {\n try {\n Hostname = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n Hostname = \"default\";\n LOGGER.warn(\"Can not get current hostname\", e);\n }\n }\n return Hostname;\n }",
"public void update(int number) {\n byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_INT];\n ByteUtils.writeInt(numberInBytes, number, 0);\n update(numberInBytes);\n }",
"public static double elementSumSq( DMatrixD1 m ) {\n\n // minimize round off error\n double maxAbs = CommonOps_DDRM.elementMaxAbs(m);\n if( maxAbs == 0)\n return 0;\n\n double total = 0;\n \n int N = m.getNumElements();\n for( int i = 0; i < N; i++ ) {\n double d = m.data[i]/maxAbs;\n total += d*d;\n }\n\n return maxAbs*total*maxAbs;\n }",
"public Equation process( String equation , boolean debug ) {\n compile(equation,true,debug).perform();\n return this;\n }",
"public static Document removeTags(Document dom, String tagName) {\n NodeList list;\n try {\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n\n while (list.getLength() > 0) {\n Node sc = list.item(0);\n\n if (sc != null) {\n sc.getParentNode().removeChild(sc);\n }\n\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n }\n } catch (XPathExpressionException e) {\n LOGGER.error(\"Error while removing tag \" + tagName, e);\n }\n\n return dom;\n\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 }",
"public static int getId(Context context, String id, String defType) {\n String type = \"R.\" + defType + \".\";\n if (id.startsWith(type)) {\n id = id.substring(type.length());\n }\n\n Resources r = context.getResources();\n int resId = r.getIdentifier(id, defType,\n context.getPackageName());\n if (resId > 0) {\n return resId;\n } else {\n throw new RuntimeAssertion(\"Specified resource '%s' could not be found\", id);\n }\n }",
"public static int[] getTileScreenSize(double[] worldSize, double scale) {\n\t\tint screenWidth = (int) Math.round(scale * worldSize[0]);\n\t\tint screenHeight = (int) Math.round(scale * worldSize[1]);\n\t\treturn new int[] { screenWidth, screenHeight };\n\t}"
] |
Use this API to fetch sslpolicylabel resource of given name . | [
"public static sslpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tsslpolicylabel obj = new sslpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tsslpolicylabel response = (sslpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public static boolean queryHasResult(Statement stmt, String sql) {\n try {\n ResultSet rs = stmt.executeQuery(sql);\n try {\n return rs.next();\n } finally {\n rs.close();\n }\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }",
"public void addNotification(@Observes final DesignerNotificationEvent event) {\n if (user.getIdentifier().equals(event.getUserId())) {\n\n if (event.getNotification() != null && !event.getNotification().equals(\"openinxmleditor\")) {\n final NotificationPopupView view = new NotificationPopupView();\n activeNotifications.add(view);\n view.setPopupPosition(getMargin(),\n activeNotifications.size() * SPACING);\n\n view.setNotification(event.getNotification());\n view.setType(event.getType());\n view.setNotificationWidth(getWidth() + \"px\");\n view.show(new Command() {\n\n @Override\n public void execute() {\n //The notification has been shown and can now be removed\n deactiveNotifications.add(view);\n remove();\n }\n });\n }\n }\n }",
"public static void numberToBytes(int number, byte[] buffer, int start, int length) {\n for (int index = start + length - 1; index >= start; index--) {\n buffer[index] = (byte)(number & 0xff);\n number = number >> 8;\n }\n }",
"public ProjectCalendar getDefaultCalendar()\n {\n String calendarName = m_properties.getDefaultCalendarName();\n ProjectCalendar calendar = getCalendarByName(calendarName);\n if (calendar == null)\n {\n if (m_calendars.isEmpty())\n {\n calendar = addDefaultBaseCalendar();\n }\n else\n {\n calendar = m_calendars.get(0);\n }\n }\n return calendar;\n }",
"public boolean setCustomResponse(String pathName, String customResponse) throws Exception {\n // figure out the new ordinal\n int nextOrdinal = this.getNextOrdinalForMethodId(-1, pathName);\n\n // add override\n this.addMethodToResponseOverride(pathName, \"-1\");\n\n // set argument\n return this.setMethodArguments(pathName, \"-1\", nextOrdinal, customResponse);\n }",
"public static Cluster swapGreedyRandomPartitions(final Cluster nextCandidateCluster,\n final List<Integer> nodeIds,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<StoreDefinition> storeDefs) {\n\n System.out.println(\"GreedyRandom : nodeIds:\" + nodeIds);\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n int nodeIdA = -1;\n int nodeIdB = -1;\n int partitionIdA = -1;\n int partitionIdB = -1;\n\n for(int nodeIdAPrime: nodeIds) {\n System.out.println(\"GreedyRandom : processing nodeId:\" + nodeIdAPrime);\n List<Integer> partitionIdsAPrime = new ArrayList<Integer>();\n partitionIdsAPrime.addAll(returnCluster.getNodeById(nodeIdAPrime).getPartitionIds());\n Collections.shuffle(partitionIdsAPrime);\n\n int maxPartitionsInAPrime = Math.min(greedySwapMaxPartitionsPerNode,\n partitionIdsAPrime.size());\n\n for(int offsetAPrime = 0; offsetAPrime < maxPartitionsInAPrime; offsetAPrime++) {\n Integer partitionIdAPrime = partitionIdsAPrime.get(offsetAPrime);\n List<Pair<Integer, Integer>> partitionIdsZone = new ArrayList<Pair<Integer, Integer>>();\n for(int nodeIdBPrime: nodeIds) {\n if(nodeIdBPrime == nodeIdAPrime)\n continue;\n for(Integer partitionIdBPrime: returnCluster.getNodeById(nodeIdBPrime)\n .getPartitionIds()) {\n partitionIdsZone.add(new Pair<Integer, Integer>(nodeIdBPrime,\n partitionIdBPrime));\n }\n }\n\n Collections.shuffle(partitionIdsZone);\n int maxPartitionsInZone = Math.min(greedySwapMaxPartitionsPerZone,\n partitionIdsZone.size());\n for(int offsetZone = 0; offsetZone < maxPartitionsInZone; offsetZone++) {\n Integer nodeIdBPrime = partitionIdsZone.get(offsetZone).getFirst();\n Integer partitionIdBPrime = partitionIdsZone.get(offsetZone).getSecond();\n Cluster swapResult = swapPartitions(returnCluster,\n nodeIdAPrime,\n partitionIdAPrime,\n nodeIdBPrime,\n partitionIdBPrime);\n double swapUtility = new PartitionBalance(swapResult, storeDefs).getUtility();\n if(swapUtility < currentUtility) {\n currentUtility = swapUtility;\n System.out.println(\" -> \" + currentUtility);\n nodeIdA = nodeIdAPrime;\n partitionIdA = partitionIdAPrime;\n nodeIdB = nodeIdBPrime;\n partitionIdB = partitionIdBPrime;\n }\n }\n }\n }\n\n if(nodeIdA == -1) {\n return returnCluster;\n }\n return swapPartitions(returnCluster, nodeIdA, partitionIdA, nodeIdB, partitionIdB);\n }",
"@Pure\n\tpublic static <K, V> Pair<K, V> of(K k, V v) {\n\t\treturn new Pair<K, V>(k, v);\n\t}",
"public static Integer distance(String h1, String h2) {\n\t\tHammingDistance distance = new HammingDistance();\n\t\treturn distance.apply(h1, h2);\n\t}",
"public Metadata createMetadata(String typeName, Metadata metadata) {\n String scope = Metadata.scopeBasedOnType(typeName);\n return this.createMetadata(typeName, scope, metadata);\n }"
] |
Sets the initial pivot ordering and compute the F-norm squared for each column | [
"protected void setupPivotInfo() {\n for( int col = 0; col < numCols; col++ ) {\n pivots[col] = col;\n double c[] = dataQR[col];\n double norm = 0;\n for( int row = 0; row < numRows; row++ ) {\n double element = c[row];\n norm += element*element;\n }\n normsCol[col] = norm;\n }\n }"
] | [
"private boolean interpolationsDisagree(TrackPositionUpdate lastUpdate, TrackPositionUpdate currentUpdate) {\n long now = System.nanoTime();\n return Math.abs(interpolateTimeSinceUpdate(lastUpdate, now) - interpolateTimeSinceUpdate(currentUpdate, now)) >\n slack.get();\n }",
"public void add(T value) {\n Element<T> element = new Element<T>(bundle, value);\n element.previous = tail;\n if (tail != null) tail.next = element;\n tail = element;\n if (head == null) head = element;\n }",
"static DisplayMetrics getDisplayMetrics(final Context context) {\n final WindowManager\n windowManager =\n (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n final DisplayMetrics metrics = new DisplayMetrics();\n windowManager.getDefaultDisplay().getMetrics(metrics);\n return metrics;\n }",
"protected void\t\tcalcLocal(Bone bone, int parentId)\n {\n if (parentId < 0)\n {\n bone.LocalMatrix.set(bone.WorldMatrix);\n return;\n }\n\t/*\n\t * WorldMatrix = WorldMatrix(parent) * LocalMatrix\n\t * LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix\n\t */\n getWorldMatrix(parentId, mTempMtxA);\t// WorldMatrix(par)\n mTempMtxA.invert();\t\t\t\t\t // INVERSE[ WorldMatrix(parent) ]\n mTempMtxA.mul(bone.WorldMatrix, bone.LocalMatrix); // LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix\n }",
"public static double I(int n, double x) {\r\n if (n < 0)\r\n throw new IllegalArgumentException(\"the variable n out of range.\");\r\n else if (n == 0)\r\n return I0(x);\r\n else if (n == 1)\r\n return I(x);\r\n\r\n if (x == 0.0)\r\n return 0.0;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n double tox = 2.0 / Math.abs(x);\r\n double bip = 0, ans = 0.0;\r\n double bi = 1.0;\r\n\r\n for (int j = 2 * (n + (int) Math.sqrt(ACC * n)); j > 0; j--) {\r\n double bim = bip + j * tox * bi;\r\n bip = bi;\r\n bi = bim;\r\n\r\n if (Math.abs(bi) > BIGNO) {\r\n ans *= BIGNI;\r\n bi *= BIGNI;\r\n bip *= BIGNI;\r\n }\r\n\r\n if (j == n)\r\n ans = bip;\r\n }\r\n\r\n ans *= I0(x) / bi;\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }",
"private Path getPath(PropertyWriter writer, JsonStreamContext sc) {\n LinkedList<PathElement> elements = new LinkedList<>();\n\n if (sc != null) {\n elements.add(new PathElement(writer.getName(), sc.getCurrentValue()));\n sc = sc.getParent();\n }\n\n while (sc != null) {\n if (sc.getCurrentName() != null && sc.getCurrentValue() != null) {\n elements.addFirst(new PathElement(sc.getCurrentName(), sc.getCurrentValue()));\n }\n sc = sc.getParent();\n }\n\n return new Path(elements);\n }",
"public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) {\n try {\n return zkClient.getChildren(path);\n } catch (ZkNoNodeException e) {\n return null;\n }\n }",
"private void openBrowser(URI url) throws IOException {\n if (Desktop.isDesktopSupported()) {\n Desktop.getDesktop().browse(url);\n } else {\n LOGGER.error(\"Can not open browser because this capability is not supported on \" +\n \"your platform. You can use the link below to open the report manually.\");\n }\n }",
"public static String makeHTMLTable(String[][] table, String[] rowLabels, String[] colLabels) {\r\n StringBuilder buff = new StringBuilder();\r\n buff.append(\"<table class=\\\"auto\\\" border=\\\"1\\\" cellspacing=\\\"0\\\">\\n\");\r\n // top row\r\n buff.append(\"<tr>\\n\");\r\n buff.append(\"<td></td>\\n\"); // the top left cell\r\n for (int j = 0; j < table[0].length; j++) { // assume table is a rectangular matrix\r\n buff.append(\"<td class=\\\"label\\\">\").append(colLabels[j]).append(\"</td>\\n\");\r\n }\r\n buff.append(\"</tr>\\n\");\r\n // all other rows\r\n for (int i = 0; i < table.length; i++) {\r\n // one row\r\n buff.append(\"<tr>\\n\");\r\n buff.append(\"<td class=\\\"label\\\">\").append(rowLabels[i]).append(\"</td>\\n\");\r\n for (int j = 0; j < table[i].length; j++) {\r\n buff.append(\"<td class=\\\"data\\\">\");\r\n buff.append(((table[i][j] != null) ? table[i][j] : \"\"));\r\n buff.append(\"</td>\\n\");\r\n }\r\n buff.append(\"</tr>\\n\");\r\n }\r\n buff.append(\"</table>\");\r\n return buff.toString();\r\n }"
] |
Recursively read the WBS structure from a PEP file.
@param parent parent container for tasks
@param id initial WBS ID | [
"private void readWBS(ChildTaskContainer parent, Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"WBSTAB\");\n\n while (currentID.intValue() != 0)\n {\n MapRow row = table.find(currentID);\n Integer taskID = row.getInteger(\"TASK_ID\");\n Task task = readTask(parent, taskID);\n Integer childID = row.getInteger(\"CHILD_ID\");\n if (childID.intValue() != 0)\n {\n readWBS(task, childID);\n }\n currentID = row.getInteger(\"NEXT_ID\");\n }\n }"
] | [
"public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }",
"private void initializeLogging() {\n\t\t// Since logging is static, make sure this is done only once even if\n\t\t// multiple clients are created (e.g., during tests)\n\t\tif (consoleAppender != null) {\n\t\t\treturn;\n\t\t}\n\n\t\tconsoleAppender = new ConsoleAppender();\n\t\tconsoleAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\t\tLevelRangeFilter filter = new LevelRangeFilter();\n\t\tfilter.setLevelMin(Level.TRACE);\n\t\tfilter.setLevelMax(Level.INFO);\n\t\tconsoleAppender.addFilter(filter);\n\t\tconsoleAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender);\n\n\t\terrorAppender = new ConsoleAppender();\n\t\terrorAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\terrorAppender.setThreshold(Level.WARN);\n\t\terrorAppender.setTarget(ConsoleAppender.SYSTEM_ERR);\n\t\terrorAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(errorAppender);\n\t}",
"public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret,\n String token) {\n targetOauth = new JsonObject();\n this.consumerSecret = consumerSecret;\n this.consumerKey = consumerKey;\n this.tokenSecret = tokenSecret;\n this.token = token;\n return this;\n }",
"@Deprecated\r\n public static URL buildUrl(String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {\r\n return buildUrl(\"http\", port, path, parameters);\r\n }",
"@PostConstruct\n public void checkUniqueSchemes() {\n Multimap<String, ConfigFileLoaderPlugin> schemeToPluginMap = HashMultimap.create();\n\n for (ConfigFileLoaderPlugin plugin: getLoaderPlugins()) {\n schemeToPluginMap.put(plugin.getUriScheme(), plugin);\n }\n\n StringBuilder violations = new StringBuilder();\n for (String scheme: schemeToPluginMap.keySet()) {\n final Collection<ConfigFileLoaderPlugin> plugins = schemeToPluginMap.get(scheme);\n if (plugins.size() > 1) {\n violations.append(\"\\n\\n* \").append(\"There are has multiple \")\n .append(ConfigFileLoaderPlugin.class.getSimpleName())\n .append(\" plugins that support the scheme: '\").append(scheme).append('\\'')\n .append(\":\\n\\t\").append(plugins);\n }\n }\n\n if (violations.length() > 0) {\n throw new IllegalStateException(violations.toString());\n }\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 MACAddressSection toEUI(boolean extended) {\n\t\tMACAddressSegment[] segs = toEUISegments(extended);\n\t\tif(segs == null) {\n\t\t\treturn null;\n\t\t}\n\t\tMACAddressCreator creator = getMACNetwork().getAddressCreator();\n\t\treturn createSectionInternal(creator, segs, Math.max(0, addressSegmentIndex - 4) << 1, extended);\n\t}",
"public static void setBackgroundDrawable(View view, Drawable drawable) {\n if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {\n view.setBackgroundDrawable(drawable);\n } else {\n view.setBackground(drawable);\n }\n }",
"public synchronized void addListener(CollectionProxyListener listener)\r\n {\r\n if (_listeners == null)\r\n {\r\n _listeners = new ArrayList();\r\n }\r\n // to avoid multi-add of same listener, do check\r\n if(!_listeners.contains(listener))\r\n {\r\n _listeners.add(listener);\r\n }\r\n }"
] |
Try Oracle update batching and call setExecuteBatch or revert to
JDBC update batching. See 12-2 Update Batching in the Oracle9i
JDBC Developer's Guide and Reference.
@param stmt the prepared statement to be used for batching
@throws PlatformException upon JDBC failure | [
"public void beforeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSetExecuteBatch;\r\n final Method methodSendBatch;\r\n methodSetExecuteBatch = ClassHelper.getMethod(stmt, \"setExecuteBatch\", PARAM_TYPE_INTEGER);\r\n methodSendBatch = ClassHelper.getMethod(stmt, \"sendBatch\", null);\r\n\r\n final boolean statementBatchingSupported = methodSetExecuteBatch != null && methodSendBatch != null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // Set number of statements per batch\r\n methodSetExecuteBatch.invoke(stmt, PARAM_STATEMENT_BATCH_SIZE);\r\n m_batchStatementsInProgress.put(stmt, methodSendBatch);\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 super.beforeBatch(stmt);\r\n }\r\n }"
] | [
"protected <T extends Listener> Collection<T> copyList(Class<T> listenerClass,\n Stream<Object> listeners, int sizeHint) {\n if (sizeHint == 0) {\n return Collections.emptyList();\n }\n return listeners\n .map(listenerClass::cast)\n .collect(Collectors.toCollection(() -> new ArrayList<>(sizeHint)));\n }",
"public ConnectionRepository readConnectionRepository(InputStream inst)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readConnectionRepository(inst);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository from \" + inst, e);\r\n }\r\n }",
"public Map<String, String> getSitePath() {\n\n if (m_sitePaths == null) {\n m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object rootPath) {\n\n if (rootPath instanceof String) {\n return getRequestContext().removeSiteRoot((String)rootPath);\n }\n return null;\n }\n });\n }\n return m_sitePaths;\n }",
"public ImmutableList<AbstractElement> getFirstSetGrammarElements() {\n\t\tif (firstSetGrammarElements == null) {\n\t\t\tfirstSetGrammarElements = ImmutableList.copyOf(mutableFirstSetGrammarElements);\n\t\t}\n\t\treturn firstSetGrammarElements;\n\t}",
"public EventBus emit(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }",
"private void addGroups(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Group group : file.getGroups())\n {\n final Group g = group;\n MpxjTreeNode childNode = new MpxjTreeNode(group)\n {\n @Override public String toString()\n {\n return g.getName();\n }\n };\n parentNode.add(childNode);\n }\n }",
"protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\texp.setText(\"$V{\" + var.getName() + \"}\");\n\t\texp.setValueClass(var.getValueClass());\n\t\treturn exp;\n\t}",
"protected void init(DMatrixRMaj A ) {\n UBV = A;\n\n m = UBV.numRows;\n n = UBV.numCols;\n\n min = Math.min(m,n);\n int max = Math.max(m,n);\n\n if( b.length < max+1 ) {\n b = new double[ max+1 ];\n u = new double[ max+1 ];\n }\n if( gammasU.length < m ) {\n gammasU = new double[ m ];\n }\n if( gammasV.length < n ) {\n gammasV = new double[ n ];\n }\n }",
"public void addRequiredValues(@Nonnull final Values sourceValues) {\n Object taskDirectory = sourceValues.getObject(TASK_DIRECTORY_KEY, Object.class);\n MfClientHttpRequestFactoryProvider requestFactoryProvider =\n sourceValues.getObject(CLIENT_HTTP_REQUEST_FACTORY_KEY,\n MfClientHttpRequestFactoryProvider.class);\n Template template = sourceValues.getObject(TEMPLATE_KEY, Template.class);\n PDFConfig pdfConfig = sourceValues.getObject(PDF_CONFIG_KEY, PDFConfig.class);\n String subReportDir = sourceValues.getString(SUBREPORT_DIR_KEY);\n\n this.values.put(TASK_DIRECTORY_KEY, taskDirectory);\n this.values.put(CLIENT_HTTP_REQUEST_FACTORY_KEY, requestFactoryProvider);\n this.values.put(TEMPLATE_KEY, template);\n this.values.put(PDF_CONFIG_KEY, pdfConfig);\n this.values.put(SUBREPORT_DIR_KEY, subReportDir);\n this.values.put(VALUES_KEY, this);\n this.values.put(JOB_ID_KEY, sourceValues.getString(JOB_ID_KEY));\n this.values.put(LOCALE_KEY, sourceValues.getObject(LOCALE_KEY, Locale.class));\n }"
] |
Check whether the given is is matched by one of the include expressions.
@param id id to check
@param includes list of include regular expressions
@return true when id is included | [
"protected boolean check(String id, List<String> includes) {\n\t\tif (null != includes) {\n\t\t\tfor (String check : includes) {\n\t\t\t\tif (check(id, check)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}"
] | [
"public static <T> T assertNull(T value, String message) {\n if (value != null)\n throw new IllegalStateException(message);\n return value;\n }",
"public static final long getLong(byte[] data, int offset)\n {\n if (data.length != 8)\n {\n throw new UnexpectedStructureException();\n }\n\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"private static LblTree createTree(TreeWalker walker) {\n\t\tNode parent = walker.getCurrentNode();\n\t\tLblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1\n\t\tfor (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {\n\t\t\tnode.add(createTree(walker));\n\t\t}\n\t\twalker.setCurrentNode(parent);\n\t\treturn node;\n\t}",
"public void stop() {\n if (runnerThread == null) {\n return;\n }\n\n runnerThread.interrupt();\n\n nsLock.writeLock().lock();\n try {\n if (runnerThread == null) {\n return;\n }\n\n this.cancel();\n this.close();\n\n while (runnerThread.isAlive()) {\n runnerThread.interrupt();\n try {\n runnerThread.join(1000);\n } catch (final Exception e) {\n e.printStackTrace();\n return;\n }\n }\n runnerThread = null;\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"public static boolean isPackageOrClassName(String s) {\n if (S.blank(s)) {\n return false;\n }\n S.List parts = S.fastSplit(s, \".\");\n if (parts.size() < 2) {\n return false;\n }\n for (String part: parts) {\n if (!Character.isJavaIdentifierStart(part.charAt(0))) {\n return false;\n }\n for (int i = 1, len = part.length(); i < len; ++i) {\n if (!Character.isJavaIdentifierPart(part.charAt(i))) {\n return false;\n }\n }\n }\n return true;\n }",
"protected AbstractColumn buildSimpleBarcodeColumn() {\n\t\tBarCodeColumn column = new BarCodeColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\tcolumn.setApplicationIdentifier(applicationIdentifier);\n\t\tcolumn.setBarcodeType(barcodeType);\n\t\tcolumn.setShowText(showText);\n\t\tcolumn.setCheckSum(checkSum);\n\t\treturn column;\n\t}",
"private static DataHandler getDataHandlerForString(Event event) {\n try {\n return new DataHandler(new ByteDataSource(event.getContent().getBytes(\"UTF-8\")));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }",
"@Override\n public void stop()\n {\n synchronized (killHook)\n {\n jqmlogger.info(\"JQM engine \" + this.node.getName() + \" has received a stop order\");\n\n // Kill hook should be removed\n try\n {\n if (!Runtime.getRuntime().removeShutdownHook(killHook))\n {\n jqmlogger.error(\"The engine could not unregister its shutdown hook\");\n }\n }\n catch (IllegalStateException e)\n {\n // This happens if the stop sequence is initiated by the shutdown hook itself.\n jqmlogger.info(\"Stop order is due to an admin operation (KILL/INT)\");\n }\n }\n\n // Stop pollers\n int pollerCount = pollers.size();\n for (QueuePoller p : pollers.values())\n {\n p.stop();\n }\n\n // Scheduler\n this.scheduler.stop();\n\n // Jetty is closed automatically when all pollers are down\n\n // Wait for the end of the world\n if (pollerCount > 0)\n {\n try\n {\n this.ended.acquire();\n }\n catch (InterruptedException e)\n {\n jqmlogger.error(\"interrupted\", e);\n }\n }\n\n // Send a KILL signal to remaining job instances, and wait some more.\n if (this.getCurrentlyRunningJobCount() > 0)\n {\n this.runningJobInstanceManager.killAll();\n try\n {\n Thread.sleep(10000);\n }\n catch (InterruptedException e)\n {\n jqmlogger.error(\"interrupted\", e);\n }\n }\n\n jqmlogger.debug(\"Stop order was correctly handled. Engine for node \" + this.node.getName() + \" has stopped.\");\n }",
"public int size(final K1 firstKey, final K2 secondKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);\n\t\tif( innerMap1 == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t// existence check on inner map1\n\t\tfinal HashMap<K3, V> innerMap2 = innerMap1.get(secondKey);\n\t\tif( innerMap2 == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap2.size();\n\t}"
] |
Call the named method
@param obj The object to call the method on
@param c The class of the object
@param name The name of the method
@param args The method arguments
@return The result of the method | [
"public static <T> Object callMethod(Object obj,\n Class<T> c,\n String name,\n Class<?>[] classes,\n Object[] args) {\n try {\n Method m = getMethod(c, name, classes);\n return m.invoke(obj, args);\n } catch(InvocationTargetException e) {\n throw getCause(e);\n } catch(IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }"
] | [
"public CollectionRequest<Task> subtasks(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public static base_responses delete(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 deleteresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public final int toCodePoints(char[] src, int srcOff, int srcLen, int[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int codePointCount = 0;\n for (int i = 0; i < srcLen; ) {\n final int cp = codePointAt(src, srcOff + i, srcOff + srcLen);\n final int charCount = Character.charCount(cp);\n dest[destOff + codePointCount++] = cp;\n i += charCount;\n }\n return codePointCount;\n }",
"public static String getTitleGalleryKey(String gallery) {\n\n StringBuffer sb = new StringBuffer(GUI_TITLE_PREFIX);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_TITLE_POSTFIX);\n return sb.toString();\n }",
"@SuppressWarnings(\"unused\")\n public Handedness getHandedness()\n {\n if ((currentControllerEvent == null) || currentControllerEvent.isRecycled())\n {\n return null;\n }\n return currentControllerEvent.handedness == 0.0f ?\n Handedness.LEFT : Handedness.RIGHT;\n }",
"private ProjectCalendarDateRanges getRanges(Date date, Calendar cal, Day day)\n {\n ProjectCalendarDateRanges ranges = getException(date);\n if (ranges == null)\n {\n ProjectCalendarWeek week = getWorkWeek(date);\n if (week == null)\n {\n week = this;\n }\n\n if (day == null)\n {\n if (cal == null)\n {\n cal = Calendar.getInstance();\n cal.setTime(date);\n }\n day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n }\n\n ranges = week.getHours(day);\n }\n return ranges;\n }",
"public List<CRFCliqueTree> getCliqueTrees(String filename, DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n List<CRFCliqueTree> cts = new ArrayList<CRFCliqueTree>();\r\n ObjectBank<List<IN>> docs = makeObjectBankFromFile(filename, readerAndWriter);\r\n for (List<IN> doc : docs) {\r\n cts.add(getCliqueTree(doc));\r\n }\r\n\r\n return cts;\r\n }",
"public static final Color getColor(byte[] data, int offset)\n {\n Color result = null;\n\n if (getByte(data, offset + 3) == 0)\n {\n int r = getByte(data, offset);\n int g = getByte(data, offset + 1);\n int b = getByte(data, offset + 2);\n result = new Color(r, g, b);\n }\n\n return result;\n }",
"private void getWeeklyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n int currentDay = calendar.get(Calendar.DAY_OF_WEEK);\n\n while (moreDates(calendar, dates))\n {\n int offset = 0;\n for (int dayIndex = 0; dayIndex < 7; dayIndex++)\n {\n if (getWeeklyDay(Day.getInstance(currentDay)))\n {\n if (offset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, offset);\n offset = 0;\n }\n if (!moreDates(calendar, dates))\n {\n break;\n }\n dates.add(calendar.getTime());\n }\n\n ++offset;\n ++currentDay;\n\n if (currentDay > 7)\n {\n currentDay = 1;\n }\n }\n\n if (frequency > 1)\n {\n offset += (7 * (frequency - 1));\n }\n calendar.add(Calendar.DAY_OF_YEAR, offset);\n }\n }"
] |
Add a path to a profile, returns the id
@param id ID of profile
@param pathname name of path
@param actualPath value of path
@return ID of path created
@throws Exception exception | [
"public int addPathnameToProfile(int id, String pathname, String actualPath) throws Exception {\n int pathOrder = getPathOrder(id).size() + 1;\n int pathId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_PATH\n + \"(\" + Constants.PATH_PROFILE_PATHNAME + \",\"\n + Constants.PATH_PROFILE_ACTUAL_PATH + \",\"\n + Constants.PATH_PROFILE_GROUP_IDS + \",\"\n + Constants.PATH_PROFILE_PROFILE_ID + \",\"\n + Constants.PATH_PROFILE_PATH_ORDER + \",\"\n + Constants.PATH_PROFILE_CONTENT_TYPE + \",\"\n + Constants.PATH_PROFILE_REQUEST_TYPE + \",\"\n + Constants.PATH_PROFILE_GLOBAL + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?, ?, ?);\",\n PreparedStatement.RETURN_GENERATED_KEYS\n );\n statement.setString(1, pathname);\n statement.setString(2, actualPath);\n statement.setString(3, \"\");\n statement.setInt(4, id);\n statement.setInt(5, pathOrder);\n statement.setString(6, Constants.PATH_PROFILE_DEFAULT_CONTENT_TYPE); // should be set by UI/API\n statement.setInt(7, Constants.REQUEST_TYPE_GET); // should be set by UI/API\n statement.setBoolean(8, false);\n statement.executeUpdate();\n\n // execute statement and get resultSet which will have the generated path ID as the first field\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n pathId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add path\");\n }\n } catch (SQLException e) {\n throw e;\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 // need to add to request response table for all clients\n for (Client client : ClientService.getInstance().findAllClients(id)) {\n this.addPathToRequestResponseTable(id, client.getUUID(), pathId);\n }\n\n return pathId;\n }"
] | [
"public static String regexFindFirst(String pattern, String str) {\n return regexFindFirst(Pattern.compile(pattern), str, 1);\n }",
"public static base_response unset(nitro_service client, coparameter resource, String[] args) throws Exception{\n\t\tcoparameter unsetresource = new coparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public ByteArray readBytes(int size) throws IOException\n {\n byte[] data = new byte[size];\n m_stream.read(data);\n return new ByteArray(data);\n }",
"public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url,\n String fileName, long fileSize) throws InterruptedException, IOException {\n //Create a upload session\n BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize);\n return this.uploadHelper(session, stream, fileSize);\n }",
"public Set<ConstraintViolation> validate() {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int record = 1; record <= 3; ++record) {\r\n\t\t\terrors.addAll(validate(record));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}",
"public void promote() {\n URL url = VERSION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, \"current\");\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"type\", \"file_version\");\n jsonObject.add(\"id\", this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(jsonObject.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n this.parseJSON(JsonObject.readFrom(response.getJSON()));\n }",
"private Criteria buildPrefetchCriteriaMultipleKeys(Collection ids, FieldDescriptor fields[])\r\n {\r\n Criteria crit = new Criteria();\r\n Iterator iter = ids.iterator();\r\n Object[] val;\r\n Identity id;\r\n\r\n while (iter.hasNext())\r\n {\r\n Criteria c = new Criteria();\r\n id = (Identity) iter.next();\r\n val = id.getPrimaryKeyValues();\r\n for (int i = 0; i < val.length; i++)\r\n {\r\n if (val[i] == null)\r\n {\r\n c.addIsNull(fields[i].getAttributeName());\r\n }\r\n else\r\n {\r\n c.addEqualTo(fields[i].getAttributeName(), val[i]);\r\n }\r\n }\r\n crit.addOrCriteria(c);\r\n }\r\n\r\n return crit;\r\n }",
"public void removeLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (declaration.getStatus().getServiceReferencesBounded().contains(declarationBinderRef)) {\n linkerManagement.unlink(declaration, declarationBinderRef);\n }\n }\n }",
"public void addColumnIsNull(String column)\r\n {\r\n\t\t// PAW\r\n\t\t//SelectionCriteria c = ValueCriteria.buildNullCriteria(column, getAlias());\r\n\t\tSelectionCriteria c = ValueCriteria.buildNullCriteria(column, getUserAlias(column));\r\n c.setTranslateAttribute(false);\r\n addSelectionCriteria(c);\r\n }"
] |
Use this API to fetch the statistics of all nsacl6_stats resources that are configured on netscaler. | [
"public static nsacl6_stats[] get(nitro_service service) throws Exception{\n\t\tnsacl6_stats obj = new nsacl6_stats();\n\t\tnsacl6_stats[] response = (nsacl6_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}"
] | [
"public Object getObjectByIdentity(Identity id)\r\n throws PersistenceBrokerException\r\n {\r\n checkOpen();\r\n ObjectEnvelope envelope = objectEnvelopeTable.getByIdentity(id);\r\n if (envelope != null)\r\n {\r\n return (envelope.needsDelete() ? null : envelope.getObject());\r\n }\r\n else\r\n {\r\n return getBroker().getObjectByIdentity(id);\r\n }\r\n }",
"public void setDynamicValue(String attribute, String value) {\n\n if (null == m_dynamicValues) {\n m_dynamicValues = new ConcurrentHashMap<String, String>();\n }\n m_dynamicValues.put(attribute, value);\n }",
"public static base_responses unset(nitro_service client, String sitename[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite unsetresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tunsetresources[i] = new gslbsite();\n\t\t\t\tunsetresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public Number getMinutesPerYear()\n {\n return Integer.valueOf(NumberHelper.getInt(getMinutesPerDay()) * NumberHelper.getInt(getDaysPerMonth()) * 12);\n }",
"public static vpntrafficpolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpntrafficpolicy_vpnglobal_binding obj = new vpntrafficpolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tvpntrafficpolicy_vpnglobal_binding response[] = (vpntrafficpolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"boolean awaitState(final InternalState expected) {\n synchronized (this) {\n final InternalState initialRequired = this.requiredState;\n for(;;) {\n final InternalState required = this.requiredState;\n // Stop in case the server failed to reach the state\n if(required == InternalState.FAILED) {\n return false;\n // Stop in case the required state changed\n } else if (initialRequired != required) {\n return false;\n }\n final InternalState current = this.internalState;\n if(expected == current) {\n return true;\n }\n try {\n wait();\n } catch(InterruptedException e) {\n Thread.currentThread().interrupt();\n return false;\n }\n }\n }\n }",
"public Date getDate(String path) throws ParseException {\n return BoxDateFormat.parse(this.getValue(path).asString());\n }",
"public synchronized void stop () {\n if (isRunning()) {\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n WaveformFinder.getInstance().removeWaveformListener(waveformListener);\n BeatGridFinder.getInstance().removeBeatGridListener(beatGridListener);\n running.set(false);\n pendingUpdates.clear();\n queueHandler.interrupt();\n queueHandler = null;\n\n // Report the loss of our signatures, on the proper thread, outside our lock\n final Set<Integer> dyingSignatures = new HashSet<Integer>(signatures.keySet());\n signatures.clear();\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Integer player : dyingSignatures) {\n deliverSignatureUpdate(player, null);\n }\n }\n });\n }\n deliverLifecycleAnnouncement(logger, false);\n }",
"@Override\n public JavaClassBuilderAt at(TypeReferenceLocation... locations)\n {\n if (locations != null)\n this.locations = Arrays.asList(locations);\n return this;\n }"
] |
Inserts an array of Parcelable values into the mapping of the underlying Bundle, replacing any
existing value for the given key. Either key or value may be null.
@param key a String, or null
@param value an array of Parcelable objects, or null
@return this bundler instance to chain method calls | [
"public Bundler put(String key, Parcelable[] value) {\n delegate.putParcelableArray(key, value);\n return this;\n }"
] | [
"private void setBandFinalHeight(JRDesignBand band, int currHeigth, boolean fitToContent) {\n if (band != null) {\n int finalHeight = LayoutUtils.findVerticalOffset(band);\n //noinspection StatementWithEmptyBody\n if (finalHeight < currHeigth && !fitToContent) {\n //nothing\n } else {\n band.setHeight(finalHeight);\n }\n }\n\n }",
"public List<CRFCliqueTree> getCliqueTrees(String filename, DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n List<CRFCliqueTree> cts = new ArrayList<CRFCliqueTree>();\r\n ObjectBank<List<IN>> docs = makeObjectBankFromFile(filename, readerAndWriter);\r\n for (List<IN> doc : docs) {\r\n cts.add(getCliqueTree(doc));\r\n }\r\n\r\n return cts;\r\n }",
"private void initDefaultScopeType(EnhancedAnnotation<T> annotatedAnnotation) {\n Set<Annotation> scopeTypes = new HashSet<Annotation>();\n scopeTypes.addAll(annotatedAnnotation.getMetaAnnotations(Scope.class));\n scopeTypes.addAll(annotatedAnnotation.getMetaAnnotations(NormalScope.class));\n if (scopeTypes.size() > 1) {\n throw MetadataLogger.LOG.multipleScopes(annotatedAnnotation);\n } else if (scopeTypes.size() == 1) {\n this.defaultScopeType = scopeTypes.iterator().next();\n }\n }",
"private void handleFailedSendDataRequest(SerialMessage originalMessage) {\n\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\n\t\tif (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD)\n\t\t\treturn;\n\t\t\n\t\tif (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {\n\t\t\tZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);\n\t\t\t\n\t\t\tif (wakeUpCommandClass != null) {\n\t\t\t\twakeUpCommandClass.setAwake(false);\n\t\t\t\twakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue.\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)\n\t\t\treturn;\n\t\t\n\t\tnode.incrementResendCount();\n\t\t\n\t\tlogger.error(\"Got an error while sending data to node {}. Resending message.\", node.getNodeId());\n\t\tthis.sendData(originalMessage);\n\t}",
"@PrefMetadata(type = CmsTimeWarpPreference.class)\n public String getTimeWarp() {\n\n long warp = m_settings.getTimeWarp();\n return warp < 0 ? \"\" : \"\" + warp; // if timewarp < 0 (i.e. time warp is not set), use the empty string because we don't want the date selector widget to interpret the negative value\n }",
"public Try<R,Throwable> execute(T input){\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)));\n\t\t \n\t}",
"private void addListeners(ProjectReader reader)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n reader.addProjectListener(listener);\n }\n }\n }",
"public static BoxTermsOfService.Info create(BoxAPIConnection api,\n BoxTermsOfService.TermsOfServiceStatus termsOfServiceStatus,\n BoxTermsOfService.TermsOfServiceType termsOfServiceType, String text) {\n URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"status\", termsOfServiceStatus.toString())\n .add(\"tos_type\", termsOfServiceType.toString())\n .add(\"text\", text);\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxTermsOfService createdTermsOfServices = new BoxTermsOfService(api, responseJSON.get(\"id\").asString());\n\n return createdTermsOfServices.new Info(responseJSON);\n }",
"private Integer getReleaseId() {\n\t\tfinal String[] versionParts = stringVersion.split(\"-\");\n\t\t\n\t\tif(isBranch() && versionParts.length >= 3){\n\t\t\treturn Integer.valueOf(versionParts[2]);\n\t\t}\n\t\telse if(versionParts.length >= 2){\n\t\t\treturn Integer.valueOf(versionParts[1]);\n\t\t}\n\n\t\treturn 0;\n\t}"
] |
Generate JSON format as result of the scan.
@since 1.2 | [
"private static void generateJson(CellScanner cellScanner, Function<Bytes, String> encoder,\n PrintStream out) throws JsonIOException {\n Gson gson = new GsonBuilder().serializeNulls().setDateFormat(DateFormat.LONG)\n .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setVersion(1.0)\n .create();\n\n Map<String, String> json = new LinkedHashMap<>();\n for (RowColumnValue rcv : cellScanner) {\n json.put(FLUO_ROW, encoder.apply(rcv.getRow()));\n json.put(FLUO_COLUMN_FAMILY, encoder.apply(rcv.getColumn().getFamily()));\n json.put(FLUO_COLUMN_QUALIFIER, encoder.apply(rcv.getColumn().getQualifier()));\n json.put(FLUO_COLUMN_VISIBILITY, encoder.apply(rcv.getColumn().getVisibility()));\n json.put(FLUO_VALUE, encoder.apply(rcv.getValue()));\n gson.toJson(json, out);\n out.append(\"\\n\");\n\n if (out.checkError()) {\n break;\n }\n }\n out.flush();\n }"
] | [
"private Client getClient(){\n final ClientConfig cfg = new DefaultClientConfig();\n cfg.getClasses().add(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider.class);\n cfg.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, timeout);\n\n return Client.create(cfg);\n }",
"private static void filter(String filename, String filtername) throws Exception\n {\n ProjectFile project = new UniversalProjectReader().read(filename);\n Filter filter = project.getFilters().getFilterByName(filtername);\n\n if (filter == null)\n {\n displayAvailableFilters(project);\n }\n else\n {\n System.out.println(filter);\n System.out.println();\n\n if (filter.isTaskFilter())\n {\n processTaskFilter(project, filter);\n }\n else\n {\n processResourceFilter(project, filter);\n }\n }\n }",
"public static final String[] getRequiredSolrFields() {\n\n if (null == m_requiredSolrFields) {\n List<Locale> locales = OpenCms.getLocaleManager().getAvailableLocales();\n m_requiredSolrFields = new String[14 + (locales.size() * 6)];\n int count = 0;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_PATH;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_TYPE;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_CREATED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_LASTMODIFIED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_EXPIRED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_RELEASED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_SIZE;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_STATE;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_USER_CREATED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_ID;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_USER_LAST_MODIFIED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_ADDITIONAL_INFO;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_CONTAINER_TYPES;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_RESOURCE_LOCALES;\n for (Locale locale : locales) {\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsSearchField.FIELD_TITLE_UNSTORED,\n locale.toString()) + \"_s\";\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsPropertyDefinition.PROPERTY_TITLE,\n locale.toString()) + CmsSearchField.FIELD_DYNAMIC_PROPERTIES_DIRECT + \"_s\";\n m_requiredSolrFields[count++] = CmsPropertyDefinition.PROPERTY_TITLE\n + CmsSearchField.FIELD_DYNAMIC_PROPERTIES_DIRECT\n + \"_s\";\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsSearchField.FIELD_DESCRIPTION,\n locale.toString()) + \"_s\";\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsPropertyDefinition.PROPERTY_DESCRIPTION,\n locale.toString()) + CmsSearchField.FIELD_DYNAMIC_PROPERTIES + \"_s\";\n m_requiredSolrFields[count++] = CmsPropertyDefinition.PROPERTY_DESCRIPTION\n + CmsSearchField.FIELD_DYNAMIC_PROPERTIES\n + \"_s\";\n }\n }\n return m_requiredSolrFields;\n }",
"public Widget findChildByName(final String name) {\n final List<Widget> groups = new ArrayList<>();\n groups.add(this);\n\n return findChildByNameInAllGroups(name, groups);\n }",
"private Filter getFilter(String layerFilter, String[] featureIds) throws GeomajasException {\n\t\tFilter filter = null;\n\t\tif (null != layerFilter) {\n\t\t\tfilter = filterService.parseFilter(layerFilter);\n\t\t}\n\t\tif (null != featureIds) {\n\t\t\tFilter fidFilter = filterService.createFidFilter(featureIds);\n\t\t\tif (null == filter) {\n\t\t\t\tfilter = fidFilter;\n\t\t\t} else {\n\t\t\t\tfilter = filterService.createAndFilter(filter, fidFilter);\n\t\t\t}\n\t\t}\n\t\treturn filter;\n\t}",
"public static String getVariablesMapExpression(Collection variables) {\n StringBuilder variablesMap = new StringBuilder(\"new \" + PropertiesMap.class.getName() + \"()\");\n for (Object variable : variables) {\n JRVariable jrvar = (JRVariable) variable;\n String varname = jrvar.getName();\n variablesMap.append(\".with(\\\"\").append(varname).append(\"\\\",$V{\").append(varname).append(\"})\");\n }\n return variablesMap.toString();\n }",
"public static Command newSetGlobal(String identifier,\n Object object) {\n return getCommandFactoryProvider().newSetGlobal( identifier,\n object );\n }",
"public void setTexCoord(String texName, String texCoordAttr, String shaderVarName)\n {\n synchronized (textures)\n {\n GVRTexture tex = textures.get(texName);\n\n if (tex != null)\n {\n tex.setTexCoord(texCoordAttr, shaderVarName);\n }\n else\n {\n throw new UnsupportedOperationException(\"Texture must be set before updating texture coordinate information\");\n }\n }\n }",
"public static base_response export(nitro_service client, application resource) throws Exception {\n\t\tapplication exportresource = new application();\n\t\texportresource.appname = resource.appname;\n\t\texportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\texportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}"
] |
Delete rows that match the prepared statement. | [
"public int delete(DatabaseConnection databaseConnection, PreparedDelete<T> preparedDelete) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedDelete.compile(databaseConnection, StatementType.DELETE);\n\t\ttry {\n\t\t\tint result = compiledStatement.runUpdate();\n\t\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\t\tdao.notifyChanges();\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}"
] | [
"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 }",
"public static nsacl6[] get(nitro_service service) throws Exception{\n\t\tnsacl6 obj = new nsacl6();\n\t\tnsacl6[] response = (nsacl6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void addFilter(Filter filter)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.add(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.add(filter);\n }\n\n m_filtersByName.put(filter.getName(), filter);\n m_filtersByID.put(filter.getID(), filter);\n }",
"public Class<?> getColumnType(int c) {\n\n for (int r = 0; r < m_data.size(); r++) {\n Object val = m_data.get(r).get(c);\n if (val != null) {\n return val.getClass();\n }\n }\n return Object.class;\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, WaveformDetail> getLoadedDetails() {\n ensureRunning();\n if (!isFindingDetails()) {\n throw new IllegalStateException(\"WaveformFinder is not configured to find waveform details.\");\n }\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformDetail>(detailHotCache));\n }",
"public static String getFailureDescriptionAsString(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n return \"\";\n }\n final String msg;\n if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) {\n if (result.hasDefined(ClientConstants.OP)) {\n msg = String.format(\"Operation '%s' at address '%s' failed: %s\", result.get(ClientConstants.OP), result.get(ClientConstants.OP_ADDR), result\n .get(ClientConstants.FAILURE_DESCRIPTION));\n } else {\n msg = String.format(\"Operation failed: %s\", result.get(ClientConstants.FAILURE_DESCRIPTION));\n }\n } else {\n msg = String.format(\"An unexpected response was found checking the deployment. Result: %s\", result);\n }\n return msg;\n }",
"public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \"=?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"=?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\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 (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }",
"private void initBeanNameDefaulted(EnhancedAnnotation<T> annotatedAnnotation) {\n if (annotatedAnnotation.isAnnotationPresent(Named.class)) {\n if (!\"\".equals(annotatedAnnotation.getAnnotation(Named.class).value())) {\n throw MetadataLogger.LOG.valueOnNamedStereotype(annotatedAnnotation);\n }\n beanNameDefaulted = true;\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 }"
] |
Adds the given value to the set.
@return true if the value was actually new | [
"public boolean add(long key) {\n final int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;\n final Entry entryOriginal = table[index];\n for (Entry entry = entryOriginal; entry != null; entry = entry.next) {\n if (entry.key == key) {\n return false;\n }\n }\n table[index] = new Entry(key, entryOriginal);\n size++;\n if (size > threshold) {\n setCapacity(2 * capacity);\n }\n return true;\n }"
] | [
"public void setRegularExpression(String regularExpression) {\n\t\tif (regularExpression != null)\n\t\t\tthis.regularExpression = Pattern.compile(regularExpression);\n\t\telse\n\t\t\tthis.regularExpression = null;\n\t}",
"@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n String dir = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean verbose = false;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_DIR)) {\n dir = (String) options.valueOf(AdminParserUtils.OPT_DIR);\n }\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n if(options.has(OPT_VERBOSE)) {\n verbose = true;\n }\n\n // execute command\n File directory = AdminToolUtils.createDir(dir);\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {\n metaKeys = Lists.newArrayList();\n for(Object key: MetadataStore.METADATA_KEYS) {\n metaKeys.add((String) key);\n }\n }\n\n doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose);\n }",
"public static base_response unset(nitro_service client, nslimitselector resource, String[] args) throws Exception{\n\t\tnslimitselector unsetresource = new nslimitselector();\n\t\tunsetresource.selectorname = resource.selectorname;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public MIMEType addParameter(String name, String value) {\n Map<String, String> copy = new LinkedHashMap<>(this.parameters);\n copy.put(name, value);\n return new MIMEType(type, subType, copy);\n }",
"@Nullable\n @VisibleForTesting\n protected PolygonSymbolizer createPolygonSymbolizer(final PJsonObject styleJson) {\n if (this.allowNullSymbolizer && !styleJson.has(JSON_FILL_COLOR)) {\n return null;\n }\n\n final PolygonSymbolizer symbolizer = this.styleBuilder.createPolygonSymbolizer();\n symbolizer.setFill(createFill(styleJson));\n\n symbolizer.setStroke(createStroke(styleJson, false));\n\n return symbolizer;\n }",
"public JsonObject getJsonObject() {\n\n JsonObject obj = new JsonObject();\n obj.add(\"field\", this.field);\n\n obj.add(\"value\", this.value);\n\n return obj;\n }",
"private boolean findAndSetManifestFromArtifactory(ArtifactoryServer server, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateImagePath = DockerUtils.getImagePath(imageTag);\n String manifestPath;\n\n // Try to get manifest, assuming reverse proxy\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Try to get manifest, assuming proxy-less\n candidateImagePath = candidateImagePath.substring(candidateImagePath.indexOf(\"/\") + 1);\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Couldn't find correct manifest\n listener.getLogger().println(\"Could not find corresponding manifest.json file in Artifactory.\");\n return false;\n }",
"public void setAssociation(String collectionRole, Association association) {\n\t\tif ( associations == null ) {\n\t\t\tassociations = new HashMap<>();\n\t\t}\n\t\tassociations.put( collectionRole, association );\n\t}",
"public static <T> void injectBoundFields(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends FieldInjectionPoint<?, ?>> injectableFields) {\n for (FieldInjectionPoint<?, ?> injectableField : injectableFields) {\n injectableField.inject(instance, manager, creationalContext);\n }\n }"
] |
Removes an existing metadata value.
@param path the path that designates the key. Must be prefixed with a "/".
@return this metadata object. | [
"public Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\n }"
] | [
"protected boolean hasKey() {\n boolean result = false;\n String requestURI = this.request.getUri();\n parseKeys(requestURI);\n\n if(this.parsedKeys != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. No key specified.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Error: No key specified !\");\n }\n return result;\n }",
"public void insertBefore(Vertex vtx, Vertex next) {\n vtx.prev = next.prev;\n if (next.prev == null) {\n head = vtx;\n } else {\n next.prev.next = vtx;\n }\n vtx.next = next;\n next.prev = vtx;\n }",
"public String calculateCacheKey(String sql, int[] columnIndexes) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\tfor (int i=0; i < columnIndexes.length; i++){\r\n\t\t\ttmp.append(columnIndexes[i]);\r\n\t\t\ttmp.append(\"CI,\");\r\n\t\t}\r\n\t\treturn tmp.toString();\r\n\t}",
"public static void addOverrideToPath() throws Exception {\n Client client = new Client(\"ProfileName\", false);\n\n // Use the fully qualified name for a plugin override.\n client.addMethodToResponseOverride(\"Test Path\", \"com.groupon.odo.sample.Common.delay\");\n\n // The third argument is the ordinal - the nth instance of this override added to this path\n // The final arguments count and type are determined by the override. \"delay\" used in this sample\n // has a single int argument - # of milliseconds delay to simulate\n client.setMethodArguments(\"Test Path\", \"com.groupon.odo.sample.Common.delay\", 1, \"100\");\n }",
"public void dispatchKeyEvent(int code, int action) {\n int keyCode = 0;\n int keyAction = 0;\n if (code == BUTTON_1) {\n keyCode = KeyEvent.KEYCODE_BUTTON_1;\n } else if (code == BUTTON_2) {\n keyCode = KeyEvent.KEYCODE_BUTTON_2;\n }\n\n if (action == ACTION_DOWN) {\n keyAction = KeyEvent.ACTION_DOWN;\n } else if (action == ACTION_UP) {\n keyAction = KeyEvent.ACTION_UP;\n }\n\n KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);\n setKeyEvent(keyEvent);\n }",
"public static base_response enable(nitro_service client, Long clid) throws Exception {\n\t\tclusterinstance enableresource = new clusterinstance();\n\t\tenableresource.clid = clid;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}",
"public static Node addPartitionToNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.addPartitionsToNode(node, Sets.newHashSet(donatedPartition));\n }",
"public static Tuple2<Double, Double> getRandomGeographicalLocation() {\r\n return new Tuple2<>(\r\n (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100,\r\n (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100);\r\n }",
"@SuppressWarnings(\"unchecked\")\n public List<Field> getValueAsList() {\n return (List<Field>) type.convert(getValue(), Type.LIST);\n }"
] |
Takes a string of the form "x1=y1,x2=y2,..." and returns Map
@param map A string of the form "x1=y1,x2=y2,..."
@return A Map m is returned such that m.get(xn) = yn | [
"public static Map<String, String> mapStringToMap(String map) {\r\n String[] m = map.split(\"[,;]\");\r\n Map<String, String> res = new HashMap<String, String>();\r\n for (String str : m) {\r\n int index = str.lastIndexOf('=');\r\n String key = str.substring(0, index);\r\n String val = str.substring(index + 1);\r\n res.put(key.trim(), val.trim());\r\n }\r\n return res;\r\n }"
] | [
"public static void writeInt(byte[] bytes, int value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 24));\n bytes[offset + 1] = (byte) (0xFF & (value >> 16));\n bytes[offset + 2] = (byte) (0xFF & (value >> 8));\n bytes[offset + 3] = (byte) (0xFF & value);\n }",
"public void refreshBitmapShader()\n\t{\n\t\tshader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);\n\t}",
"public PathElement getElement(int index) {\n final List<PathElement> list = pathAddressList;\n return list.get(index);\n }",
"public void swapSubstring(BitString other, int start, int length)\n {\n assertValidIndex(start);\n other.assertValidIndex(start);\n \n int word = start / WORD_LENGTH;\n\n int partialWordSize = (WORD_LENGTH - start) % WORD_LENGTH;\n if (partialWordSize > 0)\n {\n swapBits(other, word, 0xFFFFFFFF << (WORD_LENGTH - partialWordSize));\n ++word;\n }\n\n int remainingBits = length - partialWordSize;\n int stop = remainingBits / WORD_LENGTH;\n for (int i = word; i < stop; i++)\n {\n int temp = data[i];\n data[i] = other.data[i];\n other.data[i] = temp;\n }\n\n remainingBits %= WORD_LENGTH;\n if (remainingBits > 0)\n {\n swapBits(other, word, 0xFFFFFFFF >>> (WORD_LENGTH - remainingBits));\n }\n }",
"public void setHomeAsUpIndicator(Drawable indicator) {\n if(!deviceSupportMultiPane()) {\n pulsante.setHomeAsUpIndicator(indicator);\n }\n else {\n actionBar.setHomeAsUpIndicator(indicator);\n }\n }",
"public void disableAll(int profileId, String client_uuid) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.CLIENT_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.CLIENT_CLIENT_UUID + \" =? \"\n );\n statement.setInt(1, profileId);\n statement.setString(2, client_uuid);\n statement.executeUpdate();\n statement.close();\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 }",
"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 static KieRuntimeLogger newFileLogger(KieRuntimeEventManager session,\n String fileName) {\n return getKnowledgeRuntimeLoggerProvider().newFileLogger( session,\n fileName );\n }",
"void onPatternChange() {\n\n PatternType patternType = m_model.getPatternType();\n boolean isSeries = !patternType.equals(PatternType.NONE);\n setSerialOptionsVisible(isSeries);\n m_seriesCheckBox.setChecked(isSeries);\n if (isSeries) {\n m_groupPattern.selectButton(m_patternButtons.get(patternType));\n m_controller.getPatternView().onValueChange();\n m_patternOptions.setWidget(m_controller.getPatternView());\n onEndTypeChange();\n }\n m_controller.sizeChanged();\n }"
] |
Determine if a key version is invalid by comparing the version's
existence and required writes configuration
@param keyVersionNodeSetMap A map that contains keys mapping to a map
that maps versions to set of PrefixNodes
@param requiredWrite Required Write configuration | [
"public static void cleanIneligibleKeys(Map<ByteArray, Map<Value, Set<ClusterNode>>> keyVersionNodeSetMap,\n int requiredWrite) {\n Set<ByteArray> keysToDelete = new HashSet<ByteArray>();\n for (Map.Entry<ByteArray, Map<Value, Set<ClusterNode>>> entry : keyVersionNodeSetMap.entrySet()) {\n Set<Value> valuesToDelete = new HashSet<Value>();\n\n ByteArray key = entry.getKey();\n Map<Value, Set<ClusterNode>> valueNodeSetMap = entry.getValue();\n // mark version for deletion if not enough writes\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : valueNodeSetMap.entrySet()) {\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n if (nodeSet.size() < requiredWrite) {\n valuesToDelete.add(versionNodeSetEntry.getKey());\n }\n }\n // delete versions\n for (Value v : valuesToDelete) {\n valueNodeSetMap.remove(v);\n }\n // mark key for deletion if no versions left\n if (valueNodeSetMap.size() == 0) {\n keysToDelete.add(key);\n }\n }\n // delete keys\n for (ByteArray k : keysToDelete) {\n keyVersionNodeSetMap.remove(k);\n }\n }"
] | [
"public void fireEvent(final WorkerEvent event, final Worker worker, final String queue, final Job job, \n final Object runner, final Object result, final Throwable t) {\n final ConcurrentSet<WorkerListener> listeners = this.eventListenerMap.get(event);\n if (listeners != null) {\n for (final WorkerListener listener : listeners) {\n if (listener != null) {\n try {\n listener.onEvent(event, worker, queue, job, runner, result, t);\n } catch (Exception e) {\n log.error(\"Failure executing listener \" + listener + \" for event \" + event \n + \" from queue \" + queue + \" on worker \" + worker, e);\n }\n }\n }\n }\n }",
"private void deliverMasterYieldResponse(int fromPlayer, boolean yielded) {\n for (final MasterHandoffListener listener : getMasterHandoffListeners()) {\n try {\n listener.yieldResponse(fromPlayer, yielded);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master yield response to listener\", t);\n }\n }\n }",
"public static Interface[] get(nitro_service service) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tInterface[] response = (Interface[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static dnsnsecrec get(nitro_service service, String hostname) throws Exception{\n\t\tdnsnsecrec obj = new dnsnsecrec();\n\t\tobj.set_hostname(hostname);\n\t\tdnsnsecrec response = (dnsnsecrec) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static Command newQuery(String identifier,\n String name) {\n return getCommandFactoryProvider().newQuery( identifier,\n name );\n\n }",
"public GenericCriteria process(ProjectProperties properties, byte[] data, int dataOffset, int entryOffset, List<GenericCriteriaPrompt> prompts, List<FieldType> fields, boolean[] criteriaType)\n {\n m_properties = properties;\n m_prompts = prompts;\n m_fields = fields;\n m_criteriaType = criteriaType;\n m_dataOffset = dataOffset;\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = true;\n m_criteriaType[1] = true;\n }\n\n m_criteriaBlockMap.clear();\n\n m_criteriaData = data;\n m_criteriaTextStart = MPPUtility.getShort(m_criteriaData, m_dataOffset + getCriteriaTextStartOffset());\n\n //\n // Populate the map\n //\n int criteriaStartOffset = getCriteriaStartOffset();\n int criteriaBlockSize = getCriteriaBlockSize();\n\n //System.out.println();\n //System.out.println(ByteArrayHelper.hexdump(data, dataOffset, criteriaStartOffset, false));\n\n if (m_criteriaData.length <= m_criteriaTextStart)\n {\n return null; // bad data\n }\n\n while (criteriaStartOffset + criteriaBlockSize <= m_criteriaTextStart)\n {\n byte[] block = new byte[criteriaBlockSize];\n System.arraycopy(m_criteriaData, m_dataOffset + criteriaStartOffset, block, 0, criteriaBlockSize);\n m_criteriaBlockMap.put(Integer.valueOf(criteriaStartOffset), block);\n //System.out.println(Integer.toHexString(criteriaStartOffset) + \": \" + ByteArrayHelper.hexdump(block, false));\n criteriaStartOffset += criteriaBlockSize;\n }\n\n if (entryOffset == -1)\n {\n entryOffset = getCriteriaStartOffset();\n }\n\n List<GenericCriteria> list = new LinkedList<GenericCriteria>();\n processBlock(list, m_criteriaBlockMap.get(Integer.valueOf(entryOffset)));\n GenericCriteria criteria;\n if (list.isEmpty())\n {\n criteria = null;\n }\n else\n {\n criteria = list.get(0);\n }\n return criteria;\n }",
"private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }",
"public FinishRequest toFinishRequest(boolean includeHeaders) {\n if (includeHeaders) {\n return new FinishRequest(body, copyHeaders(headers), statusCode);\n } else {\n String mime = null;\n if (body!=null) {\n mime = \"text/plain\";\n if (headers!=null && (headers.containsKey(\"Content-Type\") || headers.containsKey(\"content-type\"))) {\n mime = headers.get(\"Content-Type\");\n if (mime==null) {\n mime = headers.get(\"content-type\");\n }\n }\n }\n\n return new FinishRequest(body, mime, statusCode);\n }\n }",
"protected void markStatementsForDeletion(StatementDocument currentDocument,\n\t\t\tList<Statement> deleteStatements) {\n\t\tfor (Statement statement : deleteStatements) {\n\t\t\tboolean found = false;\n\t\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\t\tif (!sg.getProperty().equals(statement.getMainSnak().getPropertyId())) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tStatement changedStatement = null;\n\t\t\t\tfor (Statement existingStatement : sg) {\n\t\t\t\t\tif (existingStatement.equals(statement)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\ttoDelete.add(statement.getStatementId());\n\t\t\t\t\t} else if (existingStatement.getStatementId().equals(\n\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t\t// (we assume all existing statement ids to be nonempty\n\t\t\t\t\t\t// here)\n\t\t\t\t\t\tchangedStatement = existingStatement;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!found) {\n\t\t\t\t\tStringBuilder warning = new StringBuilder();\n\t\t\t\t\twarning.append(\"Cannot delete statement (id \")\n\t\t\t\t\t\t\t.append(statement.getStatementId())\n\t\t\t\t\t\t\t.append(\") since it is not present in data. Statement was:\\n\")\n\t\t\t\t\t\t\t.append(statement);\n\n\t\t\t\t\tif (changedStatement != null) {\n\t\t\t\t\t\twarning.append(\n\t\t\t\t\t\t\t\t\"\\nThe data contains another statement with the same id: maybe it has been edited? Other statement was:\\n\")\n\t\t\t\t\t\t\t\t.append(changedStatement);\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn(warning.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] |
So that we get these packages caught Java class analysis. | [
"private void registerPackageInTypeInterestFactory(String pkg)\n {\n TypeInterestFactory.registerInterest(pkg + \"_pkg\", pkg.replace(\".\", \"\\\\.\"), pkg, TypeReferenceLocation.IMPORT);\n // TODO: Finish the implementation\n }"
] | [
"public void setFarClippingDistance(float far) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setFarClippingDistance(far);\n centerCamera.setFarClippingDistance(far);\n ((GVRCameraClippingDistanceInterface)rightCamera).setFarClippingDistance(far);\n }\n }",
"public Set<String> rangeByRank(final long start, final long end) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n return jedis.zrange(getKey(), start, end);\n }\n });\n }",
"private static JsonArray getJsonArray(List<String> keys) {\n JsonArray array = new JsonArray();\n for (String key : keys) {\n array.add(key);\n }\n\n return array;\n }",
"@Override\n\tprotected final void subAppend(final LoggingEvent event) {\n\t\tif (event instanceof ScheduledFileRollEvent) {\n\t\t\t// the scheduled append() call has been made by a different thread\n\t\t\tsynchronized (this) {\n\t\t\t\tif (this.closed) {\n\t\t\t\t\t// just consume the event\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.rollFile(event);\n\t\t\t}\n\t\t} else if (event instanceof FileRollEvent) {\n\t\t\t// definitely want to avoid rolling here whilst a file roll event is still being handled\n\t\t\tsuper.subAppend(event);\n\t\t} else {\n\n\t\t\tif(event instanceof FoundationLof4jLoggingEvent){\n\t\t\t\tFoundationLof4jLoggingEvent foundationLof4jLoggingEvent = (FoundationLof4jLoggingEvent)event;\n\t\t\t\tfoundationLof4jLoggingEvent.setAppenderName(this.getName());\n\t\t\t}\n\t\t\t\n\t\t\tthis.rollFile(event);\n\t\t\tsuper.subAppend(event);\n\t\t}\n\t}",
"public void download(OutputStream output, ProgressListener listener) {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n InputStream input = response.getBody(listener);\n\n long totalRead = 0;\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = input.read(buffer);\n totalRead += n;\n while (n != -1) {\n output.write(buffer, 0, n);\n n = input.read(buffer);\n totalRead += n;\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n\n response.disconnect();\n }",
"public Optional<SoyMsgBundle> resolve(final Optional<Locale> locale) throws IOException {\n if (!locale.isPresent()) {\n return Optional.absent();\n }\n\n synchronized (msgBundles) {\n SoyMsgBundle soyMsgBundle = null;\n if (isHotReloadModeOff()) {\n soyMsgBundle = msgBundles.get(locale.get());\n }\n if (soyMsgBundle == null) {\n soyMsgBundle = createSoyMsgBundle(locale.get());\n if (soyMsgBundle == null) {\n soyMsgBundle = createSoyMsgBundle(new Locale(locale.get().getLanguage()));\n }\n\n if (soyMsgBundle == null && fallbackToEnglish) {\n soyMsgBundle = createSoyMsgBundle(Locale.ENGLISH);\n }\n\n if (soyMsgBundle == null) {\n return Optional.absent();\n }\n\n if (isHotReloadModeOff()) {\n msgBundles.put(locale.get(), soyMsgBundle);\n }\n }\n\n return Optional.fromNullable(soyMsgBundle);\n }\n }",
"protected int complete(CommandContext ctx, ParsedCommandLine parsedCmd, OperationCandidatesProvider candidatesProvider, final String buffer, int cursor, List<String> candidates) {\n\n if(parsedCmd.isRequestComplete()) {\n return -1;\n }\n\n // Headers completion\n if(parsedCmd.endsOnHeaderListStart() || parsedCmd.hasHeaders()) {\n return completeHeaders(ctx, parsedCmd, candidatesProvider, buffer, cursor, candidates);\n }\n\n // Completed.\n if(parsedCmd.endsOnPropertyListEnd()) {\n return buffer.length();\n }\n\n // Complete properties\n if (parsedCmd.hasProperties() || parsedCmd.endsOnPropertyListStart()\n || parsedCmd.endsOnNotOperator()) {\n return completeProperties(ctx, parsedCmd, candidatesProvider, buffer, candidates);\n }\n\n // Complete Operation name\n if (parsedCmd.hasOperationName() || parsedCmd.endsOnAddressOperationNameSeparator()) {\n return completeOperationName(ctx, parsedCmd, candidatesProvider, buffer, candidates);\n }\n\n // Finally Complete address\n return completeAddress(ctx, parsedCmd, candidatesProvider, buffer, candidates);\n }",
"public static String getJavaCommand(final Path javaHome) {\n final Path resolvedJavaHome = javaHome == null ? findJavaHome() : javaHome;\n final String exe;\n if (resolvedJavaHome == null) {\n exe = \"java\";\n } else {\n exe = resolvedJavaHome.resolve(\"bin\").resolve(\"java\").toString();\n }\n if (exe.contains(\" \")) {\n return \"\\\"\" + exe + \"\\\"\";\n }\n if (WINDOWS) {\n return exe + \".exe\";\n }\n return exe;\n }",
"private void createAndAddButton(PatternType pattern, String messageKey) {\n\n CmsRadioButton btn = new CmsRadioButton(pattern.toString(), Messages.get().key(messageKey));\n btn.addStyleName(I_CmsWidgetsLayoutBundle.INSTANCE.widgetCss().radioButtonlabel());\n btn.setGroup(m_groupPattern);\n m_patternButtons.put(pattern, btn);\n m_patternRadioButtonsPanel.add(btn);\n\n }"
] |
Provides a consistent ordering over lists. First compares by the first
element. If that element is equal, the next element is considered, and so
on. | [
"public static <T extends Comparable<T>> int compareLists(List<T> list1, List<T> list2) {\r\n if (list1 == null && list2 == null)\r\n return 0;\r\n if (list1 == null || list2 == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n int size1 = list1.size();\r\n int size2 = list2.size();\r\n int size = Math.min(size1, size2);\r\n for (int i = 0; i < size; i++) {\r\n int c = list1.get(i).compareTo(list2.get(i));\r\n if (c != 0)\r\n return c;\r\n }\r\n if (size1 < size2)\r\n return -1;\r\n if (size1 > size2)\r\n return 1;\r\n return 0;\r\n }"
] | [
"private void readWBS(ChildTaskContainer parent, Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"WBSTAB\");\n\n while (currentID.intValue() != 0)\n {\n MapRow row = table.find(currentID);\n Integer taskID = row.getInteger(\"TASK_ID\");\n Task task = readTask(parent, taskID);\n Integer childID = row.getInteger(\"CHILD_ID\");\n if (childID.intValue() != 0)\n {\n readWBS(task, childID);\n }\n currentID = row.getInteger(\"NEXT_ID\");\n }\n }",
"public static void acceptsHex(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_X, OPT_HEX), \"fetch key/entry by key value of hex type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }",
"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 Object getObjectByIdentity(Identity id)\r\n throws PersistenceBrokerException\r\n {\r\n checkOpen();\r\n ObjectEnvelope envelope = objectEnvelopeTable.getByIdentity(id);\r\n if (envelope != null)\r\n {\r\n return (envelope.needsDelete() ? null : envelope.getObject());\r\n }\r\n else\r\n {\r\n return getBroker().getObjectByIdentity(id);\r\n }\r\n }",
"public Object getBeliefValue(String agent_name, final String belief_name,\n 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 belief_value = bia.getBeliefbase()\n .getBelief(belief_name).getFact();\n return null;\n }\n }).get(new ThreadSuspendable());\n return belief_value;\n }",
"private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception {\n if (tries >= 5) {\n throw new BindException(\"Unable to bind to several ports, most recently \" + relay.getPort() + \". Giving up\");\n }\n try {\n if (server.isStarted()) {\n relay.start();\n } else {\n throw new RuntimeException(\"Can't start SslRelay: server is not started (perhaps it was just shut down?)\");\n }\n } catch (BindException e) {\n // doh - the port is being used up, let's pick a new port\n LOG.info(\"Unable to bind to port %d, going to try port %d now\", relay.getPort(), relay.getPort() + 1);\n relay.setPort(relay.getPort() + 1);\n startRelayWithPortTollerance(server, relay, tries + 1);\n }\n }",
"public synchronized void stop() {\n if (isRunning()) {\n try {\n setSendingStatus(false);\n } catch (Throwable t) {\n logger.error(\"Problem stopping sending status during shutdown\", t);\n }\n DeviceFinder.getInstance().removeIgnoredAddress(socket.get().getLocalAddress());\n socket.get().close();\n socket.set(null);\n broadcastAddress.set(null);\n updates.clear();\n setTempoMaster(null);\n setDeviceNumber((byte)0); // Set up for self-assignment if restarted.\n deliverLifecycleAnnouncement(logger, false);\n }\n }",
"private void readHolidays()\n {\n for (MapRow row : m_tables.get(\"HOL\"))\n {\n ProjectCalendar calendar = m_calendarMap.get(row.getInteger(\"CALENDAR_ID\"));\n if (calendar != null)\n {\n Date date = row.getDate(\"DATE\");\n ProjectCalendarException exception = calendar.addCalendarException(date, date);\n if (row.getBoolean(\"ANNUAL\"))\n {\n RecurringData recurring = new RecurringData();\n recurring.setRecurrenceType(RecurrenceType.YEARLY);\n recurring.setYearlyAbsoluteFromDate(date);\n recurring.setStartDate(date);\n exception.setRecurring(recurring);\n // TODO set end date based on project end date\n }\n }\n }\n }",
"public static String readFlowId(Message message) {\n String flowId = null;\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n List<String> flowIds = headers.get(FLOWID_HTTP_HEADER_NAME);\n if (flowIds != null && flowIds.size() > 0) {\n flowId = flowIds.get(0);\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' found: \" + flowId);\n }\n } else {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' found\");\n }\n }\n\n return flowId;\n }"
] |
Returns the connection count in this registry.
Note it might count connections that are closed but not removed from registry yet
@return the connection count | [
"public int count() {\n int n = 0;\n for (ConcurrentMap<?, ?> bag : registry.values()) {\n n += bag.size();\n }\n return n;\n }"
] | [
"private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueTag tag) {\n for (RekordboxAnlz.CueEntry cueEntry : tag.cues()) { // TODO: Need to figure out how to identify deleted entries to ignore.\n if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) {\n entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()),\n Util.timeToHalfFrame(cueEntry.loopTime())));\n } else {\n entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time())));\n }\n }\n }",
"public void setDividerPadding(float padding, final Axis axis) {\n if (axis == getOrientationAxis()) {\n super.setDividerPadding(padding, axis);\n } else {\n Log.w(TAG, \"Cannot apply divider padding for wrong axis [%s], orientation = %s\",\n axis, getOrientation());\n }\n }",
"public static cacheobject[] get(nitro_service service) throws Exception{\n\t\tcacheobject obj = new cacheobject();\n\t\tcacheobject[] response = (cacheobject[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void fillRectangle(Rectangle rect, Color color) {\n\t\ttemplate.saveState();\n\t\tsetFill(color);\n\t\ttemplate.rectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight());\n\t\ttemplate.fill();\n\t\ttemplate.restoreState();\n\t}",
"public static boolean isFalse(Expression expression) {\r\n if (expression == null) {\r\n return false;\r\n }\r\n if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) {\r\n if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression\r\n && \"FALSE\".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) {\r\n return true;\r\n }\r\n }\r\n return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isFalseExpression())\r\n || \"Boolean.FALSE\".equals(expression.getText());\r\n }",
"@Override\n\tpublic Trajectory subList(int fromIndex, int toIndex) {\n\t\tTrajectory t = new Trajectory(dimension);\n\t\t\n\t\tfor(int i = fromIndex; i < toIndex; i++){\n\t\t\tt.add(this.get(i));\n\t\t}\n\t\treturn t;\n\t}",
"private static String getColumnTitle(final PropertyDescriptor _property) {\n final StringBuilder buffer = new StringBuilder();\n final String name = _property.getName();\n buffer.append(Character.toUpperCase(name.charAt(0)));\n for (int i = 1; i < name.length(); i++) {\n final char c = name.charAt(i);\n if (Character.isUpperCase(c)) {\n buffer.append(' ');\n }\n buffer.append(c);\n }\n return buffer.toString();\n }",
"private void checkAnonymous(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 String access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);\r\n\r\n if (!\"anonymous\".equals(access))\r\n {\r\n throw new ConstraintException(\"The access property of the field \"+fieldDef.getName()+\" defined in class \"+fieldDef.getOwner().getName()+\" cannot be changed\");\r\n }\r\n\r\n if ((fieldDef.getName() == null) || (fieldDef.getName().length() == 0))\r\n {\r\n throw new ConstraintException(\"An anonymous field defined in class \"+fieldDef.getOwner().getName()+\" has no name\");\r\n }\r\n }",
"public void setWidth(int width) {\n this.width = width;\n getElement().getStyle().setWidth(width, Style.Unit.PX);\n }"
] |
The main conversion method.
@param image A BufferedImage containing the image that needs to be converted
@param favicon When ico is true it will convert ico file into 16 x 16 size
@return A string containing the ASCII version of the original image. | [
"public String convert(BufferedImage image, boolean favicon) {\n // Reset statistics before anything\n statsArray = new int[12];\n // Begin the timer\n dStart = System.nanoTime();\n // Scale the image\n image = scale(image, favicon);\n // The +1 is for the newline characters\n StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight());\n\n for (int y = 0; y < image.getHeight(); y++) {\n // At the end of each line, add a newline character\n if (sb.length() != 0) sb.append(\"\\n\");\n for (int x = 0; x < image.getWidth(); x++) {\n //\n Color pixelColor = new Color(image.getRGB(x, y), true);\n int alpha = pixelColor.getAlpha();\n boolean isTransient = alpha < 0.1;\n double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250);\n final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue);\n sb.append(s);\n }\n }\n imgArray = sb.toString().toCharArray();\n dEnd = System.nanoTime();\n return sb.toString();\n }"
] | [
"protected boolean hasPermissions(CmsObject cms, CmsSolrDocument doc, CmsResourceFilter filter) {\r\n\r\n return null != (filter == null ? getResource(cms, doc) : getResource(cms, doc, filter));\r\n }",
"private void harvestReturnValue(\r\n Object obj,\r\n CallableStatement callable,\r\n FieldDescriptor fmd,\r\n int index)\r\n throws PersistenceBrokerSQLException\r\n {\r\n\r\n try\r\n {\r\n // If we have a field descriptor, then we can harvest\r\n // the return value.\r\n if ((callable != null) && (fmd != null) && (obj != null))\r\n {\r\n // Get the value and convert it to it's appropriate\r\n // java type.\r\n Object value = fmd.getJdbcType().getObjectFromColumn(callable, index);\r\n\r\n // Set the value of the persistent field.\r\n fmd.getPersistentField().set(obj, fmd.getFieldConversion().sqlToJava(value));\r\n\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n String msg = \"SQLException during the execution of harvestReturnValue\"\r\n + \" class=\"\r\n + obj.getClass().getName()\r\n + \",\"\r\n + \" field=\"\r\n + fmd.getAttributeName()\r\n + \" : \"\r\n + e.getMessage();\r\n logger.error(msg,e);\r\n throw new PersistenceBrokerSQLException(msg, e);\r\n }\r\n }",
"public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) {\n\t\tdouble x = lognormalVolatiltiy * Math.sqrt(maturity / 8);\n\t\tdouble y = org.apache.commons.math3.special.Erf.erf(x);\n\t\tdouble normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y;\n\n\t\treturn normalVol;\n\t}",
"public static List<Node> getSiblings(Node parent, Node element) {\n\t\tList<Node> result = new ArrayList<>();\n\t\tNodeList list = parent.getChildNodes();\n\n\t\tfor (int i = 0; i < list.getLength(); i++) {\n\t\t\tNode el = list.item(i);\n\n\t\t\tif (el.getNodeName().equals(element.getNodeName())) {\n\t\t\t\tresult.add(el);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}",
"public void setFieldConversionClassName(String fieldConversionClassName)\r\n {\r\n try\r\n {\r\n this.fieldConversion = (FieldConversion) ClassHelper.newInstance(fieldConversionClassName);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\r\n \"Could not instantiate FieldConversion class using default constructor\", e);\r\n }\r\n }",
"public static <T extends WindupVertexFrame> T addTypeToModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type)\n {\n Vertex vertex = frame.getElement();\n graphContext.getGraphTypeManager().addTypeToElement(type, vertex);\n return graphContext.getFramed().frameElement(vertex, type);\n }",
"public void validate() throws PackagingException {\n if (control == null || !control.isDirectory()) {\n throw new PackagingException(\"The 'control' attribute doesn't point to a directory. \" + control);\n }\n\n if (changesIn != null) {\n\n if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) {\n throw new PackagingException(\"The 'changesIn' setting needs to point to a readable file. \" + changesIn + \" was not found/readable.\");\n }\n\n if (changesOut != null && !isWritableFile(changesOut)) {\n throw new PackagingException(\"Cannot write the output for 'changesOut' to \" + changesOut);\n }\n\n if (changesSave != null && !isWritableFile(changesSave)) {\n throw new PackagingException(\"Cannot write the output for 'changesSave' to \" + changesSave);\n }\n\n } else {\n if (changesOut != null || changesSave != null) {\n throw new PackagingException(\"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.\");\n }\n }\n\n if (Compression.toEnum(compression) == null) {\n throw new PackagingException(\"The compression method '\" + compression + \"' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')\");\n }\n\n if (deb == null) {\n throw new PackagingException(\"You need to specify where the deb file is supposed to be created.\");\n }\n\n getDigestCode(digest);\n }",
"public static ClientBuilder account(String account) {\n logger.config(\"Account: \" + account);\n return ClientBuilder.url(\n convertStringToURL(String.format(\"https://%s.cloudant.com\", account)));\n }",
"public static bridgegroup_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_nsip_binding obj = new bridgegroup_nsip_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_nsip_binding response[] = (bridgegroup_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Gets the element view.
@return the element view | [
"@PrefMetadata(type = CmsElementViewPreference.class)\n public String getElementView() {\n\n return m_settings.getAdditionalPreference(CmsElementViewPreference.PREFERENCE_NAME, false);\n }"
] | [
"protected static final float[] getSpreadInRange(float member, int count, int max, int offset) {\n // to find the spread, we first find the min that is a\n // multiple of max/count away from the member\n\n int interval = max / count;\n float min = (member + offset) % interval;\n\n if (min == 0 && member == max) {\n min += interval;\n }\n\n float[] range = new float[count];\n for (int i = 0; i < count; i++) {\n range[i] = min + interval * i + offset;\n }\n\n return range;\n }",
"public Axis getOrientationAxis() {\n final Axis axis;\n switch(getOrientation()) {\n case HORIZONTAL:\n axis = Axis.X;\n break;\n case VERTICAL:\n axis = Axis.Y;\n break;\n case STACK:\n axis = Axis.Z;\n break;\n default:\n Log.w(TAG, \"Unsupported orientation %s\", mOrientation);\n axis = Axis.X;\n break;\n }\n return axis;\n }",
"public static base_response update(nitro_service client, dospolicy resource) throws Exception {\n\t\tdospolicy updateresource = new dospolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.qdepth = resource.qdepth;\n\t\tupdateresource.cltdetectrate = resource.cltdetectrate;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public HttpConnection setRequestBody(final InputStream input, final long inputLength) {\n try {\n return setRequestBody(new InputStreamWrappingGenerator(input, inputLength),\n inputLength);\n } catch (IOException e) {\n logger.log(Level.SEVERE, \"Error copying input stream for request body\", e);\n throw new RuntimeException(e);\n }\n }",
"@Override\r\n public String replace(File file, String flickrId, boolean async) throws FlickrException {\r\n Payload payload = new Payload(file, flickrId);\r\n return sendReplaceRequest(async, payload);\r\n }",
"public ModelNode registerDeploymentSubsystemResource(final String subsystemName, final Resource resource) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n assert resource != null : \"The resource cannot be null\";\n return registerDeploymentSubResource(subsystemName, PathAddress.EMPTY_ADDRESS, resource);\n }",
"protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) {\n if (value == null) {\n return \"\";\n }\n else {\n // midnight GMT\n Date date = new Date(0);\n // offset by timezone and value\n date.setTime(UTCDateBox.timezoneOffsetMillis(date) + value.longValue());\n // format it\n return fmt.format(date);\n }\n }",
"public void storeIfNew(final DbArtifact fromClient) {\n final DbArtifact existing = repositoryHandler.getArtifact(fromClient.getGavc());\n\n if(existing != null){\n existing.setLicenses(fromClient.getLicenses());\n store(existing);\n }\n\n if(existing == null){\n\t store(fromClient);\n }\n }",
"public static int getId(Context context, String id, String defType) {\n String type = \"R.\" + defType + \".\";\n if (id.startsWith(type)) {\n id = id.substring(type.length());\n }\n\n Resources r = context.getResources();\n int resId = r.getIdentifier(id, defType,\n context.getPackageName());\n if (resId > 0) {\n return resId;\n } else {\n throw new RuntimeAssertion(\"Specified resource '%s' could not be found\", id);\n }\n }"
] |
Internal used method to retrieve object based on Identity.
@param id
@return
@throws PersistenceBrokerException | [
"public Object doGetObjectByIdentity(Identity id) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled()) logger.debug(\"getObjectByIdentity \" + id);\n\n // check if object is present in ObjectCache:\n Object obj = objectCache.lookup(id);\n // only perform a db lookup if necessary (object not cached yet)\n if (obj == null)\n {\n obj = getDBObject(id);\n }\n else\n {\n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n // if specified in the ClassDescriptor the instance must be refreshed\n if (cld.isAlwaysRefresh())\n {\n refreshInstance(obj, id, cld);\n }\n // now refresh all references\n checkRefreshRelationships(obj, id, cld);\n }\n\n // Invoke events on PersistenceBrokerAware instances and listeners\n AFTER_LOOKUP_EVENT.setTarget(obj);\n fireBrokerEvent(AFTER_LOOKUP_EVENT);\n AFTER_LOOKUP_EVENT.setTarget(null);\n\n //logger.info(\"RETRIEVING object \" + obj);\n return obj;\n }"
] | [
"public GVRAnimator animate(int animIndex, float timeInSec)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n anim.animate(timeInSec);\n return anim;\n }",
"public static BufferedImage resizeToWidth(BufferedImage originalImage, int widthOut) {\n \n int width = originalImage.getWidth();\n \n int height = originalImage.getHeight();\n \n int widthPercent = (widthOut * 100) / width;\n \n int newHeight = (height * widthPercent) / 100;\n \n BufferedImage resizedImage =\n new BufferedImage(widthOut, newHeight, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(originalImage, 0, 0, widthOut, newHeight, null);\n g.dispose();\n \n return resizedImage;\n }",
"public PhotoContext getContext(String photoId) 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\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 PhotoContext photoContext = new PhotoContext();\r\n Collection<Element> payload = response.getPayloadCollection();\r\n for (Element payloadElement : payload) {\r\n String tagName = payloadElement.getTagName();\r\n if (tagName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (tagName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setNextPhoto(photo);\r\n }\r\n }\r\n return photoContext;\r\n }",
"private Renderer recycle(View convertView, T content) {\n Renderer renderer = (Renderer) convertView.getTag();\n renderer.onRecycle(content);\n return renderer;\n }",
"public AsciiTable setPaddingLeftRight(int padding){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private List<MapRow> sort(List<MapRow> rows, final String attribute)\n {\n Collections.sort(rows, new Comparator<MapRow>()\n {\n @Override public int compare(MapRow o1, MapRow o2)\n {\n String value1 = o1.getString(attribute);\n String value2 = o2.getString(attribute);\n return value1.compareTo(value2);\n }\n });\n return rows;\n }",
"private static void registerImage(String imageId, String imageTag, String targetRepo,\n ArrayListMultimap<String, String> artifactsProps, int buildInfoId) throws IOException {\n DockerImage image = new DockerImage(imageId, imageTag, targetRepo, buildInfoId, artifactsProps);\n images.add(image);\n }",
"public void validate() throws PackagingException {\n if (control == null || !control.isDirectory()) {\n throw new PackagingException(\"The 'control' attribute doesn't point to a directory. \" + control);\n }\n\n if (changesIn != null) {\n\n if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) {\n throw new PackagingException(\"The 'changesIn' setting needs to point to a readable file. \" + changesIn + \" was not found/readable.\");\n }\n\n if (changesOut != null && !isWritableFile(changesOut)) {\n throw new PackagingException(\"Cannot write the output for 'changesOut' to \" + changesOut);\n }\n\n if (changesSave != null && !isWritableFile(changesSave)) {\n throw new PackagingException(\"Cannot write the output for 'changesSave' to \" + changesSave);\n }\n\n } else {\n if (changesOut != null || changesSave != null) {\n throw new PackagingException(\"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.\");\n }\n }\n\n if (Compression.toEnum(compression) == null) {\n throw new PackagingException(\"The compression method '\" + compression + \"' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')\");\n }\n\n if (deb == null) {\n throw new PackagingException(\"You need to specify where the deb file is supposed to be created.\");\n }\n\n getDigestCode(digest);\n }",
"public static String readDesignerVersion(ServletContext context) {\n String retStr = \"\";\n BufferedReader br = null;\n try {\n InputStream inputStream = context.getResourceAsStream(\"/META-INF/MANIFEST.MF\");\n br = new BufferedReader(new InputStreamReader(inputStream,\n \"UTF-8\"));\n String line;\n while ((line = br.readLine()) != null) {\n if (line.startsWith(BUNDLE_VERSION)) {\n retStr = line.substring(BUNDLE_VERSION.length() + 1);\n retStr = retStr.trim();\n }\n }\n inputStream.close();\n } catch (Exception e) {\n logger.error(e.getMessage(),\n e);\n } finally {\n if (br != null) {\n IOUtils.closeQuietly(br);\n }\n }\n return retStr;\n }"
] |
Populates a Map instance representing the IDs and names of
projects available in the current file.
@param is input stream used to read XER file
@return Map instance containing ID and name pairs
@throws MPXJException | [
"public Map<Integer, String> listProjects(InputStream is) throws MPXJException\n {\n try\n {\n m_tables = new HashMap<String, List<Row>>();\n processFile(is);\n\n Map<Integer, String> result = new HashMap<Integer, String>();\n\n List<Row> rows = getRows(\"project\", null, null);\n for (Row row : rows)\n {\n Integer id = row.getInteger(\"proj_id\");\n String name = row.getString(\"proj_short_name\");\n result.put(id, name);\n }\n\n return result;\n }\n\n finally\n {\n m_tables = null;\n m_currentTable = null;\n m_currentFieldNames = null;\n }\n }"
] | [
"public boolean contains(Vector3 p) {\n\t\tboolean ans = false;\n\t\tif(this.halfplane || p== null) return false;\n\n\t\tif (isCorner(p)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tPointLinePosition a12 = PointLineTest.pointLineTest(a,b,p);\n\t\tPointLinePosition a23 = PointLineTest.pointLineTest(b,c,p);\n\t\tPointLinePosition a31 = PointLineTest.pointLineTest(c,a,p);\n\n\t\tif ((a12 == PointLinePosition.LEFT && a23 == PointLinePosition.LEFT && a31 == PointLinePosition.LEFT ) ||\n\t\t\t\t(a12 == PointLinePosition.RIGHT && a23 == PointLinePosition.RIGHT && a31 == PointLinePosition.RIGHT ) ||\n\t\t\t\t(a12 == PointLinePosition.ON_SEGMENT ||a23 == PointLinePosition.ON_SEGMENT || a31 == PointLinePosition.ON_SEGMENT)) {\n\t\t\tans = true;\n\t\t}\n\n\t\treturn ans;\n\t}",
"public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = ((FieldDescriptorDef)_fields.get(objA)).getProperty(\"id\");\r\n String idBStr = ((FieldDescriptorDef)_fields.get(objB)).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try\r\n {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex)\r\n {\r\n return 1;\r\n }\r\n try\r\n {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex)\r\n {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }",
"public final void notifyContentItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart + headerItemCount, itemCount);\n }",
"public static int toIntWithDefault(String value, int defaultValue) {\n\n int result = defaultValue;\n try {\n result = Integer.parseInt(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n // Do nothing, return default.\n }\n return result;\n }",
"protected String format(String key, String defaultPattern, Object... args) {\n String escape = escape(defaultPattern);\n String s = lookupPattern(key, escape);\n Object[] objects = escapeAll(args);\n return MessageFormat.format(s, objects);\n }",
"private static List<CmsCategory> getCategories(CmsObject cms, CmsResource resource) {\n\n if ((null != resource) && (null != cms)) {\n try {\n return CmsCategoryService.getInstance().readResourceCategories(cms, resource);\n } catch (CmsException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return new ArrayList<CmsCategory>(0);\n }",
"public void fire(StepFinishedEvent event) {\n Step step = stepStorage.adopt();\n event.process(step);\n\n notifier.fire(event);\n }",
"public static AT_Row createRule(TableRowType type, TableRowStyle style){\r\n\t\tValidate.notNull(type);\r\n\t\tValidate.validState(type!=TableRowType.UNKNOWN);\r\n\t\tValidate.validState(type!=TableRowType.CONTENT);\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN);\r\n\r\n\t\treturn new AT_Row(){\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowType getType(){\r\n\t\t\t\treturn type;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowStyle getStyle(){\r\n\t\t\t\treturn style;\r\n\t\t\t}\r\n\t\t};\r\n\t}",
"public static base_response update(nitro_service client, responderparam resource) throws Exception {\n\t\tresponderparam updateresource = new responderparam();\n\t\tupdateresource.undefaction = resource.undefaction;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Build the tree of joins for the given criteria | [
"private void buildJoinTree(Criteria crit)\r\n {\r\n Enumeration e = crit.getElements();\r\n\r\n while (e.hasMoreElements())\r\n {\r\n Object o = e.nextElement();\r\n if (o instanceof Criteria)\r\n {\r\n buildJoinTree((Criteria) o);\r\n }\r\n else\r\n {\r\n SelectionCriteria c = (SelectionCriteria) o;\r\n \r\n // BRJ skip SqlCriteria\r\n if (c instanceof SqlCriteria)\r\n {\r\n continue;\r\n }\r\n \r\n // BRJ: Outer join for OR\r\n boolean useOuterJoin = (crit.getType() == Criteria.OR);\r\n\r\n // BRJ: do not build join tree for subQuery attribute \r\n if (c.getAttribute() != null && c.getAttribute() instanceof String)\r\n {\r\n\t\t\t\t\t//buildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getAlias(), c.getPathClasses());\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n if (c instanceof FieldCriteria)\r\n {\r\n FieldCriteria cc = (FieldCriteria) c;\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) cc.getValue(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n }\r\n }\r\n }"
] | [
"protected void removeWatermark(URLTemplate itemUrl) {\n URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID());\n URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"private String getOrdinal(Integer value)\n {\n String result;\n int index = value.intValue();\n if (index >= ORDINAL.length)\n {\n result = \"every \" + index + \"th\";\n }\n else\n {\n result = ORDINAL[index];\n }\n return result;\n }",
"public void show() {\n if (!(container instanceof RootPanel)) {\n if (!(container instanceof MaterialDialog)) {\n container.getElement().getStyle().setPosition(Style.Position.RELATIVE);\n }\n div.getElement().getStyle().setPosition(Style.Position.ABSOLUTE);\n }\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.HIDDEN);\n }\n if (type == LoaderType.CIRCULAR) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.LOADER_WRAPPER);\n div.add(preLoader);\n } else if (type == LoaderType.PROGRESS) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.PROGRESS_WRAPPER);\n progress.getElement().getStyle().setProperty(\"margin\", \"auto\");\n div.add(progress);\n }\n container.add(div);\n }",
"private void updateRemoveR() {\n for( int i = 1; i < n+1; i++ ) {\n for( int j = 0; j < n; j++ ) {\n double sum = 0;\n for( int k = i-1; k <= j; k++ ) {\n sum += U_tran.data[i*m+k] * R.data[k*n+j];\n }\n R.data[(i-1)*n+j] = sum;\n }\n }\n }",
"public long nextUniqueTransaction(long timeMs) {\n long id = timeMs;\n for (; ; ) {\n long old = transactionID.get();\n if (old >= id)\n id = old + 1;\n if (transactionID.compareAndSet(old, id))\n break;\n }\n return id;\n }",
"public void setNearClippingDistance(float near) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near);\n centerCamera.setNearClippingDistance(near);\n ((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near);\n }\n }",
"public void removeHoursFromDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = null;\n }",
"public void growMaxColumns( int desiredColumns , boolean preserveValue ) {\n if( col_idx.length < desiredColumns+1 ) {\n int[] c = new int[ desiredColumns+1 ];\n if( preserveValue )\n System.arraycopy(col_idx,0,c,0,col_idx.length);\n col_idx = c;\n }\n }",
"public static <T> Observable<T> map(Observable<?> fromObservable, final T toValue) {\n if (fromObservable != null) {\n return fromObservable.subscribeOn(Schedulers.io())\n .map(new RXMapper<T>(toValue));\n } else {\n return Observable.empty();\n }\n }"
] |
This method skips the end-of-line markers in the RTF document.
It also indicates if the end of the embedded object has been reached.
@param text RTF document test
@param offset offset into the RTF document
@return new offset | [
"private static int skipEndOfLine(String text, int offset)\n {\n char c;\n boolean finished = false;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case ' ': // found that OBJDATA could be followed by a space the EOL\n case '\\r':\n case '\\n':\n {\n ++offset;\n break;\n }\n\n case '}':\n {\n offset = -1;\n finished = true;\n break;\n }\n\n default:\n {\n finished = true;\n break;\n }\n }\n }\n\n return (offset);\n }"
] | [
"public static nspbr6_stats get(nitro_service service, String name) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tobj.set_name(name);\n\t\tnspbr6_stats response = (nspbr6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"protected void queryTimerEnd(String sql, long queryStartTime) {\r\n\t\tif ((this.queryExecuteTimeLimit != 0) \r\n\t\t\t\t&& (this.connectionHook != null)){\r\n\t\t\tlong timeElapsed = (System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t\tif (timeElapsed > this.queryExecuteTimeLimit){\r\n\t\t\t\tthis.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif (this.statisticsEnabled){\r\n\t\t\tthis.statistics.incrementStatementsExecuted();\r\n\t\t\tthis.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t}\r\n\r\n\t}",
"public void setNamespace(String prefix, String namespaceURI) {\n ensureNotNull(\"Prefix\", prefix);\n ensureNotNull(\"Namespace URI\", namespaceURI);\n\n namespaces.put(prefix, namespaceURI);\n }",
"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}",
"void rollback() {\n if (publishedFullRegistry == null) {\n return;\n }\n writeLock.lock();\n try {\n publishedFullRegistry.readLock.lock();\n try {\n clear(true);\n copy(publishedFullRegistry, this);\n modified = false;\n } finally {\n publishedFullRegistry.readLock.unlock();\n }\n } finally {\n writeLock.unlock();\n }\n }",
"public static GVRMesh createQuad(GVRContext gvrContext, float width, float height) {\n GVRMesh mesh = new GVRMesh(gvrContext);\n\n float[] vertices = { width * -0.5f, height * 0.5f, 0.0f, width * -0.5f,\n height * -0.5f, 0.0f, width * 0.5f, height * 0.5f, 0.0f,\n width * 0.5f, height * -0.5f, 0.0f };\n mesh.setVertices(vertices);\n\n final float[] normals = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f, 1.0f };\n mesh.setNormals(normals);\n\n final float[] texCoords = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,\n 1.0f };\n mesh.setTexCoords(texCoords);\n\n char[] triangles = { 0, 1, 2, 1, 3, 2 };\n mesh.setIndices(triangles);\n\n return mesh;\n }",
"private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException {\n\t\tif (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultSvgDocument document = new DefaultSvgDocument(writer, false);\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer()));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new SvgTileWriter());\n\t\t\treturn document;\n\t\t} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultVmlDocument document = new DefaultVmlDocument(writer);\n\t\t\tint coordWidth = tile.getScreenWidth();\n\t\t\tint coordHeight = tile.getScreenHeight();\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,\n\t\t\t\t\tcoordHeight));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight));\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\treturn document;\n\t\t} else {\n\t\t\tthrow new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);\n\t\t}\n\t}",
"public String getUuidFromResponse(ResponseOnSingeRequest myResponse) {\n\n String uuid = PcConstants.NA;\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(getJobIdRegex());\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n uuid = matcher.group(1);\n }\n\n return uuid;\n }",
"public static void validateExternalizersPresent(EmbeddedCacheManager externalCacheManager) {\n\t\tMap<Integer, AdvancedExternalizer<?>> externalizerMap = externalCacheManager\n\t\t\t\t.getCacheManagerConfiguration()\n\t\t\t\t.serialization()\n\t\t\t\t.advancedExternalizers();\n\t\tfor ( AdvancedExternalizer<?> ogmExternalizer : ogmExternalizers.values() ) {\n\t\t\tfinal Integer externalizerId = ogmExternalizer.getId();\n\t\t\tAdvancedExternalizer<?> registeredExternalizer = externalizerMap.get( externalizerId );\n\t\t\tif ( registeredExternalizer == null ) {\n\t\t\t\tthrow log.externalizersNotRegistered( externalizerId, ogmExternalizer.getClass() );\n\t\t\t}\n\t\t\telse if ( !registeredExternalizer.getClass().equals( ogmExternalizer ) ) {\n\t\t\t\tif ( registeredExternalizer.getClass().toString().equals( ogmExternalizer.getClass().toString() ) ) {\n\t\t\t\t\t// same class name, yet different Class definition!\n\t\t\t\t\tthrow log.registeredExternalizerNotLoadedFromOGMClassloader( registeredExternalizer.getClass() );\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow log.externalizerIdNotMatchingType( externalizerId, registeredExternalizer, ogmExternalizer );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] |
Get information about this database.
@return DbInfo encapsulating the database info
@see <a
href="https://console.bluemix.net/docs/services/Cloudant/api/database.html#getting-database-details"
target="_blank">Databases - read</a> | [
"public DbInfo info() {\n return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).getDatabaseUri(),\n DbInfo.class);\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 final Integer getInteger(Number value)\n {\n Integer result = null;\n if (value != null)\n {\n if (value instanceof Integer)\n {\n result = (Integer) value;\n }\n else\n {\n result = Integer.valueOf((int) Math.round(value.doubleValue()));\n }\n }\n return (result);\n }",
"private void setTaskNotes(Task task, byte[] data, ExtendedData taskExtData, FixDeferFix taskVarData)\n {\n String notes = taskExtData.getString(TASK_NOTES);\n if (notes == null && data.length == 366)\n {\n byte[] offsetData = taskVarData.getByteArray(getOffset(data, 362));\n if (offsetData != null && offsetData.length >= 12)\n {\n notes = taskVarData.getString(getOffset(offsetData, 8));\n \n // We do pick up some random stuff with this approach, and \n // we don't know enough about the file format to know when to ignore it\n // so we'll use a heuristic here to ignore anything that\n // doesn't look like RTF.\n if (notes != null && notes.indexOf('{') == -1)\n {\n notes = null;\n }\n }\n }\n \n if (notes != null)\n {\n if (m_reader.getPreserveNoteFormatting() == false)\n {\n notes = RtfHelper.strip(notes);\n }\n\n task.setNotes(notes);\n }\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 }",
"public void refreshCredentials() {\n if (this.credsProvider == null)\n return;\n\n try {\n AlibabaCloudCredentials creds = this.credsProvider.getCredentials();\n this.accessKeyID = creds.getAccessKeyId();\n this.accessKeySecret = creds.getAccessKeySecret();\n\n if (creds instanceof BasicSessionCredentials) {\n this.securityToken = ((BasicSessionCredentials) creds).getSessionToken();\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"public static base_response delete(nitro_service client, String ipv6prefix) throws Exception {\n\t\tonlinkipv6prefix deleteresource = new onlinkipv6prefix();\n\t\tdeleteresource.ipv6prefix = ipv6prefix;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"protected Violation createViolation(SourceCode sourceCode, ASTNode node, String message) {\n String sourceLine = sourceCode.line(node.getLineNumber()-1);\n return createViolation(node.getLineNumber(), sourceLine, message);\n }",
"public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\n }",
"@Programmatic\n public <T> List<T> fromExcel(\n final Blob excelBlob,\n final Class<T> cls,\n final String sheetName) throws ExcelService.Exception {\n return fromExcel(excelBlob, new WorksheetSpec(cls, sheetName));\n }"
] |
Fetch the specified expression from the cache or create it if necessary.
@param expressionString the expression string
@return the expression
@throws ParseException oops | [
"private Expression getExpression(String expressionString) throws ParseException {\n\t\tif (!expressionCache.containsKey(expressionString)) {\n\t\t\tExpression expression;\n\t\t\texpression = parser.parseExpression(expressionString);\n\t\t\texpressionCache.put(expressionString, expression);\n\t\t}\n\t\treturn expressionCache.get(expressionString);\n\n\t}"
] | [
"public static IndexedContainer getPrincipalContainer(\n CmsObject cms,\n List<? extends I_CmsPrincipal> list,\n String captionID,\n String descID,\n String iconID,\n String ouID,\n String icon,\n List<FontIcon> iconList) {\n\n IndexedContainer res = new IndexedContainer();\n\n res.addContainerProperty(captionID, String.class, \"\");\n res.addContainerProperty(ouID, String.class, \"\");\n res.addContainerProperty(iconID, FontIcon.class, new CmsCssIcon(icon));\n if (descID != null) {\n res.addContainerProperty(descID, String.class, \"\");\n }\n\n for (I_CmsPrincipal group : list) {\n\n Item item = res.addItem(group);\n item.getItemProperty(captionID).setValue(group.getSimpleName());\n item.getItemProperty(ouID).setValue(group.getOuFqn());\n if (descID != null) {\n item.getItemProperty(descID).setValue(group.getDescription(A_CmsUI.get().getLocale()));\n }\n }\n\n for (int i = 0; i < iconList.size(); i++) {\n res.getItem(res.getIdByIndex(i)).getItemProperty(iconID).setValue(iconList.get(i));\n }\n\n return res;\n }",
"protected int compare(MethodDesc o1, MethodDesc o2) {\n\t\tfinal Class<?>[] paramTypes1 = o1.getParameterTypes();\n\t\tfinal Class<?>[] paramTypes2 = o2.getParameterTypes();\n\n\t\t// sort by parameter types from left to right\n\t\tfor (int i = 0; i < paramTypes1.length; i++) {\n\t\t\tfinal Class<?> class1 = paramTypes1[i];\n\t\t\tfinal Class<?> class2 = paramTypes2[i];\n\n\t\t\tif (class1.equals(class2))\n\t\t\t\tcontinue;\n\t\t\tif (class1.isAssignableFrom(class2) || Void.class.equals(class2))\n\t\t\t\treturn -1;\n\t\t\tif (class2.isAssignableFrom(class1) || Void.class.equals(class1))\n\t\t\t\treturn 1;\n\t\t}\n\n\t\t// sort by declaring class (more specific comes first).\n\t\tif (!o1.getDeclaringClass().equals(o2.getDeclaringClass())) {\n\t\t\tif (o1.getDeclaringClass().isAssignableFrom(o2.getDeclaringClass()))\n\t\t\t\treturn 1;\n\t\t\tif (o2.getDeclaringClass().isAssignableFrom(o1.getDeclaringClass()))\n\t\t\t\treturn -1;\n\t\t}\n\n\t\t// sort by target\n\t\tfinal int compareTo = ((Integer) targets.indexOf(o2.target)).compareTo(targets.indexOf(o1.target));\n\t\treturn compareTo;\n\t}",
"public void assignField(ConnectionSource connectionSource, Object data, Object val, boolean parentObject,\n\t\t\tObjectCache objectCache) throws SQLException {\n\n\t\tif (logger.isLevelEnabled(Level.TRACE)) {\n\t\t\tlogger.trace(\"assiging from data {}, val {}: {}\", (data == null ? \"null\" : data.getClass()),\n\t\t\t\t\t(val == null ? \"null\" : val.getClass()), val);\n\t\t}\n\t\t// if this is a foreign object then val is the foreign object's id val\n\t\tif (foreignRefField != null && val != null) {\n\t\t\t// get the current field value which is the foreign-id\n\t\t\tObject foreignRef = extractJavaFieldValue(data);\n\t\t\t/*\n\t\t\t * See if we don't need to create a new foreign object. If we are refreshing and the id field has not\n\t\t\t * changed then there is no need to create a new foreign object and maybe lose previously refreshed field\n\t\t\t * information.\n\t\t\t */\n\t\t\tif (foreignRef != null && foreignRef.equals(val)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// awhitlock: raised as OrmLite issue: bug #122\n\t\t\tObject cachedVal;\n\t\t\tObjectCache foreignCache = foreignDao.getObjectCache();\n\t\t\tif (foreignCache == null) {\n\t\t\t\tcachedVal = null;\n\t\t\t} else {\n\t\t\t\tcachedVal = foreignCache.get(getType(), val);\n\t\t\t}\n\t\t\tif (cachedVal != null) {\n\t\t\t\tval = cachedVal;\n\t\t\t} else if (!parentObject) {\n\t\t\t\t// the value we are to assign to our field is now the foreign object itself\n\t\t\t\tval = createForeignObject(connectionSource, val, objectCache);\n\t\t\t}\n\t\t}\n\n\t\tif (fieldSetMethod == null) {\n\t\t\ttry {\n\t\t\t\tfield.set(data, val);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tif (val == null) {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\"Could not assign object '\" + val + \"' to field \" + this, e);\n\t\t\t\t} else {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \" to field \" + this, e);\n\t\t\t\t}\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \"' to field \" + this, e);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tfieldSetMethod.invoke(data, val);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow SqlExceptionUtil\n\t\t\t\t\t\t.create(\"Could not call \" + fieldSetMethod + \" on object with '\" + val + \"' for \" + this, e);\n\t\t\t}\n\t\t}\n\t}",
"private boolean hasBidirectionalAssociation(Class clazz)\r\n {\r\n ClassDescriptor cdesc;\r\n Collection refs;\r\n boolean hasBidirAssc;\r\n\r\n if (_withoutBidirAssc.contains(clazz))\r\n {\r\n return false;\r\n }\r\n\r\n if (_withBidirAssc.contains(clazz))\r\n {\r\n return true;\r\n }\r\n\r\n // first time we meet this class, let's look at metadata\r\n cdesc = _pb.getClassDescriptor(clazz);\r\n refs = cdesc.getObjectReferenceDescriptors();\r\n hasBidirAssc = false;\r\n REFS_CYCLE:\r\n for (Iterator it = refs.iterator(); it.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor ord;\r\n ClassDescriptor relCDesc;\r\n Collection relRefs;\r\n\r\n ord = (ObjectReferenceDescriptor) it.next();\r\n relCDesc = _pb.getClassDescriptor(ord.getItemClass());\r\n relRefs = relCDesc.getObjectReferenceDescriptors();\r\n for (Iterator relIt = relRefs.iterator(); relIt.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor relOrd;\r\n\r\n relOrd = (ObjectReferenceDescriptor) relIt.next();\r\n if (relOrd.getItemClass().equals(clazz))\r\n {\r\n hasBidirAssc = true;\r\n break REFS_CYCLE;\r\n }\r\n }\r\n }\r\n if (hasBidirAssc)\r\n {\r\n _withBidirAssc.add(clazz);\r\n }\r\n else\r\n {\r\n _withoutBidirAssc.add(clazz);\r\n }\r\n\r\n return hasBidirAssc;\r\n }",
"public static scpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tscpolicy_stats obj = new scpolicy_stats();\n\t\tobj.set_name(name);\n\t\tscpolicy_stats response = (scpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static PredicateExpression all(Object... rhs) {\n PredicateExpression ex = new PredicateExpression( \"$all\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }",
"public void cache(Identity oid, Object obj)\r\n {\r\n if (oid != null && obj != null)\r\n {\r\n ObjectCache cache = getCache(oid, obj, METHOD_CACHE);\r\n if (cache != null)\r\n {\r\n cache.cache(oid, obj);\r\n }\r\n }\r\n }",
"private ColorItem buildColorItem(int colorId, String label) {\n Color color;\n String colorName;\n switch (colorId) {\n case 0:\n color = new Color(0, 0, 0, 0);\n colorName = \"No Color\";\n break;\n case 1:\n color = Color.PINK;\n colorName = \"Pink\";\n break;\n case 2:\n color = Color.RED;\n colorName = \"Red\";\n break;\n case 3:\n color = Color.ORANGE;\n colorName = \"Orange\";\n break;\n case 4:\n color = Color.YELLOW;\n colorName = \"Yellow\";\n break;\n case 5:\n color = Color.GREEN;\n colorName = \"Green\";\n break;\n case 6:\n color = Color.CYAN;\n colorName = \"Aqua\";\n break;\n case 7:\n color = Color.BLUE;\n colorName = \"Blue\";\n break;\n case 8:\n color = new Color(128, 0, 128);\n colorName = \"Purple\";\n break;\n default:\n color = new Color(0, 0, 0, 0);\n colorName = \"Unknown Color\";\n }\n return new ColorItem(colorId, label, color, colorName);\n }",
"public void update(int width, int height, float[] data)\n throws IllegalArgumentException\n {\n if ((width <= 0) || (height <= 0) ||\n (data == null) || (data.length < height * width * mFloatsPerPixel))\n {\n throw new IllegalArgumentException();\n }\n NativeFloatImage.update(getNative(), width, height, 0, data);\n }"
] |
Multiply two complex numbers.
@param z1 Complex Number.
@param z2 Complex Number.
@return Returns new ComplexNumber instance containing the multiply of specified complex numbers. | [
"public static ComplexNumber Multiply(ComplexNumber z1, ComplexNumber z2) {\r\n double z1R = z1.real, z1I = z1.imaginary;\r\n double z2R = z2.real, z2I = z2.imaginary;\r\n\r\n return new ComplexNumber(z1R * z2R - z1I * z2I, z1R * z2I + z1I * z2R);\r\n }"
] | [
"public void release(Contextual<T> contextual, T instance) {\n synchronized (dependentInstances) {\n for (ContextualInstance<?> dependentInstance : dependentInstances) {\n // do not destroy contextual again, since it's just being destroyed\n if (contextual == null || !(dependentInstance.getContextual().equals(contextual))) {\n destroy(dependentInstance);\n }\n }\n }\n if (resourceReferences != null) {\n for (ResourceReference<?> reference : resourceReferences) {\n reference.release();\n }\n }\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 }",
"public static appflowpolicy_appflowglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_appflowglobal_binding obj = new appflowpolicy_appflowglobal_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_appflowglobal_binding response[] = (appflowpolicy_appflowglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"protected void logIncompatibleValueError(PropertyIdValue propertyIdValue,\n\t\t\tString datatype, String valueType) {\n\t\tlogger.warn(\"Property \" + propertyIdValue.getId() + \" has type \\\"\"\n\t\t\t\t+ datatype + \"\\\" but a value of type \" + valueType\n\t\t\t\t+ \". Data ignored.\");\n\t}",
"private Map<String, Integer> runSampling(\n final ProctorContext proctorContext,\n final Set<String> targetTestNames,\n final TestType testType,\n final int determinationsToRun\n ) {\n final Set<String> targetTestGroups = getTargetTestGroups(targetTestNames);\n final Map<String, Integer> testGroupToOccurrences = Maps.newTreeMap();\n for (final String testGroup : targetTestGroups) {\n testGroupToOccurrences.put(testGroup, 0);\n }\n\n for (int i = 0; i < determinationsToRun; ++i) {\n final Identifiers identifiers = TestType.RANDOM.equals(testType)\n ? new Identifiers(Collections.<TestType, String>emptyMap(), /* randomEnabled */ true)\n : Identifiers.of(testType, Long.toString(random.nextLong()));\n final AbstractGroups groups = supplier.getRandomGroups(proctorContext, identifiers);\n for (final Entry<String, TestBucket> e : groups.getProctorResult().getBuckets().entrySet()) {\n final String testName = e.getKey();\n if (targetTestNames.contains(testName)) {\n final int group = e.getValue().getValue();\n final String testGroup = testName + group;\n testGroupToOccurrences.put(testGroup, testGroupToOccurrences.get(testGroup) + 1);\n }\n }\n }\n\n return testGroupToOccurrences;\n }",
"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 Bundler put(String key, String value) {\n delegate.putString(key, value);\n return this;\n }",
"private String toPath(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(CmsWorkplace.getSkinUri(), ICON_FOLDER, \"\" + name.hashCode()) + size.getSuffix();\n }",
"public static <E> Set<E> setify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (Set<E>) collectify(mapper, source, Set.class, targetElementType);\n }"
] |
Convert a Java LinkedList to a Scala Iterable.
@param linkedList Java LinkedList to convert
@return Scala Iterable | [
"public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) {\n return JavaConverters.asScalaIterableConverter(linkedList).asScala();\n }"
] | [
"public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }",
"@Nonnull\n protected Payload getPayload(final String testName) {\n // Get the current bucket.\n final TestBucket testBucket = buckets.get(testName);\n\n // Lookup Payloads for this test\n if (testBucket != null) {\n final Payload payload = testBucket.getPayload();\n if (null != payload) {\n return payload;\n }\n }\n\n return Payload.EMPTY_PAYLOAD;\n }",
"public static ModelNode getParentAddress(final ModelNode address) {\n if (address.getType() != ModelType.LIST) {\n throw new IllegalArgumentException(\"The address type must be a list.\");\n }\n final ModelNode result = new ModelNode();\n final List<Property> addressParts = address.asPropertyList();\n if (addressParts.isEmpty()) {\n throw new IllegalArgumentException(\"The address is empty.\");\n }\n for (int i = 0; i < addressParts.size() - 1; ++i) {\n final Property property = addressParts.get(i);\n result.add(property.getName(), property.getValue());\n }\n return result;\n }",
"@NonNull\n @Override\n public Loader<SortedList<FtpFile>> getLoader() {\n return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {\n @Override\n public SortedList<FtpFile> loadInBackground() {\n SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class, new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {\n @Override\n public int compare(FtpFile lhs, FtpFile rhs) {\n if (lhs.isDirectory() && !rhs.isDirectory()) {\n return -1;\n } else if (rhs.isDirectory() && !lhs.isDirectory()) {\n return 1;\n } else {\n return lhs.getName().compareToIgnoreCase(rhs.getName());\n }\n }\n\n @Override\n public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {\n return oldItem.getName().equals(newItem.getName());\n }\n\n @Override\n public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {\n return item1.getName().equals(item2.getName());\n }\n });\n\n\n if (!ftp.isConnected()) {\n // Connect\n try {\n ftp.connect(server, port);\n\n ftp.setFileType(FTP.ASCII_FILE_TYPE);\n ftp.enterLocalPassiveMode();\n ftp.setUseEPSVwithIPv4(false);\n\n if (!(loggedIn = ftp.login(username, password))) {\n ftp.logout();\n Log.e(TAG, \"Login failed\");\n }\n } catch (IOException e) {\n if (ftp.isConnected()) {\n try {\n ftp.disconnect();\n } catch (IOException ignored) {\n }\n }\n Log.e(TAG, \"Could not connect to server.\");\n }\n }\n\n if (loggedIn) {\n try {\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n sortedList.beginBatchedUpdates();\n for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {\n FtpFile file;\n if (f.isDirectory()) {\n file = new FtpDir(mCurrentPath, f.getName());\n } else {\n file = new FtpFile(mCurrentPath, f.getName());\n }\n if (isItemVisible(file)) {\n sortedList.add(file);\n }\n }\n sortedList.endBatchedUpdates();\n } catch (IOException e) {\n Log.e(TAG, \"IOException: \" + e.getMessage());\n }\n }\n\n return sortedList;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n forceLoad();\n }\n };\n }",
"public static final Boolean parseBoolean(String value)\n {\n return (value == null || value.charAt(0) != '1' ? Boolean.FALSE : Boolean.TRUE);\n }",
"static boolean isOnClasspath(String className) {\n boolean isOnClassPath = true;\n try {\n Class.forName(className);\n } catch (ClassNotFoundException exception) {\n isOnClassPath = false;\n }\n return isOnClassPath;\n }",
"private double convertMaturity(int maturityInMonths) {\r\n\t\tSchedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, 12);\r\n\t\treturn schedule.getFixing(0);\r\n\t}",
"@Override\n\tpublic void close() {\n\t\tlogger.info(\"Finished processing.\");\n\t\tthis.timer.stop();\n\t\tthis.lastSeconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\tprintStatus();\n\t}",
"public static base_responses add(nitro_service client, dnsview resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsview addresources[] = new dnsview[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnsview();\n\t\t\t\taddresources[i].viewname = resources[i].viewname;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Extracts the rank of a matrix using a preexisting decomposition.
@see #singularThreshold(SingularValueDecomposition_F64)
@param svd A precomputed decomposition. Not modified.
@param threshold Tolerance used to determine of a singular value is singular.
@return The rank of the decomposed matrix. | [
"public static int rank(SingularValueDecomposition_F64 svd , double threshold ) {\n int numRank=0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] > threshold)\n numRank++;\n }\n\n return numRank;\n }"
] | [
"private static DumpContentType guessDumpContentType(String fileName) {\n\t\tString lcDumpName = fileName.toLowerCase();\n\t\tif (lcDumpName.contains(\".json.gz\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".json.bz2\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".sql.gz\")) {\n\t\t\treturn DumpContentType.SITES;\n\t\t} else if (lcDumpName.contains(\".xml.bz2\")) {\n\t\t\tif (lcDumpName.contains(\"daily\")) {\n\t\t\t\treturn DumpContentType.DAILY;\n\t\t\t} else if (lcDumpName.contains(\"current\")) {\n\t\t\t\treturn DumpContentType.CURRENT;\n\t\t\t} else {\n\t\t\t\treturn DumpContentType.FULL;\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.warn(\"Could not guess type of the dump file \\\"\" + fileName\n\t\t\t\t\t+ \"\\\". Defaulting to json.gz.\");\n\t\t\treturn DumpContentType.JSON;\n\t\t}\n\t}",
"private void handleIncomingRequestMessage(SerialMessage incomingMessage) {\n\t\tlogger.debug(\"Message type = REQUEST\");\n\t\tswitch (incomingMessage.getMessageClass()) {\n\t\t\tcase ApplicationCommandHandler:\n\t\t\t\thandleApplicationCommandRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase SendData:\n\t\t\t\thandleSendDataRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase ApplicationUpdate:\n\t\t\t\thandleApplicationUpdateRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\tdefault:\n\t\t\tlogger.warn(String.format(\"TODO: Implement processing of Request Message = %s (0x%02X)\",\n\t\t\t\t\tincomingMessage.getMessageClass().getLabel(),\n\t\t\t\t\tincomingMessage.getMessageClass().getKey()));\n\t\t\tbreak;\t\n\t\t}\n\t}",
"protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\texp.setText(\"$V{\" + var.getName() + \"}\");\n\t\texp.setValueClass(var.getValueClass());\n\t\treturn exp;\n\t}",
"public static FreeMarkerOperation create(Furnace furnace, String templatePath, String outputFilename,\n String... varNames)\n {\n return new FreeMarkerOperation(furnace, templatePath, outputFilename, varNames);\n }",
"public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {\n MultipartContent.Part part = new MultipartContent.Part()\n .setContent(new InputStreamContent(fileType, fileContent))\n .setHeaders(new HttpHeaders().set(\n \"Content-Disposition\",\n String.format(\"form-data; name=\\\"file\\\"; filename=\\\"%s\\\"\", fileName) // TODO: escape fileName?\n ));\n MultipartContent content = new MultipartContent()\n .setMediaType(new HttpMediaType(\"multipart/form-data\").setParameter(\"boundary\", UUID.randomUUID().toString()))\n .addPart(part);\n\n String path = String.format(\"/tasks/%s/attachments\", task);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"POST\")\n .data(content);\n }",
"private void _handleMultiValues(ArrayList<String> values, String key, String command) {\n if (key == null) return;\n\n if (values == null || values.isEmpty()) {\n _generateEmptyMultiValueError(key);\n return;\n }\n\n ValidationResult vr;\n\n // validate the key\n vr = validator.cleanMultiValuePropertyKey(key);\n\n // Check for an error\n if (vr.getErrorCode() != 0) {\n pushValidationResult(vr);\n }\n\n // reset the key\n Object _key = vr.getObject();\n String cleanKey = (_key != null) ? vr.getObject().toString() : null;\n\n // if key is empty generate an error and return\n if (cleanKey == null || cleanKey.isEmpty()) {\n _generateInvalidMultiValueKeyError(key);\n return;\n }\n\n key = cleanKey;\n\n try {\n JSONArray currentValues = _constructExistingMultiValue(key, command);\n JSONArray newValues = _cleanMultiValues(values, key);\n _validateAndPushMultiValue(currentValues, newValues, values, key, command);\n\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Error handling multi value operation for key \" + key, t);\n }\n }",
"@Override\n public Future<RawGcsCreationToken> continueObjectCreationAsync(final RawGcsCreationToken token,\n final ByteBuffer chunk, long timeoutMillis) {\n try {\n ensureInitialized();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n final Environment environment = ApiProxy.getCurrentEnvironment();\n return writePool.schedule(new Callable<RawGcsCreationToken>() {\n @Override\n public RawGcsCreationToken call() throws Exception {\n ApiProxy.setEnvironmentForCurrentThread(environment);\n return append(token, chunk);\n }\n }, 50, TimeUnit.MILLISECONDS);\n }",
"public static boolean isClassClassNodeWrappingConcreteType(ClassNode classNode) {\n GenericsType[] genericsTypes = classNode.getGenericsTypes();\n return ClassHelper.CLASS_Type.equals(classNode)\n && classNode.isUsingGenerics()\n && genericsTypes!=null\n && !genericsTypes[0].isPlaceholder()\n && !genericsTypes[0].isWildcard();\n }",
"public void joinRequest(String groupId, String message, boolean acceptRules) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_JOIN_REQUEST);\r\n parameters.put(\"group_id\", groupId);\r\n parameters.put(\"message\", message);\r\n parameters.put(\"accept_rules\", acceptRules);\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 }"
] |
Check whether the patch can be applied to a given target.
@param condition the conditions
@param target the target
@throws PatchingException | [
"static void checkUpgradeConditions(final UpgradeCondition condition, final InstallationManager.MutablePatchingTarget target) throws PatchingException {\n // See if the prerequisites are met\n for (final String required : condition.getRequires()) {\n if (!target.isApplied(required)) {\n throw PatchLogger.ROOT_LOGGER.requiresPatch(required);\n }\n }\n // Check for incompatibilities\n for (final String incompatible : condition.getIncompatibleWith()) {\n if (target.isApplied(incompatible)) {\n throw PatchLogger.ROOT_LOGGER.incompatiblePatch(incompatible);\n }\n }\n }"
] | [
"public static int toIntWithDefault(String value, int defaultValue) {\n\n int result = defaultValue;\n try {\n result = Integer.parseInt(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n // Do nothing, return default.\n }\n return result;\n }",
"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 }",
"private void setHint() {\n if (mPhoneEdit != null && mSelectedCountry != null && mSelectedCountry.getIso() != null) {\n Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.getExampleNumberForType(mSelectedCountry.getIso(), PhoneNumberUtil.PhoneNumberType.MOBILE);\n if (phoneNumber != null) {\n mPhoneEdit.setHint(mPhoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL));\n }\n }\n }",
"public static void endRequest() {\n final List<RequestScopedItem> result = CACHE.get();\n if (result != null) {\n CACHE.remove();\n for (final RequestScopedItem item : result) {\n item.invalidate();\n }\n }\n }",
"public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) {\n final IndentNode indent = new IndentNode(indentString);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(indent);\n return indent;\n }",
"@SuppressWarnings(\"unused\")\n public String getDevicePushToken(final PushType type) {\n switch (type) {\n case GCM:\n return getCachedGCMToken();\n case FCM:\n return getCachedFCMToken();\n default:\n return null;\n }\n }",
"private static Iterator<String> splitIntoDocs(Reader r) {\r\n if (TREAT_FILE_AS_ONE_DOCUMENT) {\r\n return Collections.singleton(IOUtils.slurpReader(r)).iterator();\r\n } else {\r\n Collection<String> docs = new ArrayList<String>();\r\n ObjectBank<String> ob = ObjectBank.getLineIterator(r);\r\n StringBuilder current = new StringBuilder();\r\n for (String line : ob) {\r\n if (docPattern.matcher(line).lookingAt()) {\r\n // Start new doc, store old one if non-empty\r\n if (current.length() > 0) {\r\n docs.add(current.toString());\r\n current = new StringBuilder();\r\n }\r\n }\r\n current.append(line);\r\n current.append('\\n');\r\n }\r\n if (current.length() > 0) {\r\n docs.add(current.toString());\r\n }\r\n return docs.iterator();\r\n }\r\n }",
"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 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 }"
] |
Adds OPT_N | OPT_NODE option to OptionParser, with one argument.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"public static void acceptsNodeSingle(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), \"node id\")\n .withRequiredArg()\n .describedAs(\"node-id\")\n .ofType(Integer.class);\n }"
] | [
"public static String expandLine(CharSequence self, int tabStop) {\n String s = self.toString();\n int index;\n while ((index = s.indexOf('\\t')) != -1) {\n StringBuilder builder = new StringBuilder(s);\n int count = tabStop - index % tabStop;\n builder.deleteCharAt(index);\n for (int i = 0; i < count; i++) builder.insert(index, \" \");\n s = builder.toString();\n }\n return s;\n }",
"protected void processLink(Row row)\n {\n Task predecessorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_PRED_UID\"));\n Task successorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_SUCC_UID\"));\n if (predecessorTask != null && successorTask != null)\n {\n RelationType type = RelationType.getInstance(row.getInt(\"LINK_TYPE\"));\n TimeUnit durationUnits = MPDUtility.getDurationTimeUnits(row.getInt(\"LINK_LAG_FMT\"));\n Duration duration = MPDUtility.getDuration(row.getDouble(\"LINK_LAG\").doubleValue(), durationUnits);\n Relation relation = successorTask.addPredecessor(predecessorTask, type, duration);\n relation.setUniqueID(row.getInteger(\"LINK_UID\"));\n m_eventManager.fireRelationReadEvent(relation);\n }\n }",
"public ApnsServiceBuilder withDelegate(ApnsDelegate delegate) {\n this.delegate = delegate == null ? ApnsDelegate.EMPTY : delegate;\n return this;\n }",
"@SuppressWarnings(\"unchecked\") public final List<MapRow> getRows(String name)\n {\n return (List<MapRow>) getObject(name);\n }",
"@Override\n public void close() {\n // unregister MBeans\n if(stats != null) {\n try {\n if(this.jmxEnabled)\n JmxUtils.unregisterMbean(getAggregateMetricName());\n } catch(Exception e) {}\n stats.close();\n }\n factory.close();\n queuedPool.close();\n }",
"public static XMLGregorianCalendar convertDate(Date date) {\n if (date == null) {\n return null;\n }\n\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTimeInMillis(date.getTime());\n\n try {\n return getDatatypeFactory().newXMLGregorianCalendar(gc);\r\n } catch (DatatypeConfigurationException ex) {\n return null;\n }\n }",
"public static Map<FieldType, String> getDefaultWbsFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(TaskField.UNIQUE_ID, \"wbs_id\");\n map.put(TaskField.GUID, \"guid\");\n map.put(TaskField.NAME, \"wbs_name\");\n map.put(TaskField.BASELINE_COST, \"orig_cost\");\n map.put(TaskField.REMAINING_COST, \"indep_remain_total_cost\");\n map.put(TaskField.REMAINING_WORK, \"indep_remain_work_qty\");\n map.put(TaskField.DEADLINE, \"anticip_end_date\");\n map.put(TaskField.DATE1, \"suspend_date\");\n map.put(TaskField.DATE2, \"resume_date\");\n map.put(TaskField.TEXT1, \"task_code\");\n map.put(TaskField.WBS, \"wbs_short_name\");\n\n return map;\n }",
"private void init(AttributeSet attrs) {\n inflate(getContext(), R.layout.intl_phone_input, this);\n\n /**+\n * Country spinner\n */\n mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country);\n mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext());\n mCountrySpinner.setAdapter(mCountrySpinnerAdapter);\n\n mCountries = CountriesFetcher.getCountries(getContext());\n mCountrySpinnerAdapter.addAll(mCountries);\n mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener);\n\n setFlagDefaults(attrs);\n\n /**\n * Phone text field\n */\n mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone);\n mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher);\n\n setDefault();\n setEditTextDefaults(attrs);\n }",
"public static ForwardCurveInterpolation createForwardCurveFromMonteCarloLiborModel(String name, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\n\t\tint timeIndex\t= model.getTimeIndex(startTime);\n\t\t// Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves\n\t\tArrayList<RandomVariable> liborsAtTimeIndex = new ArrayList<>();\n\t\tint firstLiborIndex = model.getLiborPeriodDiscretization().getTimeIndexNearestGreaterOrEqual(startTime);\n\t\tdouble firstLiborTime = model.getLiborPeriodDiscretization().getTime(firstLiborIndex);\n\t\tif(firstLiborTime>startTime) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(startTime, startTime, firstLiborTime));\n\t\t}\n\t\t// Vector of times for the forward curve\n\t\tdouble[] times = new double[firstLiborTime==startTime ? (model.getNumberOfLibors()-firstLiborIndex) : (model.getNumberOfLibors()-firstLiborIndex+1)];\n\t\ttimes[0]=0;\n\t\tint indexOffset = firstLiborTime==startTime ? 0 : 1;\n\t\tfor(int i=firstLiborIndex;i<model.getNumberOfLibors();i++) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(timeIndex,i));\n\t\t\ttimes[i-firstLiborIndex+indexOffset]=model.getLiborPeriodDiscretization().getTime(i)-startTime;\n\t\t}\n\n\t\tRandomVariable[] libors = liborsAtTimeIndex.toArray(new RandomVariable[liborsAtTimeIndex.size()]);\n\t\treturn ForwardCurveInterpolation.createForwardCurveFromForwards(name, times, libors, model.getLiborPeriodDiscretization().getTimeStep(firstLiborIndex));\n\n\t}"
] |
Produces a string identifying this half-edge by the point index values of
its tail and head vertices.
@return identifying string | [
"public String getVertexString() {\n if (tail() != null) {\n return \"\" + tail().index + \"-\" + head().index;\n } else {\n return \"?-\" + head().index;\n }\n }"
] | [
"public void populateContainer(Class<? extends FieldType> type, FieldContainer container, Integer id, byte[][] fixedData, Var2Data varData)\n {\n //System.out.println(container.getClass().getSimpleName()+\": \" + id);\n for (FieldItem item : m_map.values())\n {\n if (item.getType().getClass().equals(type))\n {\n //System.out.println(item.m_type);\n Object value = item.read(id, fixedData, varData);\n //System.out.println(item.m_type.getClass().getSimpleName() + \".\" + item.m_type + \": \" + value);\n container.set(item.getType(), value);\n }\n }\n }",
"protected ValueContainer[] getAllValues(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return m_broker.serviceBrokerHelper().getAllRwValues(cld, obj);\r\n }",
"public static void archiveFile(@NotNull final ArchiveOutputStream out,\n @NotNull final VirtualFileDescriptor source,\n final long fileSize) throws IOException {\n if (!source.hasContent()) {\n throw new IllegalArgumentException(\"Provided source is not a file: \" + source.getPath());\n }\n //noinspection ChainOfInstanceofChecks\n if (out instanceof TarArchiveOutputStream) {\n final TarArchiveEntry entry = new TarArchiveEntry(source.getPath() + source.getName());\n entry.setSize(fileSize);\n entry.setModTime(source.getTimeStamp());\n out.putArchiveEntry(entry);\n } else if (out instanceof ZipArchiveOutputStream) {\n final ZipArchiveEntry entry = new ZipArchiveEntry(source.getPath() + source.getName());\n entry.setSize(fileSize);\n entry.setTime(source.getTimeStamp());\n out.putArchiveEntry(entry);\n } else {\n throw new IOException(\"Unknown archive output stream\");\n }\n final InputStream input = source.getInputStream();\n try {\n IOUtil.copyStreams(input, fileSize, out, IOUtil.BUFFER_ALLOCATOR);\n } finally {\n if (source.shouldCloseStream()) {\n input.close();\n }\n }\n out.closeArchiveEntry();\n }",
"public boolean isIPv4Mapped() {\n\t\t//::ffff:x:x/96 indicates IPv6 address mapped to IPv4\n\t\tif(getSegment(5).matches(IPv6Address.MAX_VALUE_PER_SEGMENT)) {\n\t\t\tfor(int i = 0; i < 5; i++) {\n\t\t\t\tif(!getSegment(i).isZero()) {\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}",
"@SuppressWarnings(\"unchecked\")\n public void setVars(final Map<String, ? extends Object> vars) {\n this.vars = (Map<String, Object>)vars;\n }",
"public static base_responses delete(nitro_service client, String serverip[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (serverip != null && serverip.length > 0) {\n\t\t\tntpserver deleteresources[] = new ntpserver[serverip.length];\n\t\t\tfor (int i=0;i<serverip.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = serverip[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void uploadFields(\n final Set<String> fields,\n final Function<Map<String, String>, Void> filenameCallback,\n final I_CmsErrorCallback errorCallback) {\n\n disableAllFileFieldsExcept(fields);\n final String id = CmsJsUtils.generateRandomId();\n updateFormAction(id);\n // Using an array here because we can only store the handler registration after it has been created , but\n final HandlerRegistration[] registration = {null};\n registration[0] = addSubmitCompleteHandler(new SubmitCompleteHandler() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void onSubmitComplete(SubmitCompleteEvent event) {\n\n enableAllFileFields();\n registration[0].removeHandler();\n CmsUUID sessionId = m_formSession.internalGetSessionId();\n RequestBuilder requestBuilder = CmsXmlContentUgcApi.SERVICE.uploadFiles(\n sessionId,\n fields,\n id,\n new AsyncCallback<Map<String, String>>() {\n\n public void onFailure(Throwable caught) {\n\n m_formSession.getContentFormApi().handleError(caught, errorCallback);\n\n }\n\n public void onSuccess(Map<String, String> fileNames) {\n\n filenameCallback.apply(fileNames);\n\n }\n });\n m_formSession.getContentFormApi().getRpcHelper().executeRpc(requestBuilder);\n m_formSession.getContentFormApi().getRequestCounter().decrement();\n }\n });\n m_formSession.getContentFormApi().getRequestCounter().increment();\n submit();\n }",
"public static SQLException create(String message, Throwable cause) {\n\t\tSQLException sqlException;\n\t\tif (cause instanceof SQLException) {\n\t\t\t// if the cause is another SQLException, pass alot of the SQL state\n\t\t\tsqlException = new SQLException(message, ((SQLException) cause).getSQLState());\n\t\t} else {\n\t\t\tsqlException = new SQLException(message);\n\t\t}\n\t\tsqlException.initCause(cause);\n\t\treturn sqlException;\n\t}",
"public boolean detectOperaMobile() {\r\n\r\n if ((userAgent.indexOf(engineOpera) != -1)\r\n && ((userAgent.indexOf(mini) != -1) || (userAgent.indexOf(mobi) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }"
] |
Reads filter parameters.
@param params the params
@return the criterias | [
"private Map<String, Criteria> getCriterias(Map<String, String[]> params) {\n Map<String, Criteria> result = new HashMap<String, Criteria>();\n for (Map.Entry<String, String[]> param : params.entrySet()) {\n for (Criteria criteria : FILTER_CRITERIAS) {\n if (criteria.getName().equals(param.getKey())) {\n try {\n Criteria[] parsedCriterias = criteria.parseValue(param.getValue()[0]);\n for (Criteria parsedCriteria : parsedCriterias) {\n result.put(parsedCriteria.getName(), parsedCriteria);\n }\n } catch (Exception e) {\n // Exception happened during paring\n LOG.log(Level.SEVERE, \"Error parsing parameter \" + param.getKey(), e);\n }\n break;\n }\n }\n }\n return result;\n }"
] | [
"public static nsspparams get(nitro_service service) throws Exception{\n\t\tnsspparams obj = new nsspparams();\n\t\tnsspparams[] response = (nsspparams[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public double[][] Kernel2D(int size) {\n if (((size % 2) == 0) || (size < 3) || (size > 101)) {\n try {\n throw new Exception(\"Wrong size\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n int r = size / 2;\n double[][] kernel = new double[size][size];\n\n // compute kernel\n double sum = 0;\n for (int y = -r, i = 0; i < size; y++, i++) {\n for (int x = -r, j = 0; j < size; x++, j++) {\n kernel[i][j] = Function2D(x, y);\n sum += kernel[i][j];\n }\n }\n\n for (int i = 0; i < kernel.length; i++) {\n for (int j = 0; j < kernel[0].length; j++) {\n kernel[i][j] /= sum;\n }\n }\n\n return kernel;\n }",
"public Map<String, Object> getValues(double evaluationTime, MonteCarloSimulationInterface model) throws CalculationException\n\t{\n\t\tRandomVariableInterface values = getValue(evaluationTime, model);\n\n\t\tif(values == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sum up values on path\n\t\tdouble value = values.getAverage();\n\t\tdouble error = values.getStandardError();\n\n\t\tMap<String, Object> results = new HashMap<String, Object>();\n\t\tresults.put(\"value\", value);\n\t\tresults.put(\"error\", error);\n\n\t\treturn results;\n\t}",
"private boolean markAsObsolete(ContentReference ref) {\n if (obsoleteContents.containsKey(ref.getHexHash())) { //This content is already marked as obsolete\n if (obsoleteContents.get(ref.getHexHash()) + obsolescenceTimeout < System.currentTimeMillis()) {\n DeploymentRepositoryLogger.ROOT_LOGGER.obsoleteContentCleaned(ref.getContentIdentifier());\n removeContent(ref);\n return true;\n }\n } else {\n obsoleteContents.put(ref.getHexHash(), System.currentTimeMillis()); //Mark content as obsolete\n }\n return false;\n }",
"private Object filterValue(Object value)\n {\n if (value instanceof Boolean && !((Boolean) value).booleanValue())\n {\n value = null;\n }\n if (value instanceof String && ((String) value).isEmpty())\n {\n value = null;\n }\n if (value instanceof Double && ((Double) value).doubleValue() == 0.0)\n {\n value = null;\n }\n if (value instanceof Integer && ((Integer) value).intValue() == 0)\n {\n value = null;\n }\n if (value instanceof Duration && ((Duration) value).getDuration() == 0.0)\n {\n value = null;\n }\n\n return value;\n }",
"protected Query buildMtoNImplementorQuery(Collection ids)\r\n {\r\n String[] indFkCols = getFksToThisClass();\r\n String[] indItemFkCols = getFksToItemClass();\r\n FieldDescriptor[] pkFields = getOwnerClassDescriptor().getPkFields();\r\n FieldDescriptor[] itemPkFields = getItemClassDescriptor().getPkFields();\r\n String[] cols = new String[indFkCols.length + indItemFkCols.length];\r\n int[] jdbcTypes = new int[indFkCols.length + indItemFkCols.length];\r\n\r\n // concatenate the columns[]\r\n System.arraycopy(indFkCols, 0, cols, 0, indFkCols.length);\r\n System.arraycopy(indItemFkCols, 0, cols, indFkCols.length, indItemFkCols.length);\r\n\r\n Criteria crit = buildPrefetchCriteria(ids, indFkCols, indItemFkCols, itemPkFields);\r\n\r\n // determine the jdbcTypes of the pks\r\n for (int i = 0; i < pkFields.length; i++)\r\n {\r\n jdbcTypes[i] = pkFields[i].getJdbcType().getType();\r\n }\r\n for (int i = 0; i < itemPkFields.length; i++)\r\n {\r\n jdbcTypes[pkFields.length + i] = itemPkFields[i].getJdbcType().getType();\r\n }\r\n\r\n ReportQueryByMtoNCriteria q = new ReportQueryByMtoNCriteria(getItemClassDescriptor().getClassOfObject(), cols,\r\n crit, false);\r\n q.setIndirectionTable(getCollectionDescriptor().getIndirectionTable());\r\n q.setJdbcTypes(jdbcTypes);\r\n\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n //check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n q.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n \r\n return q;\r\n }",
"public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"public static Drawable decideIcon(ImageHolder imageHolder, Context ctx, int iconColor, boolean tint) {\n if (imageHolder == null) {\n return null;\n } else {\n return imageHolder.decideIcon(ctx, iconColor, tint);\n }\n }",
"public void setAlias(UserAlias userAlias)\r\n\t{\r\n\t\tm_alias = userAlias.getName();\r\n\r\n\t\t// propagate to SelectionCriteria,not to Criteria\r\n\t\tfor (int i = 0; i < m_criteria.size(); i++)\r\n\t\t{\r\n\t\t\tif (!(m_criteria.elementAt(i) instanceof Criteria))\r\n\t\t\t{\r\n\t\t\t\t((SelectionCriteria) m_criteria.elementAt(i)).setAlias(userAlias);\r\n\t\t\t}\r\n\t\t}\r\n\t}"
] |
Extract WOEID after XML loads | [
"private void parseResponse(InputStream inputStream) {\n\n try {\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(inputStream);\n doc.getDocumentElement().normalize();\n\n NodeList nodes = doc.getElementsByTagName(\"place\");\n\n for (int i = 0; i < nodes.getLength(); i++) {\n Node node = nodes.item(i);\n\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element element = (Element) node;\n _woeid = getValue(\"woeid\", element);\n }\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }"
] | [
"protected AbstractElement getEnclosingSingleElementGroup(AbstractElement elementToParse) {\n\t\tEObject container = elementToParse.eContainer();\n\t\tif (container instanceof Group) {\n\t\t\tif (((Group) container).getElements().size() == 1) {\n\t\t\t\treturn (AbstractElement) container;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"private String generateAbbreviatedExceptionMessage(final Throwable throwable) {\n\n\t\tfinal StringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\": \");\n\t\tbuilder.append(throwable.getClass().getCanonicalName());\n\t\tbuilder.append(\": \");\n\t\tbuilder.append(throwable.getMessage());\n\n\t\tThrowable cause = throwable.getCause();\n\t\twhile (cause != null) {\n\t\t\tbuilder.append('\\n');\n\t\t\tbuilder.append(\"Caused by: \");\n\t\t\tbuilder.append(cause.getClass().getCanonicalName());\n\t\t\tbuilder.append(\": \");\n\t\t\tbuilder.append(cause.getMessage());\n\t\t\t// make sure the exception cause is not itself to prevent infinite\n\t\t\t// looping\n\t\t\tassert (cause != cause.getCause());\n\t\t\tcause = (cause == cause.getCause() ? null : cause.getCause());\n\t\t}\n\t\treturn builder.toString();\n\t}",
"public File getStylesheetPath()\n {\n String path = System.getProperty(STYLESHEET_KEY);\n return path == null ? null : new File(path);\n }",
"public static void awaitRoute(URL routeUrl, int timeout, TimeUnit timeoutUnit, int repetitions, int... statusCodes) {\n AtomicInteger successfulAwaitsInARow = new AtomicInteger(0);\n await().atMost(timeout, timeoutUnit).until(() -> {\n if (tryConnect(routeUrl, statusCodes)) {\n successfulAwaitsInARow.incrementAndGet();\n } else {\n successfulAwaitsInARow.set(0);\n }\n return successfulAwaitsInARow.get() >= repetitions;\n });\n }",
"public boolean isIdProperty(OgmEntityPersister persister, List<String> namesWithoutAlias) {\n\t\tString join = StringHelper.join( namesWithoutAlias, \".\" );\n\t\tType propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );\n\t\tString[] identifierColumnNames = persister.getIdentifierColumnNames();\n\t\tif ( propertyType.isComponentType() ) {\n\t\t\tString[] embeddedColumnNames = persister.getPropertyColumnNames( join );\n\t\t\tfor ( String embeddedColumn : embeddedColumnNames ) {\n\t\t\t\tif ( !ArrayHelper.contains( identifierColumnNames, embeddedColumn ) ) {\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 ArrayHelper.contains( identifierColumnNames, join );\n\t}",
"public static String ptb2Text(String ptbText) {\r\n StringBuilder sb = new StringBuilder(ptbText.length()); // probably an overestimate\r\n PTB2TextLexer lexer = new PTB2TextLexer(new StringReader(ptbText));\r\n try {\r\n for (String token; (token = lexer.next()) != null; ) {\r\n sb.append(token);\r\n }\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n return sb.toString();\r\n }",
"public static void scale(GVRMesh mesh, float x, float y, float z) {\n final float [] vertices = mesh.getVertices();\n final int vsize = vertices.length;\n\n for (int i = 0; i < vsize; i += 3) {\n vertices[i] *= x;\n vertices[i + 1] *= y;\n vertices[i + 2] *= z;\n }\n\n mesh.setVertices(vertices);\n }",
"private static long daysBetween(Date date1, Date date2) {\n long diff;\n if (date2.after(date1)) {\n diff = date2.getTime() - date1.getTime();\n } else {\n diff = date1.getTime() - date2.getTime();\n }\n return diff / (24 * 60 * 60 * 1000);\n }",
"protected void internalClose() throws SQLException {\r\n\t\ttry {\r\n\t\t\tclearStatementCaches(true);\r\n\t\t\tif (this.connection != null){ // safety!\r\n\t\t\t\tthis.connection.close();\r\n\r\n\t\t\t\tif (!this.connectionTrackingDisabled && this.finalizableRefs != null){\r\n\t\t\t\t\tthis.finalizableRefs.remove(this.connection);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tthis.logicallyClosed.set(true);\r\n\t\t} catch (SQLException e) {\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}"
] |
Writes the given configuration to the given file. | [
"public void write(Configuration config)\n throws IOException {\n\n pp.startDocument();\n pp.startElement(\"duke\", null);\n\n // FIXME: here we should write the objects, but that's not\n // possible with the current API. we don't need that for the\n // genetic algorithm at the moment, but it would be useful.\n\n pp.startElement(\"schema\", null);\n\n writeElement(\"threshold\", \"\" + config.getThreshold());\n if (config.getMaybeThreshold() != 0.0)\n writeElement(\"maybe-threshold\", \"\" + config.getMaybeThreshold());\n\n for (Property p : config.getProperties())\n writeProperty(p);\n\n pp.endElement(\"schema\");\n\n String dbclass = config.getDatabase(false).getClass().getName();\n AttributeListImpl atts = new AttributeListImpl();\n atts.addAttribute(\"class\", \"CDATA\", dbclass);\n pp.startElement(\"database\", atts);\n pp.endElement(\"database\");\n\n if (config.isDeduplicationMode())\n for (DataSource src : config.getDataSources())\n writeDataSource(src);\n else {\n pp.startElement(\"group\", null);\n for (DataSource src : config.getDataSources(1))\n writeDataSource(src);\n pp.endElement(\"group\");\n\n pp.startElement(\"group\", null);\n for (DataSource src : config.getDataSources(2))\n writeDataSource(src);\n pp.endElement(\"group\");\n }\n\n pp.endElement(\"duke\");\n pp.endDocument();\n }"
] | [
"public FieldLocation getFieldLocation(FieldType type)\n {\n FieldLocation result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFieldLocation();\n }\n return result;\n }",
"private AlbumArt requestArtworkInternal(final DataReference artReference, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n\n // First check if we are using cached data for this slot.\n MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(artReference));\n if (cache != null) {\n final AlbumArt result = cache.getAlbumArt(null, artReference);\n if (result != null) {\n artCache.put(artReference, result);\n }\n return result;\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(artReference.getSlotReference());\n if (sourceDetails != null) {\n final AlbumArt provided = MetadataFinder.getInstance().allMetadataProviders.getAlbumArt(sourceDetails, artReference);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (MetadataFinder.getInstance().isPassive() && failIfPassive && artReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // We have to actually request the art using the dbserver protocol.\n ConnectionManager.ClientTask<AlbumArt> task = new ConnectionManager.ClientTask<AlbumArt>() {\n @Override\n public AlbumArt useClient(Client client) throws Exception {\n return getArtwork(artReference.rekordboxId, SlotReference.getSlotReference(artReference), trackType, client);\n }\n };\n\n try {\n AlbumArt artwork = ConnectionManager.getInstance().invokeWithClientSession(artReference.player, task, \"requesting artwork\");\n if (artwork != null) { // Our cache file load or network request succeeded, so add to the level 2 cache.\n artCache.put(artReference, artwork);\n }\n return artwork;\n } catch (Exception e) {\n logger.error(\"Problem requesting album art, returning null\", e);\n }\n return null;\n }",
"private static boolean equalAsInts(Vec2d a, Vec2d b) {\n return ((int) a.x) == ((int) b.x) && ((int) a.y) == ((int) b.y);\n }",
"private static void dumpTree(PrintWriter pw, DirectoryEntry dir, String prefix, boolean showData, boolean hex, String indent) throws Exception\n {\n long byteCount;\n\n for (Iterator<Entry> iter = dir.getEntries(); iter.hasNext();)\n {\n Entry entry = iter.next();\n if (entry instanceof DirectoryEntry)\n {\n String childIndent = indent;\n if (childIndent != null)\n {\n childIndent += \" \";\n }\n\n String childPrefix = prefix + \"[\" + entry.getName() + \"].\";\n pw.println(\"start dir: \" + prefix + entry.getName());\n dumpTree(pw, (DirectoryEntry) entry, childPrefix, showData, hex, childIndent);\n pw.println(\"end dir: \" + prefix + entry.getName());\n }\n else\n if (entry instanceof DocumentEntry)\n {\n if (showData)\n {\n pw.println(\"start doc: \" + prefix + entry.getName());\n if (hex == true)\n {\n byteCount = hexdump(new DocumentInputStream((DocumentEntry) entry), pw);\n }\n else\n {\n byteCount = asciidump(new DocumentInputStream((DocumentEntry) entry), pw);\n }\n pw.println(\"end doc: \" + prefix + entry.getName() + \" (\" + byteCount + \" bytes read)\");\n }\n else\n {\n if (indent != null)\n {\n pw.print(indent);\n }\n pw.println(\"doc: \" + prefix + entry.getName());\n }\n }\n else\n {\n pw.println(\"found unknown: \" + prefix + entry.getName());\n }\n }\n }",
"private void performDynamicStep() {\n // initially look for singular values of zero\n if( findingZeros ) {\n if( steps > 6 ) {\n findingZeros = false;\n } else {\n double scale = computeBulgeScale();\n performImplicitSingleStep(scale,0,false);\n }\n } else {\n // For very large and very small numbers the only way to prevent overflow/underflow\n // is to have a common scale between the wilkinson shift and the implicit single step\n // What happens if you don't is that when the wilkinson shift returns the value it\n // computed it multiplies it by the scale twice, which will cause an overflow\n double scale = computeBulgeScale();\n // use the wilkinson shift to perform a step\n double lambda = selectWilkinsonShift(scale);\n\n performImplicitSingleStep(scale,lambda,false);\n }\n }",
"public ParallelTaskBuilder setSshPassword(String password) {\n this.sshMeta.setPassword(password);\n this.sshMeta.setSshLoginType(SshLoginType.PASSWORD);\n return this;\n }",
"private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1));\n mpxjResource.setName(gpResource.getName());\n mpxjResource.setEmailAddress(gpResource.getContacts());\n mpxjResource.setText(1, gpResource.getPhone());\n mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction()));\n\n net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate();\n if (gpRate != null)\n {\n mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS));\n }\n readResourceCustomFields(gpResource, mpxjResource);\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }",
"public Iterator<K> tailIterator(@NotNull final K key) {\n return new Iterator<K>() {\n\n private Stack<TreePos<K>> stack;\n private boolean hasNext;\n private boolean hasNextValid;\n\n @Override\n public boolean hasNext() {\n if (hasNextValid) {\n return hasNext;\n }\n hasNextValid = true;\n if (stack == null) {\n Node<K> root = getRoot();\n if (root == null) {\n hasNext = false;\n return hasNext;\n }\n stack = new Stack<>();\n if (!root.getLess(key, stack)) {\n stack.push(new TreePos<>(root));\n }\n }\n TreePos<K> treePos = stack.peek();\n if (treePos.node.isLeaf()) {\n while (treePos.pos >= (treePos.node.isTernary() ? 2 : 1)) {\n stack.pop();\n if (stack.isEmpty()) {\n hasNext = false;\n return hasNext;\n }\n treePos = stack.peek();\n }\n } else {\n if (treePos.pos == 0) {\n treePos = new TreePos<>(treePos.node.getFirstChild());\n } else if (treePos.pos == 1) {\n treePos = new TreePos<>(treePos.node.getSecondChild());\n } else {\n treePos = new TreePos<>(treePos.node.getThirdChild());\n }\n stack.push(treePos);\n while (!treePos.node.isLeaf()) {\n treePos = new TreePos<>(treePos.node.getFirstChild());\n stack.push(treePos);\n }\n }\n treePos.pos++;\n hasNext = true;\n return hasNext;\n }\n\n @Override\n public K next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n hasNextValid = false;\n TreePos<K> treePos = stack.peek();\n // treePos.pos must be 1 or 2 here\n return treePos.pos == 1 ? treePos.node.getFirstKey() : treePos.node.getSecondKey();\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n };\n }",
"public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n if (creationalContext != null) {\n T instance = contextual.create(creationalContext);\n if (creationalContext instanceof WeldCreationalContext<?>) {\n addDependentInstance(instance, contextual, (WeldCreationalContext<T>) creationalContext);\n }\n return instance;\n } else {\n return null;\n }\n }"
] |
Transforms a config file with an XSLT transform.
@param name file name of the config file
@param transform file name of the XSLT file
@throws Exception if something goes wrong | [
"public void transform(String name, String transform) throws Exception {\n\n File configFile = new File(m_configDir, name);\n File transformFile = new File(m_xsltDir, transform);\n try (InputStream stream = new FileInputStream(transformFile)) {\n StreamSource source = new StreamSource(stream);\n transform(configFile, source);\n }\n }"
] | [
"public static int numberAwareCompareTo(Comparable self, Comparable other) {\n NumberAwareComparator<Comparable> numberAwareComparator = new NumberAwareComparator<Comparable>();\n return numberAwareComparator.compare(self, other);\n }",
"@Api\n\tpublic void setNamedRoles(Map<String, List<NamedRoleInfo>> namedRoles) {\n\t\tthis.namedRoles = namedRoles;\n\t\tldapRoleMapping = new HashMap<String, Set<String>>();\n\t\tfor (String roleName : namedRoles.keySet()) {\n\t\t\tif (!ldapRoleMapping.containsKey(roleName)) {\n\t\t\t\tldapRoleMapping.put(roleName, new HashSet<String>());\n\t\t\t}\n\t\t\tfor (NamedRoleInfo role : namedRoles.get(roleName)) {\n\t\t\t\tldapRoleMapping.get(roleName).add(role.getName());\n\t\t\t}\n\t\t}\n\t}",
"void saveAction() {\n\n Map<Object, Object> filters = getFilters();\n m_table.clearFilters();\n\n try {\n\n m_model.save();\n disableSaveButtons();\n\n } catch (CmsException e) {\n LOG.error(m_messages.key(Messages.ERR_SAVING_CHANGES_0), e);\n CmsErrorDialog.showErrorDialog(m_messages.key(Messages.ERR_SAVING_CHANGES_0), e);\n }\n\n setFilters(filters);\n\n }",
"public boolean invokeFunction(String funcName, Object[] args)\n {\n mLastError = null;\n if (mScriptFile != null)\n {\n if (mScriptFile.invokeFunction(funcName, args))\n {\n return true;\n }\n }\n mLastError = mScriptFile.getLastError();\n if ((mLastError != null) && !mLastError.contains(\"is not defined\"))\n {\n getGVRContext().logError(mLastError, this);\n }\n return false;\n }",
"public static void checkOperatorIsValid(int operatorCode) {\n switch (operatorCode) {\n case OPERATOR_LT:\n case OPERATOR_LE:\n case OPERATOR_EQ:\n case OPERATOR_NE:\n case OPERATOR_GE:\n case OPERATOR_GT:\n case OPERATOR_UNKNOWN:\n return;\n default:\n throw new IllegalStateException(String.format(Locale.US, ERROR_INVALID_CODE, operatorCode));\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 }",
"public Set<CoreDocumentSynchronizationConfig> getSynchronizedDocuments(\n final MongoNamespace namespace\n ) {\n this.waitUntilInitialized();\n try {\n ongoingOperationsGroup.enter();\n return this.syncConfig.getSynchronizedDocuments(namespace);\n } finally {\n ongoingOperationsGroup.exit();\n }\n }",
"public static void log(String label, byte[] data)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(ByteArrayHelper.hexdump(data, true));\n LOG.flush();\n }\n }",
"private boolean keyAlreadyExists(String newKey) {\n\n Collection<?> itemIds = m_table.getItemIds();\n for (Object itemId : itemIds) {\n if (m_table.getItem(itemId).getItemProperty(TableProperty.KEY).getValue().equals(newKey)) {\n return true;\n }\n }\n return false;\n }"
] |
Verifies that the received image is identical to the original one.
@param xopOriginal
@param xopResponse | [
"private void verifyXopResponse(XopBean xopOriginal, XopBean xopResponse) {\n if (!Arrays.equals(xopResponse.getBytes(), xopOriginal.getBytes())) {\n throw new RuntimeException(\"Received XOP attachment is corrupted\");\n }\n System.out.println();\n System.out.println(\"XOP attachment has been successfully received\");\n }"
] | [
"public void writeNameValuePair(String name, Date value) throws IOException\n {\n internalWriteNameValuePair(name, m_format.format(value));\n }",
"public Object assignIdValue(ConnectionSource connectionSource, Object data, Number val, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\tObject idVal = dataPersister.convertIdNumber(val);\n\t\tif (idVal == null) {\n\t\t\tthrow new SQLException(\"Invalid class \" + dataPersister + \" for sequence-id \" + this);\n\t\t} else {\n\t\t\tassignField(connectionSource, data, idVal, false, objectCache);\n\t\t\treturn idVal;\n\t\t}\n\t}",
"private void checkRowReader(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String rowReaderName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_ROW_READER);\r\n\r\n if (rowReaderName == null)\r\n {\r\n return;\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(rowReaderName, ROW_READER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+rowReaderName+\" specified as row-reader of class \"+classDef.getName()+\" does not implement the interface \"+ROW_READER_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the row-reader class \"+rowReaderName+\" of class \"+classDef.getName());\r\n }\r\n }",
"private int countHours(Integer hours)\n {\n int value = hours.intValue();\n int hoursPerDay = 0;\n int hour = 0;\n while (value > 0)\n {\n // Move forward until we find a working hour\n while (hour < 24)\n {\n if ((value & 0x1) != 0)\n {\n ++hoursPerDay;\n }\n value = value >> 1;\n ++hour;\n }\n }\n return hoursPerDay;\n }",
"public void deleteById(String id) {\n if (idToVersion.containsKey(id)) {\n String version = idToVersion.remove(id);\n expirationVersion.remove(version);\n versionToItem.remove(version);\n if (collectionCachePath != null\n && !collectionCachePath.resolve(version).toFile().delete()) {\n log.debug(\"couldn't delete \" + version);\n }\n }\n }",
"@PostConstruct\n\tprotected void init() throws IOException {\n\t\t// base configuration from XML file\n\t\tif (null != configurationFile) {\n\t\t\tlog.debug(\"Get base configuration from {}\", configurationFile);\n\t\t\tmanager = new DefaultCacheManager(configurationFile);\n\t\t} else {\n\t\t\tGlobalConfigurationBuilder builder = new GlobalConfigurationBuilder();\n\t\t\tbuilder.globalJmxStatistics().allowDuplicateDomains(true);\n\t\t\tmanager = new DefaultCacheManager(builder.build());\n\t\t}\n\n\t\tif (listener == null) {\n\t\t\tlistener = new InfinispanCacheListener();\n\t\t}\n\t\tmanager.addListener(listener);\n\n\t\t// cache for caching the cache configurations (hmmm, sounds a bit strange)\n\t\tMap<String, Map<CacheCategory, CacheService>> cacheCache = \n\t\t\t\tnew HashMap<String, Map<CacheCategory, CacheService>>();\n\n\t\t// build default configuration\n\t\tif (null != defaultConfiguration) {\n\t\t\tsetCaches(cacheCache, null, defaultConfiguration);\n\t\t}\n\n\t\t// build layer specific configurations\n\t\tfor (Layer layer : layerMap.values()) {\n\t\t\tCacheInfo ci = configurationService.getLayerExtraInfo(layer.getLayerInfo(), CacheInfo.class);\n\t\t\tif (null != ci) {\n\t\t\t\tsetCaches(cacheCache, layer, ci);\n\t\t\t}\n\t\t}\n\t}",
"static DisplayMetrics getDisplayMetrics(final Context context) {\n final WindowManager\n windowManager =\n (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n final DisplayMetrics metrics = new DisplayMetrics();\n windowManager.getDefaultDisplay().getMetrics(metrics);\n return metrics;\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 synchronized void addListener(CollectionProxyListener listener)\r\n {\r\n if (_listeners == null)\r\n {\r\n _listeners = new ArrayList();\r\n }\r\n // to avoid multi-add of same listener, do check\r\n if(!_listeners.contains(listener))\r\n {\r\n _listeners.add(listener);\r\n }\r\n }"
] |
Swap the current version folder for a new one
@param newStoreDirectory The path to the new version directory | [
"@JmxOperation(description = \"swapFiles changes this store to use the new data directory\")\n public void swapFiles(String newStoreDirectory) {\n logger.info(\"Swapping files for store '\" + getName() + \"' to \" + newStoreDirectory);\n File newVersionDir = new File(newStoreDirectory);\n\n if(!newVersionDir.exists())\n throw new VoldemortException(\"File \" + newVersionDir.getAbsolutePath()\n + \" does not exist.\");\n\n if(!(newVersionDir.getParentFile().compareTo(storeDir.getAbsoluteFile()) == 0 && ReadOnlyUtils.checkVersionDirName(newVersionDir)))\n throw new VoldemortException(\"Invalid version folder name '\"\n + newVersionDir\n + \"'. Either parent directory is incorrect or format(version-n) is incorrect\");\n\n // retrieve previous version for (a) check if last write is winning\n // (b) if failure, rollback use\n File previousVersionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n if(previousVersionDir == null)\n throw new VoldemortException(\"Could not find any latest directory to swap with in store '\"\n + getName() + \"'\");\n\n long newVersionId = ReadOnlyUtils.getVersionId(newVersionDir);\n long previousVersionId = ReadOnlyUtils.getVersionId(previousVersionDir);\n if(newVersionId == -1 || previousVersionId == -1)\n throw new VoldemortException(\"Unable to parse folder names (\" + newVersionDir.getName()\n + \",\" + previousVersionDir.getName()\n + \") since format(version-n) is incorrect\");\n\n // check if we're greater than latest since we want last write to win\n if(previousVersionId > newVersionId) {\n logger.info(\"No swap required since current latest version \" + previousVersionId\n + \" is greater than swap version \" + newVersionId);\n deleteBackups();\n return;\n }\n\n logger.info(\"Acquiring write lock on '\" + getName() + \"':\");\n fileModificationLock.writeLock().lock();\n boolean success = false;\n try {\n close();\n logger.info(\"Opening primary files for store '\" + getName() + \"' at \"\n + newStoreDirectory);\n\n // open the latest store\n open(newVersionDir);\n success = true;\n } finally {\n try {\n // we failed to do the swap, attempt a rollback to last version\n if(!success)\n rollback(previousVersionDir);\n\n } finally {\n fileModificationLock.writeLock().unlock();\n if(success)\n logger.info(\"Swap operation completed successfully on store \" + getName()\n + \", releasing lock.\");\n else\n logger.error(\"Swap operation failed.\");\n }\n }\n\n // okay we have released the lock and the store is now open again, it is\n // safe to do a potentially slow delete if we have one too many backups\n deleteBackups();\n }"
] | [
"private boolean isSpecial(final char chr) {\n\t\treturn ((chr == '.') || (chr == '?') || (chr == '*') || (chr == '^') || (chr == '$') || (chr == '+')\n\t\t\t\t|| (chr == '[') || (chr == ']') || (chr == '(') || (chr == ')') || (chr == '|') || (chr == '\\\\')\n\t\t\t\t|| (chr == '&'));\n\t}",
"public static void applyToOrTransparent(ColorHolder colorHolder, Context ctx, GradientDrawable gradientDrawable) {\n if (colorHolder != null && gradientDrawable != null) {\n colorHolder.applyTo(ctx, gradientDrawable);\n } else if (gradientDrawable != null) {\n gradientDrawable.setColor(Color.TRANSPARENT);\n }\n }",
"public void log(Level level, String msg) {\n\t\tlogIfEnabled(level, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}",
"public Duration getStartSlack()\n {\n Duration startSlack = (Duration) getCachedValue(TaskField.START_SLACK);\n if (startSlack == null)\n {\n Duration duration = getDuration();\n if (duration != null)\n {\n startSlack = DateHelper.getVariance(this, getEarlyStart(), getLateStart(), duration.getUnits());\n set(TaskField.START_SLACK, startSlack);\n }\n }\n return (startSlack);\n }",
"CueList getCueList(int rekordboxId, CdjStatus.TrackSourceSlot slot, Client client)\n throws IOException {\n Message response = client.simpleRequest(Message.KnownType.CUE_LIST_REQ, null,\n client.buildRMST(Message.MenuIdentifier.DATA, slot), new NumberField(rekordboxId));\n if (response.knownType == Message.KnownType.CUE_LIST) {\n return new CueList(response);\n }\n logger.error(\"Unexpected response type when requesting cue list: {}\", response);\n return null;\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 }",
"public Jar addPackageOf(Class<?> clazz, Filter filter) throws IOException {\n try {\n final String path = clazz.getPackage().getName().replace('.', '/');\n URL dirURL = clazz.getClassLoader().getResource(path);\n if (dirURL != null && dirURL.getProtocol().equals(\"file\"))\n addDir(Paths.get(path), Paths.get(dirURL.toURI()), filter, false);\n else {\n if (dirURL == null) // In case of a jar file, we can't actually find a directory.\n dirURL = clazz.getClassLoader().getResource(clazz.getName().replace('.', '/') + \".class\");\n\n if (dirURL.getProtocol().equals(\"jar\")) {\n final URI jarUri = new URI(dirURL.getPath().substring(0, dirURL.getPath().indexOf('!')));\n try (JarInputStream jis1 = newJarInputStream(Files.newInputStream(Paths.get(jarUri)))) {\n for (JarEntry entry; (entry = jis1.getNextJarEntry()) != null;) {\n try {\n if (entry.getName().startsWith(path + '/')) {\n if (filter == null || filter.filter(entry.getName()))\n addEntryNoClose(jos, entry.getName(), jis1);\n }\n } catch (ZipException e) {\n if (!e.getMessage().startsWith(\"duplicate entry\"))\n throw e;\n }\n }\n }\n } else\n throw new AssertionError();\n }\n return this;\n } catch (URISyntaxException e) {\n throw new AssertionError(e);\n }\n }",
"private boolean checkZoneRequirement(HashMap<Integer, Integer> requiredRepFactor, int zoneId) {\n if(requiredRepFactor.containsKey(zoneId)) {\n if(requiredRepFactor.get(zoneId) == 0) {\n return false;\n } else {\n requiredRepFactor.put(zoneId, requiredRepFactor.get(zoneId) - 1);\n return true;\n }\n }\n return false;\n\n }",
"private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }"
] |
Stop interpolating playback position for all active players. | [
"@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n BeatFinder.getInstance().removeBeatListener(beatListener);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n running.set(false);\n positions.clear();\n updates.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }"
] | [
"public synchronized HttpServer<Buffer, Buffer> start() throws Exception {\n\t\tif (server == null) {\n\t\t\tserver = createProtocolListener();\n\t\t}\n\t\treturn server;\n\t}",
"public ParallelTaskBuilder prepareTcp(String command) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.TCP);\n cb.getTcpMeta().setCommand(command);\n return cb;\n }",
"public static int cudnnCTCLoss(\n cudnnHandle handle, \n cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the timing steps, N is the\n mini batch size, A is the alphabet size) */\n Pointer probs, /** probabilities after softmax, in GPU memory */\n int[] labels, /** labels, in CPU memory */\n int[] labelLengths, /** the length of each label, in CPU memory */\n int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */\n Pointer costs, /** the returned costs of CTC, in GPU memory */\n cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the dimensions are T,N,A */\n Pointer gradients, /** the returned CTC gradients, in GPU memory, to compute costs only, set it to NULL */\n int algo, /** algorithm selected, supported now 0 and 1 */\n cudnnCTCLossDescriptor ctcLossDesc, \n Pointer workspace, /** pointer to the workspace, in GPU memory */\n long workSpaceSizeInBytes)/** the workspace size needed */\n {\n return checkResult(cudnnCTCLossNative(handle, probsDesc, probs, labels, labelLengths, inputLengths, costs, gradientsDesc, gradients, algo, ctcLossDesc, workspace, workSpaceSizeInBytes));\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}",
"public static appfwprofile_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tobj.set_name(name);\n\t\tappfwprofile_stats response = (appfwprofile_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"@Pure\n\tpublic static <K, V> Pair<K, V> of(K k, V v) {\n\t\treturn new Pair<K, V>(k, v);\n\t}",
"public void retrieveEngine() throws GeneralSecurityException, IOException {\n if (serverEngineFactory == null) {\n return;\n }\n engine = serverEngineFactory.retrieveHTTPServerEngine(nurl.getPort());\n if (engine == null) {\n engine = serverEngineFactory.getHTTPServerEngine(nurl.getHost(), nurl.getPort(), nurl.getProtocol());\n }\n\n assert engine != null;\n TLSServerParameters serverParameters = engine.getTlsServerParameters();\n if (serverParameters != null && serverParameters.getCertConstraints() != null) {\n CertificateConstraintsType constraints = serverParameters.getCertConstraints();\n if (constraints != null) {\n certConstraints = CertConstraintsJaxBUtils.createCertConstraints(constraints);\n }\n }\n\n // When configuring for \"http\", however, it is still possible that\n // Spring configuration has configured the port for https.\n if (!nurl.getProtocol().equals(engine.getProtocol())) {\n throw new IllegalStateException(\"Port \" + engine.getPort() + \" is configured with wrong protocol \\\"\" + engine.getProtocol() + \"\\\" for \\\"\" + nurl + \"\\\"\");\n }\n }",
"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 }",
"private int runCommitScript() {\n\n if (m_checkout && !m_fetchAndResetBeforeImport) {\n m_logStream.println(\"Skipping script....\");\n return 0;\n }\n try {\n m_logStream.flush();\n String commandParam;\n if (m_resetRemoteHead) {\n commandParam = resetRemoteHeadScriptCommand();\n } else if (m_resetHead) {\n commandParam = resetHeadScriptCommand();\n } else if (m_checkout) {\n commandParam = checkoutScriptCommand();\n } else {\n commandParam = checkinScriptCommand();\n }\n String[] cmd = {\"bash\", \"-c\", commandParam};\n m_logStream.println(\"Calling the script as follows:\");\n m_logStream.println();\n m_logStream.println(cmd[0] + \" \" + cmd[1] + \" \" + cmd[2]);\n ProcessBuilder builder = new ProcessBuilder(cmd);\n m_logStream.close();\n m_logStream = null;\n Redirect redirect = Redirect.appendTo(new File(DEFAULT_LOGFILE_PATH));\n builder.redirectOutput(redirect);\n builder.redirectError(redirect);\n Process scriptProcess = builder.start();\n int exitCode = scriptProcess.waitFor();\n scriptProcess.getOutputStream().close();\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, true));\n return exitCode;\n } catch (InterruptedException | IOException e) {\n e.printStackTrace(m_logStream);\n return -1;\n }\n\n }"
] |
In the case where the prefix sits at a segment boundary, and the prefix sequence is null - null - 0, this changes to prefix sequence of null - x - 0, where x is segment bit length.
Note: We allow both [null, null, 0] and [null, x, 0] where x is segment length. However, to avoid inconsistencies when doing segment replacements,
and when getting subsections, in the calling constructor we normalize [null, null, 0] to become [null, x, 0].
We need to support [null, x, 0] so that we can create subsections and full addresses ending with [null, x] where x is bit length.
So we defer to that when constructing addresses and sections.
Also note that in our append/appendNetowrk/insert/replace we have special handling for cases like inserting [null] into [null, 8, 0] at index 2.
The straight replace would give [null, 8, null, 0] which is wrong.
In that code we end up with [null, null, 8, 0] by doing a special trick:
We remove the end of [null, 8, 0] and do an append [null, 0] and we'd remove prefix from [null, 8] to get [null, null] and then we'd do another append to get [null, null, null, 0]
The final step is this normalization here that gives [null, null, 8, 0]
However, when users construct AddressDivisionGrouping or IPAddressDivisionGrouping, either one is allowed: [null, null, 0] and [null, x, 0].
Since those objects cannot be further subdivided with getSection/getNetworkSection/getHostSection or grown with appended/inserted/replaced,
there are no inconsistencies introduced, we are simply more user-friendly.
Also note that normalization of AddressDivisionGrouping or IPAddressDivisionGrouping is really not possible without the address creator objects we use for addresses and sections,
that allow us to recreate new segments of the correct type.
@param sectionPrefixBits
@param segments
@param segmentBitCount
@param segmentByteCount
@param segProducer | [
"protected static <S extends IPAddressSegment> void normalizePrefixBoundary(\n\t\t\tint sectionPrefixBits,\n\t\t\tS segments[],\n\t\t\tint segmentBitCount,\n\t\t\tint segmentByteCount,\n\t\t\tBiFunction<S, Integer, S> segProducer) {\n\t\t//we've already verified segment prefixes in super constructor. We simply need to check the case where the prefix is at a segment boundary,\n\t\t//whether the network side has the correct prefix\n\t\tint networkSegmentIndex = getNetworkSegmentIndex(sectionPrefixBits, segmentByteCount, segmentBitCount);\n\t\tif(networkSegmentIndex >= 0) {\n\t\t\tS segment = segments[networkSegmentIndex];\n\t\t\tif(!segment.isPrefixed()) {\n\t\t\t\tsegments[networkSegmentIndex] = segProducer.apply(segment, segmentBitCount);\n\t\t\t}\n\t\t}\n\t}"
] | [
"protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj);\r\n }",
"public void stop() {\n if (runnerThread == null) {\n return;\n }\n\n runnerThread.interrupt();\n\n nsLock.writeLock().lock();\n try {\n if (runnerThread == null) {\n return;\n }\n\n this.cancel();\n this.close();\n\n while (runnerThread.isAlive()) {\n runnerThread.interrupt();\n try {\n runnerThread.join(1000);\n } catch (final Exception e) {\n e.printStackTrace();\n return;\n }\n }\n runnerThread = null;\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"private Set<File> findThriftFiles() throws IOException, MojoExecutionException {\n final File thriftSourceRoot = getThriftSourceRoot();\n Set<File> thriftFiles = new HashSet<File>();\n if (thriftSourceRoot != null && thriftSourceRoot.exists()) {\n thriftFiles.addAll(findThriftFilesInDirectory(thriftSourceRoot));\n }\n getLog().info(\"finding thrift files in dependencies\");\n extractFilesFromDependencies(findThriftDependencies(), getResourcesOutputDirectory());\n if (buildExtractedThrift && getResourcesOutputDirectory().exists()) {\n thriftFiles.addAll(findThriftFilesInDirectory(getResourcesOutputDirectory()));\n }\n getLog().info(\"finding thrift files in referenced (reactor) projects\");\n thriftFiles.addAll(getReferencedThriftFiles());\n return thriftFiles;\n }",
"public static String getGalleryNotFoundKey(String gallery) {\n\n StringBuffer sb = new StringBuffer(ERROR_REASON_NO_PREFIX);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_TITLE_POSTFIX);\n return sb.toString();\n }",
"public FieldDescriptor getAutoIncrementField()\r\n {\r\n if (m_autoIncrementField == null)\r\n {\r\n FieldDescriptor[] fds = getPkFields();\r\n\r\n for (int i = 0; i < fds.length; i++)\r\n {\r\n FieldDescriptor fd = fds[i];\r\n if (fd.isAutoIncrement())\r\n {\r\n m_autoIncrementField = fd;\r\n break;\r\n }\r\n }\r\n }\r\n if (m_autoIncrementField == null)\r\n {\r\n LoggerFactory.getDefaultLogger().warn(\r\n this.getClass().getName()\r\n + \": \"\r\n + \"Could not find autoincrement attribute for class: \"\r\n + this.getClassNameOfObject());\r\n }\r\n return m_autoIncrementField;\r\n }",
"public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}",
"private Integer getNullOnValue(Integer value, int nullValue)\n {\n return (NumberHelper.getInt(value) == nullValue ? null : value);\n }",
"@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 }",
"public int[] sampleBatchWithReplacement() {\n // Sample the indices with replacement.\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n batch[i] = Prng.nextInt(numExamples);\n }\n return batch;\n }"
] |
Generates the points for an arc based on two bearings from a centre point
and a radius.
@param center The LatLong point of the center.
@param startBearing North is 0 degrees, East is 90 degrees, etc.
@param endBearing North is 0 degrees, East is 90 degrees, etc.
@param radius In metres
@return An array of LatLong points in an MVC array representing the arc.
Using this method directly you will need to push the centre point onto
the array in order to close it, if desired. | [
"public static final MVCArray buildArcPoints(LatLong center, double startBearing, double endBearing, double radius) {\n int points = DEFAULT_ARC_POINTS;\n\n MVCArray res = new MVCArray();\n\n if (startBearing > endBearing) {\n endBearing += 360.0;\n }\n double deltaBearing = endBearing - startBearing;\n deltaBearing = deltaBearing / points;\n for (int i = 0; (i < points + 1); i++) {\n res.push(center.getDestinationPoint(startBearing + i * deltaBearing, radius));\n }\n\n return res;\n\n }"
] | [
"public <T> T getSPI(Class<T> spiType)\n {\n return getSPI(spiType, SecurityActions.getContextClassLoader());\n }",
"public static void logBeforeExit(ExitLogger logger) {\n try {\n if (logged.compareAndSet(false, true)) {\n logger.logExit();\n }\n } catch (Throwable ignored){\n // ignored\n }\n }",
"public String getWorkplaceLink(CmsObject cms, String resourceName, boolean forceSecure) {\n\n String result = substituteLinkForUnknownTarget(cms, resourceName, forceSecure);\n return appendServerPrefix(cms, result, resourceName, true);\n\n }",
"protected void appenHtmlFooter(StringBuffer buffer) {\n\n if (m_configuredFooter != null) {\n buffer.append(m_configuredFooter);\n } else {\n buffer.append(\" </body>\\r\\n\" + \"</html>\");\n }\n }",
"private void populateDateTimeSettings(Record record, ProjectProperties properties)\n {\n properties.setDateOrder(record.getDateOrder(0));\n properties.setTimeFormat(record.getTimeFormat(1));\n\n Date time = getTimeFromInteger(record.getInteger(2));\n if (time != null)\n {\n properties.setDefaultStartTime(time);\n }\n\n Character c = record.getCharacter(3);\n if (c != null)\n {\n properties.setDateSeparator(c.charValue());\n }\n\n c = record.getCharacter(4);\n if (c != null)\n {\n properties.setTimeSeparator(c.charValue());\n }\n\n properties.setAMText(record.getString(5));\n properties.setPMText(record.getString(6));\n properties.setDateFormat(record.getDateFormat(7));\n properties.setBarTextDateFormat(record.getDateFormat(8));\n }",
"public void read(InputStream is) throws IOException\n {\n byte[] headerBlock = new byte[20];\n is.read(headerBlock);\n\n int headerLength = PEPUtility.getShort(headerBlock, 8);\n int recordCount = PEPUtility.getInt(headerBlock, 10);\n int recordLength = PEPUtility.getInt(headerBlock, 16);\n StreamHelper.skip(is, headerLength - headerBlock.length);\n\n byte[] record = new byte[recordLength];\n for (int recordIndex = 1; recordIndex <= recordCount; recordIndex++)\n {\n is.read(record);\n readRow(recordIndex, record);\n }\n }",
"private static void loadFile(String filePath) {\n final Path path = FileSystems.getDefault().getPath(filePath);\n\n try {\n data.clear();\n data.load(Files.newBufferedReader(path));\n } catch(IOException e) {\n LOG.warn(\"Exception while loading \" + path.toString(), e);\n }\n }",
"public boolean find() {\r\n if (findIterator == null) {\r\n findIterator = root.iterator();\r\n }\r\n if (findCurrent != null && matches()) {\r\n return true;\r\n }\r\n while (findIterator.hasNext()) {\r\n findCurrent = findIterator.next();\r\n resetChildIter(findCurrent);\r\n if (matches()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public static ResourceResolutionContext context(ResourceResolutionComponent[] components,\n Map<String, Object> messageParams) {\n return new ResourceResolutionContext(components, messageParams);\n }"
] |
Formats the value provided with the specified DateTimeFormat | [
"protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) {\n if (value == null) {\n return \"\";\n }\n else {\n // midnight GMT\n Date date = new Date(0);\n // offset by timezone and value\n date.setTime(UTCDateBox.timezoneOffsetMillis(date) + value.longValue());\n // format it\n return fmt.format(date);\n }\n }"
] | [
"static DocumentVersionInfo getRemoteVersionInfo(final BsonDocument remoteDocument) {\n final BsonDocument version = getDocumentVersionDoc(remoteDocument);\n return new DocumentVersionInfo(\n version,\n remoteDocument != null\n ? BsonUtils.getDocumentId(remoteDocument) : null\n );\n }",
"public void setDateAttribute(String name, Date value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DateAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\t}",
"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}",
"public void promoteModule(final String moduleId) {\n final DbModule module = getModule(moduleId);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n final DbArtifact artifact = repositoryHandler.getArtifact(gavc);\n artifact.setPromoted(true);\n repositoryHandler.store(artifact);\n }\n\n repositoryHandler.promoteModule(module);\n }",
"public static base_responses kill(nitro_service client, systemsession resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemsession killresources[] = new systemsession[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tkillresources[i] = new systemsession();\n\t\t\t\tkillresources[i].sid = resources[i].sid;\n\t\t\t\tkillresources[i].all = resources[i].all;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, killresources,\"kill\");\n\t\t}\n\t\treturn result;\n\t}",
"public ILog getLog(String topic, int partition) {\n TopicNameValidator.validate(topic);\n Pool<Integer, Log> p = getLogPool(topic, partition);\n return p == null ? null : p.get(partition);\n }",
"public final void notifyContentItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount, itemCount);\n }",
"public List<T> nextPermutationAsList()\n {\n List<T> permutation = new ArrayList<T>(elements.length);\n return nextPermutationAsList(permutation);\n }",
"public void fire(TestCaseEvent event) {\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n notifier.fire(event);\n }"
] |
Replace the last element of an address with a static path element.
@param element the path element
@return the operation address transformer | [
"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 }"
] | [
"public static cacheselector[] get(nitro_service service, options option) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tcacheselector[] response = (cacheselector[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"public SerialMessage getMultiChannelCapabilityGetMessage(ZWaveEndpoint endpoint) {\r\n\t\tlogger.debug(\"Creating new message for application command MULTI_CHANNEL_CAPABILITY_GET for node {} and endpoint {}\", this.getNode().getNodeId(), endpoint.getEndpointId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, 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) MULTI_CHANNEL_CAPABILITY_GET,\r\n\t\t\t\t\t\t\t\t(byte) endpoint.getEndpointId() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\r\n\t}",
"public synchronized void maybeThrottle(int eventsSeen) {\n if (maxRatePerSecond > 0) {\n long now = time.milliseconds();\n try {\n rateSensor.record(eventsSeen, now);\n } catch (QuotaViolationException e) {\n // If we're over quota, we calculate how long to sleep to compensate.\n double currentRate = e.getValue();\n if (currentRate > this.maxRatePerSecond) {\n double excessRate = currentRate - this.maxRatePerSecond;\n long sleepTimeMs = Math.round(excessRate / this.maxRatePerSecond * voldemort.utils.Time.MS_PER_SECOND);\n if(logger.isDebugEnabled()) {\n logger.debug(\"Throttler quota exceeded:\\n\" +\n \"eventsSeen \\t= \" + eventsSeen + \" in this call of maybeThrotte(),\\n\" +\n \"currentRate \\t= \" + currentRate + \" events/sec,\\n\" +\n \"maxRatePerSecond \\t= \" + this.maxRatePerSecond + \" events/sec,\\n\" +\n \"excessRate \\t= \" + excessRate + \" events/sec,\\n\" +\n \"sleeping for \\t\" + sleepTimeMs + \" ms to compensate.\\n\" +\n \"rateConfig.timeWindowMs() = \" + rateConfig.timeWindowMs());\n }\n if (sleepTimeMs > rateConfig.timeWindowMs()) {\n logger.warn(\"Throttler sleep time (\" + sleepTimeMs + \" ms) exceeds \" +\n \"window size (\" + rateConfig.timeWindowMs() + \" ms). This will likely \" +\n \"result in not being able to honor the rate limit accurately.\");\n // When using the HDFS Fetcher, setting the hdfs.fetcher.buffer.size\n // too high could cause this problem.\n }\n time.sleep(sleepTimeMs);\n } else if (logger.isDebugEnabled()) {\n logger.debug(\"Weird. Got QuotaValidationException but measured rate not over rateLimit: \" +\n \"currentRate = \" + currentRate + \" , rateLimit = \" + this.maxRatePerSecond);\n }\n }\n }\n }",
"public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException {\n\t\tMap<Double, RandomVariable> sum = new HashMap<>();\n\n\t\tfor(double time: timeDiscretization) {\n\t\t\tsum.put(time, realizations.get(time).add(process.getProcessValue(time, 0)));\n\t\t}\n\n\t\treturn new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum);\n\t}",
"public static List<Sentence> splitSentences(CharSequence text) {\n return JavaConversions.seqAsJavaList(\n TwitterKoreanProcessor.splitSentences(text)\n );\n }",
"boolean lockInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireNanos(permit, unit.toNanos(timeout));\n }",
"public void configure(@Observes(precedence = -200) ArquillianDescriptor arquillianDescriptor) {\n restAssuredConfigurationInstanceProducer.set(\n RestAssuredConfiguration.fromMap(arquillianDescriptor\n .extension(\"restassured\")\n .getExtensionProperties()));\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 JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, Connection con, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n if (_parameters == null)\n _parameters = new HashMap<String, Object>();\n\n visitSubreports(dr, _parameters);\n compileOrLoadSubreports(dr, _parameters, \"r\");\n\n DynamicJasperDesign jd = generateJasperDesign(dr);\n Map<String, Object> params = new HashMap<String, Object>();\n if (!_parameters.isEmpty()) {\n registerParams(jd, _parameters);\n params.putAll(_parameters);\n }\n registerEntities(jd, dr, layoutManager);\n layoutManager.applyLayout(jd, dr);\n JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n //JRProperties.setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());\n JasperReport jr = JasperCompileManager.compileReport(jd);\n params.putAll(jd.getParametersWithValues());\n jp = JasperFillManager.fillReport(jr, params, con);\n\n return jp;\n }"
] |
This method is called to alert project listeners to the fact that
a task has been read from a project file.
@param task task instance | [
"public void fireTaskReadEvent(Task task)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.taskRead(task);\n }\n }\n }"
] | [
"public static void unregisterContextualInstance(EjbDescriptor<?> descriptor) {\n Set<Class<?>> classes = CONTEXTUAL_SESSION_BEANS.get();\n classes.remove(descriptor.getBeanClass());\n if (classes.isEmpty()) {\n CONTEXTUAL_SESSION_BEANS.remove();\n }\n }",
"public static java.sql.Time newTime() {\n return new java.sql.Time(System.currentTimeMillis() % DAY_MILLIS);\n }",
"@SuppressWarnings(\"deprecation\")\n\tprivate static WriteConcern mergeWriteConcern(WriteConcern original, WriteConcern writeConcern) {\n\t\tif ( original == null ) {\n\t\t\treturn writeConcern;\n\t\t}\n\t\telse if ( writeConcern == null ) {\n\t\t\treturn original;\n\t\t}\n\t\telse if ( original.equals( writeConcern ) ) {\n\t\t\treturn original;\n\t\t}\n\n\t\tObject wObject;\n\t\tint wTimeoutMS;\n\t\tboolean fsync;\n\t\tBoolean journal;\n\n\t\tif ( original.getWObject() instanceof String ) {\n\t\t\twObject = original.getWString();\n\t\t}\n\t\telse if ( writeConcern.getWObject() instanceof String ) {\n\t\t\twObject = writeConcern.getWString();\n\t\t}\n\t\telse {\n\t\t\twObject = Math.max( original.getW(), writeConcern.getW() );\n\t\t}\n\n\t\twTimeoutMS = Math.min( original.getWtimeout(), writeConcern.getWtimeout() );\n\n\t\tfsync = original.getFsync() || writeConcern.getFsync();\n\n\t\tif ( original.getJournal() == null ) {\n\t\t\tjournal = writeConcern.getJournal();\n\t\t}\n\t\telse if ( writeConcern.getJournal() == null ) {\n\t\t\tjournal = original.getJournal();\n\t\t}\n\t\telse {\n\t\t\tjournal = original.getJournal() || writeConcern.getJournal();\n\t\t}\n\n\t\tif ( wObject instanceof String ) {\n\t\t\treturn new WriteConcern( (String) wObject, wTimeoutMS, fsync, journal );\n\t\t}\n\t\telse {\n\t\t\treturn new WriteConcern( (int) wObject, wTimeoutMS, fsync, journal );\n\t\t}\n\t}",
"public AsciiTable setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static <T> int indexOf(T[] array, T element) {\n\t\tfor ( int i = 0; i < array.length; i++ ) {\n\t\t\tif ( array[i].equals( element ) ) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}",
"public AsciiTable setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"static Style get(final GridParam params) {\n final StyleBuilder builder = new StyleBuilder();\n\n final Symbolizer pointSymbolizer = crossSymbolizer(\"shape://plus\", builder, CROSS_SIZE,\n params.gridColor);\n final Style style = builder.createStyle(pointSymbolizer);\n final List<Symbolizer> symbolizers = style.featureTypeStyles().get(0).rules().get(0).symbolizers();\n\n if (params.haloRadius > 0.0) {\n Symbolizer halo = crossSymbolizer(\"cross\", builder, CROSS_SIZE + params.haloRadius * 2.0,\n params.haloColor);\n symbolizers.add(0, halo);\n }\n\n return style;\n }",
"private boolean parseRemoteDomainControllerAttributes_1_5(final XMLExtendedStreamReader reader, final ModelNode address,\n final List<ModelNode> list, boolean allowDiscoveryOptions) throws XMLStreamException {\n\n final ModelNode update = new ModelNode();\n update.get(OP_ADDR).set(address);\n update.get(OP).set(RemoteDomainControllerAddHandler.OPERATION_NAME);\n\n // Handle attributes\n AdminOnlyDomainConfigPolicy adminOnlyPolicy = AdminOnlyDomainConfigPolicy.DEFAULT;\n boolean requireDiscoveryOptions = false;\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n if (!isNoNamespaceAttribute(reader, i)) {\n throw unexpectedAttribute(reader, i);\n } else {\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n switch (attribute) {\n case HOST: {\n DomainControllerWriteAttributeHandler.HOST.parseAndSetParameter(value, update, reader);\n break;\n }\n case PORT: {\n DomainControllerWriteAttributeHandler.PORT.parseAndSetParameter(value, update, reader);\n break;\n }\n case SECURITY_REALM: {\n DomainControllerWriteAttributeHandler.SECURITY_REALM.parseAndSetParameter(value, update, reader);\n break;\n }\n case USERNAME: {\n DomainControllerWriteAttributeHandler.USERNAME.parseAndSetParameter(value, update, reader);\n break;\n }\n case ADMIN_ONLY_POLICY: {\n DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.parseAndSetParameter(value, update, reader);\n ModelNode nodeValue = update.get(DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.getName());\n if (nodeValue.getType() != ModelType.EXPRESSION) {\n adminOnlyPolicy = AdminOnlyDomainConfigPolicy.getPolicy(nodeValue.asString());\n }\n break;\n }\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n }\n\n if (!update.hasDefined(DomainControllerWriteAttributeHandler.HOST.getName())) {\n if (allowDiscoveryOptions) {\n requireDiscoveryOptions = isRequireDiscoveryOptions(adminOnlyPolicy);\n } else {\n throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.HOST.getLocalName()));\n }\n }\n if (!update.hasDefined(DomainControllerWriteAttributeHandler.PORT.getName())) {\n if (allowDiscoveryOptions) {\n requireDiscoveryOptions = requireDiscoveryOptions || isRequireDiscoveryOptions(adminOnlyPolicy);\n } else {\n throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.PORT.getLocalName()));\n }\n }\n\n list.add(update);\n return requireDiscoveryOptions;\n }",
"public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable, long maxWaitTime, TimeUnit unit) {\n \tCollection<MemberResponse<T>> result = new ArrayList<MemberResponse<T>>(members.size());\n \t\n \tMap<Member, Future<T>> resultFutures = execSvc.submitToMembers(callable, members);\n \tfor(Entry<Member, Future<T>> futureEntry : resultFutures.entrySet()) {\n \t\tFuture<T> future = futureEntry.getValue();\n \t\tMember member = futureEntry.getKey();\n \t\t\n \t\ttry {\n if(maxWaitTime > 0) {\n \tresult.add(new MemberResponse<T>(member, future.get(maxWaitTime, unit)));\n } else {\n \tresult.add(new MemberResponse<T>(member, future.get()));\n } \n //ignore exceptions... return what you can\n } catch (InterruptedException e) {\n \tThread.currentThread().interrupt(); //restore interrupted status and return what we have\n \treturn result;\n } catch (MemberLeftException e) {\n \tlog.warn(\"Member {} left while trying to get a distributed callable result\", member);\n } catch (ExecutionException e) {\n \tif(e.getCause() instanceof InterruptedException) {\n \t //restore interrupted state and return\n \t Thread.currentThread().interrupt();\n \t return result;\n \t} else {\n \t log.warn(\"Unable to execute callable on \"+member+\". There was an error.\", e);\n \t}\n } catch (TimeoutException e) {\n \tlog.error(\"Unable to execute task on \"+member+\" within 10 seconds.\");\n } catch (RuntimeException e) {\n \tlog.error(\"Unable to execute task on \"+member+\". An unexpected error occurred.\", e);\n }\n \t}\n \n return result;\n }"
] |
domain.xml | [
"public static ExtensibleConfigurationPersister createDomainXmlConfigurationPersister(final ConfigurationFile file, ExecutorService executorService, ExtensionRegistry extensionRegistry, final HostControllerEnvironment environment) {\n DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry);\n\n boolean suppressLoad = false;\n ConfigurationFile.InteractionPolicy policy = file.getInteractionPolicy();\n final boolean isReloaded = environment.getRunningModeControl().isReloaded();\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW && (file.getBootFile().exists() && file.getBootFile().length() != 0))) {\n throw HostControllerLogger.ROOT_LOGGER.cannotOverwriteDomainXmlWithEmpty(file.getBootFile().getName());\n }\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW || policy == ConfigurationFile.InteractionPolicy.DISCARD)) {\n suppressLoad = true;\n }\n\n BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), \"domain\"), domainXml, domainXml, suppressLoad);\n for (Namespace namespace : Namespace.domainValues()) {\n if (!namespace.equals(Namespace.CURRENT)) {\n persister.registerAdditionalRootElement(new QName(namespace.getUriString(), \"domain\"), domainXml);\n }\n }\n extensionRegistry.setWriterRegistry(persister);\n return persister;\n }"
] | [
"public static netbridge_vlan_binding[] get(nitro_service service, String name) throws Exception{\n\t\tnetbridge_vlan_binding obj = new netbridge_vlan_binding();\n\t\tobj.set_name(name);\n\t\tnetbridge_vlan_binding response[] = (netbridge_vlan_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"protected Collection provideStateManagers(Collection pojos)\r\n {\r\n \tPersistenceCapable pc;\r\n \tint [] fieldNums;\r\n \tIterator iter = pojos.iterator();\r\n \tCollection result = new ArrayList();\r\n \t\r\n \twhile (iter.hasNext())\r\n \t{\r\n \t\t// obtain a StateManager\r\n \t\tpc = (PersistenceCapable) iter.next();\r\n \t\tIdentity oid = new Identity(pc, broker);\r\n \t\tStateManagerInternal smi = pmi.getStateManager(oid, pc.getClass()); \r\n \t\t\r\n \t\t// fetch attributes into StateManager\r\n\t\t\tJDOClass jdoClass = Helper.getJDOClass(pc.getClass());\r\n\t\t\tfieldNums = jdoClass.getManagedFieldNumbers();\r\n\r\n\t\t\tFieldManager fm = new OjbFieldManager(pc, broker);\r\n\t\t\tsmi.replaceFields(fieldNums, fm);\r\n\t\t\tsmi.retrieve();\r\n\t\t\t\r\n\t\t\t// get JDO PersistencecCapable instance from SM and add it to result collection\r\n\t\t\tObject instance = smi.getObject();\r\n\t\t\tresult.add(instance);\r\n \t}\r\n \treturn result; \r\n\t}",
"public static void writeFully(ByteBuffer buffer, WritableByteChannel channel) throws IOException {\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\n }",
"public static ComplexNumber Pow(ComplexNumber z1, double n) {\r\n\r\n double norm = Math.pow(z1.getMagnitude(), n);\r\n double angle = 360 - Math.abs(Math.toDegrees(Math.atan(z1.imaginary / z1.real)));\r\n\r\n double common = n * angle;\r\n\r\n double r = norm * Math.cos(Math.toRadians(common));\r\n double i = norm * Math.sin(Math.toRadians(common));\r\n\r\n return new ComplexNumber(r, i);\r\n\r\n }",
"private String getValueFromProp(final String propValue) {\n\n String value = propValue;\n // remove quotes\n value = value.trim();\n if ((value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\")) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.substring(1, value.length() - 1);\n }\n return value;\n }",
"public ActivityCodeValue addValue(Integer uniqueID, String name, String description)\n {\n ActivityCodeValue value = new ActivityCodeValue(this, uniqueID, name, description);\n m_values.add(value);\n return value;\n }",
"public static boolean canParseColor(final String colorString) {\n try {\n return ColorParser.toColor(colorString) != null;\n } catch (Exception exc) {\n return false;\n }\n }",
"public static FilePath createAndGetTempDir(final FilePath ws) throws IOException, InterruptedException {\n // The token that combines the project name and unique number to create unique workspace directory.\n String workspaceList = System.getProperty(\"hudson.slaves.WorkspaceList\");\n return ws.act(new MasterToSlaveCallable<FilePath, IOException>() {\n @Override\n public FilePath call() {\n final FilePath tempDir = ws.sibling(ws.getName() + Objects.toString(workspaceList, \"@\") + \"tmp\").child(\"artifactory\");\n File tempDirFile = new File(tempDir.getRemote());\n tempDirFile.mkdirs();\n tempDirFile.deleteOnExit();\n return tempDir;\n }\n });\n }",
"public static int getSystemPort(String portIdentifier) {\n int defaultPort = 0;\n\n if (portIdentifier.compareTo(Constants.SYS_API_PORT) == 0) {\n defaultPort = Constants.DEFAULT_API_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_DB_PORT) == 0) {\n defaultPort = Constants.DEFAULT_DB_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_FWD_PORT) == 0) {\n defaultPort = Constants.DEFAULT_FWD_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_HTTP_PORT) == 0) {\n defaultPort = Constants.DEFAULT_HTTP_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_HTTPS_PORT) == 0) {\n defaultPort = Constants.DEFAULT_HTTPS_PORT;\n } else {\n return defaultPort;\n }\n\n String portStr = System.getenv(portIdentifier);\n return (portStr == null || portStr.isEmpty()) ? defaultPort : Integer.valueOf(portStr);\n }"
] |
Convert a URL Encoded name back to the original form.
@param name the name to URL urlDecode.
@param encoding the string encoding to be used (i.e. UTF-8)
@return the name in original form.
@throws UnsupportedEncodingException if the encoding is not supported. | [
"String urlDecode(String name, String encoding) throws UnsupportedEncodingException {\n return URLDecoder.decode(name, encoding);\n }"
] | [
"private void renderThumbnail(Video video) {\n Picasso.with(getContext()).cancelRequest(thumbnail);\n Picasso.with(getContext())\n .load(video.getThumbnail())\n .placeholder(R.drawable.placeholder)\n .into(thumbnail);\n }",
"public static double blackScholesDigitalOptionValue(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 1.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate analytic value\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn valueAnalytic;\n\t\t}\n\t}",
"public boolean hasMoreElements()\r\n {\r\n try\r\n {\r\n if (!hasCalledCheck)\r\n {\r\n hasCalledCheck = true;\r\n hasNext = resultSetAndStatment.m_rs.next();\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n LoggerFactory.getDefaultLogger().error(e);\r\n //releaseDbResources();\r\n hasNext = false;\r\n }\r\n finally\r\n {\r\n if(!hasNext)\r\n {\r\n releaseDbResources();\r\n }\r\n }\r\n return hasNext;\r\n }",
"private static BoxRetentionPolicyAssignment.Info createAssignment(BoxAPIConnection api, String policyID,\r\n JsonObject assignTo, JsonArray filter) {\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL());\r\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\r\n\r\n JsonObject requestJSON = new JsonObject()\r\n .add(\"policy_id\", policyID)\r\n .add(\"assign_to\", assignTo);\r\n\r\n if (filter != null) {\r\n requestJSON.add(\"filter_fields\", filter);\r\n }\r\n\r\n request.setBody(requestJSON.toString());\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n BoxRetentionPolicyAssignment createdAssignment\r\n = new BoxRetentionPolicyAssignment(api, responseJSON.get(\"id\").asString());\r\n return createdAssignment.new Info(responseJSON);\r\n }",
"public String calculateCacheKey(String sql, int[] columnIndexes) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\tfor (int i=0; i < columnIndexes.length; i++){\r\n\t\t\ttmp.append(columnIndexes[i]);\r\n\t\t\ttmp.append(\"CI,\");\r\n\t\t}\r\n\t\treturn tmp.toString();\r\n\t}",
"public CollectionRequest<Team> findByOrganization(String organization) {\n \n String path = String.format(\"/organizations/%s/teams\", organization);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"private String getRequestBody(ServletRequest request) throws IOException {\n\n final StringBuilder sb = new StringBuilder();\n\n String line = request.getReader().readLine();\n while (null != line) {\n sb.append(line);\n line = request.getReader().readLine();\n }\n\n return sb.toString();\n }",
"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 }",
"@Override\n public void close() {\n // unregister MBeans\n if(stats != null) {\n try {\n if(this.jmxEnabled)\n JmxUtils.unregisterMbean(getAggregateMetricName());\n } catch(Exception e) {}\n stats.close();\n }\n factory.close();\n queuedPool.close();\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.