query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Tests whether the two field descriptors are equal, i.e. have same name, same column and same jdbc-type. @param first The first field @param second The second field @return <code>true</code> if they are equal
[ "private boolean isEqual(FieldDescriptorDef first, FieldDescriptorDef second)\r\n {\r\n return first.getName().equals(second.getName()) &&\r\n first.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN).equals(second.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN)) &&\r\n first.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE).equals(second.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n }" ]
[ "public static Chart getMSDLineWithActiveTransportModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double velocity) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = Math.pow(velocity*(i*timelag), 2) + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + (v*t)^2\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "@Override\n public void init(NamedList args) {\n\n Object regex = args.remove(PARAM_REGEX);\n if (null == regex) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REGEX);\n }\n try {\n m_regex = Pattern.compile(regex.toString());\n } catch (PatternSyntaxException e) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Invalid regex: \" + regex, e);\n }\n\n Object replacement = args.remove(PARAM_REPLACEMENT);\n if (null == replacement) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REPLACEMENT);\n }\n m_replacement = replacement.toString();\n\n Object source = args.remove(PARAM_SOURCE);\n if (null == source) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_SOURCE);\n }\n m_source = source.toString();\n\n Object target = args.remove(PARAM_TARGET);\n if (null == target) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_TARGET);\n }\n m_target = target.toString();\n\n }", "private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) {\n List<String> sourceFileNames = new ArrayList<String>();\n for(String fileName: fileNames) {\n String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL);\n if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) {\n sourceFileNames.add(fileName);\n }\n }\n return sourceFileNames;\n }", "public static void main(String[] args) {\n if (args.length < 2) { // NOSONAR\n LOGGER.error(\"There must be at least two arguments\");\n return;\n }\n int lastIndex = args.length - 1;\n AllureReportGenerator reportGenerator = new AllureReportGenerator(\n getFiles(Arrays.copyOf(args, lastIndex))\n );\n reportGenerator.generate(new File(args[lastIndex]));\n }", "public Set<Class<?>> getPrevented() {\n if (this.prevent == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(this.prevent);\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 responderglobal_responderpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tresponderglobal_responderpolicy_binding obj = new responderglobal_responderpolicy_binding();\n\t\tresponderglobal_responderpolicy_binding response[] = (responderglobal_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void writePredecessors(Project.Tasks.Task xml, Task mpx)\n {\n List<Project.Tasks.Task.PredecessorLink> list = xml.getPredecessorLink();\n\n List<Relation> predecessors = mpx.getPredecessors();\n for (Relation rel : predecessors)\n {\n Integer taskUniqueID = rel.getTargetTask().getUniqueID();\n list.add(writePredecessor(taskUniqueID, rel.getType(), rel.getLag()));\n m_eventManager.fireRelationWrittenEvent(rel);\n }\n }", "private void writeImages() {\n\t\tfor (ValueMap gv : this.valueMaps) {\n\t\t\tgv.writeImage();\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"map-site-count.csv\"))) {\n\t\t\tout.println(\"Site key,Number of geo items\");\n\t\t\tout.println(\"wikidata total,\" + this.count);\n\t\t\tfor (Entry<String, Integer> entry : this.siteCounts.entrySet()) {\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue());\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}" ]
This method reads a four byte integer from the input stream. @param is the input stream @return byte value @throws IOException on file read error or EOF
[ "protected int readInt(InputStream is) throws IOException\n {\n byte[] data = new byte[4];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getInt(data, 0));\n }" ]
[ "public FindByIndexOptions useIndex(String designDocument, String indexName) {\r\n assertNotNull(designDocument, \"designDocument\");\r\n assertNotNull(indexName, \"indexName\");\r\n JsonArray index = new JsonArray();\r\n index.add(new JsonPrimitive(designDocument));\r\n index.add(new JsonPrimitive(indexName));\r\n this.useIndex = index;\r\n return this;\r\n }", "public static dnszone_domain_binding[] get(nitro_service service, String zonename) throws Exception{\n\t\tdnszone_domain_binding obj = new dnszone_domain_binding();\n\t\tobj.set_zonename(zonename);\n\t\tdnszone_domain_binding response[] = (dnszone_domain_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private String formatCurrency(Number value)\n {\n return (value == null ? null : m_formats.getCurrencyFormat().format(value));\n }", "public static Properties loadProps(String filename) {\n Properties props = new Properties();\n FileInputStream fis = null;\n try {\n fis = new FileInputStream(filename);\n props.load(fis);\n return props;\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n } finally {\n Closer.closeQuietly(fis);\n }\n\n }", "public static streamidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tstreamidentifier_stats obj = new streamidentifier_stats();\n\t\tobj.set_name(name);\n\t\tstreamidentifier_stats response = (streamidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public static vpnglobal_appcontroller_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_appcontroller_binding obj = new vpnglobal_appcontroller_binding();\n\t\tvpnglobal_appcontroller_binding response[] = (vpnglobal_appcontroller_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_response add(nitro_service client, gslbsite resource) throws Exception {\n\t\tgslbsite addresource = new gslbsite();\n\t\taddresource.sitename = resource.sitename;\n\t\taddresource.sitetype = resource.sitetype;\n\t\taddresource.siteipaddress = resource.siteipaddress;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.metricexchange = resource.metricexchange;\n\t\taddresource.nwmetricexchange = resource.nwmetricexchange;\n\t\taddresource.sessionexchange = resource.sessionexchange;\n\t\taddresource.triggermonitor = resource.triggermonitor;\n\t\taddresource.parentsite = resource.parentsite;\n\t\treturn addresource.add_resource(client);\n\t}", "private String filterTag(String tag) {\r\n\t AttributeValues answerAV = TagSet.getTagSet().fromTag(tag);\r\n\t answerAV.removeNonlexicalAttributes();\r\n\t return TagSet.getTagSet().toTag(answerAV);\r\n }", "public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }" ]
Will spawn a thread for each type in rootEntities, they will all re-join on endAllSignal when finished. @param backend @throws InterruptedException if interrupted while waiting for endAllSignal.
[ "private void doBatchWork(BatchBackend backend) throws InterruptedException {\n\t\tExecutorService executor = Executors.newFixedThreadPool( typesToIndexInParallel, \"BatchIndexingWorkspace\" );\n\t\tfor ( IndexedTypeIdentifier indexedTypeIdentifier : rootIndexedTypes ) {\n\t\t\texecutor.execute( new BatchIndexingWorkspace( gridDialect, searchFactoryImplementor, sessionFactory, indexedTypeIdentifier,\n\t\t\t\t\tcacheMode, endAllSignal, monitor, backend, tenantId ) );\n\t\t}\n\t\texecutor.shutdown();\n\t\tendAllSignal.await(); // waits for the executor to finish\n\t}" ]
[ "public static int Mod(int x, int m) {\r\n if (m < 0) m = -m;\r\n int r = x % m;\r\n return r < 0 ? r + m : r;\r\n }", "private void validationRelations(Task task)\n {\n List<Relation> predecessors = task.getPredecessors();\n if (!predecessors.isEmpty())\n {\n ArrayList<Relation> invalid = new ArrayList<Relation>();\n for (Relation relation : predecessors)\n {\n Task sourceTask = relation.getSourceTask();\n Task targetTask = relation.getTargetTask();\n\n String sourceOutlineNumber = sourceTask.getOutlineNumber();\n String targetOutlineNumber = targetTask.getOutlineNumber();\n\n if (sourceOutlineNumber != null && targetOutlineNumber != null && sourceOutlineNumber.startsWith(targetOutlineNumber + '.'))\n {\n invalid.add(relation);\n }\n }\n\n for (Relation relation : invalid)\n {\n relation.getSourceTask().removePredecessor(relation.getTargetTask(), relation.getType(), relation.getLag());\n }\n }\n }", "public void fireCalendarWrittenEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarWritten(calendar);\n }\n }\n }", "public void deleteServerGroup(int id) {\n try {\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_ID + \" = \" + id + \";\");\n\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = \" + id);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "private boolean checkConfig(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n return \"true\".equalsIgnoreCase((String)config.getProperties().get(\"collector.lifecycleEvent\"));\n }", "private void registerPerformanceMonitor(String beanName,\n BeanDefinitionRegistry registry) {\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n if (!registry.containsBeanDefinition(perfMonitorName)) {\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class);\n registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition());\n }\n }", "public final List<MtasSolrStatus> checkForExceptions() {\n List<MtasSolrStatus> statusWithException = null;\n for (MtasSolrStatus item : data) {\n if (item.checkResponseForException()) {\n if (statusWithException == null) {\n statusWithException = new ArrayList<>();\n }\n statusWithException.add(item);\n }\n }\n return statusWithException;\n }", "public float getNormalX(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 * SIZEOF_FLOAT);\n }", "protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }" ]
Converts the given dislect to a human-readable datasource type.
[ "public static String resolveDataSourceTypeFromDialect(String dialect)\n {\n if (StringUtils.contains(dialect, \"Oracle\"))\n {\n return \"Oracle\";\n }\n else if (StringUtils.contains(dialect, \"MySQL\"))\n {\n return \"MySQL\";\n }\n else if (StringUtils.contains(dialect, \"DB2390Dialect\"))\n {\n return \"DB2/390\";\n }\n else if (StringUtils.contains(dialect, \"DB2400Dialect\"))\n {\n return \"DB2/400\";\n }\n else if (StringUtils.contains(dialect, \"DB2\"))\n {\n return \"DB2\";\n }\n else if (StringUtils.contains(dialect, \"Ingres\"))\n {\n return \"Ingres\";\n }\n else if (StringUtils.contains(dialect, \"Derby\"))\n {\n return \"Derby\";\n }\n else if (StringUtils.contains(dialect, \"Pointbase\"))\n {\n return \"Pointbase\";\n }\n else if (StringUtils.contains(dialect, \"Postgres\"))\n {\n return \"Postgres\";\n }\n else if (StringUtils.contains(dialect, \"SQLServer\"))\n {\n return \"SQLServer\";\n }\n else if (StringUtils.contains(dialect, \"Sybase\"))\n {\n return \"Sybase\";\n }\n else if (StringUtils.contains(dialect, \"HSQLDialect\"))\n {\n return \"HyperSQL\";\n }\n else if (StringUtils.contains(dialect, \"H2Dialect\"))\n {\n return \"H2\";\n }\n \n return dialect;\n\n }" ]
[ "public void createTag(final String tagUrl, final String commitMessage)\n throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new SVNCreateTagCallable(tagUrl, commitMessage, getLocation(), getSvnAuthenticationProvider(build),\n buildListener));\n }", "public boolean evaluate(Object feature) {\n\t\t// Checks to ensure that the attribute has been set\n\t\tif (attribute == null) {\n\t\t\treturn false;\n\t\t}\n\t\t// Note that this converts the attribute to a string\n\t\t// for comparison. Unlike the math or geometry filters, which\n\t\t// require specific types to function correctly, this filter\n\t\t// using the mandatory string representation in Java\n\t\t// Of course, this does not guarantee a meaningful result, but it\n\t\t// does guarantee a valid result.\n\t\t// LOGGER.finest(\"pattern: \" + pattern);\n\t\t// LOGGER.finest(\"string: \" + attribute.getValue(feature));\n\t\t// return attribute.getValue(feature).toString().matches(pattern);\n\t\tObject value = attribute.evaluate(feature);\n\n\t\tif (null == value) {\n\t\t\treturn false;\n\t\t}\n\n\t\tMatcher matcher = getMatcher();\n\t\tmatcher.reset(value.toString());\n\n\t\treturn matcher.matches();\n\t}", "public ThumborUrlBuilder resize(int width, int height) {\n if (width < 0 && width != ORIGINAL_SIZE) {\n throw new IllegalArgumentException(\"Width must be a positive number.\");\n }\n if (height < 0 && height != ORIGINAL_SIZE) {\n throw new IllegalArgumentException(\"Height must be a positive number.\");\n }\n if (width == 0 && height == 0) {\n throw new IllegalArgumentException(\"Both width and height must not be zero.\");\n }\n hasResize = true;\n resizeWidth = width;\n resizeHeight = height;\n return this;\n }", "public static vpnglobal_intranetip_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_intranetip_binding obj = new vpnglobal_intranetip_binding();\n\t\tvpnglobal_intranetip_binding response[] = (vpnglobal_intranetip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private Optional<? extends SoyMsgBundle> mergeMsgBundles(final Locale locale, final List<SoyMsgBundle> soyMsgBundles) {\n if (soyMsgBundles.isEmpty()) {\n return Optional.absent();\n }\n\n final List<SoyMsg> msgs = Lists.newArrayList();\n for (final SoyMsgBundle smb : soyMsgBundles) {\n for (final Iterator<SoyMsg> it = smb.iterator(); it.hasNext();) {\n msgs.add(it.next());\n }\n }\n\n return Optional.of(new SoyMsgBundleImpl(locale.toString(), msgs));\n }", "public static Variable upcastToGeneratedBuilder(\n SourceBuilder code, Datatype datatype, String builder) {\n return code.scope().computeIfAbsent(Declaration.UPCAST, () -> {\n Variable base = new Variable(\"base\");\n code.addLine(UPCAST_COMMENT)\n .addLine(\"%s %s = %s;\", datatype.getGeneratedBuilder(), base, builder);\n return base;\n });\n }", "public void synchronizeTaskIDToHierarchy()\n {\n clear();\n\n int currentID = (getByID(Integer.valueOf(0)) == null ? 1 : 0);\n for (Task task : m_projectFile.getChildTasks())\n {\n task.setID(Integer.valueOf(currentID++));\n add(task);\n currentID = synchroizeTaskIDToHierarchy(task, currentID);\n }\n }", "public static void addTTLIndex(DBCollection collection, String field, int ttl) {\n if (ttl <= 0) {\n throw new IllegalArgumentException(\"TTL must be positive\");\n }\n collection.createIndex(new BasicDBObject(field, 1), new BasicDBObject(\"expireAfterSeconds\", ttl));\n }", "public void forAllReferenceDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getReferences(); it.hasNext(); )\r\n {\r\n _curReferenceDef = (ReferenceDescriptorDef)it.next();\r\n // first we check whether it is an inherited anonymous reference\r\n if (_curReferenceDef.isAnonymous() && (_curReferenceDef.getOwner() != _curClassDef))\r\n {\r\n continue;\r\n }\r\n if (!isFeatureIgnored(LEVEL_REFERENCE) &&\r\n !_curReferenceDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curReferenceDef = null;\r\n }" ]
Returns true if the specified class node is a trait. @param cNode a class node to test @return true if the classnode represents a trait
[ "public static boolean isTrait(final ClassNode cNode) {\n return cNode!=null\n && ((cNode.isInterface() && !cNode.getAnnotations(TRAIT_CLASSNODE).isEmpty())\n || isAnnotatedWithTrait(cNode));\n }" ]
[ "public static void main(String[] args) {\n\t\ttry {\n\t\t\tJarRunner runner = new JarRunner(args);\n\t\t\trunner.runIfConfigured();\n\t\t} catch (NumberFormatException e) {\n\t\t\tSystem.err.println(\"Could not parse number \" + e.getMessage());\n\t\t\tSystem.exit(1);\n\t\t} catch (RuntimeException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\tSystem.exit(1);\n\t\t}\n\t}", "public static onlinkipv6prefix[] get(nitro_service service) throws Exception{\n\t\tonlinkipv6prefix obj = new onlinkipv6prefix();\n\t\tonlinkipv6prefix[] response = (onlinkipv6prefix[])obj.get_resources(service);\n\t\treturn response;\n\t}", "protected void checkJobType(final String jobName, final Class<?> jobType) {\n if (jobName == null) {\n throw new IllegalArgumentException(\"jobName must not be null\");\n }\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n if (!(Runnable.class.isAssignableFrom(jobType)) \n && !(Callable.class.isAssignableFrom(jobType))) {\n throw new IllegalArgumentException(\n \"jobType must implement either Runnable or Callable: \" + jobType);\n }\n }", "private void addSuperClasses(Integer directSuperClass,\n\t\t\tClassRecord subClassRecord) {\n\t\tif (subClassRecord.superClasses.contains(directSuperClass)) {\n\t\t\treturn;\n\t\t}\n\t\tsubClassRecord.superClasses.add(directSuperClass);\n\t\tClassRecord superClassRecord = getClassRecord(directSuperClass);\n\t\tif (superClassRecord == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (Integer superClass : superClassRecord.directSuperClasses) {\n\t\t\taddSuperClasses(superClass, subClassRecord);\n\t\t}\n\t}", "static String encodeUriComponent(String source, String encoding, Type type) throws UnsupportedEncodingException {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\tAssert.hasLength(encoding, \"Encoding must not be empty\");\n\t\tbyte[] bytes = encodeBytes(source.getBytes(encoding), type);\n\t\treturn new String(bytes, \"US-ASCII\");\n\t}", "public void alias( Object ...args ) {\n if( args.length % 2 == 1 )\n throw new RuntimeException(\"Even number of arguments expected\");\n\n for (int i = 0; i < args.length; i += 2) {\n aliasGeneric( args[i], (String)args[i+1]);\n }\n }", "public BoundRequestBuilder createRequest()\n throws HttpRequestCreateException {\n BoundRequestBuilder builder = null;\n\n getLogger().debug(\"AHC completeUrl \" + requestUrl);\n\n try {\n\n switch (httpMethod) {\n case GET:\n builder = client.prepareGet(requestUrl);\n break;\n case POST:\n builder = client.preparePost(requestUrl);\n break;\n case PUT:\n builder = client.preparePut(requestUrl);\n break;\n case HEAD:\n builder = client.prepareHead(requestUrl);\n break;\n case OPTIONS:\n builder = client.prepareOptions(requestUrl);\n break;\n case DELETE:\n builder = client.prepareDelete(requestUrl);\n break;\n default:\n break;\n }\n\n PcHttpUtils.addHeaders(builder, this.httpHeaderMap);\n if (!Strings.isNullOrEmpty(postData)) {\n builder.setBody(postData);\n String charset = \"\";\n if (null!=this.httpHeaderMap) {\n charset = this.httpHeaderMap.get(\"charset\");\n }\n if(!Strings.isNullOrEmpty(charset)) {\n builder.setBodyEncoding(charset);\n }\n }\n\n } catch (Exception t) {\n throw new HttpRequestCreateException(\n \"Error in creating request in Httpworker. \"\n + \" If BoundRequestBuilder is null. Then fail to create.\",\n t);\n }\n\n return builder;\n\n }", "public static Set<String> getRoundingNames(String... providers) {\n return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryRoundingsSpi loaded, query functionality is not available.\"))\n .getRoundingNames(providers);\n }", "protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) {\n if (text.indexOf(':') == -1) {\n text = text.replace(\" \", \"\");\n int numdigits = 0;\n int lastdigit = 0;\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (Character.isDigit(c)) {\n numdigits++;\n lastdigit = i;\n }\n }\n if (numdigits == 1 || numdigits == 2) {\n // insert :00\n int colon = lastdigit + 1;\n text = text.substring(0, colon) + \":00\" + text.substring(colon);\n }\n else if (numdigits > 2) {\n // insert :\n int colon = lastdigit - 1;\n text = text.substring(0, colon) + \":\" + text.substring(colon);\n }\n return parseUsingFallbacks(text, timeFormat);\n }\n else {\n return null;\n }\n }" ]
Ask the specified player for a Folder menu for exploring its raw filesystem. This is a request for unanalyzed items, so we do a typed menu request. @param slotReference the player and slot for which the menu is desired @param sortOrder the order in which responses should be sorted, 0 for default, see Section 6.11.1 of the <a href="https://github.com/Deep-Symmetry/dysentery/blob/master/doc/Analysis.pdf">Packet Analysis document</a> for details @param folderId identifies the folder whose contents should be listed, use -1 to get the root folder @return the entries in the folder menu @throws Exception if there is a problem obtaining the menu
[ "public List<Message> requestFolderMenuFrom(final SlotReference slotReference, final int sortOrder, final int folderId)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n logger.debug(\"Requesting Key menu.\");\n Message response = client.menuRequestTyped(Message.KnownType.FOLDER_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,\n CdjStatus.TrackType.UNANALYZED, new NumberField(sortOrder), new NumberField(folderId), new NumberField(0xffffff));\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.UNANALYZED, response);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock player for menu operations.\");\n }\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting folder menu\");\n }" ]
[ "public static Boolean parseBoolean(String value) throws ParseException\n {\n Boolean result = null;\n Integer number = parseInteger(value);\n if (number != null)\n {\n result = number.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;\n }\n\n return result;\n }", "public PhotoList<Photo> getPopularPhotos(Date date, StatsSort sort, int perPage, int page) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_POPULAR_PHOTOS);\n if (date != null) {\n parameters.put(\"date\", String.valueOf(date.getTime() / 1000L));\n }\n if (sort != null) {\n parameters.put(\"sort\", sort.name());\n }\n addPaginationParameters(parameters, perPage, page);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n return parsePopularPhotos(response);\n }", "public void addFile(File file) {\n String name = \"file\";\n files.put(normalizeDuplicateName(name), file);\n }", "private List<String> parseParams(String param) {\n\t\tAssert.hasText(param, \"param must not be empty nor null\");\n\t\tList<String> paramsToUse = new ArrayList<>();\n\t\tMatcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN.matcher(param);\n\t\tint start = 0;\n\t\twhile (regexMatcher.find()) {\n\t\t\tString p = removeQuoting(param.substring(start, regexMatcher.start()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t\tstart = regexMatcher.start();\n\t\t}\n\t\tif (param != null && param.length() > 0) {\n\t\t\tString p = removeQuoting(param.substring(start, param.length()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t}\n\t\treturn paramsToUse;\n\t}", "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 }", "private void addReverse(final File[] files) {\n for (int i = files.length - 1; i >= 0; --i) {\n stack.add(files[i]);\n }\n }", "public Point3d[] getVertices() {\n Point3d[] vtxs = new Point3d[numVertices];\n for (int i = 0; i < numVertices; i++) {\n vtxs[i] = pointBuffer[vertexPointIndices[i]].pnt;\n }\n return vtxs;\n }", "public static final String getUnicodeString(byte[] data, int offset)\n {\n int length = getUnicodeStringLengthInBytes(data, offset);\n return length == 0 ? \"\" : new String(data, offset, length, CharsetHelper.UTF16LE);\n }", "public ItemRequest<Task> removeFollowers(String task) {\n \n String path = String.format(\"/tasks/%s/removeFollowers\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }" ]
Stops this progress bar.
[ "public ProgressBar stop() {\n target.kill();\n try {\n thread.join();\n target.consoleStream.print(\"\\n\");\n target.consoleStream.flush();\n }\n catch (InterruptedException ex) { }\n return this;\n }" ]
[ "public final PJsonObject toJSON() {\n try {\n JSONObject json = new JSONObject();\n for (String key: this.obj.keySet()) {\n Object opt = opt(key);\n if (opt instanceof PYamlObject) {\n opt = ((PYamlObject) opt).toJSON().getInternalObj();\n } else if (opt instanceof PYamlArray) {\n opt = ((PYamlArray) opt).toJSON().getInternalArray();\n }\n json.put(key, opt);\n }\n return new PJsonObject(json, this.getContextName());\n } catch (Throwable e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }", "private void updateDetail(TrackMetadataUpdate update, WaveformDetail detail) {\n detailHotCache.put(DeckReference.getDeckReference(update.player, 0), detail); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n detailHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), detail);\n }\n }\n }\n deliverWaveformDetailUpdate(update.player, detail);\n }", "public static ResourceBundle getCurrentResourceBundle(String locale) {\n\t\ttry {\n\t\t\tif (null != locale && !locale.isEmpty()) {\n\t\t\t\treturn getCurrentResourceBundle(LocaleUtils.toLocale(locale));\n\t\t\t}\n\t\t} catch (IllegalArgumentException ex) {\n\t\t\t// do nothing\n\t\t}\n\t\treturn getCurrentResourceBundle((Locale) null);\n\t}", "private String getParentOutlineNumber(String outlineNumber)\n {\n String result;\n int index = outlineNumber.lastIndexOf('.');\n if (index == -1)\n {\n result = \"\";\n }\n else\n {\n result = outlineNumber.substring(0, index);\n }\n return result;\n }", "@SuppressWarnings(\"unchecked\")\n protected String addeDependency(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addDependency(dependency);\n }", "public static final String printPercent(Double value)\n {\n return value == null ? null : Double.toString(value.doubleValue() / 100.0);\n }", "public User findByEmail(String email) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_FIND_BY_EMAIL);\r\n\r\n parameters.put(\"find_email\", email);\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 userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n user.setUsername(XMLUtilities.getChildValue(userElement, \"username\"));\r\n return user;\r\n }", "void addOption(final String value) {\n Assert.checkNotNullParam(\"value\", value);\n synchronized (options) {\n options.add(value);\n }\n }", "public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }" ]
add some validation to see if this miss anything. @return true, if successful @throws ParallelTaskInvalidException the parallel task invalid exception
[ "public boolean validation() throws ParallelTaskInvalidException {\n\n ParallelTask task = new ParallelTask();\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n task = new ParallelTask(requestProtocol, concurrency, httpMeta,\n targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null, responseContext,\n replacementVarMapNodeSpecific,\n replacementVarMap, requestReplacementType, config);\n boolean valid = false;\n\n try {\n valid = task.validateWithFillDefault();\n } catch (ParallelTaskInvalidException e) {\n logger.info(\"task is invalid \" + e);\n }\n\n return valid;\n\n }" ]
[ "public ItemRequest<Task> addFollowers(String task) {\n \n String path = String.format(\"/tasks/%s/addFollowers\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public List<MapRow> read() throws IOException\n {\n List<MapRow> result = new ArrayList<MapRow>();\n int fileCount = m_stream.readInt();\n if (fileCount != 0)\n {\n for (int index = 0; index < fileCount; index++)\n {\n // We use a LinkedHashMap to preserve insertion order in iteration\n // Useful when debugging the file format.\n Map<String, Object> map = new LinkedHashMap<String, Object>();\n readBlock(map);\n result.add(new MapRow(map));\n }\n }\n return result;\n }", "public void add(Map<String, Object> map) throws SQLException {\n if (withinDataSetBatch) {\n if (batchData.size() == 0) {\n batchKeys = map.keySet();\n } else {\n if (!map.keySet().equals(batchKeys)) {\n throw new IllegalArgumentException(\"Inconsistent keys found for batch add!\");\n }\n }\n batchData.add(map);\n return;\n }\n int answer = executeUpdate(buildListQuery(map), new ArrayList<Object>(map.values()));\n if (answer != 1) {\n LOG.warning(\"Should have updated 1 row not \" + answer + \" when trying to add: \" + map);\n }\n }", "private void requestBlock() {\n next = ByteBuffer.allocate(blockSizeBytes);\n long requestTimeout = retryParams.getRequestTimeoutMillisForCurrentAttempt();\n pendingFetch = raw.readObjectAsync(next, filename, fetchPosition, requestTimeout);\n }", "private void writeImages() {\n\t\tfor (ValueMap gv : this.valueMaps) {\n\t\t\tgv.writeImage();\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"map-site-count.csv\"))) {\n\t\t\tout.println(\"Site key,Number of geo items\");\n\t\t\tout.println(\"wikidata total,\" + this.count);\n\t\t\tfor (Entry<String, Integer> entry : this.siteCounts.entrySet()) {\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue());\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public void recordCheckoutQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutQueueLength(null, queueLength);\n recordCheckoutQueueLength(null, queueLength);\n } else {\n this.checkoutQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }", "public boolean isActive(int profileId) {\n boolean active = false;\n PreparedStatement queryStatement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.CLIENT_IS_ACTIVE + \" FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= '-1' \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ? \"\n );\n queryStatement.setInt(1, profileId);\n logger.info(queryStatement.toString());\n ResultSet results = queryStatement.executeQuery();\n if (results.next()) {\n active = results.getBoolean(Constants.CLIENT_IS_ACTIVE);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return active;\n }", "public double nextDouble(double lo, double hi) {\n if (lo < 0) {\n if (nextInt(2) == 0)\n return -nextDouble(0, -lo);\n else\n return nextDouble(0, hi);\n } else {\n return (lo + (hi - lo) * nextDouble());\n }\n }", "public static spilloverpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tspilloverpolicy_stats[] response = (spilloverpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}" ]
Extracts baseline work from the MPP file for a specific baseline. Returns null if no baseline work is present, otherwise returns a list of timephased work items. @param assignment parent assignment @param calendar baseline calendar @param normaliser normaliser associated with this data @param data timephased baseline work data block @param raw flag indicating if this data is to be treated as raw @return timephased work
[ "public TimephasedWorkContainer getBaselineWork(ResourceAssignment assignment, ProjectCalendar calendar, TimephasedWorkNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedWorkContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedWork> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 8; // 8 byte header\n int blockSize = 40;\n double previousCumulativeWorkPerformedInMinutes = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n TimephasedWork work = null;\n\n while (index + blockSize <= data.length)\n {\n double cumulativeWorkInMinutes = (double) ((long) MPPUtility.getDouble(data, index + 20)) / 1000;\n if (!Duration.durationValueEquals(cumulativeWorkInMinutes, previousCumulativeWorkPerformedInMinutes))\n {\n //double unknownWorkThisPeriodInMinutes = ((long) MPPUtility.getDouble(data, index + 0)) / 1000;\n double normalActualWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 8)) / 10;\n double normalRemainingWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 28)) / 10;\n double workThisPeriodInMinutes = cumulativeWorkInMinutes - previousCumulativeWorkPerformedInMinutes;\n double overtimeWorkThisPeriodInMinutes = workThisPeriodInMinutes - (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n double overtimeFactor = overtimeWorkThisPeriodInMinutes / (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n\n double normalWorkPerDayInMinutes = 480;\n double overtimeWorkPerDayInMinutes = normalWorkPerDayInMinutes * overtimeFactor;\n\n work = new TimephasedWork();\n work.setFinish(MPPUtility.getTimestampFromTenths(data, index + 16));\n work.setStart(blockStartDate);\n work.setTotalAmount(Duration.getInstance(workThisPeriodInMinutes, TimeUnit.MINUTES));\n work.setAmountPerDay(Duration.getInstance(normalWorkPerDayInMinutes + overtimeWorkPerDayInMinutes, TimeUnit.MINUTES));\n\n previousCumulativeWorkPerformedInMinutes = cumulativeWorkInMinutes;\n\n if (list == null)\n {\n list = new LinkedList<TimephasedWork>();\n }\n list.add(work);\n //System.out.println(work);\n }\n blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n }\n\n if (list != null)\n {\n if (work != null)\n {\n work.setFinish(assignment.getFinish());\n }\n result = new DefaultTimephasedWorkContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }" ]
[ "private void processProperties() {\n state = true;\n try {\n exporterServiceFilter = getFilter(exporterServiceFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_EXPORTERSERVICE_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n\n try {\n exportDeclarationFilter = getFilter(exportDeclarationFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_EXPORTDECLARATION_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n }", "public static Object instantiate(Class clazz) throws InstantiationException\r\n {\r\n Object result = null;\r\n try\r\n {\r\n result = ClassHelper.newInstance(clazz);\r\n }\r\n catch(IllegalAccessException e)\r\n {\r\n try\r\n {\r\n result = ClassHelper.newInstance(clazz, true);\r\n }\r\n catch(Exception e1)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (clazz != null ? clazz.getName() : \"null\")\r\n + \"', message was: \" + e1.getMessage() + \")\", e1);\r\n }\r\n }\r\n return result;\r\n }", "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 Trajectory addPositionNoise(Trajectory t, double sd){\n\t\tCentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();\n\t\tTrajectory newt = new Trajectory(t.getDimension());\n\t\t\n\t\tfor(int i = 0; i < t.size(); i++){\n\t\t\tnewt.add(t.get(i));\n\t\t\tfor(int j = 1; j <= t.getDimension(); j++){\n\t\t\t\tswitch (j) {\n\t\t\t\tcase 1:\n\t\t\t\t\tnewt.get(i).setX(newt.get(i).x + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tnewt.get(i).setY(newt.get(i).y + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tnewt.get(i).setZ(newt.get(i).z + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn newt;\n\t\t\n\t}", "public static List<File> listFilesByRegex(String regex, File... directories) {\n return listFiles(directories,\n new RegexFileFilter(regex),\n CanReadFileFilter.CAN_READ);\n }", "public static HashMap<Integer, List<Integer>>\n getBalancedNumberOfPrimaryPartitionsPerNode(final Cluster nextCandidateCluster,\n Map<Integer, Integer> targetPartitionsPerZone) {\n HashMap<Integer, List<Integer>> numPartitionsPerNode = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n List<Integer> partitionsOnNode = Utils.distributeEvenlyIntoList(nextCandidateCluster.getNumberOfNodesInZone(zoneId),\n targetPartitionsPerZone.get(zoneId));\n numPartitionsPerNode.put(zoneId, partitionsOnNode);\n }\n return numPartitionsPerNode;\n }", "public Object getProperty(Object object) {\n MetaMethod getter = getGetter();\n if (getter == null) {\n if (field != null) return field.getProperty(object);\n //TODO: create a WriteOnlyException class?\n throw new GroovyRuntimeException(\"Cannot read write-only property: \" + name);\n }\n return getter.invoke(object, MetaClassHelper.EMPTY_ARRAY);\n }", "protected void appendFacetOption(StringBuffer query, final String name, final String value) {\n\n query.append(\" facet.\").append(name).append(\"=\").append(value);\n }", "private void merge(ExecutionStatistics otherStatistics) {\n for (String s : otherStatistics.executionInfo.keySet())\n {\n TimingData thisStats = this.executionInfo.get(s);\n TimingData otherStats = otherStatistics.executionInfo.get(s);\n if(thisStats == null) {\n this.executionInfo.put(s,otherStats);\n } else {\n thisStats.merge(otherStats);\n }\n\n }\n }" ]
Transforms a position according to the current transformation matrix and current page transformation. @param x @param y @return
[ "protected float[] transformPosition(float x, float y)\n {\n Point2D.Float point = super.transformedPoint(x, y);\n AffineTransform pageTransform = createCurrentPageTransformation();\n Point2D.Float transformedPoint = (Point2D.Float) pageTransform.transform(point, null);\n\n return new float[]{(float) transformedPoint.getX(), (float) transformedPoint.getY()};\n }" ]
[ "public PreparedStatementCreator count(final Dialect dialect) {\n return new PreparedStatementCreator() {\n public PreparedStatement createPreparedStatement(Connection con)\n throws SQLException {\n return getPreparedStatementCreator()\n .setSql(dialect.createCountSelect(builder.toString()))\n .createPreparedStatement(con);\n }\n };\n }", "public static Document readDocumentFromString(String s) throws Exception {\r\n InputSource in = new InputSource(new StringReader(s));\r\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n factory.setNamespaceAware(false);\r\n return factory.newDocumentBuilder().parse(in);\r\n }", "public void addAliasToConfigSite(String alias, String redirect, String offset) {\n\n long timeOffset = 0;\n try {\n timeOffset = Long.parseLong(offset);\n } catch (Throwable e) {\n // ignore\n }\n CmsSiteMatcher siteMatcher = new CmsSiteMatcher(alias, timeOffset);\n boolean redirectVal = new Boolean(redirect).booleanValue();\n siteMatcher.setRedirect(redirectVal);\n m_aliases.add(siteMatcher);\n }", "public NodeInfo getNode(String name) {\n final URI uri = uriWithPath(\"./nodes/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, NodeInfo.class);\n }", "public static base_response disable(nitro_service client, String trapname) throws Exception {\n\t\tsnmpalarm disableresource = new snmpalarm();\n\t\tdisableresource.trapname = trapname;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "public static int[] binaryToRgb(boolean[] binaryArray) {\n int[] rgbArray = new int[binaryArray.length];\n\n for (int i = 0; i < binaryArray.length; i++) {\n if (binaryArray[i]) {\n rgbArray[i] = 0x00000000;\n } else {\n rgbArray[i] = 0x00FFFFFF;\n }\n }\n return rgbArray;\n }", "private <T> Observable<PollingState<T>> updateStateFromGetResourceOperationAsync(final PollingState<T> pollingState, String url) {\n return pollAsync(url, pollingState.loggingContext())\n .flatMap(new Func1<Response<ResponseBody>, Observable<PollingState<T>>>() {\n @Override\n public Observable<PollingState<T>> call(Response<ResponseBody> response) {\n try {\n pollingState.updateFromResponseOnPutPatch(response);\n return Observable.just(pollingState);\n } catch (CloudException | IOException e) {\n return Observable.error(e);\n }\n }\n });\n }", "public Set<URI> collectOutgoingReferences(IResourceDescription description) {\n\t\tURI resourceURI = description.getURI();\n\t\tSet<URI> result = null;\n\t\tfor(IReferenceDescription reference: description.getReferenceDescriptions()) {\n\t\t\tURI targetResource = reference.getTargetEObjectUri().trimFragment();\n\t\t\tif (!resourceURI.equals(targetResource)) {\n\t\t\t\tif (result == null)\n\t\t\t\t\tresult = Sets.newHashSet(targetResource);\n\t\t\t\telse\n\t\t\t\t\tresult.add(targetResource);\n\t\t\t}\n\t\t}\n\t\tif (result != null)\n\t\t\treturn result;\n\t\treturn Collections.emptySet();\n\t}", "private void registerChildInternal(IgnoreDomainResourceTypeResource child) {\n child.setParent(this);\n children.put(child.getName(), child);\n }" ]
Build control archive of the deb @param packageControlFile the package control file @param controlFiles the other control information files (maintainer scripts, etc) @param dataSize the size of the installed package @param checksums the md5 checksums of the files in the data archive @param output @return @throws java.io.FileNotFoundException @throws java.io.IOException @throws java.text.ParseException
[ "void buildControl(BinaryPackageControlFile packageControlFile, File[] controlFiles, List<String> conffiles, StringBuilder checksums, File output) throws IOException, ParseException {\n final File dir = output.getParentFile();\n if (dir != null && (!dir.exists() || !dir.isDirectory())) {\n throw new IOException(\"Cannot write control file at '\" + output.getAbsolutePath() + \"'\");\n }\n\n final TarArchiveOutputStream outputStream = new TarArchiveOutputStream(new GZIPOutputStream(new FileOutputStream(output)));\n outputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);\n\n boolean foundConffiles = false;\n\n // create the final package control file out of the \"control\" file, copy all other files, ignore the directories\n for (File file : controlFiles) {\n if (file.isDirectory()) {\n // warn about the misplaced directory, except for directories ignored by default (.svn, cvs, etc)\n if (!isDefaultExcludes(file)) {\n console.warn(\"Found directory '\" + file + \"' in the control directory. Maybe you are pointing to wrong dir?\");\n }\n continue;\n }\n\n if (\"conffiles\".equals(file.getName())) {\n foundConffiles = true;\n }\n\n if (CONFIGURATION_FILENAMES.contains(file.getName()) || MAINTAINER_SCRIPTS.contains(file.getName())) {\n FilteredFile configurationFile = new FilteredFile(new FileInputStream(file), resolver);\n configurationFile.setOpenToken(openReplaceToken);\n configurationFile.setCloseToken(closeReplaceToken);\n addControlEntry(file.getName(), configurationFile.toString(), outputStream);\n\n } else if (!\"control\".equals(file.getName())) {\n // initialize the information stream to guess the type of the file\n InformationInputStream infoStream = new InformationInputStream(new FileInputStream(file));\n Utils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);\n infoStream.close();\n\n // fix line endings for shell scripts\n InputStream in = new FileInputStream(file);\n if (infoStream.isShell() && !infoStream.hasUnixLineEndings()) {\n byte[] buf = Utils.toUnixLineEndings(in);\n in = new ByteArrayInputStream(buf);\n }\n\n addControlEntry(file.getName(), IOUtils.toString(in), outputStream);\n\n in.close();\n }\n }\n\n if (foundConffiles) {\n console.info(\"Found file 'conffiles' in the control directory. Skipping conffiles generation.\");\n } else if ((conffiles != null) && (conffiles.size() > 0)) {\n addControlEntry(\"conffiles\", createPackageConffilesFile(conffiles), outputStream);\n } else {\n console.info(\"Skipping 'conffiles' generation. No entries defined in maven/pom or ant/build.xml.\");\n }\n\n if (packageControlFile == null) {\n throw new FileNotFoundException(\"No 'control' file found in \" + controlFiles.toString());\n }\n\n addControlEntry(\"control\", packageControlFile.toString(), outputStream);\n addControlEntry(\"md5sums\", checksums.toString(), outputStream);\n\n outputStream.close();\n }" ]
[ "public static final String decodePassword(byte[] data, byte encryptionCode)\n {\n String result;\n\n if (data.length < MINIMUM_PASSWORD_DATA_LENGTH)\n {\n result = null;\n }\n else\n {\n MPPUtility.decodeBuffer(data, encryptionCode);\n\n StringBuilder buffer = new StringBuilder();\n char c;\n\n for (int i = 0; i < PASSWORD_MASK.length; i++)\n {\n int index = PASSWORD_MASK[i];\n c = (char) data[index];\n\n if (c == 0)\n {\n break;\n }\n buffer.append(c);\n }\n\n result = buffer.toString();\n }\n\n return (result);\n }", "public static synchronized void addCachedDatabaseConfigs(Collection<DatabaseTableConfig<?>> configs) {\n\t\tMap<Class<?>, DatabaseTableConfig<?>> newMap;\n\t\tif (configMap == null) {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>();\n\t\t} else {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>(configMap);\n\t\t}\n\t\tfor (DatabaseTableConfig<?> config : configs) {\n\t\t\tnewMap.put(config.getDataClass(), config);\n\t\t\tlogger.info(\"Loaded configuration for {}\", config.getDataClass());\n\t\t}\n\t\tconfigMap = newMap;\n\t}", "public boolean unlink(Object source, String attributeName, Object target)\r\n {\r\n return linkOrUnlink(false, source, attributeName, false);\r\n }", "public static double getHaltonNumberForGivenBase(long index, int base) {\n\t\tindex += 1;\n\n\t\tdouble x = 0.0;\n\t\tdouble factor = 1.0 / base;\n\t\twhile(index > 0) {\n\t\t\tx += (index % base) * factor;\n\t\t\tfactor /= base;\n\t\t\tindex /= base;\n\t\t}\n\n\t\treturn x;\n\t}", "public void shutdown() {\n debugConnection = null;\n shuttingDown = true;\n try {\n if (serverSocket != null) {\n serverSocket.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }", "private void notifyIfStopped() {\n if (isAcceptingNewJobs() || !this.runningTasksFutures.isEmpty()) {\n return;\n }\n final File stoppedFile = new File(this.workingDirectories.getWorking(), \"stopped\");\n try {\n LOGGER.info(\"The print has finished processing jobs and can now stop\");\n stoppedFile.createNewFile();\n } catch (IOException e) {\n LOGGER.warn(\"Cannot create the {} file\", stoppedFile, e);\n }\n }", "protected byte[] getUpperBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache()) {\n\t\t\tValueCache cache = valueCache;\n\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\tif(!isMultiple()) {\n\t\t\t\tcache.lowerBytes = cached;\n\t\t\t}\n\t\t} else {\n\t\t\tValueCache cache = valueCache;\n\t\t\tif((cached = cache.upperBytes) == null) {\n\t\t\t\tif(!isMultiple()) {\n\t\t\t\t\tif((cached = cache.lowerBytes) != null) {\n\t\t\t\t\t\tcache.upperBytes = cached;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcache.lowerBytes = cache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cached;\n\t}", "public ItemRequest<Task> removeDependents(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\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 }" ]
Extract site path, base name and locale from the resource opened with the editor.
[ "private void setResourceInformation() {\n\n String sitePath = m_cms.getSitePath(m_resource);\n int pathEnd = sitePath.lastIndexOf('/') + 1;\n String baseName = sitePath.substring(pathEnd);\n m_sitepath = sitePath.substring(0, pathEnd);\n switch (CmsMessageBundleEditorTypes.BundleType.toBundleType(\n OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())) {\n case PROPERTY:\n String localeSuffix = CmsStringUtil.getLocaleSuffixForName(baseName);\n if ((null != localeSuffix) && !localeSuffix.isEmpty()) {\n baseName = baseName.substring(\n 0,\n baseName.lastIndexOf(localeSuffix) - (1 /* cut off trailing underscore, too*/));\n m_locale = CmsLocaleManager.getLocale(localeSuffix);\n }\n if ((null == m_locale) || !m_locales.contains(m_locale)) {\n m_switchedLocaleOnOpening = true;\n m_locale = m_locales.iterator().next();\n }\n break;\n case XML:\n m_locale = OpenCms.getLocaleManager().getBestAvailableLocaleForXmlContent(\n m_cms,\n m_resource,\n m_xmlBundle);\n break;\n case DESCRIPTOR:\n m_basename = baseName.substring(\n 0,\n baseName.length() - CmsMessageBundleEditorTypes.Descriptor.POSTFIX.length());\n m_locale = new Locale(\"en\");\n break;\n default:\n throw new IllegalArgumentException(\n Messages.get().container(\n Messages.ERR_UNSUPPORTED_BUNDLE_TYPE_1,\n CmsMessageBundleEditorTypes.BundleType.toBundleType(\n OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())).toString());\n }\n m_basename = baseName;\n\n }" ]
[ "public static String buildDynamicCapabilityName(String baseName, String dynamicNameElement) {\n return buildDynamicCapabilityName(baseName, new String[]{dynamicNameElement});\n }", "private static MBeanServer setQueryExpServer(QueryExp query, MBeanServer toSet) {\n // We assume the QueryExp is a QueryEval subclass or uses the QueryEval thread local\n // mechanism to store any existing MBeanServer. If that's not the case we have no\n // way to access the old mbeanserver to let us restore it\n MBeanServer result = QueryEval.getMBeanServer();\n query.setMBeanServer(toSet);\n return result;\n }", "public static void permutationVector( DMatrixSparseCSC P , int[] vector) {\n if( P.numCols != P.numRows ) {\n throw new MatrixDimensionException(\"Expected a square matrix\");\n } else if( P.nz_length != P.numCols ) {\n throw new IllegalArgumentException(\"Expected N non-zero elements in permutation matrix\");\n } else if( vector.length < P.numCols ) {\n throw new IllegalArgumentException(\"vector is too short\");\n }\n\n int M = P.numCols;\n\n for (int i = 0; i < M; i++) {\n if( P.col_idx[i+1] != i+1 )\n throw new IllegalArgumentException(\"Unexpected number of elements in a column\");\n\n vector[P.nz_rows[i]] = i;\n }\n }", "public static vlan_interface_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvlan_interface_binding obj = new vlan_interface_binding();\n\t\tobj.set_id(id);\n\t\tvlan_interface_binding response[] = (vlan_interface_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private static double pointsDistance(Point a, Point b) {\n int dx = b.x - a.x;\n int dy = b.y - a.y;\n return Math.sqrt(dx * dx + dy * dy);\n }", "protected void processStop(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n monitoringServiceClient.putEvents(Collections.singletonList(event));\n if (LOG.isLoggable(Level.INFO)) {\n LOG.info(\"Send \" + eventType + \" event to SAM Server successful!\");\n }\n }", "private T getWrappedPublisher(Publisher flexiblePublisher, Class<T> type) {\n if (!(flexiblePublisher instanceof FlexiblePublisher)) {\n throw new IllegalArgumentException(String.format(\"Publisher should be of type: '%s'. Found type: '%s'\",\n FlexiblePublisher.class, flexiblePublisher.getClass()));\n }\n\n List<ConditionalPublisher> conditions = ((FlexiblePublisher) flexiblePublisher).getPublishers();\n for (ConditionalPublisher condition : conditions) {\n if (type.isInstance(condition.getPublisher())) {\n return type.cast(condition.getPublisher());\n }\n }\n\n return null;\n }", "public static<A, Z> Function1<A, Z> lift(Func1<A, Z> f) {\n\treturn bridge.lift(f);\n }", "public App named(String name) {\n App newApp = copy();\n newApp.name = name;\n return newApp;\n }" ]
Indicates if the type is a simple Web Bean @param clazz The type to inspect @return True if simple Web Bean, false otherwise
[ "public static boolean isTypeManagedBeanOrDecoratorOrInterceptor(AnnotatedType<?> annotatedType) {\n Class<?> javaClass = annotatedType.getJavaClass();\n return !javaClass.isEnum() && !Extension.class.isAssignableFrom(javaClass)\n && Reflections.isTopLevelOrStaticNestedClass(javaClass) && !Reflections.isParameterizedTypeWithWildcard(javaClass)\n && hasSimpleCdiConstructor(annotatedType);\n }" ]
[ "public static Object getFieldValue(Object object, String fieldName) {\n try {\n return getDeclaredFieldInHierarchy(object.getClass(), fieldName).get(object);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }", "public void addWatcher(final MongoNamespace namespace,\n final Callback<ChangeEvent<BsonDocument>, Object> watcher) {\n instanceChangeStreamListener.addWatcher(namespace, watcher);\n }", "public static ServerSetup[] verbose(ServerSetup[] serverSetups) {\r\n ServerSetup[] copies = new ServerSetup[serverSetups.length];\r\n for (int i = 0; i < serverSetups.length; i++) {\r\n copies[i] = serverSetups[i].createCopy().setVerbose(true);\r\n }\r\n return copies;\r\n }", "public GVRCursorController findCursorController(GVRControllerType type) {\n for (int index = 0, size = cache.size(); index < size; index++)\n {\n int key = cache.keyAt(index);\n GVRCursorController controller = cache.get(key);\n if (controller.getControllerType().equals(type)) {\n return controller;\n }\n }\n return null;\n }", "private int getTaskCode(String field) throws MPXJException\n {\n Integer result = m_taskNumbers.get(field.trim());\n\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_TASK_FIELD_NAME + \" \" + field);\n }\n\n return (result.intValue());\n }", "public static String getBuildString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.build\");\n\t\t}\n\t\treturn versionString;\n\t}", "public List<WbSearchEntitiesResult> wbSearchEntities(String search, String language,\n Boolean strictLanguage, String type, Long limit, Long offset)\n throws MediaWikiApiErrorException {\n\n Map<String, String> parameters = new HashMap<String, String>();\n parameters.put(ApiConnection.PARAM_ACTION, \"wbsearchentities\");\n\n if (search != null) {\n parameters.put(\"search\", search);\n } else {\n throw new IllegalArgumentException(\n \"Search parameter must be specified for this action.\");\n }\n\n if (language != null) {\n parameters.put(\"language\", language);\n } else {\n throw new IllegalArgumentException(\n \"Language parameter must be specified for this action.\");\n }\n if (strictLanguage != null) {\n parameters.put(\"strictlanguage\", Boolean.toString(strictLanguage));\n }\n\n if (type != null) {\n parameters.put(\"type\", type);\n }\n\n if (limit != null) {\n parameters.put(\"limit\", Long.toString(limit));\n }\n\n if (offset != null) {\n parameters.put(\"continue\", Long.toString(offset));\n }\n\n List<WbSearchEntitiesResult> results = new ArrayList<>();\n\n try {\n JsonNode root = this.connection.sendJsonRequest(\"POST\", parameters);\n JsonNode entities = root.path(\"search\");\n for (JsonNode entityNode : entities) {\n try {\n JacksonWbSearchEntitiesResult ed = mapper.treeToValue(entityNode,\n JacksonWbSearchEntitiesResult.class);\n results.add(ed);\n } catch (JsonProcessingException e) {\n LOGGER.error(\"Error when reading JSON for entity \"\n + entityNode.path(\"id\").asText(\"UNKNOWN\") + \": \"\n + e.toString());\n }\n }\n } catch (IOException e) {\n LOGGER.error(\"Could not retrive data: \" + e.toString());\n }\n\n return results;\n }", "public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"file\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n requestJSON.add(\"action\", action.toJSONString());\n\n if (message != null && !message.isEmpty()) {\n requestJSON.add(\"message\", message);\n }\n\n if (dueAt != null) {\n requestJSON.add(\"due_at\", BoxDateFormat.format(dueAt));\n }\n\n URL url = ADD_TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxTask addedTask = new BoxTask(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedTask.new Info(responseJSON);\n }", "public static final Path resolveSecurely(Path rootPath, String path) {\n Path resolvedPath;\n if(path == null || path.isEmpty()) {\n resolvedPath = rootPath.normalize();\n } else {\n String relativePath = removeSuperflousSlashes(path);\n resolvedPath = rootPath.resolve(relativePath).normalize();\n }\n if(!resolvedPath.startsWith(rootPath)) {\n throw DeploymentRepositoryLogger.ROOT_LOGGER.forbiddenPath(path);\n }\n return resolvedPath;\n }" ]
Build a compact representation of the ModelNode. @param node The model @return A single line containing the multi lines ModelNode.toString() content.
[ "public static String compactToString(ModelNode node) {\n Objects.requireNonNull(node);\n final StringWriter stringWriter = new StringWriter();\n final PrintWriter writer = new PrintWriter(stringWriter, true);\n node.writeString(writer, true);\n return stringWriter.toString();\n }" ]
[ "public static protocolip_stats get(nitro_service service) throws Exception{\n\t\tprotocolip_stats obj = new protocolip_stats();\n\t\tprotocolip_stats[] response = (protocolip_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "protected void putResponse(JSONObject json,\n String param,\n Object value) {\n try {\n json.put(param,\n value);\n } catch (JSONException e) {\n logger.error(\"json write error\",\n e);\n }\n }", "public String get(final long index) {\n return doWithJedis(new JedisCallable<String>() {\n @Override\n public String call(Jedis jedis) {\n return jedis.lindex(getKey(), index);\n }\n });\n }", "public ParallelTaskBuilder setResponseContext(\n Map<String, Object> responseContext) {\n if (responseContext != null)\n this.responseContext = responseContext;\n else\n logger.error(\"context cannot be null. skip set.\");\n return this;\n }", "@SuppressWarnings(\"unchecked\")\n public T toObject(byte[] bytes) {\n try {\n return (T) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();\n } catch(IOException e) {\n throw new SerializationException(e);\n } catch(ClassNotFoundException c) {\n throw new SerializationException(c);\n }\n }", "private static String resolveJavaCommand(final Path javaHome) {\n final String exe;\n if (javaHome == null) {\n exe = \"java\";\n } else {\n exe = javaHome.resolve(\"bin\").resolve(\"java\").toString();\n }\n if (exe.contains(\" \")) {\n return \"\\\"\" + exe + \"\\\"\";\n }\n return exe;\n }", "private static void attachToContent(Activity activity, MenuDrawer menuDrawer) {\n /**\n * Do not call mActivity#setContentView.\n * E.g. if using with a ListActivity, Activity#setContentView is overridden and dispatched to\n * MenuDrawer#setContentView, which then again would call Activity#setContentView.\n */\n ViewGroup content = (ViewGroup) activity.findViewById(android.R.id.content);\n content.removeAllViews();\n content.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }", "public int getFaceNumIndices(int face) {\n if (null == m_faceOffsets) {\n if (face >= m_numFaces || face < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + face + \n \", Size: \" + m_numFaces);\n }\n return 3;\n }\n else {\n /* \n * no need to perform bound checks here as the array access will\n * throw IndexOutOfBoundsExceptions if the index is invalid\n */\n \n if (face == m_numFaces - 1) {\n return m_faces.capacity() / 4 - m_faceOffsets.getInt(face * 4);\n }\n \n return m_faceOffsets.getInt((face + 1) * 4) - \n m_faceOffsets.getInt(face * 4);\n }\n }", "private void ensureIndexIsUnlocked(String dataDir) {\n\n Collection<File> lockFiles = new ArrayList<File>(2);\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"index\") + \"write.lock\"));\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"spellcheck\")\n + \"write.lock\"));\n for (File lockFile : lockFiles) {\n if (lockFile.exists()) {\n lockFile.delete();\n LOG.warn(\n \"Forcely unlocking index with data dir \\\"\"\n + dataDir\n + \"\\\" by removing file \\\"\"\n + lockFile.getAbsolutePath()\n + \"\\\".\");\n }\n }\n }" ]
Use this API to update cacheselector.
[ "public static base_response update(nitro_service client, cacheselector resource) throws Exception {\n\t\tcacheselector updateresource = new cacheselector();\n\t\tupdateresource.selectorname = resource.selectorname;\n\t\tupdateresource.rule = resource.rule;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "public boolean canBeLinked(D declaration, ServiceReference<S> declarationBinderRef) {\n // Evaluate the target filter of the ImporterService on the Declaration\n Filter filter = bindersManager.getTargetFilter(declarationBinderRef);\n return filter.matches(declaration.getMetadata());\n }", "private long doMemoryManagementAndPerFrameCallbacks() {\n long currentTime = GVRTime.getCurrentTime();\n mFrameTime = (currentTime - mPreviousTimeNanos) / 1e9f;\n mPreviousTimeNanos = currentTime;\n\n /*\n * Without the sensor data, can't draw a scene properly.\n */\n if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) {\n Runnable runnable;\n while ((runnable = mRunnables.poll()) != null) {\n try {\n runnable.run();\n } catch (final Exception exc) {\n Log.e(TAG, \"Runnable-on-GL %s threw %s\", runnable, exc.toString());\n exc.printStackTrace();\n }\n }\n\n final List<GVRDrawFrameListener> frameListeners = mFrameListeners;\n for (GVRDrawFrameListener listener : frameListeners) {\n try {\n listener.onDrawFrame(mFrameTime);\n } catch (final Exception exc) {\n Log.e(TAG, \"DrawFrameListener %s threw %s\", listener, exc.toString());\n exc.printStackTrace();\n }\n }\n }\n\n return currentTime;\n }", "public Entry<T>[] entries() {\n @SuppressWarnings(\"unchecked\")\n Entry<T>[] entries = new Entry[size];\n int idx = 0;\n for (Entry entry : table) {\n while (entry != null) {\n entries[idx++] = entry;\n entry = entry.next;\n }\n }\n return entries;\n }", "private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize)\n\t\t\tthrows SQLException {\n\t\tFieldType idField = tableInfo.getIdField();\n\t\tif (idField == null) {\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Cannot delete \" + tableInfo.getDataClass() + \" because it doesn't have an id field defined\");\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(128);\n\t\tDatabaseType databaseType = dao.getConnectionSource().getDatabaseType();\n\t\tappendTableName(databaseType, sb, \"DELETE FROM \", tableInfo.getTableName());\n\t\tFieldType[] argFieldTypes = new FieldType[dataSize];\n\t\tappendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes);\n\t\treturn new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes);\n\t}", "private void performSetupExchange() throws IOException {\n Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));\n sendMessage(setupRequest);\n Message response = Message.read(is);\n if (response.knownType != Message.KnownType.MENU_AVAILABLE) {\n throw new IOException(\"Did not receive message type 0x4000 in response to setup message, got: \" + response);\n }\n if (response.arguments.size() != 2) {\n throw new IOException(\"Did not receive two arguments in response to setup message, got: \" + response);\n }\n final Field player = response.arguments.get(1);\n if (!(player instanceof NumberField)) {\n throw new IOException(\"Second argument in response to setup message was not a number: \" + response);\n }\n if (((NumberField)player).getValue() != targetPlayer) {\n throw new IOException(\"Expected to connect to player \" + targetPlayer +\n \", but welcome response identified itself as player \" + ((NumberField)player).getValue());\n }\n }", "public Future<PutObjectResult> putAsync(String key, String value) {\n return Future.of(() -> put(key, value), this.uploadService)\n .flatMap(t->t.fold(p->Future.ofResult(p),e->Future.ofError(e)));\n }", "public Build createBuild(String appName, Build build) {\n return connection.execute(new BuildCreate(appName, build), apiKey);\n }", "public static void addStory(File caseManager, String storyName,\n String testPath, String user, String feature, String benefit) throws BeastException {\n FileWriter caseManagerWriter;\n\n String storyClass = SystemReader.createClassName(storyName);\n try {\n BufferedReader reader = new BufferedReader(new FileReader(\n caseManager));\n String targetLine1 = \" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\";\n String targetLine2 = \" Result result = JUnitCore.runClasses(\" + testPath + \".\"\n + storyClass + \".class);\";\n String in;\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine1)) {\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine2)) {\n reader.close();\n // This test is already written in the case manager.\n return;\n }\n }\n reader.close();\n throw new BeastException(\"Two different stories with the same name (same method name) are being created in the same CaseManager file. That is not possible. Please, change the name of the story: \" + testPath + \".\"\n + storyClass + \".java\");\n }\n }\n reader.close();\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\" /**\\n\");\n caseManagerWriter.write(\" * This is the story: \" + storyName\n + \"\\n\");\n caseManagerWriter.write(\" * requested by: \" + user + \"\\n\");\n caseManagerWriter.write(\" * providing the feature: \" + feature\n + \"\\n\");\n caseManagerWriter.write(\" * so the user gets the benefit: \"\n + benefit + \"\\n\");\n caseManagerWriter.write(\" */\\n\");\n caseManagerWriter.write(\" @Test\\n\");\n caseManagerWriter.write(\" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\\n\");\n caseManagerWriter.write(\" Result result = JUnitCore.runClasses(\" + testPath\n + \".\" + storyClass + \".class);\\n\");\n caseManagerWriter.write(\" Assert.assertTrue(result.wasSuccessful());\\n\");\n caseManagerWriter.write(\" }\\n\");\n caseManagerWriter.write(\"\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger.getLogger(\"CreateMASCaseManager.createTest\");\n logger.info(\"ERROR writing the file\");\n }\n\n }", "public GetSingleConversationOptions filters(List<String> filters) {\n if(filters.size() == 1) { //Canvas API doesn't want the [] if it is only one value\n addSingleItem(\"filter\", filters.get(0));\n } else {\n optionsMap.put(\"filter[]\", filters);\n }\n return this;\n }" ]
Registers the parameter for the value formatter for the given variable and puts it's implementation in the parameters map. @param djVariable @param variableName
[ "protected void registerValueFormatter(DJGroupVariable djVariable, String variableName) {\n\t\tif ( djVariable.getValueFormatter() == null){\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tJRDesignParameter dparam = new JRDesignParameter();\n\t\tdparam.setName(variableName + \"_vf\"); //value formater suffix\n\t\tdparam.setValueClassName(DJValueFormatter.class.getName());\n\t\tlog.debug(\"Registering value formatter parameter for property \" + dparam.getName() );\n\t\ttry {\n\t\t\tgetDjd().addParameter(dparam);\n\t\t} catch (JRException e) {\n\t\t\tthrow new EntitiesRegistrationException(e.getMessage(),e);\n\t\t}\n\t\tgetDjd().getParametersWithValues().put(dparam.getName(), djVariable.getValueFormatter());\t\t\n\t\t\n\t}" ]
[ "public static ByteBuffer newDirectByteBuffer(long addr, int size, Object att) {\n dbbCC.setAccessible(true);\n Object b = null;\n try {\n b = dbbCC.newInstance(new Long(addr), new Integer(size), att);\n return ByteBuffer.class.cast(b);\n }\n catch(Exception e) {\n throw new IllegalStateException(String.format(\"Failed to create DirectByteBuffer: %s\", e.getMessage()));\n }\n }", "public static base_response update(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy updateresource = new spilloverpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.action = resource.action;\n\t\tupdateresource.comment = resource.comment;\n\t\treturn updateresource.update_resource(client);\n\t}", "private void setCorrectDay(Calendar date) {\n\n if (monthHasNotDay(date)) {\n date.set(Calendar.DAY_OF_MONTH, date.getActualMaximum(Calendar.DAY_OF_MONTH));\n } else {\n date.set(Calendar.DAY_OF_MONTH, m_dayOfMonth);\n }\n }", "public static base_response disable(nitro_service client, Long clid) throws Exception {\n\t\tclusterinstance disableresource = new clusterinstance();\n\t\tdisableresource.clid = clid;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "private static boolean isDisabledHandler(final LogContext logContext, final String handlerName) {\n final Map<String, String> disableHandlers = logContext.getAttachment(CommonAttributes.ROOT_LOGGER_NAME, DISABLED_HANDLERS_KEY);\n return disableHandlers != null && disableHandlers.containsKey(handlerName);\n }", "public static double elementSum( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n double sum = 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n sum += A.nz_values[i];\n }\n\n return sum;\n }", "public ItemRequest<Tag> createInWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/tags\", workspace);\n return new ItemRequest<Tag>(this, Tag.class, path, \"POST\");\n }", "public static Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>\n getDonorsAndStealersForBalance(final Cluster nextCandidateCluster,\n Map<Integer, List<Integer>> numPartitionsPerNodePerZone) {\n HashMap<Node, Integer> donorNodes = Maps.newHashMap();\n HashMap<Node, Integer> stealerNodes = Maps.newHashMap();\n\n HashMap<Integer, Integer> numNodesAssignedInZone = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n numNodesAssignedInZone.put(zoneId, 0);\n }\n for(Node node: nextCandidateCluster.getNodes()) {\n int zoneId = node.getZoneId();\n\n int offset = numNodesAssignedInZone.get(zoneId);\n numNodesAssignedInZone.put(zoneId, offset + 1);\n\n int numPartitions = numPartitionsPerNodePerZone.get(zoneId).get(offset);\n\n if(numPartitions < node.getNumberOfPartitions()) {\n donorNodes.put(node, numPartitions);\n } else if(numPartitions > node.getNumberOfPartitions()) {\n stealerNodes.put(node, numPartitions);\n }\n }\n\n // Print out donor/stealer information\n for(Node node: donorNodes.keySet()) {\n System.out.println(\"Donor Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + donorNodes.get(node));\n }\n for(Node node: stealerNodes.keySet()) {\n System.out.println(\"Stealer Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + stealerNodes.get(node));\n }\n\n return new Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>(donorNodes, stealerNodes);\n }", "public static int ptb2Text(Reader ptbText, Writer w) throws IOException {\r\n int numTokens = 0;\r\n PTB2TextLexer lexer = new PTB2TextLexer(ptbText);\r\n for (String token; (token = lexer.next()) != null; ) {\r\n numTokens++;\r\n w.write(token);\r\n }\r\n return numTokens;\r\n }" ]
This method takes the textual version of a constraint name and returns an appropriate class instance. Note that unrecognised values are treated as "As Soon As Possible" constraints. @param locale target locale @param type text version of the constraint type @return ConstraintType instance
[ "public static ConstraintType getInstance(Locale locale, String type)\n {\n int index = 0;\n\n String[] constraintTypes = LocaleData.getStringArray(locale, LocaleData.CONSTRAINT_TYPES);\n for (int loop = 0; loop < constraintTypes.length; loop++)\n {\n if (constraintTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n return (ConstraintType.getInstance(index));\n }" ]
[ "private static List<String> parseModifiers(int modifiers) {\n List<String> result = new ArrayList<String>();\n if (Modifier.isPrivate(modifiers)) {\n result.add(\"private\");\n }\n if (Modifier.isProtected(modifiers)) {\n result.add(\"protected\");\n }\n if (Modifier.isPublic(modifiers)) {\n result.add(\"public\");\n }\n if (Modifier.isAbstract(modifiers)) {\n result.add(\"abstract\");\n }\n if (Modifier.isFinal(modifiers)) {\n result.add(\"final\");\n }\n if (Modifier.isNative(modifiers)) {\n result.add(\"native\");\n }\n if (Modifier.isStatic(modifiers)) {\n result.add(\"static\");\n }\n if (Modifier.isStrict(modifiers)) {\n result.add(\"strict\");\n }\n if (Modifier.isSynchronized(modifiers)) {\n result.add(\"synchronized\");\n }\n if (Modifier.isTransient(modifiers)) {\n result.add(\"transient\");\n }\n if (Modifier.isVolatile(modifiers)) {\n result.add(\"volatile\");\n }\n if (Modifier.isInterface(modifiers)) {\n result.add(\"interface\");\n }\n return result;\n }", "protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n boolean needsCommit = false;\r\n long result = 0;\r\n /*\r\n arminw:\r\n use the associated broker instance, check if broker was in tx or\r\n we need to commit used connection.\r\n */\r\n PersistenceBroker targetBroker = getBrokerForClass();\r\n if(!targetBroker.isInTransaction())\r\n {\r\n targetBroker.beginTransaction();\r\n needsCommit = true;\r\n }\r\n try\r\n {\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n /*\r\n if 0 was returned we assume that the stored procedure\r\n did not work properly.\r\n */\r\n if (result == 0)\r\n {\r\n throw new SequenceManagerException(\"No incremented value retrieved\");\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n // maybe the sequence was not created\r\n log.info(\"Could not grab next key, message was \" + e.getMessage() +\r\n \" - try to write a new sequence entry to database\");\r\n try\r\n {\r\n // on create, make sure to get the max key for the table first\r\n long maxKey = SequenceManagerHelper.getMaxForExtent(targetBroker, field);\r\n createSequence(targetBroker, field, sequenceName, maxKey);\r\n }\r\n catch (Exception e1)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n throw new SequenceManagerException(eol + \"Could not grab next id, failed with \" + eol +\r\n e.getMessage() + eol + \"Creation of new sequence failed with \" +\r\n eol + e1.getMessage() + eol, e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id although a sequence seems to exist\", e);\r\n }\r\n }\r\n }\r\n finally\r\n {\r\n if(targetBroker != null && needsCommit)\r\n {\r\n targetBroker.commitTransaction();\r\n }\r\n }\r\n return result;\r\n }", "public static MarvinImage rgbToBinary(MarvinImage img, int threshold) {\n MarvinImage resultImage = new MarvinImage(img.getWidth(), img.getHeight(), MarvinImage.COLOR_MODEL_BINARY);\n\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n int gray = (int) ((img.getIntComponent0(x, y) * 0.3) + (img.getIntComponent1(x, y) * 0.59) + (img.getIntComponent2(x, y) * 0.11));\n\n if (gray <= threshold) {\n resultImage.setBinaryColor(x, y, true);\n } else {\n resultImage.setBinaryColor(x, y, false);\n }\n }\n }\n return resultImage;\n }", "public static BufferedImage cloneImage( BufferedImage image ) {\n\t\tBufferedImage newImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB );\n\t\tGraphics2D g = newImage.createGraphics();\n\t\tg.drawRenderedImage( image, null );\n\t\tg.dispose();\n\t\treturn newImage;\n\t}", "private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded());\n }\n\n return flatItemList;\n }", "@Override\n\tpublic void visit(FeatureTypeStyle fts) {\n\n\t\tFeatureTypeStyle copy = new FeatureTypeStyleImpl(\n\t\t\t\t(FeatureTypeStyleImpl) fts);\n\t\tRule[] rules = fts.getRules();\n\t\tint length = rules.length;\n\t\tRule[] rulesCopy = new Rule[length];\n\t\tfor (int i = 0; i < length; i++) {\n\t\t\tif (rules[i] != null) {\n\t\t\t\trules[i].accept(this);\n\t\t\t\trulesCopy[i] = (Rule) pages.pop();\n\t\t\t}\n\t\t}\n\t\tcopy.setRules(rulesCopy);\n\t\tif (fts.getTransformation() != null) {\n\t\t\tcopy.setTransformation(copy(fts.getTransformation()));\n\t\t}\n\t\tif (STRICT && !copy.equals(fts)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided FeatureTypeStyle:\" + fts);\n\t\t}\n\t\tpages.push(copy);\n\t}", "private String formatDateTimeNull(Date value)\n {\n return (value == null ? m_formats.getNullText() : m_formats.getDateTimeFormat().format(value));\n }", "private void writeCompressedText(File file, byte[] compressedContent) throws IOException\r\n {\r\n ByteArrayInputStream bais = new ByteArrayInputStream(compressedContent);\r\n GZIPInputStream gis = new GZIPInputStream(bais);\r\n BufferedReader input = new BufferedReader(new InputStreamReader(gis));\r\n BufferedWriter output = new BufferedWriter(new FileWriter(file));\r\n String line;\r\n\r\n while ((line = input.readLine()) != null)\r\n {\r\n output.write(line);\r\n output.write('\\n');\r\n }\r\n input.close();\r\n gis.close();\r\n bais.close();\r\n output.close();\r\n }", "public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) {\n if (clazz == null || prototype == null) {\n throw new IllegalArgumentException(\n \"The binding RecyclerView binding can't be configured using null instances\");\n }\n prototypes.add(prototype);\n binding.put(clazz, prototype.getClass());\n return this;\n }" ]
Returns a Bic object holding the value of the specified String. @param bic the String to be parsed. @return a Bic object holding the value represented by the string argument. @throws BicFormatException if the String doesn't contain parsable Bic. UnsupportedCountryException if bic's country is not supported.
[ "public static Bic valueOf(final String bic) throws BicFormatException,\n UnsupportedCountryException {\n BicUtil.validate(bic);\n return new Bic(bic);\n }" ]
[ "private void initStoreDefinitions(Version storesXmlVersion) {\n if(this.storeDefinitionsStorageEngine == null) {\n throw new VoldemortException(\"The store definitions directory is empty\");\n }\n\n String allStoreDefinitions = \"<stores>\";\n Version finalStoresXmlVersion = null;\n if(storesXmlVersion != null) {\n finalStoresXmlVersion = storesXmlVersion;\n }\n this.storeNames.clear();\n\n ClosableIterator<Pair<String, Versioned<String>>> storesIterator = this.storeDefinitionsStorageEngine.entries();\n\n // Some test setups may result in duplicate entries for 'store' element.\n // Do the de-dup here\n Map<String, Versioned<String>> storeNameToDefMap = new HashMap<String, Versioned<String>>();\n Version maxVersion = null;\n while(storesIterator.hasNext()) {\n Pair<String, Versioned<String>> storeDetail = storesIterator.next();\n String storeName = storeDetail.getFirst();\n Versioned<String> versionedStoreDef = storeDetail.getSecond();\n storeNameToDefMap.put(storeName, versionedStoreDef);\n Version curVersion = versionedStoreDef.getVersion();\n\n // Get the highest version from all the store entries\n if(maxVersion == null) {\n maxVersion = curVersion;\n } else if(maxVersion.compare(curVersion) == Occurred.BEFORE) {\n maxVersion = curVersion;\n }\n }\n\n // If the specified version is null, assign highest Version to\n // 'stores.xml' key\n if(finalStoresXmlVersion == null) {\n finalStoresXmlVersion = maxVersion;\n }\n\n // Go through all the individual stores and update metadata\n for(Entry<String, Versioned<String>> storeEntry: storeNameToDefMap.entrySet()) {\n String storeName = storeEntry.getKey();\n Versioned<String> versionedStoreDef = storeEntry.getValue();\n\n // Add all the store names to the list of storeNames\n this.storeNames.add(storeName);\n\n this.metadataCache.put(storeName, new Versioned<Object>(versionedStoreDef.getValue(),\n versionedStoreDef.getVersion()));\n }\n\n Collections.sort(this.storeNames);\n for(String storeName: this.storeNames) {\n Versioned<String> versionedStoreDef = storeNameToDefMap.get(storeName);\n // Stitch together to form the complete store definition list.\n allStoreDefinitions += versionedStoreDef.getValue();\n\n }\n\n allStoreDefinitions += \"</stores>\";\n\n // Update cache with the composite store definition list.\n metadataCache.put(STORES_KEY,\n convertStringToObject(STORES_KEY,\n new Versioned<String>(allStoreDefinitions,\n finalStoresXmlVersion)));\n }", "public BsonDocument toBsonDocument() {\n final BsonDocument updateDescDoc = new BsonDocument();\n updateDescDoc.put(\n Fields.UPDATED_FIELDS_FIELD,\n this.getUpdatedFields());\n\n final BsonArray removedFields = new BsonArray();\n for (final String field : this.getRemovedFields()) {\n removedFields.add(new BsonString(field));\n }\n updateDescDoc.put(\n Fields.REMOVED_FIELDS_FIELD,\n removedFields);\n\n return updateDescDoc;\n }", "public static void append(File file, Writer writer, String charset) throws IOException {\n appendBuffered(file, writer, charset);\n }", "private void flush(final boolean propagate) throws IOException {\n final int avail = baseNCodec.available(context);\n if (avail > 0) {\n final byte[] buf = new byte[avail];\n final int c = baseNCodec.readResults(buf, 0, avail, context);\n if (c > 0) {\n out.write(buf, 0, c);\n }\n }\n if (propagate) {\n out.flush();\n }\n }", "public static String getContext(final PObject[] objs) {\n StringBuilder result = new StringBuilder(\"(\");\n boolean first = true;\n for (PObject obj: objs) {\n if (!first) {\n result.append('|');\n }\n first = false;\n result.append(obj.getCurrentPath());\n }\n result.append(')');\n return result.toString();\n }", "public static csvserver_cmppolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cmppolicy_binding obj = new csvserver_cmppolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cmppolicy_binding response[] = (csvserver_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\n public boolean shouldRetry(int retryCount, Response response) {\n int code = response.code();\n //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES\n return retryCount < this.retryCount\n && (code == 408 || (code >= 500 && code != 501 && code != 505));\n }", "public void signOff(String key, WebSocketConnection connection) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> connections = registry.get(key);\n if (null == connections) {\n return;\n }\n connections.remove(connection);\n }", "public Object getProperty(Object object) {\n return java.lang.reflect.Array.getLength(object);\n }" ]
Forceful cleanup the logs
[ "@JmxOperation(description = \"Forcefully invoke the log cleaning\")\n public void cleanLogs() {\n synchronized(lock) {\n try {\n for(Environment environment: environments.values()) {\n environment.cleanLog();\n }\n } catch(DatabaseException e) {\n throw new VoldemortException(e);\n }\n }\n }" ]
[ "public static List<String> getDefaultConversionProviderChain(){\n List<String> defaultChain = getMonetaryConversionsSpi()\n .getDefaultProviderChain();\n Objects.requireNonNull(defaultChain, \"No default provider chain provided by SPI: \" +\n getMonetaryConversionsSpi().getClass().getName());\n return defaultChain;\n }", "public <T> T invokeWithClientSession(int targetPlayer, ClientTask<T> task, String description)\n throws Exception {\n if (!isRunning()) {\n throw new IllegalStateException(\"ConnectionManager is not running, aborting \" + description);\n }\n\n final Client client = allocateClient(targetPlayer, description);\n try {\n return task.useClient(client);\n } finally {\n freeClient(client);\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 final String getUnicodeString(byte[] data, int offset)\n {\n int length = getUnicodeStringLengthInBytes(data, offset);\n return length == 0 ? \"\" : new String(data, offset, length, CharsetHelper.UTF16LE);\n }", "public RedwoodConfiguration collapseExact(){\r\n tasks.add(new Runnable() { public void run() { Redwood.spliceHandler(VisibilityHandler.class, new RepeatedRecordHandler(RepeatedRecordHandler.EXACT), OutputHandler.class); } });\r\n return this;\r\n }", "private int getFlagResource(Country country) {\n return getContext().getResources().getIdentifier(\"country_\" + country.getIso().toLowerCase(), \"drawable\", getContext().getPackageName());\n }", "public float getLayoutSize(final Layout.Axis axis) {\n float size = 0;\n for (Layout layout : mLayouts) {\n size = Math.max(size, layout.getSize(axis));\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getLayoutSize [%s] axis [%s] size [%f]\", getName(), axis, size);\n return size;\n }", "public static base_response enable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature enableresource = new nsfeature();\n\t\tenableresource.feature = resource.feature;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "public static ServiceController<InstallationManager> installService(ServiceTarget serviceTarget) {\n final InstallationManagerService service = new InstallationManagerService();\n return serviceTarget.addService(InstallationManagerService.NAME, service)\n .addDependency(JBOSS_PRODUCT_CONFIG_SERVICE, ProductConfig.class, service.productConfig)\n .setInitialMode(ServiceController.Mode.ACTIVE)\n .install();\n }" ]
Closes the connection to the dbserver. This instance can no longer be used after this action.
[ "void close() {\n try {\n performTeardownExchange();\n } catch (IOException e) {\n logger.warn(\"Problem reporting our intention to close the dbserver connection\", e);\n }\n try {\n channel.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output channel\", e);\n }\n try {\n os.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client output stream\", e);\n }\n try {\n is.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client input stream\", e);\n }\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing dbserver client socket\", e);\n }\n }" ]
[ "boolean applyDomainModel(ModelNode result) {\n if(! result.hasDefined(ModelDescriptionConstants.RESULT)) {\n return false;\n }\n final List<ModelNode> bootOperations= result.get(ModelDescriptionConstants.RESULT).asList();\n return callback.applyDomainModel(bootOperations);\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 Class<? extends com.vividsolutions.jts.geom.Geometry> toInternal(LayerType layerType) {\n\t\tswitch (layerType) {\n\t\t\tcase GEOMETRY:\n\t\t\t\treturn com.vividsolutions.jts.geom.Geometry.class;\n\t\t\tcase LINESTRING:\n\t\t\t\treturn LineString.class;\n\t\t\tcase MULTILINESTRING:\n\t\t\t\treturn MultiLineString.class;\n\t\t\tcase POINT:\n\t\t\t\treturn Point.class;\n\t\t\tcase MULTIPOINT:\n\t\t\t\treturn MultiPoint.class;\n\t\t\tcase POLYGON:\n\t\t\t\treturn Polygon.class;\n\t\t\tcase MULTIPOLYGON:\n\t\t\t\treturn MultiPolygon.class;\n\t\t\tcase RASTER:\n\t\t\t\treturn null;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalStateException(\"Don't know how to handle layer type \" + layerType);\n\t\t}\n\t}", "public static String encodeQueryParam(String queryParam, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(queryParam, encoding, HierarchicalUriComponents.Type.QUERY_PARAM);\n\t}", "public static String joinStrings(List<String> strings, boolean fixCase, char withChar) {\n if (strings == null || strings.size() == 0) {\n return \"\";\n }\n StringBuilder result = null;\n for (String s : strings) {\n if (fixCase) {\n s = fixCase(s);\n }\n if (result == null) {\n result = new StringBuilder(s);\n } else {\n result.append(withChar);\n result.append(s);\n }\n }\n return result.toString();\n }", "public Stats getCollectionStats(String collectionId, Date date) throws FlickrException {\n return getStats(METHOD_GET_COLLECTION_STATS, \"collection_id\", collectionId, date);\n }", "private Double zeroIsNull(Double value)\n {\n if (value != null && value.doubleValue() == 0)\n {\n value = null;\n }\n return value;\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 }", "@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}" ]
Get the value of the fist child element with the given name. @param element The parent element @param name The child element name @return The child element value or null
[ "public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }" ]
[ "public int getIntegerBelief(String name){\n Object belief = introspector.getBeliefBase(this).get(name);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n return (Integer) count;\n }", "public Story storyOfText(Configuration configuration, String storyAsText, String storyId) {\n return configuration.storyParser().parseStory(storyAsText, storyId);\n }", "public void updateExceptions(SortedSet<Date> exceptions) {\r\n\r\n SortedSet<Date> e = null == exceptions ? new TreeSet<Date>() : exceptions;\r\n if (!m_model.getExceptions().equals(e)) {\r\n m_model.setExceptions(e);\r\n m_view.updateExceptions();\r\n valueChanged();\r\n sizeChanged();\r\n }\r\n\r\n }", "public Class getSearchClass()\r\n\t{\r\n\t\tObject obj = getExampleObject();\r\n\r\n\t\tif (obj instanceof Identity)\r\n\t\t{\r\n\t\t\treturn ((Identity) obj).getObjectsTopLevelClass();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn obj.getClass();\r\n\t\t}\r\n\t}", "public FastReportBuilder addBarcodeColumn(String title, String property,String className, int barcodeType,boolean showText, int width, boolean fixedWidth,ImageScaleMode imageScaleMode, Style style) throws ColumnBuilderException, ClassNotFoundException {\n\t\tAbstractColumn column = ColumnBuilder.getNew()\n\t\t.setColumnProperty(property, className)\n\t\t.setWidth(width)\n\t\t.setTitle(title)\n\t\t.setFixedWidth(fixedWidth)\n\t\t.setColumnType(ColumnBuilder.COLUMN_TYPE_BARCODE)\n\t\t.setStyle(style)\n\t\t.setBarcodeType(barcodeType)\n\t\t.setShowText(showText)\n\t\t.build();\n\n\t\tif (style == null)\n\t\t\tguessStyle(className, column);\n\n\t\taddColumn(column);\n\n\t\treturn this;\n\t}", "public void removeJobType(final Class<?> jobType) {\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n this.jobTypes.values().remove(jobType);\n }", "public int blast(InputStream input, OutputStream output) throws IOException\n {\n m_input = input;\n m_output = output;\n\n int lit; /* true if literals are coded */\n int dict; /* log2(dictionary size) - 6 */\n int symbol; /* decoded symbol, extra bits for distance */\n int len; /* length for copy */\n int dist; /* distance for copy */\n int copy; /* copy counter */\n //unsigned char *from, *to; /* copy pointers */\n\n /* read header */\n lit = bits(8);\n if (lit > 1)\n {\n return -1;\n }\n dict = bits(8);\n if (dict < 4 || dict > 6)\n {\n return -2;\n }\n\n /* decode literals and length/distance pairs */\n do\n {\n if (bits(1) != 0)\n {\n /* get length */\n symbol = decode(LENCODE);\n len = BASE[symbol] + bits(EXTRA[symbol]);\n if (len == 519)\n {\n break; /* end code */\n }\n\n /* get distance */\n symbol = len == 2 ? 2 : dict;\n dist = decode(DISTCODE) << symbol;\n dist += bits(symbol);\n dist++;\n if (m_first != 0 && dist > m_next)\n {\n return -3; /* distance too far back */\n }\n\n /* copy length bytes from distance bytes back */\n do\n {\n //to = m_out + m_next;\n int to = m_next;\n int from = to - dist;\n copy = MAXWIN;\n if (m_next < dist)\n {\n from += copy;\n copy = dist;\n }\n copy -= m_next;\n if (copy > len)\n {\n copy = len;\n }\n len -= copy;\n m_next += copy;\n do\n {\n //*to++ = *from++;\n m_out[to++] = m_out[from++];\n }\n while (--copy != 0);\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n while (len != 0);\n }\n else\n {\n /* get literal and write it */\n symbol = lit != 0 ? decode(LITCODE) : bits(8);\n m_out[m_next++] = (byte) symbol;\n if (m_next == MAXWIN)\n {\n //if (s->outfun(s->outhow, s->out, s->next)) return 1;\n m_output.write(m_out, 0, m_next);\n m_next = 0;\n m_first = 0;\n }\n }\n }\n while (true);\n\n if (m_next != 0)\n {\n m_output.write(m_out, 0, m_next);\n }\n\n return 0;\n }", "public static void launchPermissionSettings(Activity activity) {\n Intent intent = new Intent();\n intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);\n intent.setData(Uri.fromParts(\"package\", activity.getPackageName(), null));\n activity.startActivity(intent);\n }", "public static appfwprofile_excluderescontenttype_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_excluderescontenttype_binding obj = new appfwprofile_excluderescontenttype_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_excluderescontenttype_binding response[] = (appfwprofile_excluderescontenttype_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Checks if two types are the same or are equivalent under a variable mapping given in the type map that was provided.
[ "private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {\n\t\tif (to.equals(from))\n\t\t\treturn true;\n\n\t\tif (from instanceof TypeVariable) {\n\t\t\treturn to.equals(typeMap.get(((TypeVariable<?>) from).getName()));\n\t\t}\n\n\t\treturn false;\n\t}" ]
[ "public static base_responses enable(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 enableresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tenableresources[i] = new nsacl6();\n\t\t\t\tenableresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}", "public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }", "private static int readObjectData(int offset, String text, List<RTFEmbeddedObject> objects)\n {\n LinkedList<byte[]> blocks = new LinkedList<byte[]>();\n\n offset += (OBJDATA.length());\n offset = skipEndOfLine(text, offset);\n int length;\n int lastOffset = offset;\n\n while (offset != -1)\n {\n length = getBlockLength(text, offset);\n lastOffset = readDataBlock(text, offset, length, blocks);\n offset = skipEndOfLine(text, lastOffset);\n }\n\n RTFEmbeddedObject headerObject;\n RTFEmbeddedObject dataObject;\n\n while (blocks.isEmpty() == false)\n {\n headerObject = new RTFEmbeddedObject(blocks, 2);\n objects.add(headerObject);\n\n if (blocks.isEmpty() == false)\n {\n dataObject = new RTFEmbeddedObject(blocks, headerObject.getTypeFlag2());\n objects.add(dataObject);\n }\n }\n\n return (lastOffset);\n }", "void bootTimeScan(final DeploymentOperations deploymentOperations) {\n // WFCORE-1579: skip the scan if deployment dir is not available\n if (!checkDeploymentDir(this.deploymentDir)) {\n DeploymentScannerLogger.ROOT_LOGGER.bootTimeScanFailed(deploymentDir.getAbsolutePath());\n return;\n }\n\n this.establishDeployedContentList(this.deploymentDir, deploymentOperations);\n deployedContentEstablished = true;\n if (acquireScanLock()) {\n try {\n scan(true, deploymentOperations);\n } finally {\n releaseScanLock();\n }\n }\n }", "protected void solveL(double[] vv) {\n\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sumReal = vv[ip*2];\n double sumImg = vv[ip*2+1];\n\n vv[ip*2] = vv[i*2];\n vv[ip*2+1] = vv[i*2+1];\n\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*stride + (ii-1)*2;\n for( int j = ii-1; j < i; j++ ){\n double luReal = dataLU[index++];\n double luImg = dataLU[index++];\n\n double vvReal = vv[j*2];\n double vvImg = vv[j*2+1];\n\n sumReal -= luReal*vvReal - luImg*vvImg;\n sumImg -= luReal*vvImg + luImg*vvReal;\n }\n } else if( sumReal*sumReal + sumImg*sumImg != 0.0 ) {\n ii=i+1;\n }\n vv[i*2] = sumReal;\n vv[i*2+1] = sumImg;\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 }", "public DiffNode getChild(final NodePath nodePath)\n\t{\n\t\tif (parentNode != null)\n\t\t{\n\t\t\treturn parentNode.getChild(nodePath.getElementSelectors());\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn getChild(nodePath.getElementSelectors());\n\t\t}\n\t}", "static String fromPackageName(String packageName) {\n List<String> tokens = tokenOf(packageName);\n return fromTokens(tokens);\n }", "public static NbtAddress[] getAllByAddress( NbtAddress addr )\n throws UnknownHostException {\n try {\n NbtAddress[] addrs = CLIENT.getNodeStatus( addr );\n cacheAddressArray( addrs );\n return addrs;\n } catch( UnknownHostException uhe ) {\n throw new UnknownHostException( \"no name with type 0x\" +\n Hexdump.toHexString( addr.hostName.hexCode, 2 ) +\n ((( addr.hostName.scope == null ) ||\n ( addr.hostName.scope.length() == 0 )) ?\n \" with no scope\" : \" with scope \" + addr.hostName.scope ) +\n \" for host \" + addr.getHostAddress() );\n }\n }" ]
Populates a resource. @param resource resource instance @param record MPX record @throws MPXJException
[ "private void populateResource(Resource resource, Record record) throws MPXJException\n {\n String falseText = LocaleData.getString(m_locale, LocaleData.NO);\n\n int length = record.getLength();\n int[] model = m_resourceModel.getModel();\n\n for (int i = 0; i < length; i++)\n {\n int mpxFieldType = model[i];\n if (mpxFieldType == -1)\n {\n break;\n }\n\n String field = record.getString(i);\n\n if (field == null || field.length() == 0)\n {\n continue;\n }\n\n ResourceField resourceField = MPXResourceField.getMpxjField(mpxFieldType);\n switch (resourceField)\n {\n case OBJECTS:\n {\n resource.set(resourceField, record.getInteger(i));\n break;\n }\n\n case ID:\n {\n resource.setID(record.getInteger(i));\n break;\n }\n\n case UNIQUE_ID:\n {\n resource.setUniqueID(record.getInteger(i));\n break;\n }\n\n case MAX_UNITS:\n {\n resource.set(resourceField, record.getUnits(i));\n break;\n }\n\n case PERCENT_WORK_COMPLETE:\n case PEAK:\n {\n resource.set(resourceField, record.getPercentage(i));\n break;\n }\n\n case COST:\n case COST_PER_USE:\n case COST_VARIANCE:\n case BASELINE_COST:\n case ACTUAL_COST:\n case REMAINING_COST:\n {\n resource.set(resourceField, record.getCurrency(i));\n break;\n }\n\n case OVERTIME_RATE:\n case STANDARD_RATE:\n {\n resource.set(resourceField, record.getRate(i));\n break;\n }\n\n case REMAINING_WORK:\n case OVERTIME_WORK:\n case BASELINE_WORK:\n case ACTUAL_WORK:\n case WORK:\n case WORK_VARIANCE:\n {\n resource.set(resourceField, record.getDuration(i));\n break;\n }\n\n case ACCRUE_AT:\n {\n resource.set(resourceField, record.getAccrueType(i));\n break;\n }\n\n case LINKED_FIELDS:\n case OVERALLOCATED:\n {\n resource.set(resourceField, record.getBoolean(i, falseText));\n break;\n }\n\n default:\n {\n resource.set(resourceField, field);\n break;\n }\n }\n }\n\n if (m_projectConfig.getAutoResourceUniqueID() == true)\n {\n resource.setUniqueID(Integer.valueOf(m_projectConfig.getNextResourceUniqueID()));\n }\n\n if (m_projectConfig.getAutoResourceID() == true)\n {\n resource.setID(Integer.valueOf(m_projectConfig.getNextResourceID()));\n }\n\n //\n // Handle malformed MPX files - ensure we have a unique ID\n //\n if (resource.getUniqueID() == null)\n {\n resource.setUniqueID(resource.getID());\n }\n }" ]
[ "public static base_responses update(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy updateresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new dospolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].qdepth = resources[i].qdepth;\n\t\t\t\tupdateresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "protected void propagateOnNoPick(GVRPicker picker)\n {\n if (mEventOptions.contains(EventOptions.SEND_PICK_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n getGVRContext().getEventManager().sendEvent(this, IPickEvents.class, \"onNoPick\", picker);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n getGVRContext().getEventManager().sendEvent(mScene, IPickEvents.class, \"onNoPick\", picker);\n }\n }\n }", "public static Map<String, String> getMetadataFromSequenceFile(FileSystem fs, Path path) {\n try {\n Configuration conf = new Configuration();\n conf.setInt(\"io.file.buffer.size\", 4096);\n SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, new Configuration());\n SequenceFile.Metadata meta = reader.getMetadata();\n reader.close();\n TreeMap<Text, Text> map = meta.getMetadata();\n Map<String, String> values = new HashMap<String, String>();\n for(Map.Entry<Text, Text> entry: map.entrySet())\n values.put(entry.getKey().toString(), entry.getValue().toString());\n\n return values;\n } catch(IOException e) {\n throw new RuntimeException(e);\n }\n }", "public static MediaType nonBinaryUtf8( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, UTF_8 );\n }", "String encodePath(String in) {\n try {\n String encodedString = HierarchicalUriComponents.encodeUriComponent(in, \"UTF-8\",\n HierarchicalUriComponents.Type.PATH_SEGMENT);\n if (encodedString.startsWith(_design_prefix_encoded) ||\n encodedString.startsWith(_local_prefix_encoded)) {\n // we replaced the first slash in the design or local doc URL, which we shouldn't\n // so let's put it back\n return encodedString.replaceFirst(\"%2F\", \"/\");\n } else {\n return encodedString;\n }\n } catch (UnsupportedEncodingException uee) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(\n \"Couldn't encode ID \" + in,\n uee);\n }\n }", "private void processKnownType(FieldType type)\n {\n //System.out.println(\"Header: \" + type);\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, 36, false, 16, \"\"));\n\n GraphicalIndicator indicator = m_container.getCustomField(type).getGraphicalIndicator();\n indicator.setFieldType(type);\n int flags = m_data[m_dataOffset];\n indicator.setProjectSummaryInheritsFromSummaryRows((flags & 0x08) != 0);\n indicator.setSummaryRowsInheritFromNonSummaryRows((flags & 0x04) != 0);\n indicator.setDisplayGraphicalIndicators((flags & 0x02) != 0);\n indicator.setShowDataValuesInToolTips((flags & 0x01) != 0);\n m_dataOffset += 20;\n\n int nonSummaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int summaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int projectSummaryOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int dataSize = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n //System.out.println(\"Data\");\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, dataSize, false, 16, \"\"));\n\n int maxNonSummaryRowOffset = m_dataOffset + summaryRowOffset;\n int maxSummaryRowOffset = m_dataOffset + projectSummaryOffset;\n int maxProjectSummaryOffset = m_dataOffset + dataSize;\n\n m_dataOffset += nonSummaryRowOffset;\n\n while (m_dataOffset + 2 < maxNonSummaryRowOffset)\n {\n indicator.addNonSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxSummaryRowOffset)\n {\n indicator.addSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxProjectSummaryOffset)\n {\n indicator.addProjectSummaryCriteria(processCriteria(type));\n }\n }", "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 static nsrpcnode get(nitro_service service, String ipaddress) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tobj.set_ipaddress(ipaddress);\n\t\tnsrpcnode response = (nsrpcnode) obj.get_resource(service);\n\t\treturn response;\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 }" ]
required for rest assured base URI configuration.
[ "public void configure(@Observes(precedence = -200) ArquillianDescriptor arquillianDescriptor) {\n restAssuredConfigurationInstanceProducer.set(\n RestAssuredConfiguration.fromMap(arquillianDescriptor\n .extension(\"restassured\")\n .getExtensionProperties()));\n }" ]
[ "private boolean addDeploymentTypeBasedDependencies(ProjectModel projectModel, Pom modulePom)\n {\n if (projectModel.getProjectType() == null)\n return true;\n switch (projectModel.getProjectType()){\n case \"ear\":\n break;\n case \"war\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_SERVLET_31));\n break;\n case \"ejb\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_32));\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_CDI));\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JAVAX_ANN));\n break;\n case \"ejb-client\":\n modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_CLIENT));\n break;\n }\n return false;\n }", "public void serializeTimingData(Path outputPath)\n {\n //merge subThreads instances into the main instance\n merge();\n\n try (FileWriter fw = new FileWriter(outputPath.toFile()))\n {\n fw.write(\"Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\\n\");\n for (Map.Entry<String, TimingData> timing : executionInfo.entrySet())\n {\n TimingData data = timing.getValue();\n long totalMillis = (data.totalNanos / 1000000);\n double millisPerExecution = (double) totalMillis / (double) data.numberOfExecutions;\n fw.write(String.format(\"%6d, %6d, %8.2f, %s\\n\",\n data.numberOfExecutions, totalMillis, millisPerExecution,\n StringEscapeUtils.escapeCsv(timing.getKey())\n ));\n }\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\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 }", "@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 static final Date utc2date(Long time) {\n\n // don't accept negative values\n if (time == null || time < 0) return null;\n \n // add the timezone offset\n time += timezoneOffsetMillis(new Date(time));\n\n return new Date(time);\n }", "public static Value.Builder makeValue(Date date) {\n return Value.newBuilder().setTimestampValue(toTimestamp(date.getTime() * 1000L));\n }", "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 }", "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 start() {\n syncLock.lock();\n try {\n if (!this.isConfigured) {\n return;\n }\n instanceChangeStreamListener.stop();\n if (listenersEnabled) {\n instanceChangeStreamListener.start();\n }\n\n if (syncThread == null) {\n syncThread = new Thread(\n new DataSynchronizerRunner(\n new WeakReference<>(this),\n networkMonitor,\n logger\n ),\n \"dataSynchronizerRunnerThread\"\n );\n }\n if (syncThreadEnabled && !isRunning) {\n syncThread.start();\n isRunning = true;\n }\n } finally {\n syncLock.unlock();\n }\n }" ]
Creates an object instance according to clb, and fills its fileds width data provided by row. @param row A {@link Map} contain the Object/Row mapping for the object. @param targetClassDescriptor If the "ojbConcreteClass" feature was used, the target {@link org.apache.ojb.broker.metadata.ClassDescriptor} could differ from the descriptor this class was associated - see {@link #selectClassDescriptor}. @param targetObject If 'null' a new object instance is build, else fields of object will be refreshed. @throws PersistenceBrokerException if there ewas an error creating the new object
[ "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 }" ]
[ "public Note add(String photoId, Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\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\r\n Element noteElement = response.getPayload();\r\n note.setId(noteElement.getAttribute(\"id\"));\r\n return note;\r\n }", "public void removeFile(String name) {\n if(files.containsKey(name)) {\n files.remove(name);\n }\n\n if(fileStreams.containsKey(name)) {\n fileStreams.remove(name);\n }\n }", "protected void aliasGeneric( Object variable , String name ) {\n if( variable.getClass() == Integer.class ) {\n alias(((Integer)variable).intValue(),name);\n } else if( variable.getClass() == Double.class ) {\n alias(((Double)variable).doubleValue(),name);\n } else if( variable.getClass() == DMatrixRMaj.class ) {\n alias((DMatrixRMaj)variable,name);\n } else if( variable.getClass() == FMatrixRMaj.class ) {\n alias((FMatrixRMaj)variable,name);\n } else if( variable.getClass() == DMatrixSparseCSC.class ) {\n alias((DMatrixSparseCSC)variable,name);\n } else if( variable.getClass() == SimpleMatrix.class ) {\n alias((SimpleMatrix) variable, name);\n } else if( variable instanceof DMatrixFixed ) {\n DMatrixRMaj M = new DMatrixRMaj(1,1);\n ConvertDMatrixStruct.convert((DMatrixFixed)variable,M);\n alias(M,name);\n } else if( variable instanceof FMatrixFixed ) {\n FMatrixRMaj M = new FMatrixRMaj(1,1);\n ConvertFMatrixStruct.convert((FMatrixFixed)variable,M);\n alias(M,name);\n } else {\n throw new RuntimeException(\"Unknown value type of \"+\n (variable.getClass().getSimpleName())+\" for variable \"+name);\n }\n }", "private String getResponseString(boolean async, UploaderResponse response) {\r\n return async ? response.getTicketId() : response.getPhotoId();\r\n }", "@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (summaryFile != null) {\n try {\n Persister persister = new Persister();\n persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize summary report.\", x, Project.MSG_WARN);\n }\n }\n }", "public static String readUntilTag(Reader r) throws IOException {\r\n if (!r.ready()) {\r\n return \"\";\r\n }\r\n StringBuilder b = new StringBuilder();\r\n int c = r.read();\r\n while (c >= 0 && c != '<') {\r\n b.append((char) c);\r\n c = r.read();\r\n }\r\n return b.toString();\r\n }", "private Map<String, Entry> readEntries(String mapping, boolean ignoreCase) {\n\t\tMap<String, Entry> entries = new HashMap<>();\n\n\t\ttry {\n\t\t\t// ms, 2010-10-05: try to load the file from the CLASSPATH first\n\t\t\tInputStream is = getClass().getClassLoader().getResourceAsStream(mapping);\n\t\t\t// if not found in the CLASSPATH, load from the file system\n\t\t\tif (is == null) is = new FileInputStream(mapping);\n\t\t\tBufferedReader rd = new BufferedReader(new InputStreamReader(is));\n\n\t\t\tint lineCount = 0;\n\t\t\tfor (String line; (line = rd.readLine()) != null; ) {\n\t\t\t\tlineCount ++;\n\t\t\t\tString[] split = line.split(\"\\t\");\n\t\t\t\tif (split.length < 2 || split.length > 4)\n\t\t\t\t\tthrow new RuntimeException(\"Provided mapping file is in wrong format\");\n\t\t\t\tif (split[1].trim().equalsIgnoreCase(\"AS\")) System.err.println(\"ERRRR \" + mapping + \"|\" + line + \" at \" + lineCount);\n\t\t\t\tString stringLine = split[1].trim();\n\t\t\t\tif (ignoreCase) stringLine = stringLine.toLowerCase();\n\t\t\t\tString[] words = stringLine.split(\"\\\\s+\");\n\t\t\t\tString type = split[0].trim();\n\t\t\t\tSet<String> overwritableTypes = new HashSet<String>();\n\t\t\t\toverwritableTypes.add(flags.backgroundSymbol);\n\t\t\t\toverwritableTypes.add(null);\n\t\t\t\tdouble priority = 0;\n\t\t\t\tList<String> tokens = new ArrayList<String>();\n\n\t\t\t\ttry {\n\t\t\t\t\tif (split.length >= 3)\n\t\t\t\t\t\toverwritableTypes.addAll(Arrays.asList(split[2].trim().split(\",\")));\n\t\t\t\t\tif (split.length == 4)\n\t\t\t\t\t\tpriority = Double.parseDouble(split[3].trim());\n\n\t\t\t\t\tfor (String str : words) {\n\t\t\t\t\t\ttokens.add(str);\n\t\t\t\t\t}\n\t\t\t\t} catch(NumberFormatException e) {\n\t\t\t\t\tSystem.err.println(\"ERROR: Invalid line \" + lineCount + \" in regexner file \" + mapping + \": \\\"\" + line + \"\\\"!\");\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t\taddEntry(words, type, priority, overwritableTypes);\n\t\t\t}\n\t\t\trd.close();\n\t\t\tis.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn entries;\n\t}", "public static boolean isVector(DMatrixSparseCSC a) {\n return (a.numCols == 1 && a.numRows > 1) || (a.numRows == 1 && a.numCols>1);\n }", "public static ObjectModelResolver get(String resolverId) {\n List<ObjectModelResolver> resolvers = getResolvers();\n\n for (ObjectModelResolver resolver : resolvers) {\n if (resolver.accept(resolverId)) {\n return resolver;\n }\n }\n\n return null;\n }" ]
Create a new queued pool with key type K, request type R, and value type V. @param factory The factory that creates objects @param config The pool config @return The created pool
[ "public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory,\n ResourcePoolConfig config) {\n return new QueuedKeyedResourcePool<K, V>(factory, config);\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}", "public static SimpleFeatureType createGridFeatureType(\n @Nonnull final MapfishMapContext mapContext,\n @Nonnull final Class<? extends Geometry> geomClass) {\n final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();\n CoordinateReferenceSystem projection = mapContext.getBounds().getProjection();\n typeBuilder.add(Constants.Style.Grid.ATT_GEOM, geomClass, projection);\n typeBuilder.setName(Constants.Style.Grid.NAME_LINES);\n\n return typeBuilder.buildFeatureType();\n }", "static void processRoot(final File root, final ProcessedLayers layers, final LayerPathSetter setter) throws IOException {\n final LayersConfig layersConfig = LayersConfig.getLayersConfig(root);\n // Process layers\n final File layersDir = new File(root, layersConfig.getLayersPath());\n if (!layersDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationNoLayersConfigFound(layersDir.getAbsolutePath());\n }\n // else this isn't a root that has layers and add-ons\n } else {\n // check for a valid layer configuration\n for (final String layer : layersConfig.getLayers()) {\n File layerDir = new File(layersDir, layer);\n if (!layerDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationMissingLayer(layer, layersDir.getAbsolutePath());\n }\n // else this isn't a standard layers and add-ons structure\n return;\n }\n layers.addLayer(layer, layerDir, setter);\n }\n }\n // Finally process the add-ons\n final File addOnsDir = new File(root, layersConfig.getAddOnsPath());\n final File[] addOnsList = addOnsDir.listFiles();\n if (addOnsList != null) {\n for (final File addOn : addOnsList) {\n layers.addAddOn(addOn.getName(), addOn, setter);\n }\n }\n }", "public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) {\n\tif (value == null) {\n\t list.setSelectedIndex(0);\n\t return false;\n\t}\n\telse {\n\t int index = findValueInListBox(list, value);\n\t if (index >= 0) {\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t if (addMissingValues) {\n\t\tlist.addItem(value, value);\n\n\t\t// now that it's there, search again\n\t\tindex = findValueInListBox(list, value);\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t return false;\n\t}\n }", "public static auditmessages[] get(nitro_service service) throws Exception{\n\t\tauditmessages obj = new auditmessages();\n\t\tauditmessages[] response = (auditmessages[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public BufferedImage getBufferedImage(int width, int height) {\n // using the new approach of Java 2D API\n BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2d = (Graphics2D) buf.getGraphics();\n g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2d.drawImage(image, 0, 0, width, height, null);\n g2d.dispose();\n return (buf);\n }", "public Date getStartDate()\n {\n Date result = (Date) getCachedValue(ProjectField.START_DATE);\n if (result == null)\n {\n result = getParentFile().getStartDate();\n }\n return (result);\n }", "public String makeReport(String name, String report) {\n long increment = Long.valueOf(report);\n long currentLineCount = globalLineCounter.addAndGet(increment);\n\n if (currentLineCount >= maxScenarios) {\n return \"exit\";\n } else {\n return \"ok\";\n }\n }", "private static String buildErrorMsg(List<String> dependencies, String message) {\n final StringBuilder buffer = new StringBuilder();\n boolean isFirstElement = true;\n for (String dependency : dependencies) {\n if (!isFirstElement) {\n buffer.append(\", \");\n }\n // check if it is an instance of Artifact - add the gavc else append the object\n buffer.append(dependency);\n\n isFirstElement = false;\n }\n return String.format(message, buffer.toString());\n }" ]
Creates an instance of a NewSimpleBean from an annotated class @param clazz The annotated class @param beanManager The Bean manager @return a new NewSimpleBean instance
[ "public static <T> NewManagedBean<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new NewManagedBean<T>(attributes, clazz, new StringBeanIdentifier(BeanIdentifiers.forNewManagedBean(clazz)), beanManager);\n }" ]
[ "public RgbaColor opacify(float amount) {\n return new RgbaColor(r, g, b, alphaCheck(a + amount));\n }", "public Integer getIdFromName(String profileName) {\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.PROFILE_PROFILE_NAME + \" = ?\");\n query.setString(1, profileName);\n results = query.executeQuery();\n if (results.next()) {\n Object toReturn = results.getObject(Constants.GENERIC_ID);\n query.close();\n return (Integer) toReturn;\n }\n query.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }", "private void writeTaskBaselines(Project.Tasks.Task xmlTask, Task mpxjTask)\n {\n Project.Tasks.Task.Baseline baseline = m_factory.createProjectTasksTaskBaseline();\n boolean populated = false;\n\n Number cost = mpxjTask.getBaselineCost();\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n Duration duration = mpxjTask.getBaselineDuration();\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setDuration(DatatypeConverter.printDuration(this, duration));\n baseline.setDurationFormat(DatatypeConverter.printDurationTimeUnits(duration, false));\n }\n\n Date date = mpxjTask.getBaselineFinish();\n if (date != null)\n {\n populated = true;\n baseline.setFinish(date);\n }\n\n date = mpxjTask.getBaselineStart();\n if (date != null)\n {\n populated = true;\n baseline.setStart(date);\n }\n\n duration = mpxjTask.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(BigInteger.ZERO);\n xmlTask.getBaseline().add(baseline);\n }\n\n for (int loop = 1; loop <= 10; loop++)\n {\n baseline = m_factory.createProjectTasksTaskBaseline();\n populated = false;\n\n cost = mpxjTask.getBaselineCost(loop);\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n duration = mpxjTask.getBaselineDuration(loop);\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setDuration(DatatypeConverter.printDuration(this, duration));\n baseline.setDurationFormat(DatatypeConverter.printDurationTimeUnits(duration, false));\n }\n\n date = mpxjTask.getBaselineFinish(loop);\n if (date != null)\n {\n populated = true;\n baseline.setFinish(date);\n }\n\n date = mpxjTask.getBaselineStart(loop);\n if (date != null)\n {\n populated = true;\n baseline.setStart(date);\n }\n\n duration = mpxjTask.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(BigInteger.valueOf(loop));\n xmlTask.getBaseline().add(baseline);\n }\n }\n }", "private void readColumnBlock(int startIndex, int blockLength) throws Exception\n {\n int endIndex = startIndex + blockLength;\n List<Integer> blocks = new ArrayList<Integer>();\n for (int index = startIndex; index < endIndex - 11; index++)\n {\n if (matchChildBlock(index))\n {\n int childBlockStart = index - 2;\n blocks.add(Integer.valueOf(childBlockStart));\n }\n }\n blocks.add(Integer.valueOf(endIndex));\n\n int childBlockStart = -1;\n for (int childBlockEnd : blocks)\n {\n if (childBlockStart != -1)\n {\n int childblockLength = childBlockEnd - childBlockStart;\n try\n {\n readColumn(childBlockStart, childblockLength);\n }\n catch (UnexpectedStructureException ex)\n {\n logUnexpectedStructure();\n }\n }\n childBlockStart = childBlockEnd;\n }\n }", "private Logger createLoggerInstance(String loggerName) throws Exception\r\n {\r\n Class loggerClass = getConfiguration().getLoggerClass();\r\n Logger log = (Logger) ClassHelper.newInstance(loggerClass, String.class, loggerName);\r\n log.configure(getConfiguration());\r\n return log;\r\n }", "public void signIn(String key, WebSocketConnection connection) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.put(connection, connection);\n }", "private ColumnDef addColumnFor(FieldDescriptorDef fieldDef, TableDef tableDef)\r\n {\r\n String name = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);\r\n ColumnDef columnDef = tableDef.getColumn(name);\r\n\r\n if (columnDef == null)\r\n {\r\n columnDef = new ColumnDef(name);\r\n tableDef.addColumn(columnDef);\r\n }\r\n if (!fieldDef.isNested())\r\n { \r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_JAVANAME, fieldDef.getName());\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_ID, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID));\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_PRIMARYKEY, \"true\");\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n else if (!fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_NULLABLE, true))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n if (\"database\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT)))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_AUTOINCREMENT, \"true\");\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_SIZE, fieldDef.getSizeConstraint());\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION));\r\n }\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION));\r\n }\r\n return columnDef;\r\n }", "public PhotoList<Photo> getPhotos(String photosetId, Set<String> extras, int privacy_filter, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n if (privacy_filter > 0) {\r\n parameters.put(\"privacy_filter\", \"\" + privacy_filter);\r\n }\r\n\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element photoset = response.getPayload();\r\n NodeList photoElements = photoset.getElementsByTagName(\"photo\");\r\n photos.setPage(photoset.getAttribute(\"page\"));\r\n photos.setPages(photoset.getAttribute(\"pages\"));\r\n photos.setPerPage(photoset.getAttribute(\"per_page\"));\r\n photos.setTotal(photoset.getAttribute(\"total\"));\r\n\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement, photoset));\r\n }\r\n\r\n return photos;\r\n }", "public static String getVersionString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.version\");\n\t\t}\n\t\treturn versionString;\n\t}" ]
Returns all program element docs that have a visibility greater or equal than the specified level
[ "private <T extends ProgramElementDoc> List<T> filterByVisibility(T[] docs, Visibility visibility) {\n\tif (visibility == Visibility.PRIVATE)\n\t return Arrays.asList(docs);\n\n\tList<T> filtered = new ArrayList<T>();\n\tfor (T doc : docs) {\n\t if (Visibility.get(doc).compareTo(visibility) > 0)\n\t\tfiltered.add(doc);\n\t}\n\treturn filtered;\n }" ]
[ "@Override\n public PersistentResourceXMLDescription getParserDescription() {\n return PersistentResourceXMLDescription.builder(ElytronExtension.SUBSYSTEM_PATH, getNameSpace())\n .addAttribute(ElytronDefinition.DEFAULT_AUTHENTICATION_CONTEXT)\n .addAttribute(ElytronDefinition.INITIAL_PROVIDERS)\n .addAttribute(ElytronDefinition.FINAL_PROVIDERS)\n .addAttribute(ElytronDefinition.DISALLOWED_PROVIDERS)\n .addAttribute(ElytronDefinition.SECURITY_PROPERTIES, new AttributeParsers.PropertiesParser(null, SECURITY_PROPERTY, true), new AttributeMarshallers.PropertiesAttributeMarshaller(null, SECURITY_PROPERTY, true))\n .addChild(getAuthenticationClientParser())\n .addChild(getProviderParser())\n .addChild(getAuditLoggingParser())\n .addChild(getDomainParser())\n .addChild(getRealmParser())\n .addChild(getCredentialSecurityFactoryParser())\n .addChild(getMapperParser())\n .addChild(getHttpParser())\n .addChild(getSaslParser())\n .addChild(getTlsParser())\n .addChild(decorator(CREDENTIAL_STORES).addChild(new CredentialStoreParser().parser))\n .addChild(getDirContextParser())\n .addChild(getPolicyParser())\n .build();\n }", "protected CmsAccessControlEntry getImportAccessControlEntry(\n CmsResource res,\n String id,\n String allowed,\n String denied,\n String flags) {\n\n return new CmsAccessControlEntry(\n res.getResourceId(),\n new CmsUUID(id),\n Integer.parseInt(allowed),\n Integer.parseInt(denied),\n Integer.parseInt(flags));\n }", "private void query(String zipcode) {\n /* Setup YQL query statement using dynamic zipcode. The statement searches geo.places\n for the zipcode and returns XML which includes the WOEID. For more info about YQL go\n to: http://developer.yahoo.com/yql/ */\n String qry = URLEncoder.encode(\"SELECT woeid FROM geo.places WHERE text=\" + zipcode + \" LIMIT 1\");\n\n // Generate request URI using the query statement\n URL url;\n try {\n // get URL content\n url = new URL(\"http://query.yahooapis.com/v1/public/yql?q=\" + qry);\n URLConnection conn = url.openConnection();\n\n InputStream content = conn.getInputStream();\n parseResponse(content);\n\n } catch (MalformedURLException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }", "public static List<String> getStoreNames(List<StoreDefinition> list, boolean ignoreViews) {\n List<String> storeNameSet = new ArrayList<String>();\n for(StoreDefinition def: list)\n if(!def.isView() || !ignoreViews)\n storeNameSet.add(def.getName());\n return storeNameSet;\n }", "public boolean removeKey(long key) {\r\n\tint i = indexOfKey(key);\r\n\tif (i<0) return false; // key not contained\r\n\r\n\tthis.state[i]=REMOVED;\r\n\tthis.values[i]=0; // delta\r\n\tthis.distinct--;\r\n\r\n\tif (this.distinct < this.lowWaterMark) {\r\n\t\tint newCapacity = chooseShrinkCapacity(this.distinct,this.minLoadFactor, this.maxLoadFactor);\r\n\t\trehash(newCapacity);\r\n\t}\r\n\t\r\n\treturn true;\t\r\n}", "public static service_dospolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tservice_dospolicy_binding obj = new service_dospolicy_binding();\n\t\tobj.set_name(name);\n\t\tservice_dospolicy_binding response[] = (service_dospolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void processPick(boolean touched, MotionEvent event)\n {\n mPickEventLock.lock();\n mTouched = touched;\n mMotionEvent = event;\n doPick();\n mPickEventLock.unlock();\n }", "private String formatPercentage(Number value)\n {\n return (value == null ? null : m_formats.getPercentageDecimalFormat().format(value) + \"%\");\n }", "public String getDefaultTableName()\r\n {\r\n String name = getName();\r\n int lastDotPos = name.lastIndexOf('.');\r\n int lastDollarPos = name.lastIndexOf('$');\r\n\r\n return lastDollarPos > lastDotPos ? name.substring(lastDollarPos + 1) : name.substring(lastDotPos + 1);\r\n }" ]
Use this API to unset the properties of systemcollectionparam resource. Properties that need to be unset are specified in args array.
[ "public static base_response unset(nitro_service client, systemcollectionparam resource, String[] args) throws Exception{\n\t\tsystemcollectionparam unsetresource = new systemcollectionparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
[ "public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\n }", "private static boolean isEqual(Method m, Method a) {\n if (m.getName().equals(a.getName()) && m.getParameterTypes().length == a.getParameterTypes().length && m.getReturnType().isAssignableFrom(a.getReturnType())) {\n for (int i = 0; i < m.getParameterTypes().length; i++) {\n if (!(m.getParameterTypes()[i].isAssignableFrom(a.getParameterTypes()[i]))) {\n return false;\n }\n }\n return true;\n }\n return false;\n }", "public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter)\n throws Throwable {\n run(configuration, candidateSteps, story, filter, null);\n }", "protected void runQuery() {\n\n String pool = m_pool.getValue();\n String stmt = m_script.getValue();\n if (stmt.trim().isEmpty()) {\n return;\n }\n CmsStringBufferReport report = new CmsStringBufferReport(Locale.ENGLISH);\n List<Throwable> errors = new ArrayList<>();\n CmsSqlConsoleResults result = m_console.execute(stmt, pool, report, errors);\n if (errors.size() > 0) {\n CmsErrorDialog.showErrorDialog(report.toString() + errors.get(0).getMessage(), errors.get(0));\n } else {\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_SQLCONSOLE_QUERY_RESULTS_0));\n window.setContent(new CmsSqlConsoleResultsForm(result, report.toString()));\n A_CmsUI.get().addWindow(window);\n window.center();\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}", "public void showToast(final String message, float duration) {\n final float quadWidth = 1.2f;\n final GVRTextViewSceneObject toastSceneObject = new GVRTextViewSceneObject(this, quadWidth, quadWidth / 5,\n message);\n\n toastSceneObject.setTextSize(6);\n toastSceneObject.setTextColor(Color.WHITE);\n toastSceneObject.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);\n toastSceneObject.setBackgroundColor(Color.DKGRAY);\n toastSceneObject.setRefreshFrequency(GVRTextViewSceneObject.IntervalFrequency.REALTIME);\n\n final GVRTransform t = toastSceneObject.getTransform();\n t.setPositionZ(-1.5f);\n\n final GVRRenderData rd = toastSceneObject.getRenderData();\n final float finalOpacity = 0.7f;\n rd.getMaterial().setOpacity(0);\n rd.setRenderingOrder(2 * GVRRenderData.GVRRenderingOrder.OVERLAY);\n rd.setDepthTest(false);\n\n final GVRCameraRig rig = getMainScene().getMainCameraRig();\n rig.addChildObject(toastSceneObject);\n\n final GVRMaterialAnimation fadeOut = new GVRMaterialAnimation(rd.getMaterial(), duration / 4.0f) {\n @Override\n protected void animate(GVRHybridObject target, float ratio) {\n final GVRMaterial material = (GVRMaterial) target;\n material.setOpacity(finalOpacity - ratio * finalOpacity);\n }\n };\n fadeOut.setOnFinish(new GVROnFinish() {\n @Override\n public void finished(GVRAnimation animation) {\n rig.removeChildObject(toastSceneObject);\n }\n });\n\n final GVRMaterialAnimation fadeIn = new GVRMaterialAnimation(rd.getMaterial(), 3.0f * duration / 4.0f) {\n @Override\n protected void animate(GVRHybridObject target, float ratio) {\n final GVRMaterial material = (GVRMaterial) target;\n material.setOpacity(ratio * finalOpacity);\n }\n };\n fadeIn.setOnFinish(new GVROnFinish() {\n @Override\n public void finished(GVRAnimation animation) {\n getAnimationEngine().start(fadeOut);\n }\n });\n\n getAnimationEngine().start(fadeIn);\n }", "public void processCollection(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n CollectionDescriptorDef collDef = _curClassDef.getCollection(name);\r\n String attrName;\r\n\r\n if (collDef == null)\r\n {\r\n collDef = new CollectionDescriptorDef(name);\r\n _curClassDef.addCollection(collDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processCollection\", \" Processing collection \"+collDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n collDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n if (OjbMemberTagsHandler.getMemberDimension() > 0)\r\n {\r\n // we store the array-element type for later use\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n else\r\n { \r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n\r\n _curCollectionDef = collDef;\r\n generate(template);\r\n _curCollectionDef = null;\r\n }", "public synchronized String requestBlock(String name) {\n if (blocks.isEmpty()) {\n return \"exit\";\n }\n\n remainingBlocks.decrementAndGet();\n return blocks.poll().createResponse();\n }", "public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment){\n\t\t\tdouble minDistance = Double.MAX_VALUE;\n\t\t\tPoint2D.Double minDistancePoint = null;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/nPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < nPointsPerSegment; j++){\n\t\t \t\tPoint2D.Double candidate = new Point2D.Double(x, spline.value(x));\n\t\t \t\tdouble d = p.distance(candidate);\n\t\t \t\tif(d<minDistance){\n\t\t \t\t\tminDistance = d;\n\t\t \t\t\tminDistancePoint = candidate;\n\t\t \t\t}\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t return minDistancePoint;\n\t}" ]
Cause the container to be cleaned up, including all registered bean managers, and all deployment services
[ "public void cleanup() {\n managers.clear();\n for (BeanManagerImpl beanManager : beanDeploymentArchives.values()) {\n beanManager.cleanup();\n }\n beanDeploymentArchives.clear();\n deploymentServices.cleanup();\n deploymentManager.cleanup();\n instance.clear(contextId);\n }" ]
[ "synchronized void removeServerProcess() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);\n }", "public static Predicate anyBitsSet(final String expr, final long bits) {\n return new Predicate() {\n private String param;\n public void init(AbstractSqlCreator creator) {\n param = creator.allocateParameter();\n creator.setParameter(param, bits);\n }\n public String toSql() {\n return String.format(\"(%s & :%s) > 0\", expr, param);\n }\n };\n }", "public static List<DbModule> getAllSubmodules(final DbModule module) {\n final List<DbModule> submodules = new ArrayList<DbModule>();\n submodules.addAll(module.getSubmodules());\n\n for(final DbModule submodule: module.getSubmodules()){\n submodules.addAll(getAllSubmodules(submodule));\n }\n\n return submodules;\n }", "private static void addVersionInfo(byte[] grid, int size, int version) {\n // TODO: Zint masks with 0x41 instead of 0x01; which is correct? https://sourceforge.net/p/zint/tickets/110/\n long version_data = QR_ANNEX_D[version - 7];\n for (int i = 0; i < 6; i++) {\n grid[((size - 11) * size) + i] += (version_data >> (i * 3)) & 0x01;\n grid[((size - 10) * size) + i] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[((size - 9) * size) + i] += (version_data >> ((i * 3) + 2)) & 0x01;\n grid[(i * size) + (size - 11)] += (version_data >> (i * 3)) & 0x01;\n grid[(i * size) + (size - 10)] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[(i * size) + (size - 9)] += (version_data >> ((i * 3) + 2)) & 0x01;\n }\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}", "public static int cudnnSoftmaxBackward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnSoftmaxBackwardNative(handle, algo, mode, alpha, yDesc, y, dyDesc, dy, beta, dxDesc, dx));\n }", "public void copy(ProjectCalendar cal)\n {\n setName(cal.getName());\n setParent(cal.getParent());\n System.arraycopy(cal.getDays(), 0, getDays(), 0, getDays().length);\n for (ProjectCalendarException ex : cal.m_exceptions)\n {\n addCalendarException(ex.getFromDate(), ex.getToDate());\n for (DateRange range : ex)\n {\n ex.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n\n for (ProjectCalendarHours hours : getHours())\n {\n if (hours != null)\n {\n ProjectCalendarHours copyHours = cal.addCalendarHours(hours.getDay());\n for (DateRange range : hours)\n {\n copyHours.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n }\n }", "public static final BigInteger printDurationInIntegerTenthsOfMinutes(Duration duration)\n {\n BigInteger result = null;\n\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigInteger.valueOf((long) printDurationFractionsOfMinutes(duration, 10));\n }\n\n return result;\n }", "synchronized void openConnection(final ModelController controller, final ActiveOperation.CompletedCallback<ModelNode> callback) throws Exception {\n boolean ok = false;\n final Connection connection = connectionManager.connect();\n try {\n channelHandler.executeRequest(new ServerRegisterRequest(), null, callback);\n // HC is the same version, so it will support sending the subject\n channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IDENTITY, Boolean.TRUE);\n channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IN_VM, Boolean.TRUE);\n channelHandler.addHandlerFactory(new TransactionalProtocolOperationHandler(controller, channelHandler, responseAttachmentSupport));\n ok = true;\n } finally {\n if(!ok) {\n connection.close();\n }\n }\n }" ]
Retrieves all file version retentions. @param api the API connection to be used by the resource. @param fields the fields to retrieve. @return an iterable contains information about all file version retentions.
[ "public static Iterable<BoxFileVersionRetention.Info> getAll(BoxAPIConnection api, String ... fields) {\n return getRetentions(api, new QueryFilter(), fields);\n }" ]
[ "public Conditionals addIfMatch(Tag tag) {\n Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE));\n Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH));\n List<Tag> match = new ArrayList<>(this.match);\n\n if (tag == null) {\n tag = Tag.ALL;\n }\n if (Tag.ALL.equals(tag)) {\n match.clear();\n }\n if (!match.contains(Tag.ALL)) {\n if (!match.contains(tag)) {\n match.add(tag);\n }\n }\n else {\n throw new IllegalArgumentException(\"Tag ALL already in the list\");\n }\n return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince);\n }", "public static aaagroup_aaauser_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_aaauser_binding obj = new aaagroup_aaauser_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_aaauser_binding response[] = (aaagroup_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Map<InetSocketAddress, ServerPort> activePorts() {\n final Server server = this.server;\n if (server != null) {\n return server.activePorts();\n } else {\n return Collections.emptyMap();\n }\n }", "public static long getVisibilityCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(VISIBILITY_CACHE_WEIGHT, VISIBILITY_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\n \"Cache size must be positive for \" + VISIBILITY_CACHE_WEIGHT);\n }\n return size;\n }", "private static void waitUntilFinished(FluoConfiguration config) {\n try (Environment env = new Environment(config)) {\n List<TableRange> ranges = getRanges(env);\n\n outer: while (true) {\n long ts1 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n for (TableRange range : ranges) {\n boolean sawNotifications = waitTillNoNotifications(env, range);\n if (sawNotifications) {\n ranges = getRanges(env);\n // This range had notifications. Processing those notifications may have created\n // notifications in previously scanned ranges, so start over.\n continue outer;\n }\n }\n long ts2 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n\n // Check to ensure the Oracle issued no timestamps during the scan for notifications.\n if (ts2 - ts1 == 1) {\n break;\n }\n }\n } catch (Exception e) {\n log.error(\"An exception was thrown -\", e);\n System.exit(-1);\n }\n }", "public static double ChiSquare(double[] histogram1, double[] histogram2) {\n double r = 0;\n for (int i = 0; i < histogram1.length; i++) {\n double t = histogram1[i] + histogram2[i];\n if (t != 0)\n r += Math.pow(histogram1[i] - histogram2[i], 2) / t;\n }\n\n return 0.5 * r;\n }", "private TrackSourceSlot findTrackSourceSlot() {\n TrackSourceSlot result = TRACK_SOURCE_SLOT_MAP.get(packetBytes[41]);\n if (result == null) {\n return TrackSourceSlot.UNKNOWN;\n }\n return result;\n }", "private void deleteDir(File dir)\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].exists())\r\n {\r\n continue;\r\n }\r\n if (files[idx].isDirectory())\r\n {\r\n deleteDir(files[idx]);\r\n }\r\n else\r\n {\r\n files[idx].delete();\r\n }\r\n }\r\n dir.delete();\r\n }\r\n }", "@Override\n protected void updateState(final String name, final InstallationModificationImpl modification, final InstallationModificationImpl.InstallationState state) {\n final PatchableTarget.TargetInfo identityInfo = modification.getModifiedState();\n this.identity = new Identity() {\n @Override\n public String getVersion() {\n return modification.getVersion();\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public TargetInfo loadTargetInfo() throws IOException {\n return identityInfo;\n }\n\n @Override\n public DirectoryStructure getDirectoryStructure() {\n return modification.getDirectoryStructure();\n }\n };\n\n this.allPatches = Collections.unmodifiableList(modification.getAllPatches());\n this.layers.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getLayers().entrySet()) {\n final String layerName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putLayer(layerName, new LayerInfo(layerName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n this.addOns.clear();\n for (final Map.Entry<String, MutableTargetImpl> entry : state.getAddOns().entrySet()) {\n final String addOnName = entry.getKey();\n final MutableTargetImpl target = entry.getValue();\n putAddOn(addOnName, new LayerInfo(addOnName, target.getModifiedState(), target.getDirectoryStructure()));\n }\n }" ]
Use this API to fetch all the tunneltrafficpolicy resources that are configured on netscaler.
[ "public static tunneltrafficpolicy[] get(nitro_service service, options option) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\ttunneltrafficpolicy[] response = (tunneltrafficpolicy[])obj.get_resources(service,option);\n\t\treturn response;\n\t}" ]
[ "public synchronized void submitOperation(int requestId, AsyncOperation operation) {\n if(this.operations.containsKey(requestId))\n throw new VoldemortException(\"Request \" + requestId\n + \" already submitted to the system\");\n\n this.operations.put(requestId, operation);\n scheduler.scheduleNow(operation);\n logger.debug(\"Handling async operation \" + requestId);\n }", "void countNonZeroUsingLinkedList( int parent[] , int ll[] ) {\n\n Arrays.fill(pinv,0,m,-1);\n nz_in_V = 0;\n m2 = m;\n\n for (int k = 0; k < n; k++) {\n int i = ll[head+k]; // remove row i from queue k\n nz_in_V++; // count V(k,k) as nonzero\n if( i < 0) // add a fictitious row since there are no nz elements\n i = m2++;\n pinv[i] = k; // associate row i with V(:,k)\n if( --ll[nque+k] <= 0 )\n continue;\n nz_in_V += ll[nque+k];\n int pa;\n if( (pa = parent[k]) != -1 ) { // move all rows to parent of k\n if( ll[nque+pa] == 0)\n ll[tail+pa] = ll[tail+k];\n ll[next+ll[tail+k]] = ll[head+pa];\n ll[head+pa] = ll[next+i];\n ll[nque+pa] += ll[nque+k];\n }\n }\n for (int i = 0, k = n; i < m; i++) {\n if( pinv[i] < 0 )\n pinv[i] = k++;\n }\n\n if( nz_in_V < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in V counts\");\n }", "public static Region fromName(String name) {\n if (name == null) {\n return null;\n }\n\n Region region = VALUES_BY_NAME.get(name.toLowerCase().replace(\" \", \"\"));\n if (region != null) {\n return region;\n } else {\n return Region.create(name.toLowerCase().replace(\" \", \"\"), name);\n }\n }", "public InsertIntoTable addRowsFrom(File file, FileParser fileParser) {\n builder.addRowsFrom(file, fileParser);\n return this;\n }", "public static JSONObject loadJSONAsset(Context context, final String asset) {\n if (asset == null) {\n return new JSONObject();\n }\n return getJsonObject(org.gearvrf.widgetlib.main.Utility.readTextFile(context, asset));\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 List<DbComment> getComments(String entityId, String entityType) {\n return repositoryHandler.getComments(entityId, entityType);\n }", "public static Info ones( final Variable A , final Variable B , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableInteger && B instanceof VariableInteger ) {\n ret.op = new Operation(\"ones-ii\") {\n @Override\n public void process() {\n int numRows = ((VariableInteger)A).value;\n int numCols = ((VariableInteger)B).value;\n output.matrix.reshape(numRows,numCols);\n CommonOps_DDRM.fill(output.matrix, 1);\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }", "public static authenticationradiusaction get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tobj.set_name(name);\n\t\tauthenticationradiusaction response = (authenticationradiusaction) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Get an image as a stream. Callers must be sure to close the stream when they are done with it. @deprecated @see PhotosInterface#getImageAsStream(Photo, int) @param suffix The suffix @return The InputStream @throws IOException
[ "@Deprecated\r\n private InputStream getImageAsStream(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImageAsStream(buffer.toString());\r\n }" ]
[ "public static String getHotPartitionsDueToContiguity(final Cluster cluster,\n int hotContiguityCutoff) {\n StringBuilder sb = new StringBuilder();\n\n for(int zoneId: cluster.getZoneIds()) {\n Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId);\n for(Integer initialPartitionId: idToRunLength.keySet()) {\n int runLength = idToRunLength.get(initialPartitionId);\n if(runLength < hotContiguityCutoff)\n continue;\n\n int hotPartitionId = (initialPartitionId + runLength)\n % cluster.getNumberOfPartitions();\n Node hotNode = cluster.getNodeForPartitionId(hotPartitionId);\n sb.append(\"\\tNode \" + hotNode.getId() + \" (\" + hotNode.getHost()\n + \") has hot primary partition \" + hotPartitionId\n + \" that follows contiguous run of length \" + runLength + Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }", "private JSONArray datesToJson(Collection<Date> individualDates) {\n\n if (null != individualDates) {\n JSONArray result = new JSONArray();\n for (Date d : individualDates) {\n result.put(dateToJson(d));\n }\n return result;\n }\n return null;\n }", "public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }", "public static Info eye( final Variable A , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableMatrix ) {\n ret.op = new Operation(\"eye-m\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)A).matrix;\n output.matrix.reshape(mA.numRows,mA.numCols);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else if( A instanceof VariableInteger ) {\n ret.op = new Operation(\"eye-i\") {\n @Override\n public void process() {\n int N = ((VariableInteger)A).value;\n output.matrix.reshape(N,N);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable type \"+A);\n }\n\n return ret;\n }", "static JobContext copy() {\n JobContext current = current_.get();\n //JobContext ctxt = new JobContext(keepParent ? current : null);\n JobContext ctxt = new JobContext(null);\n if (null != current) {\n ctxt.bag_.putAll(current.bag_);\n }\n return ctxt;\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 }", "private PreparedStatement prepareBatchStatement(String sql)\r\n {\r\n String sqlCmd = sql.substring(0, 7);\r\n\r\n if (sqlCmd.equals(\"UPDATE \") || sqlCmd.equals(\"DELETE \") || (_useBatchInserts && sqlCmd.equals(\"INSERT \")))\r\n {\r\n PreparedStatement stmt = (PreparedStatement) _statements.get(sql);\r\n if (stmt == null)\r\n {\r\n // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement\r\n // interfaces, otherwise proxy.jar works incorrectly\r\n stmt = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{\r\n PreparedStatement.class, Statement.class, BatchPreparedStatement.class},\r\n new PreparedStatementInvocationHandler(this, sql, m_jcd));\r\n _statements.put(sql, stmt);\r\n }\r\n return stmt;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }", "protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) {\r\n\r\n try {\r\n\r\n if (file == null) {\r\n throw new IllegalArgumentException(\"File must not be null!\");\r\n }\r\n CmsLock lock = cms.getLock(file);\r\n CmsUser user = cms.getRequestContext().getCurrentUser();\r\n boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject()\r\n && (lock.isOwnedBy(user) || lock.isLockableBy(user))\r\n && cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT);\r\n boolean isReadOnly = !canWrite;\r\n boolean isFolder = file.isFolder();\r\n boolean isRoot = file.getRootPath().length() <= 1;\r\n\r\n Set<Action> aas = new LinkedHashSet<Action>();\r\n addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot);\r\n addAction(aas, Action.CAN_GET_PROPERTIES, true);\r\n addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly);\r\n addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot);\r\n addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot);\r\n if (isFolder) {\r\n addAction(aas, Action.CAN_GET_DESCENDANTS, true);\r\n addAction(aas, Action.CAN_GET_CHILDREN, true);\r\n addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot);\r\n addAction(aas, Action.CAN_GET_FOLDER_TREE, true);\r\n addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly);\r\n addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly);\r\n addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly);\r\n } else {\r\n addAction(aas, Action.CAN_GET_CONTENT_STREAM, true);\r\n addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly);\r\n addAction(aas, Action.CAN_GET_ALL_VERSIONS, true);\r\n }\r\n AllowableActionsImpl result = new AllowableActionsImpl();\r\n result.setAllowableActions(aas);\r\n return result;\r\n } catch (CmsException e) {\r\n handleCmsException(e);\r\n return null;\r\n }\r\n }", "public void push( Token token ) {\n size++;\n if( first == null ) {\n first = token;\n last = token;\n token.previous = null;\n token.next = null;\n } else {\n last.next = token;\n token.previous = last;\n token.next = null;\n last = token;\n }\n }" ]
Returns a set that contains all the unique entries of the given iterator in the order of their appearance. The result set is a copy of the iterator with stable order. @param iterator the iterator. May not be <code>null</code>. @return a set with the unique entries of the given iterator. Never <code>null</code>.
[ "public static <T> Set<T> toSet(Iterator<? extends T> iterator) {\n\t\treturn Sets.newLinkedHashSet(toIterable(iterator));\n\t}" ]
[ "public void setCurrencySymbol(String symbol)\n {\n if (symbol == null)\n {\n symbol = DEFAULT_CURRENCY_SYMBOL;\n }\n\n set(ProjectField.CURRENCY_SYMBOL, symbol);\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 static void checkStringNotNullOrEmpty(String parameterName,\n String value) {\n if (TextUtils.isEmpty(value)) {\n throw Exceptions.IllegalArgument(\"Current input string %s is %s.\",\n parameterName, value == null ? \"null\" : \"empty\");\n }\n }", "public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\n }", "public static String md5sum(InputStream input) throws IOException {\r\n InputStream in = new BufferedInputStream(input);\r\n try {\r\n MessageDigest digest = java.security.MessageDigest.getInstance(\"MD5\");\r\n DigestInputStream digestInputStream = new DigestInputStream(in, digest);\r\n while(digestInputStream.read() >= 0) {\r\n }\r\n OutputStream md5out = new ByteArrayOutputStream();\r\n md5out.write(digest.digest());\r\n return md5out.toString();\r\n }\r\n catch(NoSuchAlgorithmException e) {\r\n throw new IllegalStateException(\"MD5 algorithm is not available: \" + e.getMessage());\r\n }\r\n finally {\r\n in.close();\r\n }\r\n }", "public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\n }", "private static int[] getMode3PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n int[] postcodeNums = new int[postcode.length()];\r\n\r\n postcode = postcode.toUpperCase();\r\n for (int i = 0; i < postcodeNums.length; i++) {\r\n postcodeNums[i] = postcode.charAt(i);\r\n if (postcode.charAt(i) >= 'A' && postcode.charAt(i) <= 'Z') {\r\n // (Capital) letters shifted to Code Set A values\r\n postcodeNums[i] -= 64;\r\n }\r\n if (postcodeNums[i] == 27 || postcodeNums[i] == 31 || postcodeNums[i] == 33 || postcodeNums[i] >= 59) {\r\n // Not a valid postal code character, use space instead\r\n postcodeNums[i] = 32;\r\n }\r\n // Input characters lower than 27 (NUL - SUB) in postal code are interpreted as capital\r\n // letters in Code Set A (e.g. LF becomes 'J')\r\n }\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNums[5] & 0x03) << 4) | 3;\r\n primary[1] = ((postcodeNums[4] & 0x03) << 4) | ((postcodeNums[5] & 0x3c) >> 2);\r\n primary[2] = ((postcodeNums[3] & 0x03) << 4) | ((postcodeNums[4] & 0x3c) >> 2);\r\n primary[3] = ((postcodeNums[2] & 0x03) << 4) | ((postcodeNums[3] & 0x3c) >> 2);\r\n primary[4] = ((postcodeNums[1] & 0x03) << 4) | ((postcodeNums[2] & 0x3c) >> 2);\r\n primary[5] = ((postcodeNums[0] & 0x03) << 4) | ((postcodeNums[1] & 0x3c) >> 2);\r\n primary[6] = ((postcodeNums[0] & 0x3c) >> 2) | ((country & 0x3) << 4);\r\n primary[7] = (country & 0xfc) >> 2;\r\n primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);\r\n primary[9] = ((service & 0x3f0) >> 4);\r\n\r\n return primary;\r\n }", "private static void checkPreconditions(final int maxSize, final String suffix) {\n\t\tif( maxSize <= 0 ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"maxSize should be > 0 but was %d\", maxSize));\n\t\t}\n\t\tif( suffix == null ) {\n\t\t\tthrow new NullPointerException(\"suffix should not be null\");\n\t\t}\n\t}", "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 }" ]
Adds an additional label to the constructed document. @param text the text of the label @param languageCode the language code of the label @return builder object to continue construction
[ "public T withLabel(String text, String languageCode) {\n\t\twithLabel(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}" ]
[ "public DbInfo info() {\n return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).getDatabaseUri(),\n DbInfo.class);\n }", "public double Function2D(double x, double y) {\n return Math.exp(-(x * x + y * y) / (2 * sqrSigma)) / (2 * Math.PI * sqrSigma);\n }", "public ResponseOnSingeRequest onComplete(Response response) {\n\n cancelCancellable();\n try {\n \n Map<String, List<String>> responseHeaders = null;\n if (responseHeaderMeta != null) {\n responseHeaders = new LinkedHashMap<String, List<String>>();\n if (responseHeaderMeta.isGetAll()) {\n for (Map.Entry<String, List<String>> header : response\n .getHeaders()) {\n responseHeaders.put(header.getKey().toLowerCase(Locale.ROOT), header.getValue());\n }\n } else {\n for (String key : responseHeaderMeta.getKeys()) {\n if (response.getHeaders().containsKey(key)) {\n responseHeaders.put(key.toLowerCase(Locale.ROOT),\n response.getHeaders().get(key));\n }\n }\n }\n }\n\n int statusCodeInt = response.getStatusCode();\n String statusCode = statusCodeInt + \" \" + response.getStatusText();\n String charset = ParallecGlobalConfig.httpResponseBodyCharsetUsesResponseContentType &&\n response.getContentType()!=null ? \n AsyncHttpProviderUtils.parseCharset(response.getContentType())\n : ParallecGlobalConfig.httpResponseBodyDefaultCharset;\n if(charset == null){\n getLogger().error(\"charset is not provided from response content type. Use default\");\n charset = ParallecGlobalConfig.httpResponseBodyDefaultCharset; \n }\n reply(response.getResponseBody(charset), false, null, null, statusCode,\n statusCodeInt, responseHeaders);\n } catch (IOException e) {\n getLogger().error(\"fail response.getResponseBody \" + e);\n }\n\n return null;\n }", "public void setIntegerAttribute(String name, Integer value) {\n\t\tensureValue();\n\t\tAttribute attribute = new IntegerAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}", "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 void wireSteps( CanWire canWire ) {\n for( StageState steps : stages.values() ) {\n canWire.wire( steps.instance );\n }\n }", "public static <T> Set<T> toSet(Iterator<? extends T> iterator) {\n\t\treturn Sets.newLinkedHashSet(toIterable(iterator));\n\t}", "protected EntityKey getEntityKey(Tuple tuple, AssociatedEntityKeyMetadata associatedEntityKeyMetadata) {\n\t\tObject[] columnValues = new Object[ associatedEntityKeyMetadata.getAssociationKeyColumns().length];\n\t\tint i = 0;\n\n\t\tfor ( String associationKeyColumn : associatedEntityKeyMetadata.getAssociationKeyColumns() ) {\n\t\t\tcolumnValues[i] = tuple.get( associationKeyColumn );\n\t\t\ti++;\n\t\t}\n\n\t\treturn new EntityKey( associatedEntityKeyMetadata.getEntityKeyMetadata(), columnValues );\n\t}", "private static Map<String, Set<String>> expand(Map<String, Set<String>> viewToPropNames) {\n\n Set<String> baseProps = viewToPropNames.get(PropertyView.BASE_VIEW);\n\n if (baseProps == null) {\n baseProps = ImmutableSet.of();\n }\n\n if (!SquigglyConfig.isFilterImplicitlyIncludeBaseFieldsInView()) {\n\n // make an exception for full view\n Set<String> fullView = viewToPropNames.get(PropertyView.FULL_VIEW);\n\n if (fullView != null) {\n fullView.addAll(baseProps);\n }\n\n return viewToPropNames;\n }\n\n for (Map.Entry<String, Set<String>> entry : viewToPropNames.entrySet()) {\n String viewName = entry.getKey();\n Set<String> propNames = entry.getValue();\n\n if (!PropertyView.BASE_VIEW.equals(viewName)) {\n propNames.addAll(baseProps);\n }\n }\n\n return viewToPropNames;\n }" ]
Helper to read a mandatory String value. @param path The XML path of the element to read. @return The String value stored in the XML. @throws Exception thrown if the value could not be read.
[ "private String parseMandatoryStringValue(final String path) throws Exception {\n\n final String value = parseOptionalStringValue(path);\n if (value == null) {\n throw new Exception();\n }\n return value;\n }" ]
[ "private void checkMessageID(Message message) {\n if (!MessageUtils.isOutbound(message)) return;\n\n AddressingProperties maps =\n ContextUtils.retrieveMAPs(message, false, MessageUtils.isOutbound(message));\n if (maps == null) {\n maps = new AddressingProperties();\n }\n if (maps.getMessageID() == null) {\n String messageID = ContextUtils.generateUUID();\n boolean isRequestor = ContextUtils.isRequestor(message);\n maps.setMessageID(ContextUtils.getAttributedURI(messageID));\n ContextUtils.storeMAPs(maps, message, ContextUtils.isOutbound(message), isRequestor);\n }\n }", "public InetAddress getRemoteAddress() {\n final Channel channel;\n try {\n channel = strategy.getChannel();\n } catch (IOException e) {\n return null;\n }\n final Connection connection = channel.getConnection();\n final InetSocketAddress peerAddress = connection.getPeerAddress(InetSocketAddress.class);\n return peerAddress == null ? null : peerAddress.getAddress();\n }", "public String getShortMessage(Locale locale) {\n\t\tString message;\n\t\tmessage = translate(Integer.toString(exceptionCode), locale);\n\t\tif (message != null && msgParameters != null && msgParameters.length > 0) {\n\t\t\tfor (int i = 0; i < msgParameters.length; i++) {\n\t\t\t\tboolean isIncluded = false;\n\t\t\t\tString needTranslationParam = \"$${\" + i + \"}\";\n\t\t\t\tif (message.contains(needTranslationParam)) {\n\t\t\t\t\tString translation = translate(msgParameters[i], locale);\n\t\t\t\t\tif (null == translation && null != msgParameters[i]) {\n\t\t\t\t\t\ttranslation = msgParameters[i].toString();\n\t\t\t\t\t}\n\t\t\t\t\tif (null == translation) {\n\t\t\t\t\t\ttranslation = \"[null]\";\n\t\t\t\t\t}\n\t\t\t\t\tmessage = message.replace(needTranslationParam, translation);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tString verbatimParam = \"${\" + i + \"}\";\n\t\t\t\tString rs = null == msgParameters[i] ? \"[null]\" : msgParameters[i].toString();\n\t\t\t\tif (message.contains(verbatimParam)) {\n\t\t\t\t\tmessage = message.replace(verbatimParam, rs);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tif (!isIncluded) {\n\t\t\t\t\tmessage = message + \" (\" + rs + \")\"; // NOSONAR replace/contains makes StringBuilder use difficult\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn message;\n\t}", "private void logTimeTakenByRuleProvider(GraphContext graphContext, Context context, int ruleIndex, int timeTaken)\n {\n AbstractRuleProvider ruleProvider = (AbstractRuleProvider) context.get(RuleMetadataType.RULE_PROVIDER);\n if (ruleProvider == null)\n return;\n\n if (!timeTakenByProvider.containsKey(ruleProvider))\n {\n RuleProviderExecutionStatisticsModel model = new RuleProviderExecutionStatisticsService(graphContext)\n .create();\n model.setRuleIndex(ruleIndex);\n model.setRuleProviderID(ruleProvider.getMetadata().getID());\n model.setTimeTaken(timeTaken);\n\n timeTakenByProvider.put(ruleProvider, model.getElement().id());\n }\n else\n {\n RuleProviderExecutionStatisticsService service = new RuleProviderExecutionStatisticsService(graphContext);\n RuleProviderExecutionStatisticsModel model = service.getById(timeTakenByProvider.get(ruleProvider));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n logTimeTakenByPhase(graphContext, ruleProvider.getMetadata().getPhase(), timeTaken);\n }", "private boolean isCacheable(PipelineContext context) throws GeomajasException {\n\t\tVectorLayer layer = context.get(PipelineCode.LAYER_KEY, VectorLayer.class);\n\t\treturn !(layer instanceof VectorLayerLazyFeatureConversionSupport &&\n\t\t\t\t((VectorLayerLazyFeatureConversionSupport) layer).useLazyFeatureConversion());\n\t}", "public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }", "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 }", "private void writeAssignments()\n {\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n Task task = assignment.getTask();\n if (task != null && task.getUniqueID().intValue() != 0 && !task.getSummary())\n {\n writeAssignment(assignment);\n }\n }\n }\n }", "public void writeTo(File file) throws IOException {\n FileChannel channel = new FileOutputStream(file).getChannel();\n try {\n writeTo(channel);\n } finally {\n channel.close();\n }\n }" ]
Encrypt a string with AES-128 using the specified key. @param message Input string. @param key Encryption key. @return Encrypted output.
[ "@SuppressWarnings(\"InsecureCryptoUsage\") // Only used in known-weak crypto \"legacy\" mode.\n static byte[] aes128Encrypt(StringBuilder message, String key) {\n try {\n key = normalizeString(key, 16);\n rightPadString(message, '{', 16);\n Cipher cipher = Cipher.getInstance(\"AES/ECB/NoPadding\");\n cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), \"AES\"));\n return cipher.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "public String getBaselineDurationText()\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 String))\n {\n result = null;\n }\n return (String) result;\n }", "protected Object[] getParameterValues(Object specialVal, BeanManagerImpl manager, CreationalContext<?> ctx, CreationalContext<?> transientReferenceContext) {\n if (getInjectionPoints().isEmpty()) {\n if (specialInjectionPointIndex == -1) {\n return Arrays2.EMPTY_ARRAY;\n } else {\n return new Object[] { specialVal };\n }\n }\n Object[] parameterValues = new Object[getParameterInjectionPoints().size()];\n List<ParameterInjectionPoint<?, X>> parameters = getParameterInjectionPoints();\n for (int i = 0; i < parameterValues.length; i++) {\n ParameterInjectionPoint<?, ?> param = parameters.get(i);\n if (i == specialInjectionPointIndex) {\n parameterValues[i] = specialVal;\n } else if (hasTransientReferenceParameter && param.getAnnotated().isAnnotationPresent(TransientReference.class)) {\n parameterValues[i] = param.getValueToInject(manager, transientReferenceContext);\n } else {\n parameterValues[i] = param.getValueToInject(manager, ctx);\n }\n }\n return parameterValues;\n }", "private org.apache.tools.ant.types.Path addSlaveClasspath() {\n org.apache.tools.ant.types.Path path = new org.apache.tools.ant.types.Path(getProject());\n\n String [] REQUIRED_SLAVE_CLASSES = {\n SlaveMain.class.getName(),\n Strings.class.getName(),\n MethodGlobFilter.class.getName(),\n TeeOutputStream.class.getName()\n };\n\n for (String clazz : Arrays.asList(REQUIRED_SLAVE_CLASSES)) {\n String resource = clazz.replace(\".\", \"/\") + \".class\";\n File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource);\n if (f != null) {\n path.createPath().setLocation(f);\n } else {\n throw new BuildException(\"Could not locate classpath for resource: \" + resource);\n }\n }\n return path;\n }", "public static inat[] get(nitro_service service) throws Exception{\n\t\tinat obj = new inat();\n\t\tinat[] response = (inat[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public ProjectCalendarWeek addWorkWeek()\n {\n ProjectCalendarWeek week = new ProjectCalendarWeek();\n week.setParent(this);\n m_workWeeks.add(week);\n m_weeksSorted = false;\n clearWorkingDateCache();\n return week;\n }", "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 static void enableHost(String hostName) throws Exception {\n Registry myRegistry = LocateRegistry.getRegistry(\"127.0.0.1\", port);\n com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);\n\n impl.enableHost(hostName);\n }", "public static IBlur getIBlurAlgorithm(EBlurAlgorithm algorithm, ContextWrapper contextWrapper) {\n RenderScript rs = contextWrapper.getRenderScript();\n Context ctx = contextWrapper.getContext();\n\n switch (algorithm) {\n case RS_GAUSS_FAST:\n return new RenderScriptGaussianBlur(rs);\n case RS_BOX_5x5:\n return new RenderScriptBox5x5Blur(rs);\n case RS_GAUSS_5x5:\n return new RenderScriptGaussian5x5Blur(rs);\n case RS_STACKBLUR:\n return new RenderScriptStackBlur(rs, ctx);\n case STACKBLUR:\n return new StackBlur();\n case GAUSS_FAST:\n return new GaussianFastBlur();\n case BOX_BLUR:\n return new BoxBlur();\n default:\n return new IgnoreBlur();\n }\n }", "public synchronized void setMonitoredPlayer(final int player) {\n if (player < 0) {\n throw new IllegalArgumentException(\"player cannot be negative\");\n }\n clearPlaybackState();\n monitoredPlayer.set(player);\n if (player > 0) { // Start monitoring the specified player\n setPlaybackState(player, 0, false); // Start with default values for required simple state.\n VirtualCdj.getInstance().addUpdateListener(updateListener);\n MetadataFinder.getInstance().addTrackMetadataListener(metadataListener);\n cueList.set(null); // Assume the worst, but see if we have one available next.\n if (MetadataFinder.getInstance().isRunning()) {\n TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(player);\n if (metadata != null) {\n cueList.set(metadata.getCueList());\n }\n }\n WaveformFinder.getInstance().addWaveformListener(waveformListener);\n if (WaveformFinder.getInstance().isRunning() && WaveformFinder.getInstance().isFindingDetails()) {\n waveform.set(WaveformFinder.getInstance().getLatestDetailFor(player));\n } else {\n waveform.set(null);\n }\n BeatGridFinder.getInstance().addBeatGridListener(beatGridListener);\n if (BeatGridFinder.getInstance().isRunning()) {\n beatGrid.set(BeatGridFinder.getInstance().getLatestBeatGridFor(player));\n } else {\n beatGrid.set(null);\n }\n try {\n TimeFinder.getInstance().start();\n if (!animating.getAndSet(true)) {\n // Create the thread to update our position smoothly as the track plays\n new Thread(new Runnable() {\n @Override\n public void run() {\n while (animating.get()) {\n try {\n Thread.sleep(33); // Animate at 30 fps\n } catch (InterruptedException e) {\n logger.warn(\"Waveform animation thread interrupted; ending\");\n animating.set(false);\n }\n setPlaybackPosition(TimeFinder.getInstance().getTimeFor(getMonitoredPlayer()));\n }\n }\n }).start();\n }\n } catch (Exception e) {\n logger.error(\"Unable to start the TimeFinder to animate the waveform detail view\");\n animating.set(false);\n }\n } else { // Stop monitoring any player\n animating.set(false);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n WaveformFinder.getInstance().removeWaveformListener(waveformListener);\n cueList.set(null);\n waveform.set(null);\n beatGrid.set(null);\n }\n if (!autoScroll.get()) {\n invalidate();\n }\n repaint();\n }" ]
Returns all values that can be selected in the widget. @param cms the current CMS object @param rootPath the root path to the currently edited xml file (sitemap config) @param allRemoved flag, indicating if all inheritedly available formatters should be disabled @return all values that can be selected in the widget.
[ "public static List<String> getSelectOptionValues(CmsObject cms, String rootPath, boolean allRemoved) {\n\n try {\n cms = OpenCms.initCmsObject(cms);\n cms.getRequestContext().setSiteRoot(\"\");\n CmsADEConfigData adeConfig = OpenCms.getADEManager().lookupConfiguration(cms, rootPath);\n if (adeConfig.parent() != null) {\n adeConfig = adeConfig.parent();\n }\n\n List<CmsSelectWidgetOption> options = getFormatterOptionsStatic(cms, adeConfig, rootPath, allRemoved);\n List<CmsSelectWidgetOption> typeOptions = getTypeOptionsStatic(cms, adeConfig, allRemoved);\n options.addAll(typeOptions);\n List<String> result = new ArrayList<String>(options.size());\n for (CmsSelectWidgetOption o : options) {\n result.add(o.getValue());\n }\n return result;\n } catch (CmsException e) {\n // should never happen\n LOG.error(e.getLocalizedMessage(), e);\n return null;\n }\n\n }" ]
[ "public Map<Integer, RandomVariable> getGradient(){\r\n\r\n\t\tint numberOfCalculationSteps = getFunctionList().size();\r\n\r\n\t\tRandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\tomegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\tfor(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){\r\n\r\n\t\t\tomegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\tArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices();\r\n\r\n\t\t\tfor(int functionIndex:childrenList){\r\n\t\t\t\tRandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex);\r\n\t\t\t\tomegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables();\r\n\r\n\t\tMap<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>();\r\n\r\n\t\tfor(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){\r\n\t\t\tgradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]);\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}", "public void addCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(!dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().add(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.addModulesOrganization(corporateGroupId, dbOrganization);\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 base_response update(nitro_service client, ntpserver resource) throws Exception {\n\t\tntpserver updateresource = new ntpserver();\n\t\tupdateresource.serverip = resource.serverip;\n\t\tupdateresource.servername = resource.servername;\n\t\tupdateresource.minpoll = resource.minpoll;\n\t\tupdateresource.maxpoll = resource.maxpoll;\n\t\tupdateresource.preferredntpserver = resource.preferredntpserver;\n\t\tupdateresource.autokey = resource.autokey;\n\t\tupdateresource.key = resource.key;\n\t\treturn updateresource.update_resource(client);\n\t}", "public TaskProvider<GenerateHensonNavigatorTask> createHensonNavigatorGenerationTask(\n BaseVariant variant, String hensonNavigatorPackageName, File destinationFolder) {\n TaskProvider<GenerateHensonNavigatorTask> generateHensonNavigatorTask =\n project\n .getTasks()\n .register(\n \"generate\" + capitalize(variant.getName()) + \"HensonNavigator\",\n GenerateHensonNavigatorTask.class,\n (Action<GenerateHensonNavigatorTask>)\n generateHensonNavigatorTask1 -> {\n generateHensonNavigatorTask1.hensonNavigatorPackageName =\n hensonNavigatorPackageName;\n generateHensonNavigatorTask1.destinationFolder = destinationFolder;\n generateHensonNavigatorTask1.variant = variant;\n generateHensonNavigatorTask1.logger = logger;\n generateHensonNavigatorTask1.project = project;\n generateHensonNavigatorTask1.hensonNavigatorGenerator =\n hensonNavigatorGenerator;\n });\n return generateHensonNavigatorTask;\n }", "public static filterglobal_filterpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tfilterglobal_filterpolicy_binding obj = new filterglobal_filterpolicy_binding();\n\t\tfilterglobal_filterpolicy_binding response[] = (filterglobal_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "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 }", "private void handleSerialApiGetInitDataResponse(\n\t\t\tSerialMessage incomingMessage) {\n\t\tlogger.debug(String.format(\"Got MessageSerialApiGetInitData response.\"));\n\t\tthis.isConnected = true;\n\t\tint nodeBytes = incomingMessage.getMessagePayloadByte(2);\n\t\t\n\t\tif (nodeBytes != NODE_BYTES) {\n\t\t\tlogger.error(\"Invalid number of node bytes = {}\", nodeBytes);\n\t\t\treturn;\n\t\t}\n\n\t\tint nodeId = 1;\n\t\t\n\t\t// loop bytes\n\t\tfor (int i = 3;i < 3 + nodeBytes;i++) {\n\t\t\tint incomingByte = incomingMessage.getMessagePayloadByte(i);\n\t\t\t// loop bits in byte\n\t\t\tfor (int j=0;j<8;j++) {\n\t\t\t\tint b1 = incomingByte & (int)Math.pow(2.0D, j);\n\t\t\t\tint b2 = (int)Math.pow(2.0D, j);\n\t\t\t\tif (b1 == b2) {\n\t\t\t\t\tlogger.info(String.format(\"Found node id = %d\", nodeId));\n\t\t\t\t\t// Place nodes in the local ZWave Controller \n\t\t\t\t\tthis.zwaveNodes.put(nodeId, new ZWaveNode(this.homeId, nodeId, this));\n\t\t\t\t\tthis.getNode(nodeId).advanceNodeStage();\n\t\t\t\t}\n\t\t\t\tnodeId++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tlogger.info(\"------------Number of Nodes Found Registered to ZWave Controller------------\");\n\t\tlogger.info(String.format(\"# Nodes = %d\", this.zwaveNodes.size()));\n\t\tlogger.info(\"----------------------------------------------------------------------------\");\n\t\t\n\t\t// Advance node stage for the first node.\n\t}", "public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}" ]
This method writes resource data to a PM XML file.
[ "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 }" ]
[ "static JDOClass getJDOClass(Class c)\r\n\t{\r\n\t\tJDOClass rc = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tJavaModelFactory javaModelFactory = RuntimeJavaModelFactory.getInstance();\r\n\t\t\tJavaModel javaModel = javaModelFactory.getJavaModel(c.getClassLoader());\r\n\t\t\tJDOModel m = JDOModelFactoryImpl.getInstance().getJDOModel(javaModel);\r\n\t\t\trc = m.getJDOClass(c.getName());\r\n\t\t}\r\n\t\tcatch (RuntimeException ex)\r\n\t\t{\r\n\t\t\tthrow new JDOFatalInternalException(\"Not a JDO class: \" + c.getName()); \r\n\t\t}\r\n\t\treturn rc;\r\n\t}", "public static void pushClassType(CodeAttribute b, String classType) {\n if (classType.length() != 1) {\n if (classType.startsWith(\"L\") && classType.endsWith(\";\")) {\n classType = classType.substring(1, classType.length() - 1);\n }\n b.loadClass(classType);\n } else {\n char type = classType.charAt(0);\n switch (type) {\n case 'I':\n b.getstatic(Integer.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'J':\n b.getstatic(Long.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'S':\n b.getstatic(Short.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'F':\n b.getstatic(Float.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'D':\n b.getstatic(Double.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'B':\n b.getstatic(Byte.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'C':\n b.getstatic(Character.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'Z':\n b.getstatic(Boolean.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n default:\n throw new RuntimeException(\"Cannot handle primitive type: \" + type);\n }\n }\n }", "private static ClassLoader getParentCl()\n {\n try\n {\n Method m = ClassLoader.class.getMethod(\"getPlatformClassLoader\");\n return (ClassLoader) m.invoke(null);\n }\n catch (NoSuchMethodException e)\n {\n // Java < 9, just use the bootstrap CL.\n return null;\n }\n catch (Exception e)\n {\n throw new JqmInitError(\"Could not fetch Platform Class Loader\", e);\n }\n }", "private void addDownloadButton(final CmsLogFileView view) {\n\n Button button = CmsToolBar.createButton(\n FontOpenCms.DOWNLOAD,\n CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n button.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n Window window = CmsBasicDialog.prepareWindow(CmsBasicDialog.DialogWidth.wide);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n window.setContent(new CmsLogDownloadDialog(window, view.getCurrentFile()));\n A_CmsUI.get().addWindow(window);\n }\n });\n m_uiContext.addToolbarButton(button);\n }", "String getRangeUri(PropertyIdValue propertyIdValue) {\n\t\tString datatype = this.propertyRegister\n\t\t\t\t.getPropertyType(propertyIdValue);\n\n\t\tif (datatype == null)\n\t\t\treturn null;\n\n\t\tswitch (datatype) {\n\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.RDF_LANG_STRING;\n\t\tcase DatatypeIdValue.DT_STRING:\n\t\tcase DatatypeIdValue.DT_EXTERNAL_ID:\n\t\tcase DatatypeIdValue.DT_MATH:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.XSD_STRING;\n\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\tcase DatatypeIdValue.DT_ITEM:\n\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\tcase DatatypeIdValue.DT_LEXEME:\n\t\tcase DatatypeIdValue.DT_FORM:\n\t\tcase DatatypeIdValue.DT_SENSE:\n\t\tcase DatatypeIdValue.DT_TIME:\n\t\tcase DatatypeIdValue.DT_URL:\n\t\tcase DatatypeIdValue.DT_GEO_SHAPE:\n\t\tcase DatatypeIdValue.DT_TABULAR_DATA:\n\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\tthis.rdfConversionBuffer.addObjectProperty(propertyIdValue);\n\t\t\treturn Vocabulary.OWL_THING;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "public void sendEventsFromQueue() {\n if (null == queue || stopSending) {\n return;\n }\n LOG.fine(\"Scheduler called for sending events\");\n\n int packageSize = getEventsPerMessageCall();\n\n while (!queue.isEmpty()) {\n final List<Event> list = new ArrayList<Event>();\n int i = 0;\n while (i < packageSize && !queue.isEmpty()) {\n Event event = queue.remove();\n if (event != null && !filter(event)) {\n list.add(event);\n i++;\n }\n }\n if (list.size() > 0) {\n executor.execute(new Runnable() {\n public void run() {\n try {\n sendEvents(list);\n } catch (MonitoringException e) {\n e.logException(Level.SEVERE);\n }\n }\n });\n\n }\n }\n\n }", "static JDOClass getJDOClass(Class c)\r\n\t{\r\n\t\tJDOClass rc = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tJavaModelFactory javaModelFactory = RuntimeJavaModelFactory.getInstance();\r\n\t\t\tJavaModel javaModel = javaModelFactory.getJavaModel(c.getClassLoader());\r\n\t\t\tJDOModel m = JDOModelFactoryImpl.getInstance().getJDOModel(javaModel);\r\n\t\t\trc = m.getJDOClass(c.getName());\r\n\t\t}\r\n\t\tcatch (RuntimeException ex)\r\n\t\t{\r\n\t\t\tthrow new JDOFatalInternalException(\"Not a JDO class: \" + c.getName()); \r\n\t\t}\r\n\t\treturn rc;\r\n\t}", "@Override\n\tpublic String getFirst(String headerName) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\treturn headerValues != null ? headerValues.get(0) : null;\n\t}", "private Variable createVariableInferred(TokenList.Token t0, Variable variableRight) {\n Variable result;\n\n if( t0.getType() == Type.WORD ) {\n switch( variableRight.getType()) {\n case MATRIX:\n alias(new DMatrixRMaj(1,1),t0.getWord());\n break;\n\n case SCALAR:\n if( variableRight instanceof VariableInteger) {\n alias(0,t0.getWord());\n } else {\n alias(1.0,t0.getWord());\n }\n break;\n\n case INTEGER_SEQUENCE:\n alias((IntegerSequence)null,t0.getWord());\n break;\n\n default:\n throw new RuntimeException(\"Type not supported for assignment: \"+variableRight.getType());\n }\n\n result = variables.get(t0.getWord());\n } else {\n result = t0.getVariable();\n }\n return result;\n }" ]
Calculate standart deviation. @param values Values. @param mean Mean. @return Standart deviation.
[ "public static double StdDev( int[] values, double mean ){\n double stddev = 0;\n double diff;\n int hits;\n int total = 0;\n\n // for all values\n for ( int i = 0, n = values.length; i < n; i++ )\n {\n hits = values[i];\n diff = (double) i - mean;\n // accumulate std.dev.\n stddev += diff * diff * hits;\n // accumalate total\n total += hits;\n }\n\n return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) );\n }" ]
[ "public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }", "public void setOuterConeAngle(float angle)\n {\n setFloat(\"outer_cone_angle\", (float) Math.cos(Math.toRadians(angle)));\n mChanged.set(true);\n }", "public String tag(ImapRequestLineReader request) throws ProtocolException {\n CharacterValidator validator = new TagCharValidator();\n return consumeWord(request, validator);\n }", "public void cullHistory(final int profileId, final String clientUUID, final int limit) throws Exception {\n\n //Allow only 1 delete thread to run\n if (threadActive) {\n return;\n }\n\n threadActive = true;\n //Create a thread so proxy will continue to work during long delete\n Thread t1 = new Thread(new Runnable() {\n @Override\n public void run() {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n sqlQuery += \";\";\n\n Statement query = sqlConnection.createStatement();\n ResultSet results = query.executeQuery(sqlQuery);\n if (results.next()) {\n if (results.getInt(\"COUNT(\" + Constants.GENERIC_ID + \")\") < (limit + 10000)) {\n return;\n }\n }\n //Find the last item in the table\n statement = sqlConnection.prepareStatement(\"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" ORDER BY \" + Constants.GENERIC_ID + \" ASC LIMIT 1\");\n\n ResultSet resultSet = statement.executeQuery();\n if (resultSet.next()) {\n int currentSpot = resultSet.getInt(Constants.GENERIC_ID) + 100;\n int finalDelete = currentSpot + 10000;\n //Delete 100 items at a time until 10000 are deleted\n //Do this so table is unlocked frequently to allow other proxy items to access it\n while (currentSpot < finalDelete) {\n PreparedStatement deleteStatement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" AND \" + Constants.GENERIC_ID + \" < \" + currentSpot);\n deleteStatement.executeUpdate();\n currentSpot += 100;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n threadActive = false;\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }\n });\n\n t1.start();\n }", "private InputStream runSparqlQuery(String query) throws IOException {\n\t\ttry {\n\t\t\tString queryString = \"query=\" + URLEncoder.encode(query, \"UTF-8\")\n\t\t\t\t\t+ \"&format=json\";\n\t\t\tURL url = new URL(\"https://query.wikidata.org/sparql?\"\n\t\t\t\t\t+ queryString);\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url\n\t\t\t\t\t.openConnection();\n\t\t\tconnection.setRequestMethod(\"GET\");\n\n\t\t\treturn connection.getInputStream();\n\t\t} catch (UnsupportedEncodingException | MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}", "private String toPath(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(CmsWorkplace.getSkinUri(), ICON_FOLDER, \"\" + name.hashCode()) + size.getSuffix();\n }", "void awaitStabilityUninterruptibly(long timeout, TimeUnit timeUnit) throws TimeoutException {\n boolean interrupted = false;\n try {\n long toWait = timeUnit.toMillis(timeout);\n long msTimeout = System.currentTimeMillis() + toWait;\n while (true) {\n if (interrupted) {\n toWait = msTimeout - System.currentTimeMillis();\n }\n try {\n if (toWait <= 0 || !monitor.awaitStability(toWait, TimeUnit.MILLISECONDS, failed, problems)) {\n throw new TimeoutException();\n }\n break;\n } catch (InterruptedException e) {\n interrupted = true;\n }\n }\n } finally {\n if (interrupted) {\n Thread.currentThread().interrupt();\n }\n }\n }", "public static Command newStartProcess(String processId,\n Map<String, Object> parameters) {\n return getCommandFactoryProvider().newStartProcess( processId,\n parameters );\n }", "@NonNull\n @Override\n public File getParent(@NonNull final File from) {\n if (from.getPath().equals(getRoot().getPath())) {\n // Already at root, we can't go higher\n return from;\n } else if (from.getParentFile() != null) {\n return from.getParentFile();\n } else {\n return from;\n }\n }" ]
currently does not support paths with name constrains
[ "private static List<Segment> parseSegments(String origPathStr) {\n String pathStr = origPathStr;\n if (!pathStr.startsWith(\"/\")) {\n pathStr = pathStr + \"/\";\n }\n\n List<Segment> result = new ArrayList<>();\n for (String segmentStr : PATH_SPLITTER.split(pathStr)) {\n Matcher m = SEGMENT_PATTERN.matcher(segmentStr);\n if (!m.matches()) {\n throw new IllegalArgumentException(\"Bad aql path: \" + origPathStr);\n }\n Segment segment = new Segment();\n segment.attribute = m.group(1);\n segment.nodeId = m.groupCount() >= 3 ? m.group(3) : null;\n result.add(segment);\n }\n return result;\n }" ]
[ "private boolean initRequestHandler(SelectionKey selectionKey) {\n ByteBuffer inputBuffer = inputStream.getBuffer();\n int remaining = inputBuffer.remaining();\n\n // Don't have enough bytes to determine the protocol yet...\n if(remaining < 3)\n return true;\n\n byte[] protoBytes = { inputBuffer.get(0), inputBuffer.get(1), inputBuffer.get(2) };\n\n try {\n String proto = ByteUtils.getString(protoBytes, \"UTF-8\");\n inputBuffer.clear();\n RequestFormatType requestFormatType = RequestFormatType.fromCode(proto);\n requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType);\n\n if(logger.isInfoEnabled())\n logger.info(\"Protocol negotiated for \" + socketChannel.socket() + \": \"\n + requestFormatType.getDisplayName());\n\n // The protocol negotiation is the first request, so respond by\n // sticking the bytes in the output buffer, signaling the Selector,\n // and returning false to denote no further processing is needed.\n outputStream.getBuffer().put(ByteUtils.getBytes(\"ok\", \"UTF-8\"));\n prepForWrite(selectionKey);\n\n return false;\n } catch(IllegalArgumentException e) {\n // okay we got some nonsense. For backwards compatibility,\n // assume this is an old client who does not know how to negotiate\n RequestFormatType requestFormatType = RequestFormatType.VOLDEMORT_V0;\n requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType);\n\n if(logger.isInfoEnabled())\n logger.info(\"No protocol proposal given for \" + socketChannel.socket()\n + \", assuming \" + requestFormatType.getDisplayName());\n\n return true;\n }\n }", "final public void addPositionRange(int start, int end) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(start, end);\n } else {\n int[] positions = new int[end - start + 1];\n for (int i = start; i <= end; i++) {\n positions[i - start] = i;\n }\n tokenPosition.add(positions);\n }\n }", "public String createTorqueSchema(Properties attributes) throws XDocletException\r\n {\r\n String dbName = (String)getDocletContext().getConfigParam(CONFIG_PARAM_DATABASENAME);\r\n\r\n _torqueModel = new TorqueModelDef(dbName, _model);\r\n return \"\";\r\n }", "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 static String getParentId(String digest, String host) throws IOException {\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n return dockerClient.inspectImageCmd(digest).exec().getParent();\n } finally {\n closeQuietly(dockerClient);\n }\n }", "private void highlightSlice(PieModel _Slice) {\n\n int color = _Slice.getColor();\n _Slice.setHighlightedColor(Color.argb(\n 0xff,\n Math.min((int) (mHighlightStrength * (float) Color.red(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.green(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.blue(color)), 0xff)\n ));\n }", "@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> map, final Iterable<?> keys) {\n\t\treturn Maps.filterKeys(map, new Predicate<K>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(K input) {\n\t\t\t\treturn !Iterables.contains(keys, input);\n\t\t\t}\n\t\t});\n\t}", "public String buildRadio(String propName) throws CmsException {\n\n String propVal = readProperty(propName);\n StringBuffer result = new StringBuffer(\"<table border=\\\"0\\\"><tr>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"true\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_TRUE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"false\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"\" : \"checked=\\\"checked\\\"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_FALSE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(CmsStringUtil.isEmpty(propVal) ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(getPropertyInheritanceInfo(propName)).append(\n \"</td></tr></table>\");\n return result.toString();\n }", "@Deprecated\n public FluoConfiguration clearObservers() {\n Iterator<String> iter1 = getKeys(OBSERVER_PREFIX.substring(0, OBSERVER_PREFIX.length() - 1));\n while (iter1.hasNext()) {\n String key = iter1.next();\n clearProperty(key);\n }\n\n return this;\n }" ]
Adjusts the day in the provided month, that it fits the specified week day. If there's no match for that provided month, the next possible month is checked. @param date the date to adjust, with the correct year and month already set.
[ "private void setFittingWeekDay(Calendar date) {\n\n date.set(Calendar.DAY_OF_MONTH, 1);\n int weekDayFirst = date.get(Calendar.DAY_OF_WEEK);\n int firstFittingWeekDay = (((m_weekDay.toInt() + I_CmsSerialDateValue.NUM_OF_WEEKDAYS) - weekDayFirst)\n % I_CmsSerialDateValue.NUM_OF_WEEKDAYS) + 1;\n int fittingWeekDay = firstFittingWeekDay + (I_CmsSerialDateValue.NUM_OF_WEEKDAYS * m_weekOfMonth.ordinal());\n if (fittingWeekDay > date.getActualMaximum(Calendar.DAY_OF_MONTH)) {\n fittingWeekDay -= I_CmsSerialDateValue.NUM_OF_WEEKDAYS;\n }\n date.set(Calendar.DAY_OF_MONTH, fittingWeekDay);\n }" ]
[ "@SuppressWarnings(\"deprecation\")\n protected ModelNode executeReadOnlyOperation(final ModelNode operation, final OperationMessageHandler handler, final OperationTransactionControl control, final OperationStepHandler prepareStep, final int operationId) {\n final AbstractOperationContext delegateContext = getDelegateContext(operationId);\n CurrentOperationIdHolder.setCurrentOperationID(operationId);\n try {\n return executeReadOnlyOperation(operation, delegateContext.getManagementModel(), control, prepareStep, delegateContext);\n } finally {\n CurrentOperationIdHolder.setCurrentOperationID(null);\n }\n }", "public Scale getNearestScale(\n final ZoomLevels zoomLevels,\n final double tolerance,\n final ZoomLevelSnapStrategy zoomLevelSnapStrategy,\n final boolean geodetic,\n final Rectangle paintArea,\n final double dpi) {\n\n final Scale scale = getScale(paintArea, dpi);\n final Scale correctedScale;\n final double scaleRatio;\n if (geodetic) {\n final double currentScaleDenominator = scale.getGeodeticDenominator(\n getProjection(), dpi, getCenter());\n scaleRatio = scale.getDenominator(dpi) / currentScaleDenominator;\n correctedScale = scale.toResolution(scale.getResolution() / scaleRatio);\n } else {\n scaleRatio = 1;\n correctedScale = scale;\n }\n\n DistanceUnit unit = DistanceUnit.fromProjection(getProjection());\n final ZoomLevelSnapStrategy.SearchResult result = zoomLevelSnapStrategy.search(\n correctedScale, tolerance, zoomLevels);\n final Scale newScale;\n\n if (geodetic) {\n newScale = new Scale(\n result.getScale(unit).getDenominator(PDF_DPI) * scaleRatio,\n getProjection(), dpi);\n } else {\n newScale = result.getScale(unit);\n }\n\n return newScale;\n }", "private String getContentFromPath(String sourcePath,\n HostsSourceType sourceType) throws IOException {\n\n String res = \"\";\n\n if (sourceType == HostsSourceType.LOCAL_FILE) {\n res = PcFileNetworkIoUtils.readFileContentToString(sourcePath);\n } else if (sourceType == HostsSourceType.URL) {\n res = PcFileNetworkIoUtils.readStringFromUrlGeneric(sourcePath);\n }\n return res;\n\n }", "private static void flushCurrentWord( StringBuilder currentWords, List<Word> formattedWords, boolean cutWhitespace ) {\n if( currentWords.length() > 0 ) {\n if( cutWhitespace && currentWords.charAt( currentWords.length() - 1 ) == ' ' ) {\n currentWords.setLength( currentWords.length() - 1 );\n }\n formattedWords.add( new Word( currentWords.toString() ) );\n currentWords.setLength( 0 );\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 static String getScheme(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Scheme) {\n return ((Scheme) q).value();\n }\n }\n\n if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {\n String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME);\n if (s != null && s.isEmpty()) {\n return s;\n }\n }\n\n return DEFAULT_SCHEME;\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 boolean hasAbstractPackagePrivateSuperClassWithImplementation(Class<?> clazz, BridgeMethod bridgeMethod) {\n Class<?> superClass = clazz.getSuperclass();\n while (superClass != null) {\n if (Modifier.isAbstract(superClass.getModifiers()) && Reflections.isPackagePrivate(superClass.getModifiers())) {\n // if superclass is abstract, we need to dig deeper\n for (Method method : superClass.getDeclaredMethods()) {\n if (bridgeMethod.signature.matches(method) && method.getGenericReturnType().equals(bridgeMethod.returnType)\n && !Reflections.isAbstract(method)) {\n // this is the case we are after -> methods have same signature and the one in super class has actual implementation\n return true;\n }\n }\n }\n superClass = superClass.getSuperclass();\n }\n return false;\n }", "public ClassNode annotatedWith(String name) {\n ClassNode anno = infoBase.node(name);\n this.annotations.add(anno);\n anno.annotated.add(this);\n return this;\n }" ]
Parse one resource to a shape object and add it to the shapes array @param shapes @param flatJSON @param resourceId @throws org.json.JSONException
[ "private static void parseRessource(ArrayList<Shape> shapes,\n HashMap<String, JSONObject> flatJSON,\n String resourceId,\n Boolean keepGlossaryLink)\n throws JSONException {\n JSONObject modelJSON = flatJSON.get(resourceId);\n Shape current = getShapeWithId(modelJSON.getString(\"resourceId\"),\n shapes);\n\n parseStencil(modelJSON,\n current);\n\n parseProperties(modelJSON,\n current,\n keepGlossaryLink);\n parseOutgoings(shapes,\n modelJSON,\n current);\n parseChildShapes(shapes,\n modelJSON,\n current);\n parseDockers(modelJSON,\n current);\n parseBounds(modelJSON,\n current);\n parseTarget(shapes,\n modelJSON,\n current);\n }" ]
[ "public static void touch(final File folder , final String fileName) throws IOException {\n if(!folder.exists()){\n folder.mkdirs();\n }\n\n final File touchedFile = new File(folder, fileName);\n\n // The JVM will only 'touch' the file if you instantiate a\n // FileOutputStream instance for the file in question.\n // You don't actually write any data to the file through\n // the FileOutputStream. Just instantiate it and close it.\n\n try (\n FileOutputStream doneFOS = new FileOutputStream(touchedFile);\n ) {\n // Touching the file\n }\n catch (FileNotFoundException e) {\n throw new FileNotFoundException(\"Failed to the find file.\" + e);\n }\n }", "public void updateColor(TestColor color) {\n\n switch (color) {\n case green:\n m_forwardButton.setEnabled(true);\n m_confirmCheckbox.setVisible(false);\n m_status.setValue(STATUS_GREEN);\n break;\n case yellow:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_YELLOW);\n break;\n case red:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_RED);\n break;\n default:\n break;\n }\n }", "public List<TableProperty> getEditableColumns(CmsMessageBundleEditorTypes.EditMode mode) {\n\n return m_editorState.get(mode).getEditableColumns();\n }", "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 }", "void onDrawEye(int eye, int swapChainIndex, boolean use_multiview) {\n mCurrentEye = eye;\n if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) {\n GVRCameraRig mainCameraRig = mMainScene.getMainCameraRig();\n\n if (use_multiview) {\n\n if (DEBUG_STATS) {\n mTracerDrawEyes1.enter(); // this eye is drawn first\n mTracerDrawEyes2.enter();\n }\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.MULTIVIEW, swapChainIndex);\n GVRCamera camera = mMainScene.getMainCameraRig().getCenterCamera();\n GVRCamera left_camera = mMainScene.getMainCameraRig().getLeftCamera();\n renderTarget.cullFromCamera(mMainScene, camera,mRenderBundle.getShaderManager());\n\n captureCenterEye(renderTarget, true);\n capture3DScreenShot(renderTarget, true);\n\n renderTarget.render(mMainScene, left_camera, mRenderBundle.getShaderManager(),mRenderBundle.getPostEffectRenderTextureA(),\n mRenderBundle.getPostEffectRenderTextureB());\n\n captureRightEye(renderTarget, true);\n captureLeftEye(renderTarget, true);\n\n captureFinish();\n\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes2.leave();\n }\n\n\n } else {\n\n if (eye == 1) {\n if (DEBUG_STATS) {\n mTracerDrawEyes1.enter();\n }\n\n GVRCamera rightCamera = mainCameraRig.getRightCamera();\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.RIGHT, swapChainIndex);\n renderTarget.render(mMainScene, rightCamera, mRenderBundle.getShaderManager(), mRenderBundle.getPostEffectRenderTextureA(),\n mRenderBundle.getPostEffectRenderTextureB());\n captureRightEye(renderTarget, false);\n\n captureFinish();\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes.leave();\n }\n } else {\n if (DEBUG_STATS) {\n mTracerDrawEyes1.leave();\n mTracerDrawEyes.leave();\n }\n\n\n GVRRenderTarget renderTarget = mRenderBundle.getRenderTarget(EYE.LEFT, swapChainIndex);\n GVRCamera leftCamera = mainCameraRig.getLeftCamera();\n\n capture3DScreenShot(renderTarget, false);\n\n renderTarget.cullFromCamera(mMainScene, mainCameraRig.getCenterCamera(), mRenderBundle.getShaderManager());\n captureCenterEye(renderTarget, false);\n renderTarget.render(mMainScene, leftCamera, mRenderBundle.getShaderManager(), mRenderBundle.getPostEffectRenderTextureA(), mRenderBundle.getPostEffectRenderTextureB());\n\n captureLeftEye(renderTarget, false);\n\n if (DEBUG_STATS) {\n mTracerDrawEyes2.leave();\n }\n }\n }\n }\n }", "private void addAnnotationValues(ClassReference annotatedReference, AnnotationClassReference typeRef, Annotation node)\n {\n Map<String, AnnotationValue> annotationValueMap = new HashMap<>();\n if (node instanceof SingleMemberAnnotation)\n {\n SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) node;\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, singleMemberAnnotation.getValue());\n annotationValueMap.put(\"value\", value);\n }\n else if (node instanceof NormalAnnotation)\n {\n @SuppressWarnings(\"unchecked\")\n List<MemberValuePair> annotationValues = ((NormalAnnotation) node).values();\n for (MemberValuePair annotationValue : annotationValues)\n {\n String key = annotationValue.getName().toString();\n Expression expression = annotationValue.getValue();\n AnnotationValue value = getAnnotationValueForExpression(annotatedReference, expression);\n annotationValueMap.put(key, value);\n }\n }\n typeRef.setAnnotationValues(annotationValueMap);\n }", "public Response save() throws RequestException, LocalOperationException {\n Map<String, Object> templateData = new HashMap<String, Object>();\n templateData.put(\"name\", name);\n\n options.put(\"steps\", steps.toMap());\n\n templateData.put(\"template\", options);\n Request request = new Request(transloadit);\n return new Response(request.post(\"/templates\", templateData));\n }", "public Swagger read(Set<Class<?>> classes) {\n Set<Class<?>> sortedClasses = new TreeSet<>((class1, class2) -> {\n if (class1.equals(class2)) {\n return 0;\n } else if (class1.isAssignableFrom(class2)) {\n return -1;\n } else if (class2.isAssignableFrom(class1)) {\n return 1;\n }\n return class1.getName().compareTo(class2.getName());\n });\n sortedClasses.addAll(classes);\n\n Map<Class<?>, ReaderListener> listeners = new HashMap<Class<?>, ReaderListener>();\n\n for (Class<?> cls : sortedClasses) {\n if (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)) {\n try {\n listeners.put(cls, (ReaderListener) cls.newInstance());\n } catch (Exception e) {\n LOGGER.error(\"Failed to create ReaderListener\", e);\n }\n }\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.beforeScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking beforeScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n // process SwaggerDefinitions first - so we get tags in desired order\n for (Class<?> cls : sortedClasses) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n }\n\n for (Class<?> cls : sortedClasses) {\n read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.afterScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking afterScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n return swagger;\n }", "private static Map<Integer, LinkedList<MetadataCache>> gatherCandidateAttachmentGroups() {\n Map<Integer,LinkedList<MetadataCache>> candidateGroups = new TreeMap<Integer, LinkedList<MetadataCache>>();\n final Iterator<File> iterator = MetadataFinder.getInstance().getAutoAttachCacheFiles().iterator();\n while (iterator.hasNext()) {\n final File file = iterator.next();\n try {\n final MetadataCache candidate = new MetadataCache(file);\n if (candidateGroups.get(candidate.sourcePlaylist) == null) {\n candidateGroups.put(candidate.sourcePlaylist, new LinkedList<MetadataCache>());\n }\n candidateGroups.get(candidate.sourcePlaylist).add(candidate);\n } catch (Exception e) {\n logger.error(\"Unable to open metadata cache file \" + file + \", discarding\", e);\n iterator.remove();\n }\n }\n return candidateGroups;\n }" ]
Deletes all of the Directories in root that match the FileFilter @param root @param filter
[ "private static void deleteUserDirectories(final File root,\n final FileFilter filter) {\n final File[] dirs = root.listFiles(filter);\n LOGGER.info(\"Identified (\" + dirs.length + \") directories to delete\");\n for (final File dir : dirs) {\n LOGGER.info(\"Deleting \" + dir);\n if (!FileUtils.deleteQuietly(dir)) {\n LOGGER.info(\"Failed to delete directory \" + dir);\n }\n }\n }" ]
[ "public static CmsUUID readId(JSONObject obj, String key) {\n\n String strValue = obj.optString(key);\n if (!CmsUUID.isValidUUID(strValue)) {\n return null;\n }\n return new CmsUUID(strValue);\n }", "public static void Forward(double[] data) {\n\n double[] result = new double[data.length];\n double sum;\n double scale = Math.sqrt(2.0 / data.length);\n for (int f = 0; f < data.length; f++) {\n sum = 0;\n for (int t = 0; t < data.length; t++) {\n double cos = Math.cos(((2.0 * t + 1.0) * f * Math.PI) / (2.0 * data.length));\n sum += data[t] * cos * alpha(f);\n }\n result[f] = scale * sum;\n }\n for (int i = 0; i < data.length; i++) {\n data[i] = result[i];\n }\n }", "public static Date min(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) < 0) ? d1 : d2;\n }\n return result;\n }", "public ParallelTaskBuilder setReplaceVarMapToSingleTargetSingleVar(\n String variable, List<String> replaceList, String uniformTargetHost) {\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skil setting.\");\n return this;\n }\n this.replacementVarMapNodeSpecific.clear();\n this.targetHosts.clear();\n int i = 0;\n for (String replace : replaceList) {\n if (replace == null){\n logger.error(\"null replacement.. skip\");\n continue;\n }\n String hostName = PcConstants.API_PREFIX + i;\n\n replacementVarMapNodeSpecific.put(\n hostName,\n new StrStrMap().addPair(variable, replace).addPair(\n PcConstants.UNIFORM_TARGET_HOST_VAR,\n uniformTargetHost));\n targetHosts.add(hostName);\n ++i;\n }\n this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;\n logger.info(\n \"Set requestReplacementType as {} for single target. Will disable the set target hosts.\"\n + \"Also Simulated \"\n + \"Now Already set targetHost list with size {}. \\nPLEASE NOT TO SET TARGET HOSTS AGAIN WITH THIS API.\",\n requestReplacementType.toString(), targetHosts.size());\n\n return this;\n }", "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 Iterator<BoxItem.Info> iterator() {\n URL url = GET_ITEMS_URL.build(this.api.getBaseURL());\n return new BoxItemIterator(this.api, url);\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}", "public void read(File file, Table table) throws IOException\n {\n //System.out.println(\"Reading \" + file.getName());\n InputStream is = null;\n try\n {\n is = new FileInputStream(file);\n read(is, table);\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n }\n }", "protected String toHexString(boolean with0xPrefix, CharSequence zone) {\n\t\tif(isDualString()) {\n\t\t\treturn toNormalizedStringRange(toIPParams(with0xPrefix ? IPStringCache.hexPrefixedParams : IPStringCache.hexParams), getLower(), getUpper(), zone);\n\t\t}\n\t\treturn toIPParams(with0xPrefix ? IPStringCache.hexPrefixedParams : IPStringCache.hexParams).toString(this, zone);\n\t}" ]
Remove a connection from all keys. @param connection the connection
[ "public void signOff(WebSocketConnection connection) {\n for (ConcurrentMap<WebSocketConnection, WebSocketConnection> connections : registry.values()) {\n connections.remove(connection);\n }\n }" ]
[ "public void addProcedure(ProcedureDef procDef)\r\n {\r\n procDef.setOwner(this);\r\n _procedures.put(procDef.getName(), procDef);\r\n }", "public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory) {\n return create(factory, new ResourcePoolConfig());\n }", "@Override\n public void join(final long millis) throws InterruptedException {\n for (final Thread thread : this.threads) {\n thread.join(millis);\n }\n }", "@SuppressWarnings(\"unchecked\")\n public <T extends WindupVertexFrame> Iterable<T> findVariableOfType(Class<T> type)\n {\n for (Map<String, Iterable<? extends WindupVertexFrame>> topOfStack : deque)\n {\n for (Iterable<? extends WindupVertexFrame> frames : topOfStack.values())\n {\n boolean empty = true;\n for (WindupVertexFrame frame : frames)\n {\n if (!type.isAssignableFrom(frame.getClass()))\n {\n break;\n }\n else\n {\n empty = false;\n }\n }\n // now we know all the frames are of the chosen type\n if (!empty)\n return (Iterable<T>) frames;\n }\n }\n return null;\n }", "List<MwDumpFile> findDumpsOnline(DumpContentType dumpContentType) {\n\t\tList<String> dumpFileDates = findDumpDatesOnline(dumpContentType);\n\n\t\tList<MwDumpFile> result = new ArrayList<>();\n\n\t\tfor (String dateStamp : dumpFileDates) {\n\t\t\tif (dumpContentType == DumpContentType.DAILY) {\n\t\t\t\tresult.add(new WmfOnlineDailyDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, this.webResourceFetcher,\n\t\t\t\t\t\tthis.dumpfileDirectoryManager));\n\t\t\t} else if (dumpContentType == DumpContentType.JSON) {\n\t\t\t\tresult.add(new JsonOnlineDumpFile(dateStamp, this.projectName,\n\t\t\t\t\t\tthis.webResourceFetcher, this.dumpfileDirectoryManager));\n\t\t\t} else {\n\t\t\t\tresult.add(new WmfOnlineStandardDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, this.webResourceFetcher,\n\t\t\t\t\t\tthis.dumpfileDirectoryManager, dumpContentType));\n\t\t\t}\n\t\t}\n\n\t\tlogger.info(\"Found \" + result.size() + \" online dumps of type \"\n\t\t\t\t+ dumpContentType + \": \" + result);\n\n\t\treturn result;\n\t}", "public BoxUser.Info getInfo(String... fields) {\n URL url;\n if (fields.length > 0) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n } else {\n url = USER_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n }\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new Info(jsonObject);\n }", "@Override public int getItemViewType(int position) {\n T content = getItem(position);\n return rendererBuilder.getItemViewType(content);\n }", "static Parameter createParameter(final String name, final String value) {\n if (value != null && isQuoted(value)) {\n return new QuotedParameter(name, value);\n }\n return new Parameter(name, value);\n }", "public String buildRadio(String propName) throws CmsException {\n\n String propVal = readProperty(propName);\n StringBuffer result = new StringBuffer(\"<table border=\\\"0\\\"><tr>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"true\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_TRUE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"false\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"\" : \"checked=\\\"checked\\\"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_FALSE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(CmsStringUtil.isEmpty(propVal) ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(getPropertyInheritanceInfo(propName)).append(\n \"</td></tr></table>\");\n return result.toString();\n }" ]
Creates a pattern choice radio button and adds it where necessary. @param pattern the pattern that should be chosen by the button. @param messageKey the message key for the button's label.
[ "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 }" ]
[ "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 }", "private void computeCosts() {\n cost = Long.MAX_VALUE;\n for (QueueItem item : queueSpans) {\n cost = Math.min(cost, item.sequenceSpans.spans.cost());\n }\n }", "public static String httpRequest(String stringUrl, String method, Map<String, String> parameters,\n String input, String charset) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setDoOutput(true);\n conn.setRequestMethod(method);\n\n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n if (input != null) {\n OutputStream output = null;\n try {\n output = conn.getOutputStream();\n output.write(input.getBytes(charset));\n } finally {\n if (output != null) {\n output.close();\n }\n }\n }\n\n return MyStreamUtils.readContent(conn.getInputStream());\n }", "public static base_response unset(nitro_service client, tmsessionparameter resource, String[] args) throws Exception{\n\t\ttmsessionparameter unsetresource = new tmsessionparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private void deliverBeatAnnouncement(final Beat beat) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.newBeat(beat);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master beat announcement to listener\", t);\n }\n }\n }", "private static MessageInfo mapMessageInfo(MessageInfoType messageInfoType) {\n MessageInfo messageInfo = new MessageInfo();\n if (messageInfoType != null) {\n messageInfo.setFlowId(messageInfoType.getFlowId());\n messageInfo.setMessageId(messageInfoType.getMessageId());\n messageInfo.setOperationName(messageInfoType.getOperationName());\n messageInfo.setPortType(messageInfoType.getPorttype() == null\n ? \"\" : messageInfoType.getPorttype().toString());\n messageInfo.setTransportType(messageInfoType.getTransport());\n }\n return messageInfo;\n }", "String urlDecode(String name, String encoding) throws UnsupportedEncodingException {\n return URLDecoder.decode(name, encoding);\n }", "public double getDegrees() {\n double kms = getValue(GeoDistanceUnit.KILOMETRES);\n return DistanceUtils.dist2Degrees(kms, DistanceUtils.EARTH_MEAN_RADIUS_KM);\n }", "public SourceBuilder add(String fmt, Object... args) {\n TemplateApplier.withParams(args).onText(source::append).onParam(this::add).parse(fmt);\n return this;\n }" ]
We have received an update that invalidates the waveform detail for a player, so clear it and alert any listeners if this represents a change. This does not affect the hot cues; they will stick around until the player loads a new track that overwrites one or more of them. @param update the update which means we have no waveform preview for the associated player
[ "private void clearDeckDetail(TrackMetadataUpdate update) {\n if (detailHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverWaveformDetailUpdate(update.player, null);\n }\n }" ]
[ "public double[] getBasisVector( int which ) {\n if( which < 0 || which >= numComponents )\n throw new IllegalArgumentException(\"Invalid component\");\n\n DMatrixRMaj v = new DMatrixRMaj(1,A.numCols);\n CommonOps_DDRM.extract(V_t,which,which+1,0,A.numCols,v,0,0);\n\n return v.data;\n }", "public float getColorR(int vertex, int colorset) {\n if (!hasColors(colorset)) {\n throw new IllegalStateException(\"mesh has no colorset \" + colorset);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for colorset are done by java for us */\n \n return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT);\n }", "private void writeResource(Resource mpxj)\n {\n ResourceType xml = m_factory.createResourceType();\n m_apibo.getResource().add(xml);\n\n xml.setAutoComputeActuals(Boolean.TRUE);\n xml.setCalculateCostFromUnits(Boolean.TRUE);\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getResourceCalendar()));\n xml.setCurrencyObjectId(DEFAULT_CURRENCY_ID);\n xml.setDefaultUnitsPerTime(Double.valueOf(1.0));\n xml.setEmailAddress(mpxj.getEmailAddress());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(RESOURCE_ID_PREFIX + mpxj.getUniqueID());\n xml.setIsActive(Boolean.TRUE);\n xml.setMaxUnitsPerTime(getPercentage(mpxj.getMaxUnits()));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(mpxj.getParentID());\n xml.setResourceNotes(mpxj.getNotes());\n xml.setResourceType(getResourceType(mpxj));\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.RESOURCE, mpxj));\n }", "public void removePathnameFromProfile(int path_id, int profileId) {\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.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public final void visitChildren(final Visitor visitor)\n\t{\n\t\tfor (final DiffNode child : children.values())\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tchild.visit(visitor);\n\t\t\t}\n\t\t\tcatch (final StopVisitationException e)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}", "public static nspbr6[] get(nitro_service service, nspbr6_args args) throws Exception{\n\t\tnspbr6 obj = new nspbr6();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tnspbr6[] response = (nspbr6[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "private void addProperty(XMLStreamWriter writer, String name, Class<?> propertyType, String readMethod, String writeMethod) throws XMLStreamException\n {\n if (name.length() != 0)\n {\n writer.writeStartElement(\"property\");\n\n // convert property name to .NET style (i.e. first letter uppercase)\n String propertyName = name.substring(0, 1).toUpperCase() + name.substring(1);\n writer.writeAttribute(\"name\", propertyName);\n\n String type = getTypeString(propertyType);\n\n writer.writeAttribute(\"sig\", \"()\" + type);\n if (readMethod != null)\n {\n writer.writeStartElement(\"getter\");\n writer.writeAttribute(\"name\", readMethod);\n writer.writeAttribute(\"sig\", \"()\" + type);\n writer.writeEndElement();\n }\n if (writeMethod != null)\n {\n writer.writeStartElement(\"setter\");\n writer.writeAttribute(\"name\", writeMethod);\n writer.writeAttribute(\"sig\", \"(\" + type + \")V\");\n writer.writeEndElement();\n }\n\n writer.writeEndElement();\n }\n }", "public RedwoodConfiguration showOnlyChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.showOnlyChannels(channels); } });\r\n return this;\r\n }", "public void sendJsonToTagged(Object data, String ... labels) {\n for (String label : labels) {\n sendJsonToTagged(data, label);\n }\n }" ]
Processes an index descriptor tag. @param template The template @param attributes The attributes of the tag @exception XDocletException If an error occurs @doc.tag type="content" @doc.param name="documentation" optional="true" description="Documentation on the index" @doc.param name="fields" optional="false" description="The fields making up the index separated by commas" @doc.param name="name" optional="false" description="The name of the index descriptor" @doc.param name="unique" optional="true" description="Whether the index descriptor is unique" values="true,false"
[ "public String processIndexDescriptor(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n IndexDescriptorDef indexDef = _curClassDef.getIndexDescriptor(name);\r\n String attrName;\r\n \r\n if (indexDef == null)\r\n { \r\n indexDef = new IndexDescriptorDef(name);\r\n _curClassDef.addIndexDescriptor(indexDef);\r\n }\r\n\r\n if ((indexDef.getName() == null) || (indexDef.getName().length() == 0))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.INDEX_NAME_MISSING,\r\n new String[]{_curClassDef.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 indexDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }" ]
[ "@Override\n public <K, V> StoreClient<K, V> getStoreClient(final String storeName,\n final InconsistencyResolver<Versioned<V>> resolver) {\n // wrap it in LazyStoreClient here so any direct calls to this method\n // returns a lazy client\n return new LazyStoreClient<K, V>(new Callable<StoreClient<K, V>>() {\n\n @Override\n public StoreClient<K, V> call() throws Exception {\n Store<K, V, Object> clientStore = getRawStore(storeName, resolver);\n return new RESTClient<K, V>(storeName, clientStore);\n }\n }, true);\n }", "public void updateExceptions(SortedSet<Date> exceptions) {\r\n\r\n SortedSet<Date> e = null == exceptions ? new TreeSet<Date>() : exceptions;\r\n if (!m_model.getExceptions().equals(e)) {\r\n m_model.setExceptions(e);\r\n m_view.updateExceptions();\r\n valueChanged();\r\n sizeChanged();\r\n }\r\n\r\n }", "private static AbstractProject<?, ?> getProject(String fullName) {\n Item item = Hudson.getInstance().getItemByFullName(fullName);\n if (item != null && item instanceof AbstractProject) {\n return (AbstractProject<?, ?>) item;\n }\n return null;\n }", "public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }", "public static void addToString(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n boolean forPartial) {\n String typename = (forPartial ? \"partial \" : \"\") + datatype.getType().getSimpleName();\n Predicate<PropertyCodeGenerator> isOptional = generator -> {\n Initially initially = generator.initialState();\n return (initially == Initially.OPTIONAL || (initially == Initially.REQUIRED && forPartial));\n };\n boolean anyOptional = generatorsByProperty.values().stream().anyMatch(isOptional);\n boolean allOptional = generatorsByProperty.values().stream().allMatch(isOptional)\n && !generatorsByProperty.isEmpty();\n\n code.addLine(\"\")\n .addLine(\"@%s\", Override.class)\n .addLine(\"public %s toString() {\", String.class);\n if (allOptional) {\n bodyWithBuilderAndSeparator(code, datatype, generatorsByProperty, typename);\n } else if (anyOptional) {\n bodyWithBuilder(code, datatype, generatorsByProperty, typename, isOptional);\n } else {\n bodyWithConcatenation(code, generatorsByProperty, typename);\n }\n code.addLine(\"}\");\n }", "private static Iterable<String> splitAndOmitEmpty(final String str, final char splitChar) {\n return new Iterable<String>() {\n @Override\n public Iterator<String> iterator() {\n return new Iterator<String>() {\n\n int startIdx = 0;\n String next = null;\n\n @Override\n public boolean hasNext() {\n while (next == null && startIdx < str.length()) {\n int idx = str.indexOf(splitChar, startIdx);\n if (idx == startIdx) {\n // Omit empty string\n startIdx++;\n continue;\n }\n if (idx >= 0) {\n // Found the next part\n next = str.substring(startIdx, idx);\n startIdx = idx;\n } else {\n // The last part\n if (startIdx < str.length()) {\n next = str.substring(startIdx);\n startIdx = str.length();\n }\n break;\n }\n }\n return next != null;\n }\n\n @Override\n public String next() {\n if (hasNext()) {\n String next = this.next;\n this.next = null;\n return next;\n }\n throw new NoSuchElementException(\"No more element\");\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"Remove not supported\");\n }\n };\n }\n };\n }", "public static double normP1( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return CommonOps_DDRM.elementSumAbs(A);\n } else {\n return inducedP1(A);\n }\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 addCriteria(List<GenericCriteria> list, byte[] block)\n {\n byte[] leftBlock = getChildBlock(block);\n byte[] rightBlock1 = getListNextBlock(leftBlock);\n byte[] rightBlock2 = getListNextBlock(rightBlock1);\n TestOperator operator = TestOperator.getInstance(MPPUtility.getShort(block, 0) - 0x3E7);\n FieldType leftValue = getFieldType(leftBlock);\n Object rightValue1 = getValue(leftValue, rightBlock1);\n Object rightValue2 = rightBlock2 == null ? null : getValue(leftValue, rightBlock2);\n\n GenericCriteria criteria = new GenericCriteria(m_properties);\n criteria.setLeftValue(leftValue);\n criteria.setOperator(operator);\n criteria.setRightValue(0, rightValue1);\n criteria.setRightValue(1, rightValue2);\n list.add(criteria);\n\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = leftValue.getFieldTypeClass() == FieldTypeClass.TASK;\n m_criteriaType[1] = !m_criteriaType[0];\n }\n\n if (m_fields != null)\n {\n m_fields.add(leftValue);\n }\n\n processBlock(list, getListNextBlock(block));\n }" ]
resolves a Field or Property node generics by using the current class and the declaring class to extract the right meaning of the generics symbols @param an a FieldNode or PropertyNode @param type the origin type @return the new ClassNode with corrected generics
[ "private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) {\n if (!type.isUsingGenerics()) return type;\n Map<String, GenericsType> connections = new HashMap();\n //TODO: inner classes mean a different this-type. This is ignored here!\n extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass());\n type= applyGenericsContext(connections, type);\n return type;\n }" ]
[ "private long getTotalTime(ProjectCalendarDateRanges exception)\n {\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd());\n }\n return (total);\n }", "public void addExportedPackages(String... exportedPackages) {\n\t\tString oldBundles = mainAttributes.get(EXPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : exportedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(EXPORT_PACKAGE, result);\n\t}", "@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 }", "public void recordServerResult(ServerIdentity server, ModelNode response) {\n\n if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);\n }\n\n boolean serverFailed = response.has(FAILURE_DESCRIPTION);\n\n\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recording server result for '%s': failed = %s\",\n server, server);\n\n synchronized (this) {\n int previousFailed = failureCount;\n if (serverFailed) {\n failureCount++;\n }\n else {\n successCount++;\n }\n if (previousFailed <= maxFailed) {\n if (!serverFailed && (successCount + failureCount) == servers.size()) {\n // All results are in; notify parent of success\n parent.recordServerGroupResult(serverGroupName, false);\n }\n else if (serverFailed && failureCount > maxFailed) {\n parent.recordServerGroupResult(serverGroupName, true);\n }\n }\n }\n }", "public static final TimeUnit parseDurationTimeUnits(BigInteger value, TimeUnit defaultValue)\n {\n TimeUnit result = defaultValue;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 3:\n case 35:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 4:\n case 36:\n {\n result = TimeUnit.ELAPSED_MINUTES;\n break;\n }\n\n case 5:\n case 37:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 6:\n case 38:\n {\n result = TimeUnit.ELAPSED_HOURS;\n break;\n }\n\n case 7:\n case 39:\n case 53:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 8:\n case 40:\n {\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 9:\n case 41:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 10:\n case 42:\n {\n result = TimeUnit.ELAPSED_WEEKS;\n break;\n }\n\n case 11:\n case 43:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n case 44:\n {\n result = TimeUnit.ELAPSED_MONTHS;\n break;\n }\n\n case 19:\n case 51:\n {\n result = TimeUnit.PERCENT;\n break;\n }\n\n case 20:\n case 52:\n {\n result = TimeUnit.ELAPSED_PERCENT;\n break;\n }\n\n default:\n {\n result = PARENT_FILE.get().getProjectProperties().getDefaultDurationUnits();\n break;\n }\n }\n }\n\n return (result);\n }", "public void releaseDbResources()\r\n {\r\n Iterator it = m_rsIterators.iterator();\r\n while (it.hasNext())\r\n {\r\n ((OJBIterator) it.next()).releaseDbResources();\r\n }\r\n }", "public static <R extends Resource<?>, U extends PaginatedResponse<R>> Flux<R> getResources(U response) {\n return Flux.fromIterable(response.getResources());\n }", "public static void popShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.size() > 0) {\n shells.remove(shells.size() - 1);\n }\n\n }", "public static base_response expire(nitro_service client, cacheobject resource) throws Exception {\n\t\tcacheobject expireresource = new cacheobject();\n\t\texpireresource.locator = resource.locator;\n\t\texpireresource.url = resource.url;\n\t\texpireresource.host = resource.host;\n\t\texpireresource.port = resource.port;\n\t\texpireresource.groupname = resource.groupname;\n\t\texpireresource.httpmethod = resource.httpmethod;\n\t\treturn expireresource.perform_operation(client,\"expire\");\n\t}" ]
Returns value as it appeared on the command line with escape sequences and system properties not resolved. The variables, though, are resolved during the initial parsing of the command line. @param parsedLine parsed command line @param required whether the argument is required @return argument value as it appears on the command line @throws CommandFormatException in case the required argument is missing
[ "public String getOriginalValue(ParsedCommandLine parsedLine, boolean required) throws CommandFormatException {\n String value = null;\n if(parsedLine.hasProperties()) {\n if(index >= 0) {\n List<String> others = parsedLine.getOtherProperties();\n if(others.size() > index) {\n return others.get(index);\n }\n }\n\n value = parsedLine.getPropertyValue(fullName);\n if(value == null && shortName != null) {\n value = parsedLine.getPropertyValue(shortName);\n }\n }\n\n if(required && value == null && !isPresent(parsedLine)) {\n StringBuilder buf = new StringBuilder();\n buf.append(\"Required argument \");\n buf.append('\\'').append(fullName).append('\\'');\n buf.append(\" is missing.\");\n throw new CommandFormatException(buf.toString());\n }\n return value;\n }" ]
[ "public static long count(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_crldistribution_binding obj = new sslcertkey_crldistribution_binding();\n\t\tobj.set_certkey(certkey);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslcertkey_crldistribution_binding response[] = (sslcertkey_crldistribution_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}", "public boolean isConnectionHandleAlive(ConnectionHandle connection) {\r\n\t\tStatement stmt = null;\r\n\t\tboolean result = false;\r\n\t\tboolean logicallyClosed = connection.logicallyClosed.get();\r\n\t\ttry {\r\n\t\t\tconnection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed.\r\n\t\t\tString testStatement = this.config.getConnectionTestStatement();\r\n\t\t\tResultSet rs = null;\r\n\r\n\t\t\tif (testStatement == null) {\r\n\t\t\t\t// Make a call to fetch the metadata instead of a dummy query.\r\n\t\t\t\trs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE );\r\n\t\t\t} else {\r\n\t\t\t\tstmt = connection.createStatement();\r\n\t\t\t\tstmt.execute(testStatement);\r\n\t\t\t}\r\n\r\n\r\n\t\t\tif (rs != null) {\r\n\t\t\t\trs.close();\r\n\t\t\t}\r\n\r\n\t\t\tresult = true;\r\n\t\t} catch (SQLException e) {\r\n\t\t\t// connection must be broken!\r\n\t\t\tresult = false;\r\n\t\t} finally {\r\n\t\t\tconnection.logicallyClosed.set(logicallyClosed);\r\n\t\t\tconnection.setConnectionLastResetInMs(System.currentTimeMillis());\r\n\t\t\tresult = closeStatement(stmt, result);\r\n\t\t}\r\n\t\treturn result;\r\n\t}", "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 }", "public static base_response add(nitro_service client, autoscaleaction resource) throws Exception {\n\t\tautoscaleaction addresource = new autoscaleaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.parameters = resource.parameters;\n\t\taddresource.vmdestroygraceperiod = resource.vmdestroygraceperiod;\n\t\taddresource.quiettime = resource.quiettime;\n\t\taddresource.vserver = resource.vserver;\n\t\treturn addresource.add_resource(client);\n\t}", "public static void add(double[] array1, double[] array2) {\n assert (array1.length == array2.length);\n for (int i=0; i<array1.length; i++) {\n array1[i] += array2[i];\n }\n }", "public ParallelTaskBuilder prepareUdp(String command) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.UDP);\n cb.getUdpMeta().setCommand(command);\n return cb;\n }", "private int[] getPrimaryCodewords() {\r\n\r\n assert mode == 2 || mode == 3;\r\n\r\n if (primaryData.length() != 15) {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n\r\n for (int i = 9; i < 15; i++) { /* check that country code and service are numeric */\r\n if (primaryData.charAt(i) < '0' || primaryData.charAt(i) > '9') {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n }\r\n\r\n String postcode;\r\n if (mode == 2) {\r\n postcode = primaryData.substring(0, 9);\r\n int index = postcode.indexOf(' ');\r\n if (index != -1) {\r\n postcode = postcode.substring(0, index);\r\n }\r\n } else {\r\n // if (mode == 3)\r\n postcode = primaryData.substring(0, 6);\r\n }\r\n\r\n int country = Integer.parseInt(primaryData.substring(9, 12));\r\n int service = Integer.parseInt(primaryData.substring(12, 15));\r\n\r\n if (debug) {\r\n System.out.println(\"Using mode \" + mode);\r\n System.out.println(\" Postcode: \" + postcode);\r\n System.out.println(\" Country Code: \" + country);\r\n System.out.println(\" Service: \" + service);\r\n }\r\n\r\n if (mode == 2) {\r\n return getMode2PrimaryCodewords(postcode, country, service);\r\n } else { // mode == 3\r\n return getMode3PrimaryCodewords(postcode, country, service);\r\n }\r\n }", "private Map<String, String> parseAttributes(I_CmsXmlContentLocation formatterLoc) {\n\n Map<String, String> result = new LinkedHashMap<>();\n for (I_CmsXmlContentValueLocation mappingLoc : formatterLoc.getSubValues(N_ATTRIBUTE)) {\n String key = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_KEY));\n String value = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_VALUE));\n result.put(key, value);\n }\n return Collections.unmodifiableMap(result);\n }", "protected String getQueryParam() {\n\n String param = parseOptionalStringValue(m_configObject, JSON_KEY_QUERYPARAM);\n if (param == null) {\n return null != m_baseConfig ? m_baseConfig.getGeneralConfig().getQueryParam() : DEFAULT_QUERY_PARAM;\n } else {\n return param;\n }\n }" ]
Returns true if the input is a vector @param a A matrix or vector @return true if it's a vector. Column or row.
[ "public static boolean isVector(DMatrixSparseCSC a) {\n return (a.numCols == 1 && a.numRows > 1) || (a.numRows == 1 && a.numCols>1);\n }" ]
[ "protected SingleBusLocatorRegistrar getRegistrar(Bus bus) {\n SingleBusLocatorRegistrar registrar = busRegistrars.get(bus);\n if (registrar == null) {\n check(locatorClient, \"serviceLocator\", \"registerService\");\n registrar = new SingleBusLocatorRegistrar(bus);\n registrar.setServiceLocator(locatorClient);\n registrar.setEndpointPrefix(endpointPrefix);\n Map<String, String> endpointPrefixes = new HashMap<String, String>();\n endpointPrefixes.put(\"HTTP\", endpointPrefixHttp);\n endpointPrefixes.put(\"HTTPS\", endpointPrefixHttps);\n registrar.setEndpointPrefixes(endpointPrefixes);\n busRegistrars.put(bus, registrar);\n addLifeCycleListener(bus);\n }\n return registrar;\n }", "@SuppressWarnings(\"WeakerAccess\")\n public TrackMetadata requestMetadataFrom(final DataReference track, final CdjStatus.TrackType trackType) {\n return requestMetadataInternal(track, trackType, false);\n }", "public ProjectCalendarWeek getWorkWeek(Date date)\n {\n ProjectCalendarWeek week = null;\n if (!m_workWeeks.isEmpty())\n {\n sortWorkWeeks();\n\n int low = 0;\n int high = m_workWeeks.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarWeek midVal = m_workWeeks.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getDateRange().getStart(), midVal.getDateRange().getEnd(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n week = midVal;\n break;\n }\n }\n }\n }\n\n if (week == null && getParent() != null)\n {\n // Check base calendar as well for a work week.\n week = getParent().getWorkWeek(date);\n }\n return (week);\n }", "public ParallelTask execute(ParallecResponseHandler handler) {\n\n ParallelTask task = new ParallelTask();\n\n try {\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n final ParallelTask taskReal = new ParallelTask(requestProtocol,\n concurrency, httpMeta, targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta,\n handler, responseContext, \n replacementVarMapNodeSpecific, replacementVarMap,\n requestReplacementType, \n config);\n\n task = taskReal;\n\n logger.info(\"***********START_PARALLEL_HTTP_TASK_\"\n + task.getTaskId() + \"***********\");\n\n // throws ParallelTaskInvalidException\n task.validateWithFillDefault();\n\n task.setSubmitTime(System.currentTimeMillis());\n\n if (task.getConfig().isEnableCapacityAwareTaskScheduler()) {\n\n //late initialize the task scheduler\n ParallelTaskManager.getInstance().initTaskSchedulerIfNot();\n // add task to the wait queue\n ParallelTaskManager.getInstance().getWaitQ().add(task);\n\n logger.info(\"Enabled CapacityAwareTaskScheduler. Submitted task to waitQ in builder.. \"\n + task.getTaskId());\n\n } else {\n\n logger.info(\n \"Disabled CapacityAwareTaskScheduler. Immediately execute task {} \",\n task.getTaskId());\n\n Runnable director = new Runnable() {\n\n public void run() {\n ParallelTaskManager.getInstance()\n .generateUpdateExecuteTask(taskReal);\n }\n };\n new Thread(director).start();\n }\n\n if (this.getMode() == TaskRunMode.SYNC) {\n logger.info(\"Executing task {} in SYNC mode... \",\n task.getTaskId());\n\n while (task != null && !task.isCompleted()) {\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n logger.error(\"InterruptedException \" + e);\n }\n }\n }\n } catch (ParallelTaskInvalidException ex) {\n\n logger.info(\"Request is invalid with missing parts. Details: \"\n + ex.getMessage() + \" Cannot execute at this time. \"\n + \" Please review your request and try again.\\nCommand:\"\n + httpMeta.toString());\n\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.VALIDATION_ERROR,\n \"validation eror\"));\n\n } catch (Exception t) {\n logger.error(\"fail task builder. Unknown error: \" + t, t);\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.UNKNOWN, \"unknown eror\",\n t));\n }\n\n logger.info(\"***********FINISH_PARALLEL_HTTP_TASK_\" + task.getTaskId()\n + \"***********\");\n return task;\n\n }", "@SuppressWarnings(\"deprecation\")\n public boolean cancelOnTargetHosts(List<String> targetHosts) {\n\n boolean success = false;\n\n try {\n\n switch (state) {\n\n case IN_PROGRESS:\n if (executionManager != null\n && !executionManager.isTerminated()) {\n executionManager.tell(new CancelTaskOnHostRequest(\n targetHosts), executionManager);\n logger.info(\n \"asked task to stop from running on target hosts with count {}...\",\n targetHosts.size());\n } else {\n logger.info(\"manager already killed or not exist.. NO OP\");\n }\n success = true;\n break;\n case COMPLETED_WITHOUT_ERROR:\n case COMPLETED_WITH_ERROR:\n case WAITING:\n logger.info(\"will NO OP for cancelOnTargetHost as it is not in IN_PROGRESS state\");\n success = true;\n break;\n default:\n break;\n\n }\n\n } catch (Exception e) {\n logger.error(\n \"cancel task {} on hosts with count {} error with exception details \",\n this.getTaskId(), targetHosts.size(), e);\n }\n\n return success;\n }", "public void setLocale(String locale) {\n\n try {\n m_locale = LocaleUtils.toLocale(locale);\n } catch (IllegalArgumentException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_TAG_INVALID_LOCALE_1, \"cms:navigation\"), e);\n m_locale = null;\n }\n }", "public static cmppolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tobj.set_name(name);\n\t\tcmppolicy_stats response = (cmppolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public static String readFileContents(FileSystem fs, Path path, int bufferSize)\n throws IOException {\n if(bufferSize <= 0)\n return new String();\n\n FSDataInputStream input = fs.open(path);\n byte[] buffer = new byte[bufferSize];\n\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n\n while(true) {\n int read = input.read(buffer);\n if(read < 0) {\n break;\n } else {\n buffer = ByteUtils.copy(buffer, 0, read);\n }\n stream.write(buffer);\n }\n\n return new String(stream.toByteArray());\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 }" ]
for testing purpose
[ "public boolean hasCachedValue(Key key) {\n\t\ttry {\n\t\t\treadLock.lock();\n\t\t\treturn content.containsKey(key);\n\t\t} finally {\n\t\t\treadLock.unlock();\n\t\t}\n\t}" ]
[ "public static final String printBookingType(BookingType value)\n {\n return (Integer.toString(value == null ? BookingType.COMMITTED.getValue() : value.getValue()));\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 }", "public static double[] getTileLayerSize(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble div = Math.pow(2, code.getTileLevel());\n\t\tdouble tileWidth = Math.ceil((scale * maxExtent.getWidth()) / div) / scale;\n\t\tdouble tileHeight = Math.ceil((scale * maxExtent.getHeight()) / div) / scale;\n\t\treturn new double[] { tileWidth, tileHeight };\n\t}", "public static clusternodegroup[] get(nitro_service service) throws Exception{\n\t\tclusternodegroup obj = new clusternodegroup();\n\t\tclusternodegroup[] response = (clusternodegroup[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public boolean hasPossibleMethod(String name, Expression arguments) {\n int count = 0;\n\n if (arguments instanceof TupleExpression) {\n TupleExpression tuple = (TupleExpression) arguments;\n // TODO this won't strictly be true when using list expansion in argument calls\n count = tuple.getExpressions().size();\n }\n ClassNode node = this;\n do {\n for (MethodNode method : getMethods(name)) {\n if (method.getParameters().length == count && !method.isStatic()) {\n return true;\n }\n }\n node = node.getSuperClass();\n }\n while (node != null);\n return false;\n }", "private void initDatesPanel() {\n\n m_startLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_STARTTIME_0));\n m_startTime.setAllowInvalidValue(true);\n m_startTime.setValue(m_model.getStart());\n m_endLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_ENDTIME_0));\n m_endTime.setAllowInvalidValue(true);\n m_endTime.setValue(m_model.getEnd());\n m_seriesCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_SERIES_CHECKBOX_0));\n m_wholeDayCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_WHOLE_DAY_CHECKBOX_0));\n m_currentTillEndCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_0));\n m_currentTillEndCheckBox.getButton().setTitle(\n Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_HELP_0));\n }", "public static vpnvserver_authenticationsamlpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationsamlpolicy_binding obj = new vpnvserver_authenticationsamlpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationsamlpolicy_binding response[] = (vpnvserver_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public String getFullContentType() {\n final String url = this.url.toExternalForm().substring(\"data:\".length());\n final int endIndex = url.indexOf(',');\n if (endIndex >= 0) {\n final String contentType = url.substring(0, endIndex);\n if (!contentType.isEmpty()) {\n return contentType;\n }\n }\n return \"text/plain;charset=US-ASCII\";\n }", "private PreparedStatement prepareBatchStatement(String sql)\r\n {\r\n String sqlCmd = sql.substring(0, 7);\r\n\r\n if (sqlCmd.equals(\"UPDATE \") || sqlCmd.equals(\"DELETE \") || (_useBatchInserts && sqlCmd.equals(\"INSERT \")))\r\n {\r\n PreparedStatement stmt = (PreparedStatement) _statements.get(sql);\r\n if (stmt == null)\r\n {\r\n // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement\r\n // interfaces, otherwise proxy.jar works incorrectly\r\n stmt = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{\r\n PreparedStatement.class, Statement.class, BatchPreparedStatement.class},\r\n new PreparedStatementInvocationHandler(this, sql, m_jcd));\r\n _statements.put(sql, stmt);\r\n }\r\n return stmt;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }" ]
Detects if the current browser is a BlackBerry Touch device, such as the Storm, Torch, and Bold Touch. Excludes the Playbook. @return detection of a Blackberry touchscreen device
[ "public boolean detectBlackBerryTouch() {\r\n\r\n if (detectBlackBerry()\r\n && ((userAgent.indexOf(deviceBBStorm) != -1)\r\n || (userAgent.indexOf(deviceBBTorch) != -1)\r\n || (userAgent.indexOf(deviceBBBoldTouch) != -1)\r\n || (userAgent.indexOf(deviceBBCurveTouch) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }" ]
[ "public void selectTab() {\n for (Widget child : getChildren()) {\n if (child instanceof HasHref) {\n String href = ((HasHref) child).getHref();\n if (parent != null && !href.isEmpty()) {\n parent.selectTab(href.replaceAll(\"[^a-zA-Z\\\\d\\\\s:]\", \"\"));\n parent.reload();\n break;\n }\n }\n }\n }", "public static rewriteglobal_binding get(nitro_service service) throws Exception{\n\t\trewriteglobal_binding obj = new rewriteglobal_binding();\n\t\trewriteglobal_binding response = (rewriteglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static DoubleMatrix expm(DoubleMatrix A) {\n // constants for pade approximation\n final double c0 = 1.0;\n final double c1 = 0.5;\n final double c2 = 0.12;\n final double c3 = 0.01833333333333333;\n final double c4 = 0.0019927536231884053;\n final double c5 = 1.630434782608695E-4;\n final double c6 = 1.0351966873706E-5;\n final double c7 = 5.175983436853E-7;\n final double c8 = 2.0431513566525E-8;\n final double c9 = 6.306022705717593E-10;\n final double c10 = 1.4837700484041396E-11;\n final double c11 = 2.5291534915979653E-13;\n final double c12 = 2.8101705462199615E-15;\n final double c13 = 1.5440497506703084E-17;\n\n int j = Math.max(0, 1 + (int) Math.floor(Math.log(A.normmax()) / Math.log(2)));\n DoubleMatrix As = A.div((double) Math.pow(2, j)); // scaled version of A\n int n = A.getRows();\n\n // calculate D and N using special Horner techniques\n DoubleMatrix As_2 = As.mmul(As);\n DoubleMatrix As_4 = As_2.mmul(As_2);\n DoubleMatrix As_6 = As_4.mmul(As_2);\n // U = c0*I + c2*A^2 + c4*A^4 + (c6*I + c8*A^2 + c10*A^4 + c12*A^6)*A^6\n DoubleMatrix U = DoubleMatrix.eye(n).muli(c0).addi(As_2.mul(c2)).addi(As_4.mul(c4)).addi(\n DoubleMatrix.eye(n).muli(c6).addi(As_2.mul(c8)).addi(As_4.mul(c10)).addi(As_6.mul(c12)).mmuli(As_6));\n // V = c1*I + c3*A^2 + c5*A^4 + (c7*I + c9*A^2 + c11*A^4 + c13*A^6)*A^6\n DoubleMatrix V = DoubleMatrix.eye(n).muli(c1).addi(As_2.mul(c3)).addi(As_4.mul(c5)).addi(\n DoubleMatrix.eye(n).muli(c7).addi(As_2.mul(c9)).addi(As_4.mul(c11)).addi(As_6.mul(c13)).mmuli(As_6));\n\n DoubleMatrix AV = As.mmuli(V);\n DoubleMatrix N = U.add(AV);\n DoubleMatrix D = U.subi(AV);\n\n // solve DF = N for F\n DoubleMatrix F = Solve.solve(D, N);\n\n // now square j times\n for (int k = 0; k < j; k++) {\n F.mmuli(F);\n }\n\n return F;\n }", "public static int cudnnGetCTCLossWorkspaceSize(\n cudnnHandle handle, \n cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the\n timing steps, N is the mini batch size, A is the alphabet size) */\n cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the\n dimensions are T,N,A. To compute costs\n only, set it to NULL */\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 int algo, /** algorithm selected, supported now 0 and 1 */\n cudnnCTCLossDescriptor ctcLossDesc, \n long[] sizeInBytes)/** pointer to the returned workspace size */\n {\n return checkResult(cudnnGetCTCLossWorkspaceSizeNative(handle, probsDesc, gradientsDesc, labels, labelLengths, inputLengths, algo, ctcLossDesc, sizeInBytes));\n }", "public RandomVariable[]\tgetParameter() {\n\t\tdouble[] parameterAsDouble = this.getParameterAsDouble();\n\t\tRandomVariable[] parameter = new RandomVariable[parameterAsDouble.length];\n\t\tfor(int i=0; i<parameter.length; i++) {\n\t\t\tparameter[i] = new Scalar(parameterAsDouble[i]);\n\t\t}\n\t\treturn parameter;\n\t}", "public static <T extends Bean<?>> Set<T> removeDisabledBeans(Set<T> beans, final BeanManagerImpl beanManager) {\n if (beans.isEmpty()) {\n return beans;\n } else {\n for (Iterator<T> iterator = beans.iterator(); iterator.hasNext();) {\n if (!isBeanEnabled(iterator.next(), beanManager.getEnabled())) {\n iterator.remove();\n }\n }\n return beans;\n }\n }", "public static ProducerRequest readFrom(ByteBuffer buffer) {\n String topic = Utils.readShortString(buffer);\n int partition = buffer.getInt();\n int messageSetSize = buffer.getInt();\n ByteBuffer messageSetBuffer = buffer.slice();\n messageSetBuffer.limit(messageSetSize);\n buffer.position(buffer.position() + messageSetSize);\n return new ProducerRequest(topic, partition, new ByteBufferMessageSet(messageSetBuffer));\n }", "static BsonDocument getFreshVersionDocument() {\n final BsonDocument versionDoc = new BsonDocument();\n\n versionDoc.append(Fields.SYNC_PROTOCOL_VERSION_FIELD, new BsonInt32(1));\n versionDoc.append(Fields.INSTANCE_ID_FIELD, new BsonString(UUID.randomUUID().toString()));\n versionDoc.append(Fields.VERSION_COUNTER_FIELD, new BsonInt64(0L));\n\n return versionDoc;\n }", "public void restore(String state) {\n JsonObject json = JsonObject.readFrom(state);\n String accessToken = json.get(\"accessToken\").asString();\n String refreshToken = json.get(\"refreshToken\").asString();\n long lastRefresh = json.get(\"lastRefresh\").asLong();\n long expires = json.get(\"expires\").asLong();\n String userAgent = json.get(\"userAgent\").asString();\n String tokenURL = json.get(\"tokenURL\").asString();\n String baseURL = json.get(\"baseURL\").asString();\n String baseUploadURL = json.get(\"baseUploadURL\").asString();\n boolean autoRefresh = json.get(\"autoRefresh\").asBoolean();\n int maxRequestAttempts = json.get(\"maxRequestAttempts\").asInt();\n\n this.accessToken = accessToken;\n this.refreshToken = refreshToken;\n this.lastRefresh = lastRefresh;\n this.expires = expires;\n this.userAgent = userAgent;\n this.tokenURL = tokenURL;\n this.baseURL = baseURL;\n this.baseUploadURL = baseUploadURL;\n this.autoRefresh = autoRefresh;\n this.maxRequestAttempts = maxRequestAttempts;\n }" ]
Parses formatter attributes. @param formatterLoc the node location @return the map of formatter attributes (unmodifiable)
[ "private Map<String, String> parseAttributes(I_CmsXmlContentLocation formatterLoc) {\n\n Map<String, String> result = new LinkedHashMap<>();\n for (I_CmsXmlContentValueLocation mappingLoc : formatterLoc.getSubValues(N_ATTRIBUTE)) {\n String key = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_KEY));\n String value = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_VALUE));\n result.put(key, value);\n }\n return Collections.unmodifiableMap(result);\n }" ]
[ "protected boolean isDuplicate(String eventID) {\n if (this.receivedEvents == null) {\n this.receivedEvents = new LRUCache<String>();\n }\n\n return !this.receivedEvents.add(eventID);\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 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 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}", "private boolean checkConfig(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n return \"true\".equalsIgnoreCase((String)config.getProperties().get(\"collector.lifecycleEvent\"));\n }", "public static base_responses unset(nitro_service client, String name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (name != null && name.length > 0) {\n\t\t\tclusternodegroup unsetresources[] = new clusternodegroup[name.length];\n\t\t\tfor (int i=0;i<name.length;i++){\n\t\t\t\tunsetresources[i] = new clusternodegroup();\n\t\t\t\tunsetresources[i].name = name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "private void updateBundleDescriptorContent() throws CmsXmlException {\n\n if (m_descContent.hasLocale(Descriptor.LOCALE)) {\n m_descContent.removeLocale(Descriptor.LOCALE);\n }\n m_descContent.addLocale(m_cms, Descriptor.LOCALE);\n\n int i = 0;\n Property<Object> descProp;\n String desc;\n Property<Object> defaultValueProp;\n String defaultValue;\n Map<String, Item> keyItemMap = getKeyItemMap();\n List<String> keys = new ArrayList<String>(keyItemMap.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n\n m_descContent.addValue(m_cms, Descriptor.N_MESSAGE, Descriptor.LOCALE, i);\n i++;\n String messagePrefix = Descriptor.N_MESSAGE + \"[\" + i + \"]/\";\n\n m_descContent.getValue(messagePrefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(\n m_cms,\n (String)key);\n descProp = keyItemMap.get(key).getItemProperty(TableProperty.DESCRIPTION);\n if ((null != descProp) && (null != descProp.getValue())) {\n desc = descProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).setStringValue(\n m_cms,\n desc);\n }\n\n defaultValueProp = keyItemMap.get(key).getItemProperty(TableProperty.DEFAULT);\n if ((null != defaultValueProp) && (null != defaultValueProp.getValue())) {\n defaultValue = defaultValueProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).setStringValue(\n m_cms,\n defaultValue);\n }\n\n }\n }\n\n }", "@Override\n public Map<String, String> values() {\n Map<String, String> values = new LinkedHashMap<>();\n for (Row each : delegates) {\n for (Entry<String, String> entry : each.values().entrySet()) {\n String name = entry.getKey();\n if (!values.containsKey(name)) {\n values.put(name, entry.getValue());\n }\n }\n }\n return values;\n }", "private synchronized void closeIdleClients() {\n List<Client> candidates = new LinkedList<Client>(openClients.values());\n logger.debug(\"Scanning for idle clients; \" + candidates.size() + \" candidates.\");\n for (Client client : candidates) {\n if ((useCounts.get(client) < 1) &&\n ((timestamps.get(client) + idleLimit.get() * 1000) <= System.currentTimeMillis())) {\n logger.debug(\"Idle time reached for unused client {}\", client);\n closeClient(client);\n }\n }\n }" ]
Set the repeat count of an override at ordinal index @param pathName Path name @param methodName Fully qualified method name @param ordinal 1-based index of the override within the overrides of type methodName @param repeatCount new repeat count to set @return true if success, false otherwise
[ "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 }" ]
[ "protected boolean exportWithMinimalMetaData(String path) {\n\n String checkPath = path.startsWith(\"/\") ? path + \"/\" : \"/\" + path + \"/\";\n for (String p : m_parameters.getResourcesToExportWithMetaData()) {\n if (checkPath.startsWith(p)) {\n return false;\n }\n }\n return true;\n }", "private static ChangeEvent<BsonDocument> coalesceChangeEvents(\n final ChangeEvent<BsonDocument> lastUncommittedChangeEvent,\n final ChangeEvent<BsonDocument> newestChangeEvent\n ) {\n if (lastUncommittedChangeEvent == null) {\n return newestChangeEvent;\n }\n switch (lastUncommittedChangeEvent.getOperationType()) {\n case INSERT:\n switch (newestChangeEvent.getOperationType()) {\n // Coalesce replaces/updates to inserts since we believe at some point a document did not\n // exist remotely and that this replace or update should really be an insert if we are\n // still in an uncommitted state.\n case REPLACE:\n case UPDATE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.INSERT,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n case DELETE:\n switch (newestChangeEvent.getOperationType()) {\n // Coalesce inserts to replaces since we believe at some point a document existed\n // remotely and that this insert should really be an replace if we are still in an\n // uncommitted state.\n case INSERT:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.REPLACE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n case UPDATE:\n switch (newestChangeEvent.getOperationType()) {\n case UPDATE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.UPDATE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n lastUncommittedChangeEvent.getUpdateDescription() != null\n ? lastUncommittedChangeEvent\n .getUpdateDescription()\n .merge(newestChangeEvent.getUpdateDescription())\n : newestChangeEvent.getUpdateDescription(),\n newestChangeEvent.hasUncommittedWrites()\n );\n case REPLACE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.REPLACE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n case REPLACE:\n switch (newestChangeEvent.getOperationType()) {\n case UPDATE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.REPLACE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n default:\n break;\n }\n return newestChangeEvent;\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 }", "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 }", "void forcedUndeployScan() {\n\n if (acquireScanLock()) {\n try {\n ROOT_LOGGER.tracef(\"Performing a post-boot forced undeploy scan for scan directory %s\", deploymentDir.getAbsolutePath());\n ScanContext scanContext = new ScanContext(deploymentOperations);\n\n // Add remove actions to the plan for anything we count as\n // deployed that we didn't find on the scan\n for (Map.Entry<String, DeploymentMarker> missing : scanContext.toRemove.entrySet()) {\n // remove successful deployment and left will be removed\n if (scanContext.registeredDeployments.containsKey(missing.getKey())) {\n scanContext.registeredDeployments.remove(missing.getKey());\n }\n }\n Set<String> scannedDeployments = new HashSet<String>(scanContext.registeredDeployments.keySet());\n scannedDeployments.removeAll(scanContext.persistentDeployments);\n\n List<ScannerTask> scannerTasks = scanContext.scannerTasks;\n for (String toUndeploy : scannedDeployments) {\n scannerTasks.add(new UndeployTask(toUndeploy, deploymentDir, scanContext.scanStartTime, true));\n }\n try {\n executeScannerTasks(scannerTasks, deploymentOperations, true);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n\n ROOT_LOGGER.tracef(\"Forced undeploy scan complete\");\n } catch (Exception e) {\n ROOT_LOGGER.scanException(e, deploymentDir.getAbsolutePath());\n } finally {\n releaseScanLock();\n }\n }\n }", "public Eval<UploadResult> putAsync(String key, Object value) {\n return Eval.later(() -> put(key, value))\n .map(t -> t.orElse(null))\n .map(FluentFunctions.ofChecked(up -> up.waitForUploadResult()));\n\n }", "public static MarvinImage binaryToRgb(MarvinImage img) {\n MarvinImage resultImage = new MarvinImage(img.getWidth(), img.getHeight(), MarvinImage.COLOR_MODEL_RGB);\n\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n if (img.getBinaryColor(x, y)) {\n resultImage.setIntColor(x, y, 0, 0, 0);\n } else {\n resultImage.setIntColor(x, y, 255, 255, 255);\n }\n }\n }\n return resultImage;\n }", "public static NamingConvention determineNamingConvention(\n TypeElement type,\n Iterable<ExecutableElement> methods,\n Messager messager,\n Types types) {\n ExecutableElement beanMethod = null;\n ExecutableElement prefixlessMethod = null;\n for (ExecutableElement method : methods) {\n switch (methodNameConvention(method)) {\n case BEAN:\n beanMethod = firstNonNull(beanMethod, method);\n break;\n case PREFIXLESS:\n prefixlessMethod = firstNonNull(prefixlessMethod, method);\n break;\n default:\n break;\n }\n }\n if (prefixlessMethod != null) {\n if (beanMethod != null) {\n messager.printMessage(\n ERROR,\n \"Type contains an illegal mix of get-prefixed and unprefixed getter methods, e.g. '\"\n + beanMethod.getSimpleName() + \"' and '\" + prefixlessMethod.getSimpleName() + \"'\",\n type);\n }\n return new PrefixlessConvention(messager, types);\n } else {\n return new BeanConvention(messager, types);\n }\n }", "public static String fixLanguageCodeIfDeprecated(String wikimediaLanguageCode) {\n\t\tif (DEPRECATED_LANGUAGE_CODES.containsKey(wikimediaLanguageCode)) {\n\t\t\treturn DEPRECATED_LANGUAGE_CODES.get(wikimediaLanguageCode);\n\t\t} else {\n\t\t\treturn wikimediaLanguageCode;\n\t\t}\n\t}" ]
Extract the generic type from the given Class object. @param clazz the Class to check @param source the expected raw source type (can be {@code null}) @param typeIndex the index of the actual type argument @param nestingLevel the nesting level of the target type @param currentLevel the current nested level @return the generic type as Class, or {@code null} if none
[ "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}" ]
[ "void lockInterruptibly(final Integer permit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n sync.acquireInterruptibly(permit);\n }", "public static synchronized void unregisterDao(ConnectionSource connectionSource, Dao<?, ?> dao) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tremoveDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()));\n\t}", "public void addFileSet(FileSet fs) {\n add(fs);\n if (fs.getProject() == null) {\n fs.setProject(getProject());\n }\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 ScopedToken getLowerScopedToken(List<String> scopes, String resource) {\n assert (scopes != null);\n assert (scopes.size() > 0);\n URL url = null;\n try {\n url = new URL(this.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid refresh URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid refresh URL indicates a bug in the SDK.\", e);\n }\n\n StringBuilder spaceSeparatedScopes = new StringBuilder();\n for (int i = 0; i < scopes.size(); i++) {\n spaceSeparatedScopes.append(scopes.get(i));\n if (i < scopes.size() - 1) {\n spaceSeparatedScopes.append(\" \");\n }\n }\n\n String urlParameters = null;\n\n if (resource != null) {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s&resource=%s\",\n this.getAccessToken(), spaceSeparatedScopes, resource);\n } else {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s\",\n this.getAccessToken(), spaceSeparatedScopes);\n }\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n throw e;\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n ScopedToken token = new ScopedToken(jsonObject);\n token.setObtainedAt(System.currentTimeMillis());\n token.setExpiresIn(jsonObject.get(\"expires_in\").asLong() * 1000);\n return token;\n }", "@Modified(id = \"importerServices\")\n void modifiedImporterService(ServiceReference<ImporterService> serviceReference) {\n try {\n importersManager.modified(serviceReference);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.error(\"The ServiceProperty \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" of the ImporterService \"\n + bundleContext.getService(serviceReference) + \" doesn't provides a valid Filter.\"\n + \" To be used, it must provides a correct \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" ServiceProperty.\",\n invalidFilterException\n );\n importersManager.removeLinks(serviceReference);\n return;\n }\n if (importersManager.matched(serviceReference)) {\n importersManager.updateLinks(serviceReference);\n } else {\n importersManager.removeLinks(serviceReference);\n }\n }", "public void addChannel(String boneName, GVRAnimationChannel channel)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n mBoneChannels[boneId] = channel;\n mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);\n Log.d(\"BONE\", \"Adding animation channel %d %s \", boneId, boneName);\n }\n }", "public static String getVcsUrl(Map<String, String> env) {\n String url = env.get(\"SVN_URL\");\n if (StringUtils.isBlank(url)) {\n url = publicGitUrl(env.get(\"GIT_URL\"));\n }\n if (StringUtils.isBlank(url)) {\n url = env.get(\"P4PORT\");\n }\n return url;\n }", "public LayoutScroller.ScrollableList getPageScrollable() {\n return new LayoutScroller.ScrollableList() {\n\n @Override\n public int getScrollingItemsCount() {\n return MultiPageWidget.super.getScrollingItemsCount();\n }\n\n @Override\n public float getViewPortWidth() {\n return MultiPageWidget.super.getViewPortWidth();\n }\n\n @Override\n public float getViewPortHeight() {\n return MultiPageWidget.super.getViewPortHeight();\n }\n\n @Override\n public float getViewPortDepth() {\n return MultiPageWidget.super.getViewPortDepth();\n }\n\n @Override\n public boolean scrollToPosition(int pos, final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollToPosition(pos, listener);\n }\n\n @Override\n public boolean scrollByOffset(float xOffset, float yOffset, float zOffset,\n final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollByOffset(xOffset, yOffset, zOffset, listener);\n }\n\n @Override\n public void registerDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.registerDataSetObserver(observer);\n }\n\n @Override\n public void unregisterDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.unregisterDataSetObserver(observer);\n }\n\n @Override\n public int getCurrentPosition() {\n return MultiPageWidget.super.getCurrentPosition();\n }\n\n };\n }" ]
Shutdown the socket server
[ "public void close() {\n Closer.closeQuietly(acceptor);\n for (Processor processor : processors) {\n Closer.closeQuietly(processor);\n }\n }" ]
[ "private Collection parseCollection(Element collectionElement) {\n\n Collection collection = new Collection();\n collection.setId(collectionElement.getAttribute(\"id\"));\n collection.setServer(collectionElement.getAttribute(\"server\"));\n collection.setSecret(collectionElement.getAttribute(\"secret\"));\n collection.setChildCount(collectionElement.getAttribute(\"child_count\"));\n collection.setIconLarge(collectionElement.getAttribute(\"iconlarge\"));\n collection.setIconSmall(collectionElement.getAttribute(\"iconsmall\"));\n collection.setDateCreated(collectionElement.getAttribute(\"datecreate\"));\n collection.setTitle(XMLUtilities.getChildValue(collectionElement, \"title\"));\n collection.setDescription(XMLUtilities.getChildValue(collectionElement, \"description\"));\n\n Element iconPhotos = XMLUtilities.getChild(collectionElement, \"iconphotos\");\n if (iconPhotos != null) {\n NodeList photoElements = iconPhotos.getElementsByTagName(\"photo\");\n for (int i = 0; i < photoElements.getLength(); i++) {\n Element photoElement = (Element) photoElements.item(i);\n collection.addPhoto(PhotoUtils.createPhoto(photoElement));\n }\n }\n\n return collection;\n }", "public Quaternionf ConvertDirectionalVectorToQuaternion(Vector3f d) {\n d.negate();\n Quaternionf q = new Quaternionf();\n // check for exception condition\n if ((d.x == 0) && (d.z == 0)) {\n // exception condition if direction is (0,y,0):\n // straight up, straight down or all zero's.\n if (d.y > 0) { // direction straight up\n AxisAngle4f angleAxis = new AxisAngle4f(-(float) Math.PI / 2, 1, 0,\n 0);\n q.set(angleAxis);\n } else if (d.y < 0) { // direction straight down\n AxisAngle4f angleAxis = new AxisAngle4f((float) Math.PI / 2, 1, 0, 0);\n q.set(angleAxis);\n } else { // All zero's. Just set to identity quaternion\n q.identity();\n }\n } else {\n d.normalize();\n Vector3f up = new Vector3f(0, 1, 0);\n Vector3f s = new Vector3f();\n d.cross(up, s);\n s.normalize();\n Vector3f u = new Vector3f();\n d.cross(s, u);\n u.normalize();\n Matrix4f matrix = new Matrix4f(s.x, s.y, s.z, 0, u.x, u.y, u.z, 0, d.x,\n d.y, d.z, 0, 0, 0, 0, 1);\n q.setFromNormalized(matrix);\n }\n return q;\n }", "protected String sp_createSequenceQuery(String sequenceName, long maxKey)\r\n {\r\n return \"insert into \" + SEQ_TABLE_NAME + \" (\"\r\n + SEQ_NAME_STRING + \",\" + SEQ_ID_STRING +\r\n \") values ('\" + sequenceName + \"',\" + maxKey + \")\";\r\n }", "public void disconnect() {\n\t\tif (sendThread != null) {\n\t\t\tsendThread.interrupt();\n\t\t\ttry {\n\t\t\t\tsendThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\tsendThread = null;\n\t\t}\n\t\tif (receiveThread != null) {\n\t\t\treceiveThread.interrupt();\n\t\t\ttry {\n\t\t\t\treceiveThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\treceiveThread = null;\n\t\t}\n\t\tif(transactionCompleted.availablePermits() < 0)\n\t\t\ttransactionCompleted.release(transactionCompleted.availablePermits());\n\t\t\n\t\ttransactionCompleted.drainPermits();\n\t\tlogger.trace(\"Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\tif (this.serialPort != null) {\n\t\t\tthis.serialPort.close();\n\t\t\tthis.serialPort = null;\n\t\t}\n\t\tlogger.info(\"Disconnected from serial port\");\n\t}", "private void deEndify(List<CoreLabel> tokens) {\r\n if (flags.retainEntitySubclassification) {\r\n return;\r\n }\r\n tokens = new PaddedList<CoreLabel>(tokens, new CoreLabel());\r\n int k = tokens.size();\r\n String[] newAnswers = new String[k];\r\n for (int i = 0; i < k; i++) {\r\n CoreLabel c = tokens.get(i);\r\n CoreLabel p = tokens.get(i - 1);\r\n if (c.get(AnswerAnnotation.class).length() > 1 && c.get(AnswerAnnotation.class).charAt(1) == '-') {\r\n String base = c.get(AnswerAnnotation.class).substring(2);\r\n String pBase = (p.get(AnswerAnnotation.class).length() <= 2 ? p.get(AnswerAnnotation.class) : p.get(AnswerAnnotation.class).substring(2));\r\n boolean isSecond = (base.equals(pBase));\r\n boolean isStart = (c.get(AnswerAnnotation.class).charAt(0) == 'B' || c.get(AnswerAnnotation.class).charAt(0) == 'S');\r\n if (isSecond && isStart) {\r\n newAnswers[i] = intern(\"B-\" + base);\r\n } else {\r\n newAnswers[i] = intern(\"I-\" + base);\r\n }\r\n } else {\r\n newAnswers[i] = c.get(AnswerAnnotation.class);\r\n }\r\n }\r\n for (int i = 0; i < k; i++) {\r\n CoreLabel c = tokens.get(i);\r\n c.set(AnswerAnnotation.class, newAnswers[i]);\r\n }\r\n }", "@Override\n public boolean shouldRetry(int retryCount, Response response) {\n int code = response.code();\n //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES\n return retryCount < this.retryCount\n && (code == 408 || (code >= 500 && code != 501 && code != 505));\n }", "public void registerCollectionSizeGauge(\n\t\t\tCollectionSizeGauge collectionSizeGauge) {\n\t\tString name = createMetricName(LocalTaskExecutorService.class,\n\t\t\t\t\"queue-size\");\n\t\tmetrics.register(name, collectionSizeGauge);\n\t}", "private void processScheduleOptions()\n {\n List<Row> rows = getRows(\"schedoptions\", \"proj_id\", m_projectID);\n if (rows.isEmpty() == false)\n {\n Row row = rows.get(0);\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", row.getString(\"sched_calendar_on_relationship_lag\"));\n customProperties.put(\"RetainedLogic\", Boolean.valueOf(row.getBoolean(\"sched_retained_logic\")));\n customProperties.put(\"ProgressOverride\", Boolean.valueOf(row.getBoolean(\"sched_progress_override\")));\n customProperties.put(\"IgnoreOtherProjectRelationships\", row.getString(\"sched_outer_depend_type\"));\n customProperties.put(\"StartToStartLagCalculationType\", Boolean.valueOf(row.getBoolean(\"sched_lag_early_start_flag\")));\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n }\n }", "private static double pointsDistance(Point a, Point b) {\n int dx = b.x - a.x;\n int dy = b.y - a.y;\n return Math.sqrt(dx * dx + dy * dy);\n }" ]
Initialization necessary for editing a property bundle. @throws CmsLoaderException thrown if loading a bundle file fails. @throws CmsException thrown if loading a bundle file fails. @throws IOException thrown if loading a bundle file fails.
[ "private void initPropertyBundle() throws CmsLoaderException, CmsException, IOException {\n\n for (Locale l : m_locales) {\n String filePath = m_sitepath + m_basename + \"_\" + l.toString();\n CmsResource resource = null;\n if (m_cms.existsResource(\n filePath,\n CmsResourceFilter.requireType(\n OpenCms.getResourceManager().getResourceType(BundleType.PROPERTY.toString())))) {\n resource = m_cms.readResource(filePath);\n SortedProperties props = new SortedProperties();\n CmsFile file = m_cms.readFile(resource);\n props.load(\n new InputStreamReader(\n new ByteArrayInputStream(file.getContents()),\n CmsFileUtil.getEncoding(m_cms, file)));\n m_keyset.updateKeySet(null, props.keySet());\n m_bundleFiles.put(l, resource);\n }\n }\n\n }" ]
[ "private static Set<String> imageOrientationsOf(ImageMetadata metadata) {\n\n String exifIFD0DirName = new ExifIFD0Directory().getName();\n\n Tag[] tags = Arrays.stream(metadata.getDirectories())\n .filter(dir -> dir.getName().equals(exifIFD0DirName))\n .findFirst()\n .map(Directory::getTags)\n .orElseGet(() -> new Tag[0]);\n\n return Arrays.stream(tags)\n .filter(tag -> tag.getType() == 274)\n .map(Tag::getRawValue)\n .collect(Collectors.toSet());\n }", "public double getValue(ForwardCurveInterface forwardCurve, double swaprateVolatility) {\n\t\tdouble swaprate = swaprates[0];\n\t\tfor (double swaprate1 : swaprates) {\n\t\t\tif (swaprate1 != swaprate) {\n\t\t\t\tthrow new RuntimeException(\"Uneven swaprates not allows for analytical pricing.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble[] swapTenor = new double[fixingDates.length+1];\n\t\tSystem.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);\n\t\tswapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];\n\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(new TimeDiscretization(swapTenor), new TimeDiscretization(swapTenor), forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(new TimeDiscretization(swapTenor), forwardCurve);\n\n\t\treturn AnalyticFormulas.blackModelSwaptionValue(forwardSwapRate, swaprateVolatility, exerciseDate, swaprate, swapAnnuity);\n\t}", "public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }", "public final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }", "String getFacetParamKey(String facet) {\n\n I_CmsSearchControllerFacetField fieldFacet = m_result.getController().getFieldFacets().getFieldFacetController().get(\n facet);\n if (fieldFacet != null) {\n return fieldFacet.getConfig().getParamKey();\n }\n I_CmsSearchControllerFacetRange rangeFacet = m_result.getController().getRangeFacets().getRangeFacetController().get(\n facet);\n if (rangeFacet != null) {\n return rangeFacet.getConfig().getParamKey();\n }\n I_CmsSearchControllerFacetQuery queryFacet = m_result.getController().getQueryFacet();\n if ((queryFacet != null) && queryFacet.getConfig().getName().equals(facet)) {\n return queryFacet.getConfig().getParamKey();\n }\n\n // Facet did not exist\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_FACET_NOT_CONFIGURED_1, facet), new Throwable());\n\n return null;\n }", "public Vector3Axis delta(Vector3f v) {\n Vector3Axis ret = new Vector3Axis(Float.NaN, Float.NaN, Float.NaN);\n if (x != Float.NaN && v.x != Float.NaN && !equal(x, v.x)) {\n ret.set(x - v.x, Layout.Axis.X);\n }\n if (y != Float.NaN && v.y != Float.NaN && !equal(y, v.y)) {\n ret.set(y - v.y, Layout.Axis.Y);\n }\n if (z != Float.NaN && v.z != Float.NaN && !equal(z, v.z)) {\n ret.set(z - v.z, Layout.Axis.Z);\n }\n return ret;\n }", "public static String roundCorner(int radiusInner, int radiusOuter, int color) {\n if (radiusInner < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radiusOuter < 0) {\n throw new IllegalArgumentException(\"Outer radius must be greater than or equal to zero.\");\n }\n StringBuilder builder = new StringBuilder(FILTER_ROUND_CORNER).append(\"(\").append(radiusInner);\n if (radiusOuter > 0) {\n builder.append(\"|\").append(radiusOuter);\n }\n final int r = (color & 0xFF0000) >>> 16;\n final int g = (color & 0xFF00) >>> 8;\n final int b = color & 0xFF;\n return builder.append(\",\") //\n .append(r).append(\",\") //\n .append(g).append(\",\") //\n .append(b).append(\")\") //\n .toString();\n }", "public static base_response add(nitro_service client, dnspolicylabel resource) throws Exception {\n\t\tdnspolicylabel addresource = new dnspolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.transform = resource.transform;\n\t\treturn addresource.add_resource(client);\n\t}", "public String login(String token, Authentication authentication) {\n\t\tif (null == token) {\n\t\t\treturn login(authentication);\n\t\t}\n\t\ttokens.put(token, new TokenContainer(authentication));\n\t\treturn token;\n\t}" ]
Gets the index of the specified value. @param value the value of the item to be found @return the index of the value
[ "public int getIndex(T value) {\n int count = getItemCount();\n for (int i = 0; i < count; i++) {\n if (Objects.equals(getValue(i), value)) {\n return i;\n }\n }\n return -1;\n }" ]
[ "public <T> void cleanNullReferencesAll() {\n\t\tfor (Map<Object, Reference<Object>> objectMap : classMaps.values()) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}", "public static vpath get(nitro_service service, String name) throws Exception{\n\t\tvpath obj = new vpath();\n\t\tobj.set_name(name);\n\t\tvpath response = (vpath) obj.get_resource(service);\n\t\treturn response;\n\t}", "public Response remove(String id) {\r\n assertNotEmpty(id, \"id\");\r\n id = ensureDesignPrefix(id);\r\n String revision = null;\r\n // Get the revision ID from ETag, removing leading and trailing \"\r\n revision = client.executeRequest(Http.HEAD(new DatabaseURIHelper(db.getDBUri()\r\n ).documentUri(id))).getConnection().getHeaderField(\"ETag\");\r\n if (revision != null) {\r\n revision = revision.substring(1, revision.length() - 1);\r\n return db.remove(id, revision);\r\n } else {\r\n throw new CouchDbException(\"No ETag header found for design document with id \" + id);\r\n }\r\n }", "public String convertFromJavaString(String string, boolean useUnicode) {\n\t\tint firstEscapeSequence = string.indexOf('\\\\');\n\t\tif (firstEscapeSequence == -1) {\n\t\t\treturn string;\n\t\t}\n\t\tint length = string.length();\n\t\tStringBuilder result = new StringBuilder(length);\n\t\tappendRegion(string, 0, firstEscapeSequence, result);\n\t\treturn convertFromJavaString(string, useUnicode, firstEscapeSequence, result);\n\t}", "@AfterThrowing(pointcut = \"execution(* org.apache.cassandra.thrift.CassandraServer.doInsert(..))\", throwing = \"throwable\")\n public void logErrorFromThrownException(final JoinPoint joinPoint, final Throwable throwable) {\n final String className = joinPoint.getTarget().getClass().getName();\n final String methodName = joinPoint.getSignature().getName();\n\n logger.error(\"Could not write to cassandra! Method: \" + className + \".\"+ methodName + \"()\", throwable);\n }", "public static nsconfig diff(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig diffresource = new nsconfig();\n\t\tdiffresource.config1 = resource.config1;\n\t\tdiffresource.config2 = resource.config2;\n\t\tdiffresource.outtype = resource.outtype;\n\t\tdiffresource.template = resource.template;\n\t\tdiffresource.ignoredevicespecific = resource.ignoredevicespecific;\n\t\treturn (nsconfig)diffresource.perform_operationEx(client,\"diff\");\n\t}", "public static base_response unset(nitro_service client, inatparam resource, String[] args) throws Exception{\n\t\tinatparam unsetresource = new inatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private Boolean readOptionalBoolean(JSONValue val) {\n\n JSONBoolean b = null == val ? null : val.isBoolean();\n if (b != null) {\n return Boolean.valueOf(b.booleanValue());\n }\n return null;\n }", "public static void log(final String templateName, final Template template, final Values values) {\n new ValuesLogger().doLog(templateName, template, values);\n }" ]
Switches from a dense to sparse matrix
[ "public void convertToSparse() {\n switch ( mat.getType() ) {\n case DDRM: {\n DMatrixSparseCSC m = new DMatrixSparseCSC(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrixRMaj) mat, m,0);\n setMatrix(m);\n } break;\n case FDRM: {\n FMatrixSparseCSC m = new FMatrixSparseCSC(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrixRMaj) mat, m,0);\n setMatrix(m);\n } break;\n\n case DSCC:\n case FSCC:\n break;\n default:\n throw new RuntimeException(\"Conversion not supported!\");\n }\n }" ]
[ "public ArtifactName build() {\n String groupId = this.groupId;\n String artifactId = this.artifactId;\n String classifier = this.classifier;\n String packaging = this.packaging;\n String version = this.version;\n if (artifact != null && !artifact.isEmpty()) {\n final String[] artifactSegments = artifact.split(\":\");\n // groupId:artifactId:version[:packaging][:classifier].\n String value;\n switch (artifactSegments.length) {\n case 5:\n value = artifactSegments[4].trim();\n if (!value.isEmpty()) {\n classifier = value;\n }\n case 4:\n value = artifactSegments[3].trim();\n if (!value.isEmpty()) {\n packaging = value;\n }\n case 3:\n value = artifactSegments[2].trim();\n if (!value.isEmpty()) {\n version = value;\n }\n case 2:\n value = artifactSegments[1].trim();\n if (!value.isEmpty()) {\n artifactId = value;\n }\n case 1:\n value = artifactSegments[0].trim();\n if (!value.isEmpty()) {\n groupId = value;\n }\n }\n }\n return new ArtifactNameImpl(groupId, artifactId, classifier, packaging, version);\n }", "public int[][] argb() {\n return Arrays.stream(points()).map(p -> argb(p.x, p.y)).toArray(int[][]::new);\n }", "@Override\n public void registerChildren(ManagementResourceRegistration resourceRegistration) {\n // Register wildcard children last to prevent duplicate registration errors when override definitions exist\n for (ResourceDefinition rd : singletonChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n for (ResourceDefinition rd : wildcardChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n }", "private static boolean matches(@Nonnull final Pattern pattern, @Nonnull final CharSequence chars) {\n\t\treturn pattern.matcher(chars).matches();\n\t}", "public static Message create( String text, Object data, ProcessingUnit owner )\n {\n return new SimpleMessage( text, data, owner);\n }", "public final String getPath(final String key) {\n StringBuilder result = new StringBuilder();\n addPathTo(result);\n result.append(\".\");\n result.append(getPathElement(key));\n return result.toString();\n }", "public void processCalendar(Row row)\n {\n ProjectCalendar calendar = m_project.addCalendar();\n\n Integer id = row.getInteger(\"clndr_id\");\n m_calMap.put(id, calendar);\n calendar.setName(row.getString(\"clndr_name\"));\n\n try\n {\n calendar.setMinutesPerDay(Integer.valueOf((int) NumberHelper.getDouble(row.getDouble(\"day_hr_cnt\")) * 60));\n calendar.setMinutesPerWeek(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"week_hr_cnt\")) * 60)));\n calendar.setMinutesPerMonth(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"month_hr_cnt\")) * 60)));\n calendar.setMinutesPerYear(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"year_hr_cnt\")) * 60)));\n }\n catch (ClassCastException ex)\n {\n // We have seen examples of malformed calendar data where fields have been missing\n // from the record. We'll typically get a class cast exception here as we're trying\n // to process something which isn't a double.\n // We'll just return at this point as it's not clear that we can salvage anything\n // sensible from this record.\n return;\n }\n\n // Process data\n String calendarData = row.getString(\"clndr_data\");\n if (calendarData != null && !calendarData.isEmpty())\n {\n Record root = Record.getRecord(calendarData);\n if (root != null)\n {\n processCalendarDays(calendar, root);\n processCalendarExceptions(calendar, root);\n }\n }\n else\n {\n // if there is not DaysOfWeek data, Primavera seems to default to Mon-Fri, 8:00-16:00\n DateRange defaultHourRange = new DateRange(DateHelper.getTime(8, 0), DateHelper.getTime(16, 0));\n for (Day day : Day.values())\n {\n if (day != Day.SATURDAY && day != Day.SUNDAY)\n {\n calendar.setWorkingDay(day, true);\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n hours.addRange(defaultHourRange);\n }\n else\n {\n calendar.setWorkingDay(day, false);\n }\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }", "private synchronized HostServerGroupEffect getHostEffect(PathAddress address, String host, Resource root) {\n if (requiresMapping) {\n map(root);\n requiresMapping = false;\n }\n Set<String> mapped = hostsToGroups.get(host);\n if (mapped == null) {\n // Unassigned host. Treat like an unassigned profile or socket-binding-group;\n // i.e. available to all server group scoped roles.\n // Except -- WFLY-2085 -- the master HC is not open to all s-g-s-rs\n Resource hostResource = root.getChild(PathElement.pathElement(HOST, host));\n if (hostResource != null) {\n ModelNode dcModel = hostResource.getModel().get(DOMAIN_CONTROLLER);\n if (!dcModel.hasDefined(REMOTE)) {\n mapped = Collections.emptySet(); // prevents returning HostServerGroupEffect.forUnassignedHost(address, host)\n }\n }\n }\n return mapped == null ? HostServerGroupEffect.forUnassignedHost(address, host)\n : HostServerGroupEffect.forMappedHost(address, mapped, host);\n\n }", "public String toUriString(final java.net.URI uri) {\n return this.toUriString(URI.createURI(uri.normalize().toString()));\n }" ]
Validate that the Unique IDs for the entities in this container are valid for MS Project. If they are not valid, i.e one or more of them are too large, renumber them.
[ "public void validateUniqueIDsForMicrosoftProject()\n {\n if (!isEmpty())\n {\n for (T entity : this)\n {\n if (NumberHelper.getInt(entity.getUniqueID()) > MS_PROJECT_MAX_UNIQUE_ID)\n {\n renumberUniqueIDs();\n break;\n }\n }\n }\n }" ]
[ "public static base_response Import(nitro_service client, appfwsignatures resource) throws Exception {\n\t\tappfwsignatures Importresource = new appfwsignatures();\n\t\tImportresource.src = resource.src;\n\t\tImportresource.name = resource.name;\n\t\tImportresource.xslt = resource.xslt;\n\t\tImportresource.comment = resource.comment;\n\t\tImportresource.overwrite = resource.overwrite;\n\t\tImportresource.merge = resource.merge;\n\t\tImportresource.sha1 = resource.sha1;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}", "public void viewDocument(DocumentEntry entry)\n {\n InputStream is = null;\n\n try\n {\n is = new DocumentInputStream(entry);\n byte[] data = new byte[is.available()];\n is.read(data);\n m_model.setData(data);\n updateTables();\n }\n\n catch (IOException ex)\n {\n throw new RuntimeException(ex);\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n }\n\n }", "public void addProjectListeners(List<ProjectListener> listeners)\n {\n if (listeners != null)\n {\n for (ProjectListener listener : listeners)\n {\n addProjectListener(listener);\n }\n }\n }", "public static vpnvserver_responderpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_responderpolicy_binding obj = new vpnvserver_responderpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_responderpolicy_binding response[] = (vpnvserver_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Map<DeckReference, AlbumArt> getLoadedArt() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, AlbumArt>(hotCache));\n }", "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 vpnglobal_vpnnexthopserver_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_vpnnexthopserver_binding obj = new vpnglobal_vpnnexthopserver_binding();\n\t\tvpnglobal_vpnnexthopserver_binding response[] = (vpnglobal_vpnnexthopserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void logBlock(int blockIndex, int startIndex, int blockLength)\n {\n if (m_log != null)\n {\n m_log.println(\"Block Index: \" + blockIndex);\n m_log.println(\"Length: \" + blockLength + \" (\" + Integer.toHexString(blockLength) + \")\");\n m_log.println();\n m_log.println(FastTrackUtility.hexdump(m_buffer, startIndex, blockLength, true, 16, \"\"));\n m_log.flush();\n }\n }", "private void destroyRequestQueue(Queue<AsyncResourceRequest<V>> requestQueue) {\n if(requestQueue != null) {\n AsyncResourceRequest<V> resourceRequest = requestQueue.poll();\n while(resourceRequest != null) {\n destroyRequest(resourceRequest);\n resourceRequest = requestQueue.poll();\n }\n }\n }" ]
Check whether error handling works. If it works, you should see an ok, otherwise, you might see the actual error message and then the program exits.
[ "public static void checkXerbla() {\n double[] x = new double[9];\n System.out.println(\"Check whether we're catching XERBLA errors. If you see something like \\\"** On entry to DGEMM parameter number 4 had an illegal value\\\", it didn't work!\");\n try {\n NativeBlas.dgemm('N', 'N', 3, -1, 3, 1.0, x, 0, 3, x, 0, 3, 0.0, x, 0, 3);\n } catch (IllegalArgumentException e) {\n check(\"checking XERBLA\", e.getMessage().contains(\"XERBLA\"));\n return;\n }\n assert (false); // shouldn't happen\n }" ]
[ "public Iterator<BoxItem.Info> iterator() {\n URL url = GET_ITEMS_URL.build(this.api.getBaseURL());\n return new BoxItemIterator(this.api, url);\n }", "public static URL getAuthorizationURL(String clientID, URI redirectUri, String state, List<String> scopes) {\n URLTemplate template = new URLTemplate(AUTHORIZATION_URL);\n QueryStringBuilder queryBuilder = new QueryStringBuilder().appendParam(\"client_id\", clientID)\n .appendParam(\"response_type\", \"code\")\n .appendParam(\"redirect_uri\", redirectUri.toString())\n .appendParam(\"state\", state);\n\n if (scopes != null && !scopes.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n int size = scopes.size() - 1;\n int i = 0;\n while (i < size) {\n builder.append(scopes.get(i));\n builder.append(\" \");\n i++;\n }\n builder.append(scopes.get(i));\n\n queryBuilder.appendParam(\"scope\", builder.toString());\n }\n\n return template.buildWithQuery(\"\", queryBuilder.toString());\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 static String urlEncode(String path) throws URISyntaxException {\n if (isNullOrEmpty(path)) return path;\n\n return UrlEscapers.urlFragmentEscaper().escape(path);\n }", "public static final void parseExtendedAttribute(ProjectFile file, FieldContainer mpx, String value, FieldType mpxFieldID, TimeUnit durationFormat)\n {\n if (mpxFieldID != null)\n {\n switch (mpxFieldID.getDataType())\n {\n case STRING:\n {\n mpx.set(mpxFieldID, value);\n break;\n }\n\n case DATE:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeDate(value));\n break;\n }\n\n case CURRENCY:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeCurrency(value));\n break;\n }\n\n case BOOLEAN:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeBoolean(value));\n break;\n }\n\n case NUMERIC:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeNumber(value));\n break;\n }\n\n case DURATION:\n {\n mpx.set(mpxFieldID, parseDuration(file, durationFormat, value));\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n }", "public Map<String, String> getTitleLocale() {\n\n if (m_localeTitles == null) {\n m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object inputLocale) {\n\n Locale locale = null;\n if (null != inputLocale) {\n if (inputLocale instanceof Locale) {\n locale = (Locale)inputLocale;\n } else if (inputLocale instanceof String) {\n try {\n locale = LocaleUtils.toLocale((String)inputLocale);\n } catch (IllegalArgumentException | NullPointerException e) {\n // do nothing, just go on without locale\n }\n }\n }\n return getLocaleSpecificTitle(locale);\n }\n\n });\n }\n return m_localeTitles;\n }", "public static AccessorPrefix determineAccessorPrefix(@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 new AccessorPrefix(m.group(1));\n\t}", "public static CharSequence formatDuration(Context context, ReadableDuration readableDuration) {\n Resources res = context.getResources();\n Duration duration = readableDuration.toDuration();\n\n final int hours = (int) duration.getStandardHours();\n if (hours != 0) {\n return res.getQuantityString(R.plurals.joda_time_android_duration_hours, hours, hours);\n }\n\n final int minutes = (int) duration.getStandardMinutes();\n if (minutes != 0) {\n return res.getQuantityString(R.plurals.joda_time_android_duration_minutes, minutes, minutes);\n }\n\n final int seconds = (int) duration.getStandardSeconds();\n return res.getQuantityString(R.plurals.joda_time_android_duration_seconds, seconds, seconds);\n }", "public CodePage getCodePage(int field)\n {\n CodePage result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = CodePage.getInstance(m_fields[field]);\n }\n else\n {\n result = CodePage.getInstance(null);\n }\n\n return (result);\n }" ]
Returns the text content to any HTML. @param html the HTML @return the text content
[ "public static String stripHtml(String html) {\n\n if (html == null) {\n return null;\n }\n Element el = DOM.createDiv();\n el.setInnerHTML(html);\n return el.getInnerText();\n }" ]
[ "protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }", "@Deprecated\n public ModelNode remove(ModelNode model) throws NoSuchElementException {\n final Iterator<PathElement> i = pathAddressList.iterator();\n while (i.hasNext()) {\n final PathElement element = i.next();\n if (i.hasNext()) {\n model = model.require(element.getKey()).require(element.getValue());\n } else {\n final ModelNode parent = model.require(element.getKey());\n model = parent.remove(element.getValue()).clone();\n }\n }\n return model;\n }", "@Override\n public ImageSource apply(ImageSource input) {\n int w = input.getWidth();\n int h = input.getHeight();\n\n MatrixSource output = new MatrixSource(input);\n\n Vector3 n = new Vector3(0, 0, 1);\n\n for (int y = 0; y < h; y++) {\n for (int x = 0; x < w; x++) {\n\n if (x < border || x == w - border || y < border || y == h - border) {\n output.setRGB(x, y, VectorHelper.Z_NORMAL);\n continue;\n }\n\n float s0 = input.getR(x - 1, y + 1);\n float s1 = input.getR(x, y + 1);\n float s2 = input.getR(x + 1, y + 1);\n float s3 = input.getR(x - 1, y);\n float s5 = input.getR(x + 1, y);\n float s6 = input.getR(x - 1, y - 1);\n float s7 = input.getR(x, y - 1);\n float s8 = input.getR(x + 1, y - 1);\n\n float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6);\n float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2);\n\n n.set(nx, ny, scale);\n n.nor();\n\n int rgb = VectorHelper.vectorToColor(n);\n output.setRGB(x, y, rgb);\n }\n }\n\n return new MatrixSource(output);\n }", "public int readInt(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "public FieldType getFieldTypeFromVarDataKey(Integer key)\n {\n FieldType result = null;\n for (Entry<FieldType, FieldMap.FieldItem> entry : m_map.entrySet())\n {\n if (entry.getValue().getFieldLocation() == FieldLocation.VAR_DATA && entry.getValue().getVarDataKey().equals(key))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }", "public void login(Object userIdentifier) {\n session().put(config().sessionKeyUsername(), userIdentifier);\n app().eventBus().trigger(new LoginEvent(userIdentifier.toString()));\n }", "public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final ResourceRoot deploymentRoot = phaseContext.getDeploymentUnit().getAttachment(Attachments.DEPLOYMENT_ROOT);\n final ModuleSpecification moduleSpecification = phaseContext.getDeploymentUnit().getAttachment(\n Attachments.MODULE_SPECIFICATION);\n if(deploymentRoot == null)\n return;\n final ServicesAttachment servicesAttachments = phaseContext.getDeploymentUnit().getAttachment(Attachments.SERVICES);\n if(servicesAttachments != null && !servicesAttachments.getServiceImplementations(ServiceActivator.class.getName()).isEmpty()) {\n moduleSpecification.addSystemDependency(MSC_DEP);\n }\n }", "private void addAllProjectModels(ApplicationReportIndexModel navIdx, ProjectModel projectModel)\n {\n navIdx.addProjectModel(projectModel);\n for (ProjectModel childProject : projectModel.getChildProjects())\n {\n if (!Iterators.asSet(navIdx.getProjectModels()).contains(childProject))\n addAllProjectModels(navIdx, childProject);\n }\n }", "public boolean contains(Date date)\n {\n boolean result = false;\n\n if (date != null)\n {\n result = (DateHelper.compare(getFromDate(), getToDate(), date) == 0);\n }\n\n return (result);\n }" ]
Generates a schedule based on some meta data. The schedule generation considers short periods. @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. @param startDate The start date of the first period. @param frequency The frequency. @param maturity The end date of the last period. @param daycountConvention The daycount convention. @param shortPeriodConvention If short period exists, have it first or last. @param dateRollConvention Adjustment to be applied to the all dates. @param businessdayCalendar Businessday calendar (holiday calendar) to be used for date roll adjustment. @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. @param paymentOffsetDays Number of business days to be added to period end to get the payment date. @return The corresponding schedule @deprecated Will be removed in version 2.3
[ "@Deprecated\n\tpublic static Schedule createScheduleFromConventions(\n\t\t\tLocalDate referenceDate,\n\t\t\tLocalDate startDate,\n\t\t\tString frequency,\n\t\t\tdouble maturity,\n\t\t\tString daycountConvention,\n\t\t\tString shortPeriodConvention,\n\t\t\tString dateRollConvention,\n\t\t\tBusinessdayCalendar businessdayCalendar,\n\t\t\tint\tfixingOffsetDays,\n\t\t\tint\tpaymentOffsetDays\n\t\t\t)\n\t{\n\t\tLocalDate maturityDate = createDateFromDateAndOffset(startDate, maturity);\n\n\t\treturn createScheduleFromConventions(\n\t\t\t\treferenceDate,\n\t\t\t\tstartDate,\n\t\t\t\tmaturityDate,\n\t\t\t\tFrequency.valueOf(frequency.toUpperCase()),\n\t\t\t\tDaycountConvention.getEnum(daycountConvention),\n\t\t\t\tShortPeriodConvention.valueOf(shortPeriodConvention.toUpperCase()),\n\t\t\t\tDateRollConvention.getEnum(dateRollConvention),\n\t\t\t\tbusinessdayCalendar,\n\t\t\t\tfixingOffsetDays,\n\t\t\t\tpaymentOffsetDays\n\t\t\t\t);\n\n\t}" ]
[ "public static long count(nitro_service service, String id) throws Exception{\n\t\tlinkset_interface_binding obj = new linkset_interface_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tlinkset_interface_binding response[] = (linkset_interface_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}", "public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {\n\n if( decomposition.inputModified() ) {\n a = a.copy();\n }\n return decomposition.decompose(a);\n }", "private CmsVfsEntryBean buildVfsEntryBeanForQuickSearch(\n CmsResource resource,\n Multimap<CmsResource, CmsResource> childMap,\n Set<CmsResource> filterMatches,\n Set<String> parentPaths,\n boolean isRoot)\n throws CmsException {\n\n CmsObject cms = getCmsObject();\n String title = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();\n boolean isMatch = filterMatches.contains(resource);\n List<CmsVfsEntryBean> childBeans = Lists.newArrayList();\n\n Collection<CmsResource> children = childMap.get(resource);\n if (!children.isEmpty()) {\n for (CmsResource child : children) {\n CmsVfsEntryBean childBean = buildVfsEntryBeanForQuickSearch(\n child,\n childMap,\n filterMatches,\n parentPaths,\n false);\n childBeans.add(childBean);\n }\n } else if (filterMatches.contains(resource)) {\n if (parentPaths.contains(resource.getRootPath())) {\n childBeans = null;\n }\n // otherwise childBeans remains an empty list\n }\n\n String rootPath = resource.getRootPath();\n CmsVfsEntryBean result = new CmsVfsEntryBean(\n rootPath,\n resource.getStructureId(),\n title,\n CmsIconUtil.getIconClasses(CmsIconUtil.getDisplayType(cms, resource), resource.getName(), true),\n isRoot,\n isEditable(cms, resource),\n childBeans,\n isMatch);\n String siteRoot = null;\n if (OpenCms.getSiteManager().startsWithShared(rootPath)) {\n siteRoot = OpenCms.getSiteManager().getSharedFolder();\n } else {\n String tempSiteRoot = OpenCms.getSiteManager().getSiteRoot(rootPath);\n if (tempSiteRoot != null) {\n siteRoot = tempSiteRoot;\n } else {\n siteRoot = \"\";\n }\n }\n result.setSiteRoot(siteRoot);\n return result;\n }", "public void writeNameValuePair(String name, double value) throws IOException\n {\n internalWriteNameValuePair(name, Double.toString(value));\n }", "private String listToCSV(List<String> list) {\n String csvStr = \"\";\n for (String item : list) {\n csvStr += \",\" + item;\n }\n\n return csvStr.length() > 1 ? csvStr.substring(1) : csvStr;\n }", "public String name(Properties attributes) throws XDocletException\r\n {\r\n return getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\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 <T extends CanvasReader> T getReader(Class<T> type, OauthToken oauthToken) {\n return getReader(type, oauthToken, null);\n }", "public static <K, V, T> List<Versioned<V>> get(Store<K, V, T> storageEngine, K key, T transform) {\n Map<K, List<Versioned<V>>> result = storageEngine.getAll(Collections.singleton(key),\n Collections.singletonMap(key,\n transform));\n if(result.size() > 0)\n return result.get(key);\n else\n return Collections.emptyList();\n }" ]
Populates a relation list. @param task parent task @param field target task field @param data MPX relation list data
[ "private void populateRelationList(Task task, TaskField field, String data)\n {\n DeferredRelationship dr = new DeferredRelationship();\n dr.setTask(task);\n dr.setField(field);\n dr.setData(data);\n m_deferredRelationships.add(dr);\n }" ]
[ "private void setFields(Map<String, FieldType> map, MapRow row, FieldContainer container)\n {\n if (row != null)\n {\n for (Map.Entry<String, FieldType> entry : map.entrySet())\n {\n container.set(entry.getValue(), row.getObject(entry.getKey()));\n }\n }\n }", "protected int getRequestTypeFromString(String requestType) {\n if (\"GET\".equals(requestType)) {\n return REQUEST_TYPE_GET;\n }\n if (\"POST\".equals(requestType)) {\n return REQUEST_TYPE_POST;\n }\n if (\"PUT\".equals(requestType)) {\n return REQUEST_TYPE_PUT;\n }\n if (\"DELETE\".equals(requestType)) {\n return REQUEST_TYPE_DELETE;\n }\n return REQUEST_TYPE_ALL;\n }", "public static final TimeUnit getTimeUnit(int value)\n {\n TimeUnit result = null;\n\n switch (value)\n {\n case 1:\n {\n // Appears to mean \"use the document format\"\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 6:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 8:\n case 10:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return result;\n }", "private void addColumns(MpxjTreeNode parentNode, Table table)\n {\n for (Column column : table.getColumns())\n {\n final Column c = column;\n MpxjTreeNode childNode = new MpxjTreeNode(column)\n {\n @Override public String toString()\n {\n return c.getTitle();\n }\n };\n parentNode.add(childNode);\n }\n }", "public void createResourceFieldMap(Props props)\n {\n byte[] fieldMapData = null;\n for (Integer key : RESOURCE_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultResourceData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }", "public void addRelation(RelationType relationType, RelationDirection direction) {\n\tint idx = relationType.ordinal();\n\tdirections[idx] = directions[idx].sum(direction);\n }", "public static String getPunctClass(String punc) {\r\n if(punc.equals(\"%\") || punc.equals(\"-PLUS-\"))//-PLUS- is an escape for \"+\" in the ATB\r\n return \"perc\";\r\n else if(punc.startsWith(\"*\"))\r\n return \"bullet\";\r\n else if(sfClass.contains(punc))\r\n return \"sf\";\r\n else if(colonClass.contains(punc) || pEllipsis.matcher(punc).matches())\r\n return \"colon\";\r\n else if(commaClass.contains(punc))\r\n return \"comma\";\r\n else if(currencyClass.contains(punc))\r\n return \"curr\";\r\n else if(slashClass.contains(punc))\r\n return \"slash\";\r\n else if(lBracketClass.contains(punc))\r\n return \"lrb\";\r\n else if(rBracketClass.contains(punc))\r\n return \"rrb\";\r\n else if(quoteClass.contains(punc))\r\n return \"quote\";\r\n \r\n return \"\";\r\n }", "protected String sp_createSequenceQuery(String sequenceName, long maxKey)\r\n {\r\n return \"insert into \" + SEQ_TABLE_NAME + \" (\"\r\n + SEQ_NAME_STRING + \",\" + SEQ_ID_STRING +\r\n \") values ('\" + sequenceName + \"',\" + maxKey + \")\";\r\n }", "private boolean fireEventWait(WebElement webElement, Eventable eventable)\n\t\t\tthrows ElementNotVisibleException, InterruptedException {\n\t\tswitch (eventable.getEventType()) {\n\t\t\tcase click:\n\t\t\t\ttry {\n\t\t\t\t\twebElement.click();\n\t\t\t\t} catch (ElementNotVisibleException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t} catch (WebDriverException e) {\n\t\t\t\t\tthrowIfConnectionException(e);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase hover:\n\t\t\t\tLOGGER.info(\"EventType hover called but this isn't implemented yet\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tLOGGER.info(\"EventType {} not supported in WebDriver.\", eventable.getEventType());\n\t\t\t\treturn false;\n\t\t}\n\n\t\tThread.sleep(this.crawlWaitEvent);\n\t\treturn true;\n\t}" ]
Check the given URI to see if it matches. @param matchInfo the matchInfo to validate. @return True if it matches.
[ "@Override\n public final Optional<Boolean> tryOverrideValidation(final MatchInfo matchInfo) throws SocketException,\n UnknownHostException, MalformedURLException {\n for (AddressHostMatcher addressHostMatcher: this.matchersForHost) {\n if (addressHostMatcher.matches(matchInfo)) {\n return Optional.empty();\n }\n }\n\n return Optional.of(false);\n }" ]
[ "public static Object instantiate(Class clazz) throws InstantiationException\r\n {\r\n Object result = null;\r\n try\r\n {\r\n result = ClassHelper.newInstance(clazz);\r\n }\r\n catch(IllegalAccessException e)\r\n {\r\n try\r\n {\r\n result = ClassHelper.newInstance(clazz, true);\r\n }\r\n catch(Exception e1)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (clazz != null ? clazz.getName() : \"null\")\r\n + \"', message was: \" + e1.getMessage() + \")\", e1);\r\n }\r\n }\r\n return result;\r\n }", "public static void checkArrayLength(String parameterName, int actualLength,\n int expectedLength) {\n if (actualLength != expectedLength) {\n throw Exceptions.IllegalArgument(\n \"Array %s should have %d elements, not %d\", parameterName,\n expectedLength, actualLength);\n }\n }", "public static base_responses add(nitro_service client, nsacl6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsacl6 addresources[] = new nsacl6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nsacl6();\n\t\t\t\taddresources[i].acl6name = resources[i].acl6name;\n\t\t\t\taddresources[i].acl6action = resources[i].acl6action;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].established = resources[i].established;\n\t\t\t\taddresources[i].icmptype = resources[i].icmptype;\n\t\t\t\taddresources[i].icmpcode = resources[i].icmpcode;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "@Override\n public void join(final long millis) throws InterruptedException {\n for (final Thread thread : this.threads) {\n thread.join(millis);\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 }", "public static float smoothStep(float a, float b, float x) {\n\t\tif (x < a)\n\t\t\treturn 0;\n\t\tif (x >= b)\n\t\t\treturn 1;\n\t\tx = (x - a) / (b - a);\n\t\treturn x*x * (3 - 2*x);\n\t}", "public synchronized static SQLiteDatabase getConnection(Context context) {\n\t\tif (database == null) {\n\t\t\t// Construct the single helper and open the unique(!) db connection for the app\n\t\t\tdatabase = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase();\n\t\t}\n\t\treturn database;\n\t}", "public static lbvserver_filterpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_filterpolicy_binding obj = new lbvserver_filterpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_filterpolicy_binding response[] = (lbvserver_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Map<String, ClientWidgetInfo> securityClone(Map<String, ClientWidgetInfo> widgetInfo) {\n\t\tMap<String, ClientWidgetInfo> res = new HashMap<String, ClientWidgetInfo>();\n\t\tfor (Map.Entry<String, ClientWidgetInfo> entry : widgetInfo.entrySet()) {\n\t\t\tClientWidgetInfo value = entry.getValue();\n\t\t\tif (!(value instanceof ServerSideOnlyInfo)) {\n\t\t\t\tres.put(entry.getKey(), value);\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}" ]
Process class properties. @param writer output stream @param methodSet set of methods processed @param aClass class being processed @throws IntrospectionException @throws XMLStreamException
[ "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 }" ]
[ "private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }", "public 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 }", "private Bpmn2Resource unmarshall(JsonParser parser,\n String preProcessingData) throws IOException {\n try {\n parser.nextToken(); // open the object\n ResourceSet rSet = new ResourceSetImpl();\n rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(\"bpmn2\",\n new JBPMBpmn2ResourceFactoryImpl());\n Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI(\"virtual.bpmn2\"));\n rSet.getResources().add(bpmn2);\n _currentResource = bpmn2;\n\n if (preProcessingData == null || preProcessingData.length() < 1) {\n preProcessingData = \"ReadOnlyService\";\n }\n\n // do the unmarshalling now:\n Definitions def = (Definitions) unmarshallItem(parser,\n preProcessingData);\n def.setExporter(exporterName);\n def.setExporterVersion(exporterVersion);\n revisitUserTasks(def);\n revisitServiceTasks(def);\n revisitMessages(def);\n revisitCatchEvents(def);\n revisitThrowEvents(def);\n revisitLanes(def);\n revisitSubProcessItemDefs(def);\n revisitArtifacts(def);\n revisitGroups(def);\n revisitTaskAssociations(def);\n revisitTaskIoSpecification(def);\n revisitSendReceiveTasks(def);\n reconnectFlows();\n revisitGateways(def);\n revisitCatchEventsConvertToBoundary(def);\n revisitBoundaryEventsPositions(def);\n createDiagram(def);\n updateIDs(def);\n revisitDataObjects(def);\n revisitAssociationsIoSpec(def);\n revisitWsdlImports(def);\n revisitMultiInstanceTasks(def);\n addSimulation(def);\n revisitItemDefinitions(def);\n revisitProcessDoc(def);\n revisitDI(def);\n revisitSignalRef(def);\n orderDiagramElements(def);\n\n // return def;\n _currentResource.getContents().add(def);\n return _currentResource;\n } catch (Exception e) {\n _logger.error(e.getMessage());\n return _currentResource;\n } finally {\n parser.close();\n _objMap.clear();\n _idMap.clear();\n _outgoingFlows.clear();\n _sequenceFlowTargets.clear();\n _bounds.clear();\n _currentResource = null;\n }\n }", "public ListExternalToolsOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }", "public static Artifact withVersion(Version v)\n {\n Artifact artifact = new Artifact();\n artifact.version = v;\n return artifact;\n }", "@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 AppDescriptor of(String appName, Class<?> entryClass) {\n System.setProperty(\"osgl.version.suppress-var-found-warning\", \"true\");\n return of(appName, entryClass, Version.of(entryClass));\n }", "public Path getReportDirectory()\n {\n WindupConfigurationModel cfg = WindupConfigurationService.getConfigurationModel(getGraphContext());\n Path path = cfg.getOutputPath().asFile().toPath().resolve(REPORTS_DIR);\n createDirectoryIfNeeded(path);\n return path.toAbsolutePath();\n }", "public static String getJsonDatatypeFromDatatypeIri(String datatypeIri) {\n\t\tswitch (datatypeIri) {\n\t\t\tcase DatatypeIdValue.DT_ITEM:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_ITEM;\n\t\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_GLOBE_COORDINATES;\n\t\t\tcase DatatypeIdValue.DT_URL:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_URL;\n\t\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_COMMONS_MEDIA;\n\t\t\tcase DatatypeIdValue.DT_TIME:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_TIME;\n\t\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_QUANTITY;\n\t\t\tcase DatatypeIdValue.DT_STRING:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_STRING;\n\t\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_MONOLINGUAL_TEXT;\n\t\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_PROPERTY;\n\t\t\tdefault:\n\t\t\t\t//We apply the reverse algorithm of JacksonDatatypeId::getDatatypeIriFromJsonDatatype\n\t\t\t\tMatcher matcher = DATATYPE_ID_PATTERN.matcher(datatypeIri);\n\t\t\t\tif(!matcher.matches()) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Unknown datatype: \" + datatypeIri);\n\t\t\t\t}\n\t\t\n\t\t\t\tStringBuilder jsonDatatypeBuilder = new StringBuilder();\n\t\t\t\tfor(char ch : StringUtils.uncapitalize(matcher.group(1)).toCharArray()) {\n\t\t\t\t\tif(Character.isUpperCase(ch)) {\n\t\t\t\t\t\tjsonDatatypeBuilder\n\t\t\t\t\t\t\t\t.append('-')\n\t\t\t\t\t\t\t\t.append(Character.toLowerCase(ch));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjsonDatatypeBuilder.append(ch);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn jsonDatatypeBuilder.toString();\n\t\t}\n\t}" ]
Reads a quoted string value from the request.
[ "protected String consumeQuoted(ImapRequestLineReader request)\n throws ProtocolException {\n // The 1st character must be '\"'\n consumeChar(request, '\"');\n\n StringBuilder quoted = new StringBuilder();\n char next = request.nextChar();\n while (next != '\"') {\n if (next == '\\\\') {\n request.consume();\n next = request.nextChar();\n if (!isQuotedSpecial(next)) {\n throw new ProtocolException(\"Invalid escaped character in quote: '\" +\n next + '\\'');\n }\n }\n quoted.append(next);\n request.consume();\n next = request.nextChar();\n }\n\n consumeChar(request, '\"');\n\n return quoted.toString();\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 final BigInteger printEarnedValueMethod(EarnedValueMethod value)\n {\n return (value == null ? BigInteger.valueOf(EarnedValueMethod.PERCENT_COMPLETE.getValue()) : BigInteger.valueOf(value.getValue()));\n }", "@Override public void setUniqueID(Integer uniqueID)\n {\n ProjectFile parent = getParentFile();\n\n if (m_uniqueID != null)\n {\n parent.getCalendars().unmapUniqueID(m_uniqueID);\n }\n\n parent.getCalendars().mapUniqueID(uniqueID, this);\n\n m_uniqueID = uniqueID;\n }", "private void processDependencies()\n {\n Set<Task> tasksWithBars = new HashSet<Task>();\n FastTrackTable table = m_data.getTable(FastTrackTableType.ACTBARS);\n for (MapRow row : table)\n {\n Task task = m_project.getTaskByUniqueID(row.getInteger(ActBarField._ACTIVITY));\n if (task == null || tasksWithBars.contains(task))\n {\n continue;\n }\n tasksWithBars.add(task);\n\n String predecessors = row.getString(ActBarField.PREDECESSORS);\n if (predecessors == null || predecessors.isEmpty())\n {\n continue;\n }\n\n for (String predecessor : predecessors.split(\", \"))\n {\n Matcher matcher = RELATION_REGEX.matcher(predecessor);\n matcher.matches();\n\n Integer id = Integer.valueOf(matcher.group(1));\n RelationType type = RELATION_TYPE_MAP.get(matcher.group(3));\n if (type == null)\n {\n type = RelationType.FINISH_START;\n }\n\n String sign = matcher.group(4);\n double lag = NumberHelper.getDouble(matcher.group(5));\n if (\"-\".equals(sign))\n {\n lag = -lag;\n }\n\n Task targetTask = m_project.getTaskByID(id);\n if (targetTask != null)\n {\n Duration lagDuration = Duration.getInstance(lag, m_data.getDurationTimeUnit());\n Relation relation = task.addPredecessor(targetTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n }", "void bootTimeScan(final DeploymentOperations deploymentOperations) {\n // WFCORE-1579: skip the scan if deployment dir is not available\n if (!checkDeploymentDir(this.deploymentDir)) {\n DeploymentScannerLogger.ROOT_LOGGER.bootTimeScanFailed(deploymentDir.getAbsolutePath());\n return;\n }\n\n this.establishDeployedContentList(this.deploymentDir, deploymentOperations);\n deployedContentEstablished = true;\n if (acquireScanLock()) {\n try {\n scan(true, deploymentOperations);\n } finally {\n releaseScanLock();\n }\n }\n }", "private static boolean syncWithMaster(final Resource domain, final PathElement hostElement) {\n final Resource host = domain.getChild(hostElement);\n assert host != null;\n\n final Set<String> profiles = new HashSet<>();\n final Set<String> serverGroups = new HashSet<>();\n final Set<String> socketBindings = new HashSet<>();\n\n for (final Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {\n final ModelNode model = serverConfig.getModel();\n final String group = model.require(GROUP).asString();\n if (!serverGroups.contains(group)) {\n serverGroups.add(group);\n }\n if (model.hasDefined(SOCKET_BINDING_GROUP)) {\n processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings);\n }\n\n }\n\n // process referenced server-groups\n for (final Resource.ResourceEntry serverGroup : domain.getChildren(SERVER_GROUP)) {\n // If we have an unreferenced server-group\n if (!serverGroups.remove(serverGroup.getName())) {\n return true;\n }\n final ModelNode model = serverGroup.getModel();\n\n final String profile = model.require(PROFILE).asString();\n // Process the profile\n processProfile(domain, profile, profiles);\n // Process the socket-binding-group\n processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings);\n }\n // If we are missing a server group\n if (!serverGroups.isEmpty()) {\n return true;\n }\n // Process profiles\n for (final Resource.ResourceEntry profile : domain.getChildren(PROFILE)) {\n // We have an unreferenced profile\n if (!profiles.remove(profile.getName())) {\n return true;\n }\n }\n // We are missing a profile\n if (!profiles.isEmpty()) {\n return true;\n }\n // Process socket-binding groups\n for (final Resource.ResourceEntry socketBindingGroup : domain.getChildren(SOCKET_BINDING_GROUP)) {\n // We have an unreferenced socket-binding group\n if (!socketBindings.remove(socketBindingGroup.getName())) {\n return true;\n }\n }\n // We are missing a socket-binding group\n if (!socketBindings.isEmpty()) {\n return true;\n }\n // Looks good!\n return false;\n }", "private void performPermissionCheck(CmsObject cms) throws CmsPermissionViolationException {\n\n if (cms.getRequestContext().getCurrentUser().isGuestUser()) {\n throw new CmsPermissionViolationException(null);\n }\n }", "public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo info)\r\n\t{\r\n\t\tUtil.log(\"In OTMJCAManagedConnectionFactory.createManagedConnection\");\r\n\t\ttry\r\n\t\t{\r\n\t\t\tKit kit = getKit();\r\n\t\t\tPBKey key = ((OTMConnectionRequestInfo) info).getPbKey();\r\n\t\t\tOTMConnection connection = kit.acquireConnection(key);\r\n\t\t\treturn new OTMJCAManagedConnection(this, connection, key);\r\n\t\t}\r\n\t\tcatch (ResourceException e)\r\n\t\t{\r\n\t\t\tthrow new OTMConnectionRuntimeException(e.getMessage());\r\n\t\t}\r\n\t}", "public void merge() {\n Thread currentThread = Thread.currentThread();\n if(!stats.get(currentThread).equals(this) || currentThread instanceof WindupChildThread) {\n throw new IllegalArgumentException(\"Trying to merge executionstatistics from a \"\n + \"different thread that is not registered as main thread of application run\");\n }\n\n for (Thread thread : stats.keySet())\n {\n if(thread instanceof WindupChildThread && ((WindupChildThread) thread).getParentThread().equals(currentThread)) {\n merge(stats.get(thread));\n }\n }\n }" ]
Parses a String email address to an IMAP address string.
[ "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 }" ]
[ "private FieldDescriptorDef cloneField(FieldDescriptorDef fieldDef, String prefix)\r\n {\r\n FieldDescriptorDef copyFieldDef = new FieldDescriptorDef(fieldDef, prefix);\r\n\r\n copyFieldDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n\r\n Properties mod = getModification(copyFieldDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyFieldDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included field \"+\r\n copyFieldDef.getName()+\" from class \"+fieldDef.getOwner().getName()); \r\n }\r\n copyFieldDef.applyModifications(mod);\r\n }\r\n return copyFieldDef;\r\n }", "protected void addImage(PdfContext context, ImageResult imageResult) throws BadElementException, IOException {\n\t\tBbox imageBounds = imageResult.getRasterImage().getBounds();\n\t\tfloat scaleFactor = (float) (72 / getMap().getRasterResolution());\n\t\tfloat width = (float) imageBounds.getWidth() * scaleFactor;\n\t\tfloat height = (float) imageBounds.getHeight() * scaleFactor;\n\t\t// subtract screen position of lower-left corner\n\t\tfloat x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;\n\t\t// shift y to lowerleft corner, flip y to user space and subtract\n\t\t// screen position of lower-left\n\t\t// corner\n\t\tfloat y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;\n\t\tif (log.isDebugEnabled()) {\n\t\t\tlog.debug(\"adding image, width=\" + width + \",height=\" + height + \",x=\" + x + \",y=\" + y);\n\t\t}\n\t\t// opacity\n\t\tlog.debug(\"before drawImage\");\n\t\tcontext.drawImage(Image.getInstance(imageResult.getImage()), new Rectangle(x, y, x + width, y + height),\n\t\t\t\tgetSize(), getOpacity());\n\t\tlog.debug(\"after drawImage\");\n\t}", "private List<Key> getScatterKeys(\n int numSplits, Query query, PartitionId partition, Datastore datastore)\n throws DatastoreException {\n Query.Builder scatterPointQuery = createScatterQuery(query, numSplits);\n\n List<Key> keySplits = new ArrayList<Key>();\n\n QueryResultBatch batch;\n do {\n RunQueryRequest scatterRequest =\n RunQueryRequest.newBuilder()\n .setPartitionId(partition)\n .setQuery(scatterPointQuery)\n .build();\n batch = datastore.runQuery(scatterRequest).getBatch();\n for (EntityResult result : batch.getEntityResultsList()) {\n keySplits.add(result.getEntity().getKey());\n }\n scatterPointQuery.setStartCursor(batch.getEndCursor());\n scatterPointQuery.getLimitBuilder().setValue(\n scatterPointQuery.getLimit().getValue() - batch.getEntityResultsCount());\n } while (batch.getMoreResults() == MoreResultsType.NOT_FINISHED);\n Collections.sort(keySplits, DatastoreHelper.getKeyComparator());\n return keySplits;\n }", "public void get( int row , int col , Complex_F64 output ) {\n ops.get(mat,row,col,output);\n }", "public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attributes));\n }", "public void setEnterpriseNumber(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_NUMBER, index), value);\n }", "public Object convertStringToJavaField(String value, int columnPos) throws SQLException {\n\t\tif (value == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.resultStringToJava(this, value, columnPos);\n\t\t}\n\t}", "public void adjustGlassSize() {\n if (isGlassEnabled()) {\n ResizeHandler handler = getGlassResizer();\n if (handler != null) handler.onResize(null);\n }\n }", "public boolean hasSameConfiguration(BoneCPConfig that){\n\t\tif ( that != null && Objects.equal(this.acquireIncrement, that.getAcquireIncrement())\n\t\t\t\t&& Objects.equal(this.acquireRetryDelayInMs, that.getAcquireRetryDelayInMs())\n\t\t\t\t&& Objects.equal(this.closeConnectionWatch, that.isCloseConnectionWatch())\n\t\t\t\t&& Objects.equal(this.logStatementsEnabled, that.isLogStatementsEnabled())\n\t\t\t\t&& Objects.equal(this.connectionHook, that.getConnectionHook())\n\t\t\t\t&& Objects.equal(this.connectionTestStatement, that.getConnectionTestStatement())\n\t\t\t\t&& Objects.equal(this.idleConnectionTestPeriodInSeconds, that.getIdleConnectionTestPeriod(TimeUnit.SECONDS))\n\t\t\t\t&& Objects.equal(this.idleMaxAgeInSeconds, that.getIdleMaxAge(TimeUnit.SECONDS))\n\t\t\t\t&& Objects.equal(this.initSQL, that.getInitSQL())\n\t\t\t\t&& Objects.equal(this.jdbcUrl, that.getJdbcUrl())\n\t\t\t\t&& Objects.equal(this.maxConnectionsPerPartition, that.getMaxConnectionsPerPartition())\n\t\t\t\t&& Objects.equal(this.minConnectionsPerPartition, that.getMinConnectionsPerPartition())\n\t\t\t\t&& Objects.equal(this.partitionCount, that.getPartitionCount())\n\t\t\t\t&& Objects.equal(this.releaseHelperThreads, that.getReleaseHelperThreads())\n\t\t\t\t&& Objects.equal(this.statementsCacheSize, that.getStatementsCacheSize())\n\t\t\t\t&& Objects.equal(this.username, that.getUsername())\n\t\t\t\t&& Objects.equal(this.password, that.getPassword())\n\t\t\t\t&& Objects.equal(this.lazyInit, that.isLazyInit())\n\t\t\t\t&& Objects.equal(this.transactionRecoveryEnabled, that.isTransactionRecoveryEnabled())\n\t\t\t\t&& Objects.equal(this.acquireRetryAttempts, that.getAcquireRetryAttempts())\n\t\t\t\t&& Objects.equal(this.statementReleaseHelperThreads, that.getStatementReleaseHelperThreads())\n\t\t\t\t&& Objects.equal(this.closeConnectionWatchTimeoutInMs, that.getCloseConnectionWatchTimeout())\n\t\t\t\t&& Objects.equal(this.connectionTimeoutInMs, that.getConnectionTimeoutInMs())\n\t\t\t\t&& Objects.equal(this.datasourceBean, that.getDatasourceBean())\n\t\t\t\t&& Objects.equal(this.getQueryExecuteTimeLimitInMs(), that.getQueryExecuteTimeLimitInMs())\n\t\t\t\t&& Objects.equal(this.poolAvailabilityThreshold, that.getPoolAvailabilityThreshold())\n\t\t\t\t&& Objects.equal(this.poolName, that.getPoolName())\n\t\t\t\t&& Objects.equal(this.disableConnectionTracking, that.isDisableConnectionTracking())\n\n\t\t\t\t){\n\t\t\treturn true;\n\t\t} \n\n\t\treturn false;\n\t}" ]
Retrieve a duration in the form required by Phoenix. @param duration Duration instance @return formatted duration
[ "public static final String printDuration(Duration duration)\n {\n String result = null;\n if (duration != null)\n {\n result = duration.getDuration() + \" \" + printTimeUnits(duration.getUnits());\n }\n return result;\n }" ]
[ "protected List<CmsUUID> undelete() throws CmsException {\n\n List<CmsUUID> modifiedResources = new ArrayList<CmsUUID>();\n CmsObject cms = m_context.getCms();\n for (CmsResource resource : m_context.getResources()) {\n CmsLockActionRecord actionRecord = null;\n try {\n actionRecord = CmsLockUtil.ensureLock(m_context.getCms(), resource);\n cms.undeleteResource(cms.getSitePath(resource), true);\n modifiedResources.add(resource.getStructureId());\n } finally {\n if ((actionRecord != null) && (actionRecord.getChange() == LockChange.locked)) {\n\n try {\n cms.unlockResource(resource);\n } catch (CmsLockException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }\n }\n }\n return modifiedResources;\n }", "public void removeWorstFit() {\n // find the observation with the most error\n int worstIndex=-1;\n double worstError = -1;\n\n for( int i = 0; i < y.numRows; i++ ) {\n double predictedObs = 0;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n predictedObs += A.get(i,j)*coef.get(j,0);\n }\n\n double error = Math.abs(predictedObs- y.get(i,0));\n\n if( error > worstError ) {\n worstError = error;\n worstIndex = i;\n }\n }\n\n // nothing left to remove, so just return\n if( worstIndex == -1 )\n return;\n\n // remove that observation\n removeObservation(worstIndex);\n\n // update A\n solver.removeRowFromA(worstIndex);\n\n // solve for the parameters again\n solver.solve(y,coef);\n }", "public final static String process(final File file, final boolean safeMode) throws IOException\n {\n return process(file, Configuration.builder().setSafeMode(safeMode).build());\n }", "public static sslglobal_sslpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tsslglobal_sslpolicy_binding[] response = (sslglobal_sslpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public static filterpolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tfilterpolicy_csvserver_binding obj = new filterpolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\tfilterpolicy_csvserver_binding response[] = (filterpolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "static GVRCollider lookup(long nativePointer)\n {\n synchronized (sColliders)\n {\n WeakReference<GVRCollider> weakReference = sColliders.get(nativePointer);\n return weakReference == null ? null : weakReference.get();\n }\n }", "private final String getHeader(Map /* String, String */ headers, String name) {\n return (String) headers.get(name.toLowerCase());\n }", "public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) {\n if (!ignoreUnaffectedServerGroups) {\n return model;\n }\n model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups);\n addServerGroupsToModel(hostModel, model);\n return model;\n }", "public PasswordCheckResult check(boolean isAdminitrative, String userName, String password) {\n // TODO: allow custom restrictions?\n List<PasswordRestriction> passwordValuesRestrictions = getPasswordRestrictions();\n final PasswordStrengthCheckResult strengthResult = this.passwordStrengthChecker.check(userName, password, passwordValuesRestrictions);\n\n final int failedRestrictions = strengthResult.getRestrictionFailures().size();\n final PasswordStrength strength = strengthResult.getStrength();\n final boolean strongEnough = assertStrength(strength);\n\n PasswordCheckResult.Result resultAction;\n String resultMessage = null;\n if (isAdminitrative) {\n if (strongEnough) {\n if (failedRestrictions > 0) {\n resultAction = Result.WARN;\n resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();\n } else {\n resultAction = Result.ACCEPT;\n }\n } else {\n resultAction = Result.WARN;\n resultMessage = ROOT_LOGGER.passwordNotStrongEnough(strength.toString(), this.acceptable.toString());\n }\n } else {\n if (strongEnough) {\n if (failedRestrictions > 0) {\n resultAction = Result.REJECT;\n resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();\n } else {\n resultAction = Result.ACCEPT;\n }\n } else {\n if (failedRestrictions > 0) {\n resultAction = Result.REJECT;\n resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();\n } else {\n resultAction = Result.REJECT;\n resultMessage = ROOT_LOGGER.passwordNotStrongEnough(strength.toString(), this.acceptable.toString());\n }\n }\n }\n\n return new PasswordCheckResult(resultAction, resultMessage);\n\n }" ]
Drives the unit test.
[ "public HiveShellContainer evaluateStatement(List<? extends Script> scripts, Object target, TemporaryFolder temporaryFolder, Statement base) throws Throwable {\n container = null;\n FileUtil.setPermission(temporaryFolder.getRoot(), FsPermission.getDirDefault());\n try {\n LOGGER.info(\"Setting up {} in {}\", getName(), temporaryFolder.getRoot().getAbsolutePath());\n container = createHiveServerContainer(scripts, target, temporaryFolder);\n base.evaluate();\n return container;\n } finally {\n tearDown();\n }\n }" ]
[ "public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)\r\n throws SQLException\r\n {\r\n return getObjectFromColumn(rs, null, jdbcType, null, columnId);\r\n }", "@Override\n public String getText() {\n String retType = AstToTextHelper.getClassText(returnType);\n String exceptionTypes = AstToTextHelper.getThrowsClauseText(exceptions);\n String parms = AstToTextHelper.getParametersText(parameters);\n return AstToTextHelper.getModifiersText(modifiers) + \" \" + retType + \" \" + name + \"(\" + parms + \") \" + exceptionTypes + \" { ... }\";\n }", "public JsonNode wbSetClaim(String statement,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(statement,\n\t\t\t\t\"Statement parameter cannot be null when adding or changing a statement\");\n\t\t\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"claim\", statement);\n\t\t\n\t\treturn performAPIAction(\"wbsetclaim\", null, null, null, null, parameters, summary, baserevid, bot);\n\t}", "private void addReverse(final File[] files) {\n for (int i = files.length - 1; i >= 0; --i) {\n stack.add(files[i]);\n }\n }", "public static int[] insertArray(int[] original, int index, int[] inserted) {\n int[] modified = new int[original.length + inserted.length];\n System.arraycopy(original, 0, modified, 0, index);\n System.arraycopy(inserted, 0, modified, index, inserted.length);\n System.arraycopy(original, index, modified, index + inserted.length, modified.length - index - inserted.length);\n return modified;\n }", "private License getLicense(final String licenseId) {\n License result = null;\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(licenseId);\n\n if (matchingLicenses.isEmpty()) {\n result = DataModelFactory.createLicense(\"#\" + licenseId + \"# (to be identified)\", NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET);\n result.setUnknown(true);\n } else {\n if (matchingLicenses.size() > 1 && LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"%s matches multiple licenses %s. \" +\n \"Please run the report showing multiple matching on licenses\",\n licenseId, matchingLicenses.toString()));\n }\n result = mapper.getLicense(matchingLicenses.iterator().next());\n\n }\n\n return result;\n }", "private boolean subModuleExists(File dir) {\n if (isSlotDirectory(dir)) {\n return true;\n } else {\n File[] children = dir.listFiles(File::isDirectory);\n for (File child : children) {\n if (subModuleExists(child)) {\n return true;\n }\n }\n }\n\n return false;\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}", "private List<org.jfrog.hudson.pipeline.types.File> getBuildFilesList(Stream<? extends BaseBuildFileBean> buildFilesStream) {\n return buildFilesStream\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getLocalPath()))\n .filter(buildFile -> StringUtils.isNotBlank(buildFile.getRemotePath()))\n .map(org.jfrog.hudson.pipeline.types.File::new)\n .distinct()\n .collect(Collectors.toList());\n }" ]
Process an operand value used in the definition of the graphical indicator criteria. @param index position in operand list @param type field type @param criteria indicator criteria
[ "private void processOperandValue(int index, FieldType type, GraphicalIndicatorCriteria criteria)\n {\n boolean valueFlag = (MPPUtility.getInt(m_data, m_dataOffset) == 1);\n m_dataOffset += 4;\n\n if (valueFlag == false)\n {\n int fieldID = MPPUtility.getInt(m_data, m_dataOffset);\n criteria.setRightValue(index, FieldTypeHelper.getInstance(fieldID));\n m_dataOffset += 4;\n }\n else\n {\n //int dataTypeValue = MPPUtility.getShort(m_data, m_dataOffset);\n m_dataOffset += 2;\n\n switch (type.getDataType())\n {\n case DURATION: // 0x03\n {\n Duration value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(m_data, m_dataOffset), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(m_data, m_dataOffset + 4)));\n m_dataOffset += 6;\n criteria.setRightValue(index, value);\n break;\n }\n\n case NUMERIC: // 0x05\n {\n Double value = Double.valueOf(MPPUtility.getDouble(m_data, m_dataOffset));\n m_dataOffset += 8;\n criteria.setRightValue(index, value);\n break;\n }\n\n case CURRENCY: // 0x06\n {\n Double value = Double.valueOf(MPPUtility.getDouble(m_data, m_dataOffset) / 100);\n m_dataOffset += 8;\n criteria.setRightValue(index, value);\n break;\n }\n\n case STRING: // 0x08\n {\n String value = MPPUtility.getUnicodeString(m_data, m_dataOffset);\n m_dataOffset += ((value.length() + 1) * 2);\n criteria.setRightValue(index, value);\n break;\n }\n\n case BOOLEAN: // 0x0B\n {\n int value = MPPUtility.getShort(m_data, m_dataOffset);\n m_dataOffset += 2;\n criteria.setRightValue(index, value == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE: // 0x13\n {\n Date value = MPPUtility.getTimestamp(m_data, m_dataOffset);\n m_dataOffset += 4;\n criteria.setRightValue(index, value);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n }" ]
[ "public static DatagramPacket buildPacket(PacketType type, ByteBuffer deviceName, ByteBuffer payload) {\n ByteBuffer content = ByteBuffer.allocate(0x1f + payload.remaining());\n content.put(getMagicHeader());\n content.put(type.protocolValue);\n content.put(deviceName);\n content.put(payload);\n return new DatagramPacket(content.array(), content.capacity());\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 }", "@SafeVarargs\n public static <K> Set<K> set(final K... keys) {\n return new LinkedHashSet<K>(Arrays.asList(keys));\n }", "public void reinitIfClosed() {\n if (isClosed.get()) {\n logger.info(\"External Resource was released. Now Re-initializing resources ...\");\n\n ActorConfig.createAndGetActorSystem();\n httpClientStore.reinit();\n tcpSshPingResourceStore.reinit();\n try {\n Thread.sleep(1000l);\n } catch (InterruptedException e) {\n logger.error(\"error reinit httpClientStore\", e);\n }\n isClosed.set(false);\n logger.info(\"Parallel Client Resources has been reinitialized.\");\n } else {\n logger.debug(\"NO OP. Resource was not released.\");\n }\n }", "@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withTag(String key, String value) {\n if (this.inner().getTags() == null) {\n this.inner().withTags(new HashMap<String, String>());\n }\n this.inner().getTags().put(key, value);\n return (FluentModelImplT) this;\n }", "protected void reportProgress(String taskDecription) {\n if (this.progress != null) {\n if (this.progress.isCanceled()) {\n // Only AbortCompilation can stop the compiler cleanly.\n // We check cancellation again following the call to compile.\n throw new AbortCompilation(true, null);\n }\n this.progress.setTaskName(taskDecription);\n }\n }", "private void logTimeTakenByPhase(GraphContext graphContext, Class<? extends RulePhase> phase, int timeTaken)\n {\n if (!timeTakenByPhase.containsKey(phase))\n {\n RulePhaseExecutionStatisticsModel model = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class).create();\n model.setRulePhase(phase.toString());\n model.setTimeTaken(timeTaken);\n model.setOrderExecuted(timeTakenByPhase.size());\n timeTakenByPhase.put(phase, model.getElement().id());\n }\n else\n {\n GraphService<RulePhaseExecutionStatisticsModel> service = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class);\n RulePhaseExecutionStatisticsModel model = service.getById(timeTakenByPhase.get(phase));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n }", "public boolean load(GVRScene scene)\n {\n GVRAssetLoader loader = getGVRContext().getAssetLoader();\n\n if (scene == null)\n {\n scene = getGVRContext().getMainScene();\n }\n if (mReplaceScene)\n {\n loader.loadScene(getOwnerObject(), mVolume, mImportSettings, scene, null);\n }\n else\n {\n loader.loadModel(getOwnerObject(), mVolume, mImportSettings, scene);\n }\n return true;\n }", "private void populateResource(Resource resource, Record record) throws MPXJException\n {\n String falseText = LocaleData.getString(m_locale, LocaleData.NO);\n\n int length = record.getLength();\n int[] model = m_resourceModel.getModel();\n\n for (int i = 0; i < length; i++)\n {\n int mpxFieldType = model[i];\n if (mpxFieldType == -1)\n {\n break;\n }\n\n String field = record.getString(i);\n\n if (field == null || field.length() == 0)\n {\n continue;\n }\n\n ResourceField resourceField = MPXResourceField.getMpxjField(mpxFieldType);\n switch (resourceField)\n {\n case OBJECTS:\n {\n resource.set(resourceField, record.getInteger(i));\n break;\n }\n\n case ID:\n {\n resource.setID(record.getInteger(i));\n break;\n }\n\n case UNIQUE_ID:\n {\n resource.setUniqueID(record.getInteger(i));\n break;\n }\n\n case MAX_UNITS:\n {\n resource.set(resourceField, record.getUnits(i));\n break;\n }\n\n case PERCENT_WORK_COMPLETE:\n case PEAK:\n {\n resource.set(resourceField, record.getPercentage(i));\n break;\n }\n\n case COST:\n case COST_PER_USE:\n case COST_VARIANCE:\n case BASELINE_COST:\n case ACTUAL_COST:\n case REMAINING_COST:\n {\n resource.set(resourceField, record.getCurrency(i));\n break;\n }\n\n case OVERTIME_RATE:\n case STANDARD_RATE:\n {\n resource.set(resourceField, record.getRate(i));\n break;\n }\n\n case REMAINING_WORK:\n case OVERTIME_WORK:\n case BASELINE_WORK:\n case ACTUAL_WORK:\n case WORK:\n case WORK_VARIANCE:\n {\n resource.set(resourceField, record.getDuration(i));\n break;\n }\n\n case ACCRUE_AT:\n {\n resource.set(resourceField, record.getAccrueType(i));\n break;\n }\n\n case LINKED_FIELDS:\n case OVERALLOCATED:\n {\n resource.set(resourceField, record.getBoolean(i, falseText));\n break;\n }\n\n default:\n {\n resource.set(resourceField, field);\n break;\n }\n }\n }\n\n if (m_projectConfig.getAutoResourceUniqueID() == true)\n {\n resource.setUniqueID(Integer.valueOf(m_projectConfig.getNextResourceUniqueID()));\n }\n\n if (m_projectConfig.getAutoResourceID() == true)\n {\n resource.setID(Integer.valueOf(m_projectConfig.getNextResourceID()));\n }\n\n //\n // Handle malformed MPX files - ensure we have a unique ID\n //\n if (resource.getUniqueID() == null)\n {\n resource.setUniqueID(resource.getID());\n }\n }" ]
Wraps a linear solver of any type with a safe solver the ensures inputs are not modified
[ "public static <S extends Matrix, D extends Matrix> LinearSolver<S,D> safe(LinearSolver<S,D> solver ) {\n if( solver.modifiesA() || solver.modifiesB() ) {\n if( solver instanceof LinearSolverDense ) {\n return new LinearSolverSafe((LinearSolverDense)solver);\n } else if( solver instanceof LinearSolverSparse ) {\n return new LinearSolverSparseSafe((LinearSolverSparse)solver);\n } else {\n throw new IllegalArgumentException(\"Unknown solver type\");\n }\n } else {\n return solver;\n }\n }" ]
[ "public static final Number parseUnits(Number value)\n {\n return (value == null ? null : NumberHelper.getDouble(value.doubleValue() * 100));\n }", "public static final PolylineOptions buildOpenArc(LatLong center, LatLong start, LatLong end) {\n MVCArray res = buildArcPoints(center, start, end);\n return new PolylineOptions().path(res);\n }", "public <T> T find(Class<T> classType, String id, String rev) {\n assertNotEmpty(classType, \"Class\");\n assertNotEmpty(id, \"id\");\n assertNotEmpty(id, \"rev\");\n final URI uri = new DatabaseURIHelper(dbUri).documentUri(id, \"rev\", rev);\n return couchDbClient.get(uri, classType);\n }", "protected void fireEvent(HotKey hotKey) {\n HotKeyEvent event = new HotKeyEvent(hotKey);\n if (useSwingEventQueue) {\n SwingUtilities.invokeLater(event);\n } else {\n if (eventQueue == null) {\n eventQueue = Executors.newSingleThreadExecutor();\n }\n eventQueue.execute(event);\n }\n }", "public static base_response delete(nitro_service client, String servicename) throws Exception {\n\t\tgslbservice deleteresource = new gslbservice();\n\t\tdeleteresource.servicename = servicename;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void setWeeklyDay(Day day, boolean value)\n {\n if (value)\n {\n m_days.add(day);\n }\n else\n {\n m_days.remove(day);\n }\n }", "protected void countStatements(UsageStatistics usageStatistics,\n\t\t\tStatementDocument statementDocument) {\n\t\t// Count Statement data:\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\t// Count Statements:\n\t\t\tusageStatistics.countStatements += sg.size();\n\n\t\t\t// Count uses of properties in Statements:\n\t\t\tcountPropertyMain(usageStatistics, sg.getProperty(), sg.size());\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tfor (SnakGroup q : s.getQualifiers()) {\n\t\t\t\t\tcountPropertyQualifier(usageStatistics, q.getProperty(), q.size());\n\t\t\t\t}\n\t\t\t\tfor (Reference r : s.getReferences()) {\n\t\t\t\t\tusageStatistics.countReferencedStatements++;\n\t\t\t\t\tfor (SnakGroup snakGroup : r.getSnakGroups()) {\n\t\t\t\t\t\tcountPropertyReference(usageStatistics,\n\t\t\t\t\t\t\t\tsnakGroup.getProperty(), snakGroup.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "String getUriStringForRank(StatementRank rank) {\n\t\tswitch (rank) {\n\t\tcase NORMAL:\n\t\t\treturn Vocabulary.WB_NORMAL_RANK;\n\t\tcase PREFERRED:\n\t\t\treturn Vocabulary.WB_PREFERRED_RANK;\n\t\tcase DEPRECATED:\n\t\t\treturn Vocabulary.WB_DEPRECATED_RANK;\n\t\tdefault:\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t}", "public Map<String, String> decompose(Frontier frontier, String modelText) {\r\n if (!(frontier instanceof SCXMLFrontier)) {\r\n return null;\r\n }\n\r\n TransitionTarget target = ((SCXMLFrontier) frontier).getRoot().nextState;\r\n Map<String, String> variables = ((SCXMLFrontier) frontier).getRoot().variables;\n\r\n Map<String, String> decomposition = new HashMap<String, String>();\r\n decomposition.put(\"target\", target.getId());\n\r\n StringBuilder packedVariables = new StringBuilder();\r\n for (Map.Entry<String, String> variable : variables.entrySet()) {\r\n packedVariables.append(variable.getKey());\r\n packedVariables.append(\"::\");\r\n packedVariables.append(variable.getValue());\r\n packedVariables.append(\";\");\r\n }\n\r\n decomposition.put(\"variables\", packedVariables.toString());\r\n decomposition.put(\"model\", modelText);\n\r\n return decomposition;\r\n }" ]
Return cached object by key. The key will be concatenated with current session id when fetching the cached object @param key @param <T> the object type @return the cached object
[ "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 }" ]
[ "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax) {\n\t\treturn getMSDLineChart(t, lagMin, lagMax, new MeanSquaredDisplacmentFeature(t,\n\t\t\t\tlagMin));\n\t}", "public static base_responses add(nitro_service client, vlan resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tvlan addresources[] = new vlan[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new vlan();\n\t\t\t\taddresources[i].id = resources[i].id;\n\t\t\t\taddresources[i].aliasname = resources[i].aliasname;\n\t\t\t\taddresources[i].ipv6dynamicrouting = resources[i].ipv6dynamicrouting;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\n }", "public T withStatement(Statement statement) {\n\t\tPropertyIdValue pid = statement.getMainSnak()\n\t\t\t\t.getPropertyId();\n\t\tArrayList<Statement> pidStatements = this.statements.get(pid);\n\t\tif (pidStatements == null) {\n\t\t\tpidStatements = new ArrayList<Statement>();\n\t\t\tthis.statements.put(pid, pidStatements);\n\t\t}\n\n\t\tpidStatements.add(statement);\n\t\treturn getThis();\n\t}", "public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}", "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}", "public static nsrpcnode[] get(nitro_service service, String ipaddress[]) throws Exception{\n\t\tif (ipaddress !=null && ipaddress.length>0) {\n\t\t\tnsrpcnode response[] = new nsrpcnode[ipaddress.length];\n\t\t\tnsrpcnode obj[] = new nsrpcnode[ipaddress.length];\n\t\t\tfor (int i=0;i<ipaddress.length;i++) {\n\t\t\t\tobj[i] = new nsrpcnode();\n\t\t\t\tobj[i].set_ipaddress(ipaddress[i]);\n\t\t\t\tresponse[i] = (nsrpcnode) 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 load(String soundFile)\n {\n if (mSoundFile != null)\n {\n unload();\n }\n mSoundFile = soundFile;\n if (mAudioListener != null)\n {\n mAudioListener.getAudioEngine().preloadSoundFile(soundFile);\n Log.d(\"SOUND\", \"loaded audio file %s\", getSoundFile());\n }\n }", "public static nssimpleacl[] get(nitro_service service, String aclname[]) throws Exception{\n\t\tif (aclname !=null && aclname.length>0) {\n\t\t\tnssimpleacl response[] = new nssimpleacl[aclname.length];\n\t\t\tnssimpleacl obj[] = new nssimpleacl[aclname.length];\n\t\t\tfor (int i=0;i<aclname.length;i++) {\n\t\t\t\tobj[i] = new nssimpleacl();\n\t\t\t\tobj[i].set_aclname(aclname[i]);\n\t\t\t\tresponse[i] = (nssimpleacl) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
Retrieve the ordinal text for a given integer. @param value integer value @return ordinal text
[ "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 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}", "public void setKey(int keyIndex, float time, final float[] values)\n {\n int index = keyIndex * mFloatsPerKey;\n Integer valSize = mFloatsPerKey-1;\n\n if (values.length != valSize)\n {\n throw new IllegalArgumentException(\"This key needs \" + valSize.toString() + \" float per value\");\n }\n mKeys[index] = time;\n System.arraycopy(values, 0, mKeys, index + 1, values.length);\n }", "private double getConstraint(double x1, double x2)\n {\n double c1,c2,h;\n c1 = -x1*x1-x2*x2+1+0.1*Math.cos(16*Math.atan(x1/x2));\n c2 = (x1-0.5)*(x1-0.5)+(x2-0.5)*(x2-0.5)-0.5;\n if(c1>c2)\n h = (c1>0)?c1:0;\n else\n h = (c2>0)?c2:0;\n return h;\n }", "public void setModel(Database databaseModel, DescriptorRepository objModel)\r\n {\r\n _dbModel = databaseModel;\r\n _preparedModel = new PreparedModel(objModel, databaseModel);\r\n }", "public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)\n {\n CurrencySymbolPosition result = CurrencySymbolPosition.BEFORE;\n\n switch (NumberHelper.getInt(value))\n {\n case 0:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n }\n\n return (result);\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 String checkRequiredProperties(Properties props,\r\n String ... requiredProps) {\r\n for (String required : requiredProps) {\r\n if (props.getProperty(required) == null) {\r\n return required;\r\n }\r\n }\r\n return null;\r\n }", "public static <E> Collection<E> sampleWithReplacement(Collection<E> c, int n) {\r\n return sampleWithReplacement(c, n, new Random());\r\n }", "public static ipv6 get(nitro_service service) throws Exception{\n\t\tipv6 obj = new ipv6();\n\t\tipv6[] response = (ipv6[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
Write resource assignment. @param record resource assignment instance @throws IOException
[ "private void writeResourceAssignment(ResourceAssignment record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(formatResource(record.getResource()));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatUnits(record.getUnits())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getBaselineWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getActualWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getOvertimeWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getBaselineCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getActualCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTime(record.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTime(record.getFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getDelay())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getResourceUniqueID()));\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n\n ResourceAssignmentWorkgroupFields workgroup = record.getWorkgroupAssignment();\n if (workgroup == null)\n {\n workgroup = ResourceAssignmentWorkgroupFields.EMPTY;\n }\n writeResourceAssignmentWorkgroupFields(workgroup);\n\n m_eventManager.fireAssignmentWrittenEvent(record);\n }" ]
[ "public static Command newInsert(Object object,\n String outIdentifier,\n boolean returnObject,\n String entryPoint ) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier,\n returnObject,\n entryPoint );\n }", "public static nsacl6 get(nitro_service service, String acl6name) throws Exception{\n\t\tnsacl6 obj = new nsacl6();\n\t\tobj.set_acl6name(acl6name);\n\t\tnsacl6 response = (nsacl6) obj.get_resource(service);\n\t\treturn response;\n\t}", "@Override\n public final float getFloat(final int i) {\n double val = this.array.optDouble(i, Double.MAX_VALUE);\n if (val == Double.MAX_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return (float) val;\n }", "public GVRAnimator findAnimation(String name)\n {\n for (GVRAnimator anim : mAnimations)\n {\n if (name.equals(anim.getName()))\n {\n return anim;\n }\n }\n return null;\n }", "private void addContentInfo() {\n\n if (!m_cms.getRequestContext().getCurrentProject().isOnlineProject()\n && (null == m_searchController.getCommon().getConfig().getSolrIndex())\n && (null != m_addContentInfoForEntries)) {\n CmsSolrQuery query = new CmsSolrQuery();\n m_searchController.addQueryParts(query, m_cms);\n query.setStart(Integer.valueOf(0));\n query.setRows(m_addContentInfoForEntries);\n CmsContentLoadCollectorInfo info = new CmsContentLoadCollectorInfo();\n info.setCollectorClass(this.getClass().getName());\n info.setCollectorParams(query.getQuery());\n info.setId((new CmsUUID()).getStringValue());\n if (CmsJspTagEditable.getDirectEditProvider(pageContext) != null) {\n try {\n CmsJspTagEditable.getDirectEditProvider(pageContext).insertDirectEditListMetadata(\n pageContext,\n info);\n } catch (JspException e) {\n LOG.error(\"Could not write content info.\", e);\n }\n }\n }\n }", "public void setBaselineDurationText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber), value);\n }", "public static Object parsePrimitive(\n final String fieldName, final PrimitiveAttribute<?> pAtt, final PObject requestData) {\n Class<?> valueClass = pAtt.getValueClass();\n Object value;\n try {\n value = parseValue(false, new String[0], valueClass, fieldName, requestData);\n } catch (UnsupportedTypeException e) {\n String type = e.type.getName();\n if (e.type.isArray()) {\n type = e.type.getComponentType().getName() + \"[]\";\n }\n throw new RuntimeException(\n \"The type '\" + type + \"' is not a supported type when parsing json. \" +\n \"See documentation for supported types.\\n\\nUnsupported type found in attribute \" +\n fieldName\n + \"\\n\\nTo support more types add the type to \" +\n \"parseValue and parseArrayValue in this class and add a test to the test class\",\n e);\n }\n pAtt.validateValue(value);\n\n return value;\n }", "private String readHeaderString(BufferedInputStream stream) throws IOException\n {\n int bufferSize = 100;\n stream.mark(bufferSize);\n byte[] buffer = new byte[bufferSize];\n stream.read(buffer);\n Charset charset = CharsetHelper.UTF8;\n String header = new String(buffer, charset);\n int prefixIndex = header.indexOf(\"PPX!!!!|\");\n int suffixIndex = header.indexOf(\"|!!!!XPP\");\n\n if (prefixIndex != 0 || suffixIndex == -1)\n {\n throw new IOException(\"File format not recognised\");\n }\n\n int skip = suffixIndex + 9;\n stream.reset();\n stream.skip(skip);\n\n return header.substring(prefixIndex + 8, suffixIndex);\n }", "public void build(double[] coords, int nump) throws IllegalArgumentException {\n if (nump < 4) {\n throw new IllegalArgumentException(\"Less than four input points specified\");\n }\n if (coords.length / 3 < nump) {\n throw new IllegalArgumentException(\"Coordinate array too small for specified number of points\");\n }\n initBuffers(nump);\n setPoints(coords, nump);\n buildHull();\n }" ]
This method retrieves a Duration instance representing the amount of work between two dates based on this calendar. @param startDate start date @param endDate end date @param format required duration format @return amount of work
[ "public Duration getWork(Date startDate, Date endDate, TimeUnit format)\n {\n DateRange range = new DateRange(startDate, endDate);\n Long cachedResult = m_workingDateCache.get(range);\n long totalTime = 0;\n\n if (cachedResult == null)\n {\n //\n // We want the start date to be the earliest date, and the end date\n // to be the latest date. Set a flag here to indicate if we have swapped\n // the order of the supplied date.\n //\n boolean invert = false;\n if (startDate.getTime() > endDate.getTime())\n {\n invert = true;\n Date temp = startDate;\n startDate = endDate;\n endDate = temp;\n }\n\n Date canonicalStartDate = DateHelper.getDayStartDate(startDate);\n Date canonicalEndDate = DateHelper.getDayStartDate(endDate);\n\n if (canonicalStartDate.getTime() == canonicalEndDate.getTime())\n {\n ProjectCalendarDateRanges ranges = getRanges(startDate, null, null);\n if (ranges.getRangeCount() != 0)\n {\n totalTime = getTotalTime(ranges, startDate, endDate);\n }\n }\n else\n {\n //\n // Find the first working day in the range\n //\n Date currentDate = startDate;\n Calendar cal = Calendar.getInstance();\n cal.setTime(startDate);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n while (isWorkingDate(currentDate, day) == false && currentDate.getTime() < canonicalEndDate.getTime())\n {\n cal.add(Calendar.DAY_OF_YEAR, 1);\n currentDate = cal.getTime();\n day = day.getNextDay();\n }\n\n if (currentDate.getTime() < canonicalEndDate.getTime())\n {\n //\n // Calculate the amount of working time for this day\n //\n totalTime += getTotalTime(getRanges(currentDate, null, day), currentDate, true);\n\n //\n // Process each working day until we reach the last day\n //\n while (true)\n {\n cal.add(Calendar.DAY_OF_YEAR, 1);\n currentDate = cal.getTime();\n day = day.getNextDay();\n\n //\n // We have reached the last day\n //\n if (currentDate.getTime() >= canonicalEndDate.getTime())\n {\n break;\n }\n\n //\n // Skip this day if it has no working time\n //\n ProjectCalendarDateRanges ranges = getRanges(currentDate, null, day);\n if (ranges.getRangeCount() == 0)\n {\n continue;\n }\n\n //\n // Add the working time for the whole day\n //\n totalTime += getTotalTime(ranges);\n }\n }\n\n //\n // We are now at the last day\n //\n ProjectCalendarDateRanges ranges = getRanges(endDate, null, day);\n if (ranges.getRangeCount() != 0)\n {\n totalTime += getTotalTime(ranges, DateHelper.getDayStartDate(endDate), endDate);\n }\n }\n\n if (invert)\n {\n totalTime = -totalTime;\n }\n\n m_workingDateCache.put(range, Long.valueOf(totalTime));\n }\n else\n {\n totalTime = cachedResult.longValue();\n }\n\n return convertFormat(totalTime, format);\n }" ]
[ "public String text() {\n String previousText = null;\n StringBuilder buffer = null;\n for (Object child : this) {\n String text = null;\n if (child instanceof String) {\n text = (String) child;\n } else if (child instanceof Node) {\n text = ((Node) child).text();\n }\n if (text != null) {\n if (previousText == null) {\n previousText = text;\n } else {\n if (buffer == null) {\n buffer = new StringBuilder();\n buffer.append(previousText);\n }\n buffer.append(text);\n }\n }\n }\n if (buffer != null) {\n return buffer.toString();\n }\n if (previousText != null) {\n return previousText;\n }\n return \"\";\n }", "static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) {\n final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE);\n return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName));\n }", "public void setRightTableModel(TableModel model)\n {\n TableModel old = m_rightTable.getModel();\n m_rightTable.setModel(model);\n firePropertyChange(\"rightTableModel\", old, model);\n }", "public static base_response unset(nitro_service client, cmpparameter resource, String[] args) throws Exception{\n\t\tcmpparameter unsetresource = new cmpparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "@Override\n\tpublic List<Object> loadEntitiesFromTuples(SharedSessionContractImplementor session, LockOptions lockOptions, OgmLoadingContext ogmContext) {\n\t\treturn loadEntity( null, null, session, lockOptions, ogmContext );\n\t}", "public static final int findValueInListBox(ListBox list, String value) {\n\tfor (int i=0; i<list.getItemCount(); i++) {\n\t if (value.equals(list.getValue(i))) {\n\t\treturn i;\n\t }\n\t}\n\treturn -1;\n }", "@PreDestroy\n public void disconnectLocator() throws InterruptedException,\n ServiceLocatorException {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Destroy Locator client\");\n }\n\n if (endpointCollector != null) {\n endpointCollector.stopScheduledCollection();\n }\n \n if (locatorClient != null) {\n locatorClient.disconnect();\n locatorClient = null;\n }\n }", "public void setAddContentInfo(final Boolean doAddInfo) {\n\n if ((null != doAddInfo) && doAddInfo.booleanValue() && (null != m_addContentInfoForEntries)) {\n m_addContentInfoForEntries = Integer.valueOf(DEFAULT_CONTENTINFO_ROWS);\n }\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 }" ]
Sets the value for the API's "languages" parameter based on the current settings. @param properties current setting of parameters
[ "private void setRequestLanguages(WbGetEntitiesActionData properties) {\n\t\tif (this.filter.excludeAllLanguages()\n\t\t\t\t|| this.filter.getLanguageFilter() == null) {\n\t\t\treturn;\n\t\t}\n\t\tproperties.languages = ApiConnection.implodeObjects(this.filter\n\t\t\t\t.getLanguageFilter());\n\t}" ]
[ "public String putProperty(String key,\n String value) {\n return this.getProperties().put(key,\n value);\n }", "public static final BigInteger printEarnedValueMethod(EarnedValueMethod value)\n {\n return (value == null ? BigInteger.valueOf(EarnedValueMethod.PERCENT_COMPLETE.getValue()) : BigInteger.valueOf(value.getValue()));\n }", "private long validateMessage(FileChannel channel, long start, long len, ByteBuffer buffer) throws IOException {\n buffer.rewind();\n int read = channel.read(buffer, start);\n if (read < 4) return -1;\n\n // check that we have sufficient bytes left in the file\n int size = buffer.getInt(0);\n if (size < Message.MinHeaderSize) return -1;\n\n long next = start + 4 + size;\n if (next > len) return -1;\n\n // read the message\n ByteBuffer messageBuffer = ByteBuffer.allocate(size);\n long curr = start + 4;\n while (messageBuffer.hasRemaining()) {\n read = channel.read(messageBuffer, curr);\n if (read < 0) throw new IllegalStateException(\"File size changed during recovery!\");\n else curr += read;\n }\n messageBuffer.rewind();\n Message message = new Message(messageBuffer);\n if (!message.isValid()) return -1;\n else return next;\n }", "public static String rset(String input, int width)\n {\n String result; // result to return\n StringBuilder pad = new StringBuilder();\n if (input == null)\n {\n for (int i = 0; i < width - 1; i++)\n {\n pad.append(' '); // put blanks into buffer\n }\n result = \" \" + pad; // one short to use + overload\n }\n else\n {\n if (input.length() >= width)\n {\n result = input.substring(0, width); // when input is too long, truncate\n }\n else\n {\n int padLength = width - input.length(); // number of blanks to add\n for (int i = 0; i < padLength; i++)\n {\n pad.append(' '); // actually put blanks into buffer\n }\n result = pad + input; // concatenate\n }\n }\n return result;\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 ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine) {\n\t\tResult result = executionEngine.execute( getFindEntitiesQuery() );\n\t\treturn result.columnAs( BaseNeo4jEntityQueries.ENTITY_ALIAS );\n\t}", "public ListResponse listTemplates(Map<String, Object> options)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new ListResponse(request.get(\"/templates\", options));\n }", "public CurrencyQueryBuilder setCurrencyCodes(String... codes) {\n return set(CurrencyQuery.KEY_QUERY_CURRENCY_CODES, Arrays.asList(codes));\n }", "private void addProgressInterceptor() {\n httpClient.networkInterceptors().add(new Interceptor() {\n @Override\n public Response intercept(Interceptor.Chain chain) throws IOException {\n final Request request = chain.request();\n final Response originalResponse = chain.proceed(request);\n if (request.tag() instanceof ApiCallback) {\n final ApiCallback callback = (ApiCallback) request.tag();\n return originalResponse.newBuilder()\n .body(new ProgressResponseBody(originalResponse.body(), callback)).build();\n }\n return originalResponse;\n }\n });\n }" ]
handles when a member leaves and hazelcast partition data is lost. We want to find the Futures that are waiting on lost data and error them
[ "public void errorFuture(UUID taskId, Exception e) {\n DistributedFuture<GROUP, Serializable> future = remove(taskId);\n if(future != null) {\n future.setException(e);\n }\n }" ]
[ "@RequestMapping(value=\"/soy/compileJs\", method=GET)\n public ResponseEntity<String> compile(@RequestParam(required = false, value=\"hash\", defaultValue = \"\") final String hash,\n @RequestParam(required = true, value = \"file\") final String[] templateFileNames,\n @RequestParam(required = false, value = \"locale\") String locale,\n @RequestParam(required = false, value = \"disableProcessors\", defaultValue = \"false\") String disableProcessors,\n final HttpServletRequest request) throws IOException {\n return compileJs(templateFileNames, hash, new Boolean(disableProcessors).booleanValue(), request, locale);\n }", "public void prepareStatus() {\n globalLineCounter = new AtomicLong(0);\n time = new AtomicLong(System.currentTimeMillis());\n startTime = System.currentTimeMillis();\n lastCount = 0;\n\n // Status thread regularly reports on what is happening\n Thread statusThread = new Thread() {\n public void run() {\n while (true) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n System.out.println(\"Status thread interrupted\");\n }\n\n long thisTime = System.currentTimeMillis();\n long currentCount = globalLineCounter.get();\n\n if (thisTime - time.get() > 1000) {\n long oldTime = time.get();\n time.set(thisTime);\n double avgRate = 1000.0 * currentCount / (thisTime - startTime);\n double instRate = 1000.0 * (currentCount - lastCount) / (thisTime - oldTime);\n lastCount = currentCount;\n System.out.println(currentCount + \" AvgRage:\" + ((int) avgRate) + \" lines/sec instRate:\"\n + ((int) instRate) + \" lines/sec Unassigned Work: \"\n + remainingBlocks.get() + \" blocks\");\n }\n }\n }\n };\n statusThread.start();\n }", "public void execute() {\n try {\n while(true) {\n Event event = null;\n\n try {\n event = eventQueue.poll(timeout, unit);\n } catch(InterruptedException e) {\n throw new InsufficientOperationalNodesException(operation.getSimpleName()\n + \" operation interrupted!\", e);\n }\n\n if(event == null)\n throw new VoldemortException(operation.getSimpleName()\n + \" returned a null event\");\n\n if(event.equals(Event.ERROR)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName()\n + \" request, events complete due to error\");\n\n break;\n } else if(event.equals(Event.COMPLETED)) {\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, events complete\");\n\n break;\n }\n\n Action action = eventActions.get(event);\n\n if(action == null)\n throw new IllegalStateException(\"action was null for event \" + event);\n\n if(logger.isTraceEnabled())\n logger.trace(operation.getSimpleName() + \" request, action \"\n + action.getClass().getSimpleName() + \" to handle \" + event\n + \" event\");\n\n action.execute(this);\n }\n } finally {\n finished = true;\n }\n }", "public static MediaType nonBinary( MediaType.Type type, String subType, Charset charSet ) {\n ApiUtil.notNull( charSet, \"charset must not be null\" );\n return new MediaType( type, subType, charSet );\n }", "HtmlTag attr(String name, String value) {\n if (attrs == null) {\n attrs = new HashMap<>();\n }\n attrs.put(name, value);\n return this;\n }", "public boolean filter(Event event) {\n LOG.info(\"StringContentFilter called\");\n \n if (wordsToFilter != null) {\n for (String filterWord : wordsToFilter) {\n if (event.getContent() != null\n && -1 != event.getContent().indexOf(filterWord)) {\n return true;\n }\n }\n }\n return false;\n }", "private synchronized Class<?> getClass(String className) throws Exception {\n // see if we need to invalidate the class\n ClassInformation classInfo = classInformation.get(className);\n File classFile = new File(classInfo.pluginPath);\n if (classFile.lastModified() > classInfo.lastModified) {\n logger.info(\"Class {} has been modified, reloading\", className);\n logger.info(\"Thread ID: {}\", Thread.currentThread().getId());\n classInfo.loaded = false;\n classInformation.put(className, classInfo);\n\n // also cleanup anything in methodInformation with this className so it gets reloaded\n Iterator<Map.Entry<String, com.groupon.odo.proxylib.models.Method>> iter = methodInformation.entrySet().iterator();\n while (iter.hasNext()) {\n Map.Entry<String, com.groupon.odo.proxylib.models.Method> entry = iter.next();\n if (entry.getKey().startsWith(className)) {\n iter.remove();\n }\n }\n }\n\n if (!classInfo.loaded) {\n loadClass(className);\n }\n\n return classInfo.loadedClass;\n }", "public Table createTable(ProjectFile file, byte[] data, VarMeta varMeta, Var2Data varData)\n {\n Table table = new Table();\n\n table.setID(MPPUtility.getInt(data, 0));\n table.setResourceFlag(MPPUtility.getShort(data, 108) == 1);\n table.setName(MPPUtility.removeAmpersands(MPPUtility.getUnicodeString(data, 4)));\n\n byte[] columnData = null;\n Integer tableID = Integer.valueOf(table.getID());\n if (m_tableColumnDataBaseline != null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataBaseline));\n }\n\n if (columnData == null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataEnterprise));\n if (columnData == null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataStandard));\n }\n }\n\n processColumnData(file, table, columnData);\n\n //System.out.println(table);\n\n return (table);\n }", "public ItemRequest<Attachment> findById(String attachment) {\n \n String path = String.format(\"/attachments/%s\", attachment);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }" ]
Finishes the current box - empties the text line buffer and creates a DOM element from it.
[ "protected void finishBox()\n {\n \tif (textLine.length() > 0)\n \t{\n String s;\n if (isReversed(Character.getDirectionality(textLine.charAt(0))))\n s = textLine.reverse().toString();\n else\n s = textLine.toString();\n\n curstyle.setLeft(textMetrics.getX());\n curstyle.setTop(textMetrics.getTop());\n curstyle.setLineHeight(textMetrics.getHeight());\n\n\t renderText(s, textMetrics);\n\t textLine = new StringBuilder();\n\t textMetrics = null;\n \t}\n }" ]
[ "private void deleteLinks(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {\n final PersistentEntityId id = entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final Transaction envTxn = txn.getEnvironmentTransaction();\n final LinksTable links = getLinksTable(txn, entityTypeId);\n final IntHashSet deletedLinks = new IntHashSet();\n try (Cursor cursor = links.getFirstIndexCursor(envTxn)) {\n for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(new PropertyKey(entityLocalId, 0))) != null;\n success; success = cursor.getNext()) {\n final ByteIterable keyEntry = cursor.getKey();\n final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);\n if (key.getEntityLocalId() != entityLocalId) {\n break;\n }\n final ByteIterable valueEntry = cursor.getValue();\n if (links.delete(envTxn, keyEntry, valueEntry)) {\n int linkId = key.getPropertyId();\n if (getLinkName(txn, linkId) != null) {\n deletedLinks.add(linkId);\n final LinkValue linkValue = LinkValue.entryToLinkValue(valueEntry);\n txn.linkDeleted(entity.getId(), (PersistentEntityId) linkValue.getEntityId(), linkValue.getLinkId());\n }\n }\n }\n }\n for (Integer linkId : deletedLinks) {\n links.deleteAllIndex(envTxn, linkId, entityLocalId);\n }\n }", "@Override\n public Iterator<BoxItem.Info> iterator() {\n URL url = GET_COLLECTION_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxCollection.this.getID());\n return new BoxItemIterator(BoxCollection.this.getAPI(), url);\n }", "private void setDatesInternal(SortedSet<Date> dates) {\n\n if (!m_dates.equals(dates)) {\n m_dates = new TreeSet<>(dates);\n fireValueChange();\n }\n }", "private ClassLoaderInterface getClassLoader() {\n\t\tMap<String, Object> application = ActionContext.getContext().getApplication();\n\t\tif (application != null) {\n\t\t\treturn (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE);\n\t\t}\n\t\treturn null;\n\t}", "private void add(int field)\n {\n if (field < m_flags.length)\n {\n if (m_flags[field] == false)\n {\n m_flags[field] = true;\n m_fields[m_count] = field;\n ++m_count;\n }\n }\n }", "public synchronized T get(Scope scope) {\n if (instance != null) {\n return instance;\n }\n\n if (providerInstance != null) {\n if (isProvidingSingletonInScope) {\n instance = providerInstance.get();\n //gc\n providerInstance = null;\n return instance;\n }\n\n return providerInstance.get();\n }\n\n if (factoryClass != null && factory == null) {\n factory = FactoryLocator.getFactory(factoryClass);\n //gc\n factoryClass = null;\n }\n\n if (factory != null) {\n if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) {\n return factory.createInstance(scope);\n }\n instance = factory.createInstance(scope);\n //gc\n factory = null;\n return instance;\n }\n\n if (providerFactoryClass != null && providerFactory == null) {\n providerFactory = FactoryLocator.getFactory(providerFactoryClass);\n //gc\n providerFactoryClass = null;\n }\n\n if (providerFactory != null) {\n if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) {\n instance = providerFactory.createInstance(scope).get();\n //gc\n providerFactory = null;\n return instance;\n }\n if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) {\n providerInstance = providerFactory.createInstance(scope);\n //gc\n providerFactory = null;\n return providerInstance.get();\n }\n\n return providerFactory.createInstance(scope).get();\n }\n\n throw new IllegalStateException(\"A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen.\");\n }", "public void displayUseCases()\r\n {\r\n System.out.println();\r\n for (int i = 0; i < useCases.size(); i++)\r\n {\r\n System.out.println(\"[\" + i + \"] \" + ((UseCase) useCases.get(i)).getDescription());\r\n }\r\n }", "public Map<String, List<Locale>> getAvailableLocales() {\n\n if (m_availableLocales == null) {\n // create lazy map only on demand\n m_availableLocales = CmsCollectionsGenericWrapper.createLazyMap(new CmsAvailableLocaleLoaderTransformer());\n }\n return m_availableLocales;\n }", "@Override\n protected void denyImportDeclaration(ImportDeclaration importDeclaration) {\n LOG.debug(\"CXFImporter destroy a proxy for \" + importDeclaration);\n ServiceRegistration serviceRegistration = map.get(importDeclaration);\n serviceRegistration.unregister();\n\n // set the importDeclaration has unhandled\n super.unhandleImportDeclaration(importDeclaration);\n\n map.remove(importDeclaration);\n }" ]
Creates an attachment from a given array of bytes. The bytes will be Base64 encoded. @throws java.lang.IllegalArgumentException if mediaType is not binary
[ "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 }" ]
[ "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/delete\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @RequestParam(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(\"clientUUID\") String[] clientUUID) throws Exception {\n\n logger.info(\"Attempting to remove clients from the profile: \", profileIdentifier);\n logger.info(\"Attempting to remove the following clients: {}\", Arrays.toString(clientUUID));\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n for( int i = 0; i < clientUUID.length; i++ )\n {\n if (clientUUID[i].compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n clientService.remove(profileId, clientUUID[i]);\n }\n\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }", "public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException {\n Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();\n while (classNodes.hasNext()) {\n SourceUnit context = null;\n try {\n ClassNode classNode = (ClassNode) classNodes.next();\n context = classNode.getModule().getContext();\n if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) {\n int offset = 1;\n Iterator<InnerClassNode> iterator = classNode.getInnerClasses();\n while (iterator.hasNext()) {\n iterator.next();\n offset++;\n }\n body.call(context, new GeneratorContext(this.ast, offset), classNode);\n }\n } catch (CompilationFailedException e) {\n // fall through, getErrorReporter().failIfErrors() will trigger\n } catch (NullPointerException npe) {\n GroovyBugError gbe = new GroovyBugError(\"unexpected NullpointerException\", npe);\n changeBugText(gbe, context);\n throw gbe;\n } catch (GroovyBugError e) {\n changeBugText(e, context);\n throw e;\n } catch (NoClassDefFoundError e) {\n // effort to get more logging in case a dependency of a class is loaded\n // although it shouldn't have\n convertUncaughtExceptionToCompilationError(e);\n } catch (Exception e) {\n convertUncaughtExceptionToCompilationError(e);\n }\n }\n\n getErrorCollector().failIfErrors();\n }", "public AT_Row setPaddingLeftRight(int padding){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "protected void consumeChar(ImapRequestLineReader request, char expected)\n throws ProtocolException {\n char consumed = request.consume();\n if (consumed != expected) {\n throw new ProtocolException(\"Expected:'\" + expected + \"' found:'\" + consumed + '\\'');\n }\n }", "public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) {\n if(!lhs.getNodeIds().equals(rhs.getNodeIds())) {\n throw new VoldemortException(\"Node ids are not the same [ lhs cluster node ids (\"\n + lhs.getNodeIds()\n + \") not equal to rhs cluster node ids (\"\n + rhs.getNodeIds() + \") ]\");\n }\n }", "private void populateAnnotations(Collection<Annotation> annotations) {\n for (Annotation each : annotations) {\n this.annotations.put(each.annotationType(), each);\n }\n }", "public void removeLicenseFromArtifact(final String gavc, final String licenseId) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n\n //\n // The artifact may not have the exact string associated with it, but rather one\n // matching license regexp expression.\n //\n repositoryHandler.removeLicenseFromArtifact(dbArtifact, licenseId, licenseMatcher);\n }", "private void readNetscapeExt() {\n do {\n readBlock();\n if (block[0] == 1) {\n // Loop count sub-block.\n int b1 = ((int) block[1]) & 0xff;\n int b2 = ((int) block[2]) & 0xff;\n header.loopCount = (b2 << 8) | b1;\n if(header.loopCount == 0) {\n header.loopCount = GifDecoder.LOOP_FOREVER;\n }\n }\n } while ((blockSize > 0) && !err());\n }", "private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}" ]
Add "GROUP BY" clause to the SQL query statement. This can be called multiple times to add additional "GROUP BY" clauses. <p> NOTE: Use of this means that the resulting objects may not have a valid ID column value so cannot be deleted or updated. </p>
[ "public QueryBuilder<T, ID> groupBy(String columnName) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't groupBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddGroupBy(ColumnNameOrRawSql.withColumnName(columnName));\n\t\treturn this;\n\t}" ]
[ "public double getCouponPayment(int periodIndex, AnalyticModel model) {\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve with name '\" + forwardCurveName + \"' was found in the model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\t\tdouble couponPayment=fixedCoupon ;\n\t\tif(forwardCurve != null ) {\n\t\t\tcouponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex));\n\t\t}\n\t\treturn couponPayment*periodLength;\n\t}", "public static final Integer parseMinutesFromHours(String value)\n {\n Integer result = null;\n if (value != null)\n {\n result = Integer.valueOf(Integer.parseInt(value) * 60);\n }\n return result;\n }", "private static String getJsonFromRaw(Context context, int resource) {\n String json;\n try {\n InputStream inputStream = context.getResources().openRawResource(resource);\n int size = inputStream.available();\n byte[] buffer = new byte[size];\n inputStream.read(buffer);\n inputStream.close();\n json = new String(buffer, \"UTF-8\");\n } catch (IOException ex) {\n ex.printStackTrace();\n return null;\n }\n return json;\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 }", "private static boolean waitTillNoNotifications(Environment env, TableRange range)\n throws TableNotFoundException {\n boolean sawNotifications = false;\n long retryTime = MIN_SLEEP_MS;\n\n log.debug(\"Scanning tablet {} for notifications\", range);\n\n long start = System.currentTimeMillis();\n while (hasNotifications(env, range)) {\n sawNotifications = true;\n long sleepTime = Math.max(System.currentTimeMillis() - start, retryTime);\n log.debug(\"Tablet {} had notfications, will rescan in {}ms\", range, sleepTime);\n UtilWaitThread.sleep(sleepTime);\n retryTime = Math.min(MAX_SLEEP_MS, (long) (retryTime * 1.5));\n start = System.currentTimeMillis();\n }\n\n return sawNotifications;\n }", "@Deprecated\n public FluoConfiguration clearObservers() {\n Iterator<String> iter1 = getKeys(OBSERVER_PREFIX.substring(0, OBSERVER_PREFIX.length() - 1));\n while (iter1.hasNext()) {\n String key = iter1.next();\n clearProperty(key);\n }\n\n return this;\n }", "public boolean process(DMatrixRMaj A , int numSingularValues, DMatrixRMaj nullspace ) {\n decomposition.decompose(A);\n\n if( A.numRows > A.numCols ) {\n Q.reshape(A.numCols,Math.min(A.numRows,A.numCols));\n decomposition.getQ(Q, true);\n } else {\n Q.reshape(A.numCols, A.numCols);\n decomposition.getQ(Q, false);\n }\n\n nullspace.reshape(Q.numRows,numSingularValues);\n CommonOps_DDRM.extract(Q,0,Q.numRows,Q.numCols-numSingularValues,Q.numCols,nullspace,0,0);\n\n return true;\n }", "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 }", "protected static Map<String, List<Statement>> removeStatements(Set<String> statementIds, Map<String, List<Statement>> claims) {\n\t\tMap<String, List<Statement>> newClaims = new HashMap<>(claims.size());\n\t\tfor(Entry<String, List<Statement>> entry : claims.entrySet()) {\n\t\t\tList<Statement> filteredStatements = new ArrayList<>();\n\t\t\tfor(Statement s : entry.getValue()) {\n\t\t\t\tif(!statementIds.contains(s.getStatementId())) {\n\t\t\t\t\tfilteredStatements.add(s);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!filteredStatements.isEmpty()) {\n\t\t\t\tnewClaims.put(entry.getKey(),\n\t\t\t\t\tfilteredStatements);\n\t\t\t}\n\t\t}\n\t\treturn newClaims;\n\t}" ]
Gets the positive integer. @param number the number @return the positive integer
[ "private int getPositiveInteger(String number) {\n try {\n return Math.max(0, Integer.parseInt(number));\n } catch (NumberFormatException e) {\n return 0;\n }\n }" ]
[ "public ProviderContextBuilder setRateTypes(Collection<RateType> rateTypes) {\n Objects.requireNonNull(rateTypes);\n if (rateTypes.isEmpty()) {\n throw new IllegalArgumentException(\"At least one RateType is required.\");\n }\n Set<RateType> rtSet = new HashSet<>(rateTypes);\n set(ProviderContext.KEY_RATE_TYPES, rtSet);\n return this;\n }", "public void prepareStatus() {\n globalLineCounter = new AtomicLong(0);\n time = new AtomicLong(System.currentTimeMillis());\n startTime = System.currentTimeMillis();\n lastCount = 0;\n\n // Status thread regularly reports on what is happening\n Thread statusThread = new Thread() {\n public void run() {\n while (true) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n System.out.println(\"Status thread interrupted\");\n }\n\n long thisTime = System.currentTimeMillis();\n long currentCount = globalLineCounter.get();\n\n if (thisTime - time.get() > 1000) {\n long oldTime = time.get();\n time.set(thisTime);\n double avgRate = 1000.0 * currentCount / (thisTime - startTime);\n double instRate = 1000.0 * (currentCount - lastCount) / (thisTime - oldTime);\n lastCount = currentCount;\n System.out.println(currentCount + \" AvgRage:\" + ((int) avgRate) + \" lines/sec instRate:\"\n + ((int) instRate) + \" lines/sec Unassigned Work: \"\n + remainingBlocks.get() + \" blocks\");\n }\n }\n }\n };\n statusThread.start();\n }", "private XopBean createXopBean() throws Exception {\n XopBean xop = new XopBean();\n xop.setName(\"xopName\");\n \n InputStream is = getClass().getResourceAsStream(\"/java.jpg\");\n byte[] data = IOUtils.readBytesFromStream(is);\n \n // Pass java.jpg as an array of bytes\n xop.setBytes(data);\n \n // Wrap java.jpg as a DataHandler\n xop.setDatahandler(new DataHandler(\n new ByteArrayDataSource(data, \"application/octet-stream\")));\n \n if (Boolean.getBoolean(\"java.awt.headless\")) {\n System.out.println(\"Running headless. Ignoring an Image property.\");\n } else {\n xop.setImage(getImage(\"/java.jpg\"));\n }\n \n return xop;\n }", "public static InetAddress getLocalHost() throws UnknownHostException {\n InetAddress addr;\n try {\n addr = InetAddress.getLocalHost();\n } catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404\n addr = InetAddress.getByName(null);\n }\n return addr;\n }", "public void setPerms(String photoId, GeoPermissions perms) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", perms.isPublic() ? \"1\" : \"0\");\r\n parameters.put(\"is_contact\", perms.isContact() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", perms.isFriend() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", perms.isFamily() ? \"1\" : \"0\");\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n // This method has no specific response - It returns an empty sucess response\r\n // if it completes without error.\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public static responderpolicylabel_responderpolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tresponderpolicylabel_responderpolicy_binding obj = new responderpolicylabel_responderpolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tresponderpolicylabel_responderpolicy_binding response[] = (responderpolicylabel_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static Deployment of(final Path content) {\n final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam(\"content\", content));\n return new Deployment(deploymentContent, null);\n }", "public void setOuterConeAngle(float angle)\n {\n setFloat(\"outer_cone_angle\", (float) Math.cos(Math.toRadians(angle)));\n mChanged.set(true);\n }", "private int getReplicaTypeForPartition(int partitionId) {\n List<Integer> routingPartitionList = routingStrategy.getReplicatingPartitionList(partitionId);\n\n // Determine if we should host this partition, and if so, whether we are a primary,\n // secondary or n-ary replica for it\n int correctReplicaType = -1;\n for (int replica = 0; replica < routingPartitionList.size(); replica++) {\n if(nodePartitionIds.contains(routingPartitionList.get(replica))) {\n // This means the partitionId currently being iterated on should be hosted\n // by this node. Let's remember its replica type in order to make sure the\n // files we have are properly named.\n correctReplicaType = replica;\n break;\n }\n }\n\n return correctReplicaType;\n }" ]
Deletes a story. A user can only delete stories they have created. Returns an empty data record. @param story Globally unique identifier for the story. @return Request object
[ "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 }" ]
[ "int add(DownloadRequest request) {\n\t\tint downloadId = getDownloadId();\n\t\t// Tag the request as belonging to this queue and add it to the set of current requests.\n\t\trequest.setDownloadRequestQueue(this);\n\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tmCurrentRequests.add(request);\n\t\t}\n\n\t\t// Process requests in the order they are added.\n\t\trequest.setDownloadId(downloadId);\n\t\tmDownloadQueue.add(request);\n\n\t\treturn downloadId;\n\t}", "private static void parseRessource(ArrayList<Shape> shapes,\n HashMap<String, JSONObject> flatJSON,\n String resourceId,\n Boolean keepGlossaryLink)\n throws JSONException {\n JSONObject modelJSON = flatJSON.get(resourceId);\n Shape current = getShapeWithId(modelJSON.getString(\"resourceId\"),\n shapes);\n\n parseStencil(modelJSON,\n current);\n\n parseProperties(modelJSON,\n current,\n keepGlossaryLink);\n parseOutgoings(shapes,\n modelJSON,\n current);\n parseChildShapes(shapes,\n modelJSON,\n current);\n parseDockers(modelJSON,\n current);\n parseBounds(modelJSON,\n current);\n parseTarget(shapes,\n modelJSON,\n current);\n }", "protected void putConnectionBackInPartition(ConnectionHandle connectionHandle) throws SQLException {\r\n\r\n\t\tif (this.cachedPoolStrategy && ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.dumbGet().getValue()){\r\n\t\t\tconnectionHandle.logicallyClosed.set(true);\r\n\t\t\t((CachedConnectionStrategy)this.connectionStrategy).tlConnections.set(new AbstractMap.SimpleEntry<ConnectionHandle, Boolean>(connectionHandle, false));\r\n\t\t} else {\r\n\t\t\tBlockingQueue<ConnectionHandle> queue = connectionHandle.getOriginatingPartition().getFreeConnections();\r\n\t\t\t\tif (!queue.offer(connectionHandle)){ // this shouldn't fail\r\n\t\t\t\t\tconnectionHandle.internalClose();\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t}", "private void extractFile(InputStream stream, File dir) throws IOException\n {\n byte[] header = new byte[8];\n byte[] fileName = new byte[13];\n byte[] dataSize = new byte[4];\n\n stream.read(header);\n stream.read(fileName);\n stream.read(dataSize);\n\n int dataSizeValue = getInt(dataSize, 0);\n String fileNameValue = getString(fileName, 0);\n File file = new File(dir, fileNameValue);\n\n if (dataSizeValue == 0)\n {\n FileHelper.createNewFile(file);\n }\n else\n {\n OutputStream os = new FileOutputStream(file);\n FixedLengthInputStream inputStream = new FixedLengthInputStream(stream, dataSizeValue);\n Blast blast = new Blast();\n blast.blast(inputStream, os);\n os.close();\n }\n }", "public static Cluster vacateZone(Cluster currentCluster, int dropZoneId) {\n Cluster returnCluster = Cluster.cloneCluster(currentCluster);\n // Go over each node in the zone being dropped\n for(Integer nodeId: currentCluster.getNodeIdsInZone(dropZoneId)) {\n // For each node grab all the partitions it hosts\n for(Integer partitionId: currentCluster.getNodeById(nodeId).getPartitionIds()) {\n // Now for each partition find a new home..which would be a node\n // in one of the existing zones\n int finalZoneId = -1;\n int finalNodeId = -1;\n int adjacentPartitionId = partitionId;\n do {\n adjacentPartitionId = (adjacentPartitionId + 1)\n % currentCluster.getNumberOfPartitions();\n finalNodeId = currentCluster.getNodeForPartitionId(adjacentPartitionId).getId();\n finalZoneId = currentCluster.getZoneForPartitionId(adjacentPartitionId).getId();\n if(adjacentPartitionId == partitionId) {\n logger.error(\"PartitionId \" + partitionId + \"stays unchanged \\n\");\n } else {\n logger.info(\"PartitionId \" + partitionId\n + \" goes together with partition \" + adjacentPartitionId\n + \" on node \" + finalNodeId + \" in zone \" + finalZoneId);\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n finalNodeId,\n Lists.newArrayList(partitionId));\n }\n } while(finalZoneId == dropZoneId);\n }\n }\n return returnCluster;\n }", "public Boolean getBoolean(int field, String falseText)\n {\n Boolean result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = ((m_fields[field].equalsIgnoreCase(falseText) == true) ? Boolean.FALSE : Boolean.TRUE);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public EventBus emitSync(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }", "public Object getRealKey()\r\n {\r\n if(keyRealSubject != null)\r\n {\r\n return keyRealSubject;\r\n }\r\n else\r\n {\r\n TransactionExt tx = getTransaction();\r\n\r\n if((tx != null) && tx.isOpen())\r\n {\r\n prepareKeyRealSubject(tx.getBroker());\r\n }\r\n else\r\n {\r\n if(getPBKey() != null)\r\n {\r\n PBCapsule capsule = new PBCapsule(getPBKey(), null);\r\n\r\n try\r\n {\r\n prepareKeyRealSubject(capsule.getBroker());\r\n }\r\n finally\r\n {\r\n capsule.destroy();\r\n }\r\n }\r\n else\r\n {\r\n getLog().warn(\"No tx, no PBKey - can't materialise key with Identity \" + getKeyOid());\r\n }\r\n }\r\n }\r\n return keyRealSubject;\r\n }", "protected static <T, A> ManagementRequestHandler<T, A> getFallbackHandler(final ManagementRequestHeader header) {\n return new ManagementRequestHandler<T, A>() {\n @Override\n public void handleRequest(final DataInput input, ActiveOperation.ResultHandler<T> resultHandler, ManagementRequestContext<A> context) throws IOException {\n final Exception error = ProtocolLogger.ROOT_LOGGER.noSuchResponseHandler(Integer.toHexString(header.getRequestId()));\n if(resultHandler.failed(error)) {\n safeWriteErrorResponse(context.getChannel(), context.getRequestHeader(), error);\n }\n }\n };\n }" ]
Iterates through the range of prefixes in this range instance using the given prefix length. @param prefixLength @return
[ "@Override\n\tpublic Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {\n\t\tif(!isMultiple()) {\n\t\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\t\tIPAddressSeqRange orig = IPAddressSeqRange.this;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn orig != null;\n\t\t\t\t}\n\n\t\t\t @Override\n\t\t\t\tpublic IPAddressSeqRange next() {\n\t\t\t \tif(orig == null) {\n\t\t\t \t\tthrow new NoSuchElementException();\n\t\t\t \t}\n\t\t\t \tIPAddressSeqRange result = orig;\n\t\t\t \torig = null;\n\t\t\t \treturn result;\n\t\t\t }\n\t\t\t\n\t\t\t @Override\n\t\t\t\tpublic void remove() {\n\t\t\t \tthrow new UnsupportedOperationException();\n\t\t\t }\n\t\t\t};\n\t\t}\n\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\tIterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);\n\t\t\tprivate boolean first = true;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn prefixBlockIterator.hasNext();\n\t\t\t}\n\n\t\t @Override\n\t\t\tpublic IPAddressSeqRange next() {\n\t\t \tIPAddress next = prefixBlockIterator.next();\n\t\t \tif(first) {\n\t\t \t\tfirst = false;\n\t\t \t\t// next is a prefix block\n\t\t \t\tIPAddress lower = getLower();\n\t\t \t\tif(hasNext()) {\n\t\t\t \t\tif(!lower.includesZeroHost(prefixLength)) {\n\t\t\t \t\t\treturn create(lower, next.getUpper());\n\t\t\t \t\t}\n\t\t \t\t} else {\n\t\t \t\t\tIPAddress upper = getUpper();\n\t\t \t\t\tif(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\t\treturn create(lower, upper);\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t} else if(!hasNext()) {\n\t\t \t\tIPAddress upper = getUpper();\n\t\t \t\tif(!upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\treturn create(next.getLower(), upper);\n\t\t \t\t}\n\t\t \t}\n\t\t \treturn next.toSequentialRange();\n\t\t }\n\t\t\n\t\t @Override\n\t\t\tpublic void remove() {\n\t\t \tthrow new UnsupportedOperationException();\n\t\t }\n\t\t};\n\t}" ]
[ "synchronized boolean markReadMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n ContentValues cv = new ContentValues();\n cv.put(IS_READ,1);\n db.update(Table.INBOX_MESSAGES.getName(), cv,_ID + \" = ? AND \" + USER_ID + \" = ?\",new String[]{messageId,userId});\n return true;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }", "public void setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tif(htmlElementTranslator!=null){\r\n\t\t\tthis.htmlElementTranslator = htmlElementTranslator;\r\n\t\t\tthis.charTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\n\t}", "public static String toSafeFileName(String name) {\n int size = name.length();\n StringBuilder builder = new StringBuilder(size * 2);\n for (int i = 0; i < size; i++) {\n char c = name.charAt(i);\n boolean valid = c >= 'a' && c <= 'z';\n valid = valid || (c >= 'A' && c <= 'Z');\n valid = valid || (c >= '0' && c <= '9');\n valid = valid || (c == '_') || (c == '-') || (c == '.');\n\n if (valid) {\n builder.append(c);\n } else {\n // Encode the character using hex notation\n builder.append('x');\n builder.append(Integer.toHexString(i));\n }\n }\n return builder.toString();\n }", "public static auditmessages[] get(nitro_service service, auditmessages_args args) throws Exception{\n\t\tauditmessages obj = new auditmessages();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tauditmessages[] response = (auditmessages[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public void writeNameValuePair(String name, int value) throws IOException\n {\n internalWriteNameValuePair(name, Integer.toString(value));\n }", "private static void parseDockers(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"dockers\")) {\n ArrayList<Point> dockers = new ArrayList<Point>();\n\n JSONArray dockersObject = modelJSON.getJSONArray(\"dockers\");\n for (int i = 0; i < dockersObject.length(); i++) {\n Double x = dockersObject.getJSONObject(i).getDouble(\"x\");\n Double y = dockersObject.getJSONObject(i).getDouble(\"y\");\n dockers.add(new Point(x,\n y));\n }\n if (dockers.size() > 0) {\n current.setDockers(dockers);\n }\n }\n }", "private void addAllProjectModels(ApplicationReportIndexModel navIdx, ProjectModel projectModel)\n {\n navIdx.addProjectModel(projectModel);\n for (ProjectModel childProject : projectModel.getChildProjects())\n {\n if (!Iterators.asSet(navIdx.getProjectModels()).contains(childProject))\n addAllProjectModels(navIdx, childProject);\n }\n }", "public static base_response update(nitro_service client, filterhtmlinjectionparameter resource) throws Exception {\n\t\tfilterhtmlinjectionparameter updateresource = new filterhtmlinjectionparameter();\n\t\tupdateresource.rate = resource.rate;\n\t\tupdateresource.frequency = resource.frequency;\n\t\tupdateresource.strict = resource.strict;\n\t\tupdateresource.htmlsearchlen = resource.htmlsearchlen;\n\t\treturn updateresource.update_resource(client);\n\t}", "public ProjectCalendar getByName(String calendarName)\n {\n ProjectCalendar calendar = null;\n\n if (calendarName != null && calendarName.length() != 0)\n {\n Iterator<ProjectCalendar> iter = iterator();\n while (iter.hasNext() == true)\n {\n calendar = iter.next();\n String name = calendar.getName();\n\n if ((name != null) && (name.equalsIgnoreCase(calendarName) == true))\n {\n break;\n }\n\n calendar = null;\n }\n }\n\n return (calendar);\n }" ]
Use this API to add dospolicy.
[ "public static base_response add(nitro_service client, dospolicy resource) throws Exception {\n\t\tdospolicy addresource = new dospolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.qdepth = resource.qdepth;\n\t\taddresource.cltdetectrate = resource.cltdetectrate;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public Class<?> getType(String key) {\n Object val = this.data.get(key);\n return val == null ? null : val.getClass();\n }", "public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }", "private boolean isWorkingDay(ProjectCalendar mpxjCalendar, Day day)\n {\n boolean result = false;\n net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);\n if (type == null)\n {\n type = net.sf.mpxj.DayType.DEFAULT;\n }\n\n switch (type)\n {\n case WORKING:\n {\n result = true;\n break;\n }\n\n case NON_WORKING:\n {\n result = false;\n break;\n }\n\n case DEFAULT:\n {\n if (mpxjCalendar.getParent() == null)\n {\n result = false;\n }\n else\n {\n result = isWorkingDay(mpxjCalendar.getParent(), day);\n }\n break;\n }\n }\n\n return (result);\n }", "public static dnsview get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview response = (dnsview) obj.get_resource(service);\n\t\treturn response;\n\t}", "public ContentAssistEntry createProposal(final String proposal, final String prefix, final ContentAssistContext context, final String kind, final Procedure1<? super ContentAssistEntry> init) {\n boolean _isValidProposal = this.isValidProposal(proposal, prefix, context);\n if (_isValidProposal) {\n final ContentAssistEntry result = new ContentAssistEntry();\n result.setProposal(proposal);\n result.setPrefix(prefix);\n if ((kind != null)) {\n result.setKind(kind);\n }\n if ((init != null)) {\n init.apply(result);\n }\n return result;\n }\n return null;\n }", "public static void deleteMetadataTemplate(BoxAPIConnection api, String scope, String template) {\n\n URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"DELETE\");\n\n request.send();\n }", "public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName,\n String filePrefix) {\n dumpClusterToFile(outputDirName, filePrefix + currentClusterFileName, currentCluster);\n dumpClusterToFile(outputDirName, filePrefix + finalClusterFileName, finalCluster);\n }", "private List<Job> getJobs(final Jedis jedis, final String queueName, final long jobOffset, final long jobCount) throws Exception {\n final String key = key(QUEUE, queueName);\n final List<Job> jobs = new ArrayList<>();\n if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZRANGEWITHSCORES\n final Set<Tuple> elements = jedis.zrangeWithScores(key, jobOffset, jobOffset + jobCount - 1);\n for (final Tuple elementWithScore : elements) {\n final Job job = ObjectMapperFactory.get().readValue(elementWithScore.getElement(), Job.class);\n job.setRunAt(elementWithScore.getScore());\n jobs.add(job);\n }\n } else { // Else, use LRANGE\n final List<String> elements = jedis.lrange(key, jobOffset, jobOffset + jobCount - 1);\n for (final String element : elements) {\n jobs.add(ObjectMapperFactory.get().readValue(element, Job.class));\n }\n }\n return jobs;\n }", "public static String checkRequiredProperties(Properties props,\r\n String ... requiredProps) {\r\n for (String required : requiredProps) {\r\n if (props.getProperty(required) == null) {\r\n return required;\r\n }\r\n }\r\n return null;\r\n }" ]
Convenience routine to move to the next iterator if needed. @return true if the iterator is changed, false if no changes.
[ "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 }" ]
[ "private void populateAnnotations(Collection<Annotation> annotations) {\n for (Annotation each : annotations) {\n this.annotations.put(each.annotationType(), each);\n }\n }", "public void classifyAndWriteViterbiSearchGraph(String testFile, String searchGraphPrefix, DocumentReaderAndWriter<IN> readerAndWriter) throws IOException {\r\n Timing timer = new Timing();\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromFile(testFile, readerAndWriter);\r\n int numWords = 0;\r\n int numSentences = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n DFSA<String, Integer> tagLattice = getViterbiSearchGraph(doc, AnswerAnnotation.class);\r\n numWords += doc.size();\r\n PrintWriter latticeWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences\r\n + \".wlattice\"));\r\n PrintWriter vsgWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences + \".lattice\"));\r\n if (readerAndWriter instanceof LatticeWriter)\r\n ((LatticeWriter) readerAndWriter).printLattice(tagLattice, doc, latticeWriter);\r\n tagLattice.printAttFsmFormat(vsgWriter);\r\n latticeWriter.close();\r\n vsgWriter.close();\r\n numSentences++;\r\n }\r\n\r\n long millis = timer.stop();\r\n double wordspersec = numWords / (((double) millis) / 1000);\r\n NumberFormat nf = new DecimalFormat(\"0.00\"); // easier way!\r\n System.err.println(this.getClass().getName() + \" tagged \" + numWords + \" words in \" + numSentences\r\n + \" documents at \" + nf.format(wordspersec) + \" words per second.\");\r\n }", "public synchronized void addRange(final float range, final GVRSceneObject sceneObject)\n {\n if (null == sceneObject) {\n throw new IllegalArgumentException(\"sceneObject must be specified!\");\n }\n if (range < 0) {\n throw new IllegalArgumentException(\"range cannot be negative\");\n }\n\n final int size = mRanges.size();\n final float rangePow2 = range*range;\n final Object[] newElement = new Object[] {rangePow2, sceneObject};\n\n for (int i = 0; i < size; ++i) {\n final Object[] el = mRanges.get(i);\n final Float r = (Float)el[0];\n if (r > rangePow2) {\n mRanges.add(i, newElement);\n break;\n }\n }\n\n if (mRanges.size() == size) {\n mRanges.add(newElement);\n }\n\n final GVRSceneObject owner = getOwnerObject();\n if (null != owner) {\n owner.addChildObject(sceneObject);\n }\n }", "public synchronized T get(Scope scope) {\n if (instance != null) {\n return instance;\n }\n\n if (providerInstance != null) {\n if (isProvidingSingletonInScope) {\n instance = providerInstance.get();\n //gc\n providerInstance = null;\n return instance;\n }\n\n return providerInstance.get();\n }\n\n if (factoryClass != null && factory == null) {\n factory = FactoryLocator.getFactory(factoryClass);\n //gc\n factoryClass = null;\n }\n\n if (factory != null) {\n if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) {\n return factory.createInstance(scope);\n }\n instance = factory.createInstance(scope);\n //gc\n factory = null;\n return instance;\n }\n\n if (providerFactoryClass != null && providerFactory == null) {\n providerFactory = FactoryLocator.getFactory(providerFactoryClass);\n //gc\n providerFactoryClass = null;\n }\n\n if (providerFactory != null) {\n if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) {\n instance = providerFactory.createInstance(scope).get();\n //gc\n providerFactory = null;\n return instance;\n }\n if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) {\n providerInstance = providerFactory.createInstance(scope);\n //gc\n providerFactory = null;\n return providerInstance.get();\n }\n\n return providerFactory.createInstance(scope).get();\n }\n\n throw new IllegalStateException(\"A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen.\");\n }", "public void applyPatterns(String[] patterns)\n {\n m_formats = new SimpleDateFormat[patterns.length];\n for (int index = 0; index < patterns.length; index++)\n {\n m_formats[index] = new SimpleDateFormat(patterns[index]);\n }\n }", "public DataSetInfo create(int dataSet) throws InvalidDataSetException {\r\n\t\tDataSetInfo info = dataSets.get(createKey(dataSet));\r\n\t\tif (info == null) {\r\n\t\t\tint recordNumber = (dataSet >> 8) & 0xFF;\r\n\t\t\tint dataSetNumber = dataSet & 0xFF;\r\n\t\t\tthrow new UnsupportedDataSetException(recordNumber + \":\" + dataSetNumber);\r\n\t\t\t// info = super.create(dataSet);\r\n\t\t}\r\n\t\treturn info;\r\n\t}", "private void addDateWithCheckState(Date date, boolean checkState) {\n\n addCheckBox(date, checkState);\n if (!m_dates.contains(date)) {\n m_dates.add(date);\n fireValueChange();\n }\n }", "public PhotoContext getContext(String photoId, String groupId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"group_id\", groupId);\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 Collection<Element> payload = response.getPayloadCollection();\r\n PhotoContext photoContext = new PhotoContext();\r\n for (Element element : payload) {\r\n String elementName = element.getTagName();\r\n if (elementName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (elementName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setNextPhoto(photo);\r\n } else if (!elementName.equals(\"count\")) {\r\n _log.warn(\"unsupported element name: \" + elementName);\r\n }\r\n }\r\n return photoContext;\r\n }", "public static HttpResponse getResponse(String urls, HttpRequest request,\n HttpMethod method, int connectTimeoutMillis, int readTimeoutMillis) throws IOException {\n OutputStream out = null;\n InputStream content = null;\n HttpResponse response = null;\n HttpURLConnection httpConn = request\n .getHttpConnection(urls, method.name());\n httpConn.setConnectTimeout(connectTimeoutMillis);\n httpConn.setReadTimeout(readTimeoutMillis);\n\n try {\n httpConn.connect();\n if (null != request.getPayload() && request.getPayload().length > 0) {\n out = httpConn.getOutputStream();\n out.write(request.getPayload());\n }\n content = httpConn.getInputStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } catch (SocketTimeoutException e) {\n throw e;\n } catch (IOException e) {\n content = httpConn.getErrorStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } finally {\n if (content != null) {\n content.close();\n }\n httpConn.disconnect();\n }\n }" ]
Passes the Socket's InputStream and OutputStream to the closure. The streams will be closed after the closure returns, even if an exception is thrown. @param socket a Socket @param closure a Closure @return the value returned by the closure @throws IOException if an IOException occurs. @since 1.5.2
[ "public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.InputStream\",\"java.io.OutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n try {\n T result = closure.call(new Object[]{input, output});\n\n InputStream temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(input);\n closeWithWarning(output);\n }\n }" ]
[ "static String from(Class<?> entryClass) {\n List<String> tokens = tokenOf(entryClass);\n return fromTokens(tokens);\n }", "public static CallSite bootstrapCurrent(Lookup caller, String name, MethodType type) {\n return realBootstrap(caller, name, CALL_TYPES.METHOD.ordinal(), type, false, true, false);\n }", "private void persistEnabledVersion(long version) throws PersistenceFailureException {\n File disabledMarker = getDisabledMarkerFile(version);\n if (disabledMarker.exists()) {\n if (!disabledMarker.delete()) {\n throw new PersistenceFailureException(\"Failed to create the disabled marker at path: \" +\n disabledMarker.getAbsolutePath() + \"\\nThe store/version \" +\n \"will remain enabled only until the next restart.\");\n }\n }\n }", "public void addAttribute(String attributeName, String attributeValue)\r\n {\r\n if (attributeName != null && attributeName.startsWith(JDBC_PROPERTY_NAME_PREFIX))\r\n {\r\n final String jdbcPropertyName = attributeName.substring(JDBC_PROPERTY_NAME_LENGTH);\r\n jdbcProperties.setProperty(jdbcPropertyName, attributeValue);\r\n }\r\n else if (attributeName != null && attributeName.startsWith(DBCP_PROPERTY_NAME_PREFIX))\r\n {\r\n final String dbcpPropertyName = attributeName.substring(DBCP_PROPERTY_NAME_LENGTH);\r\n dbcpProperties.setProperty(dbcpPropertyName, attributeValue);\r\n }\r\n else\r\n {\r\n super.addAttribute(attributeName, attributeValue);\r\n }\r\n }", "private ReferenceDescriptorDef cloneReference(ReferenceDescriptorDef refDef, String prefix)\r\n {\r\n ReferenceDescriptorDef copyRefDef = new ReferenceDescriptorDef(refDef, prefix);\r\n\r\n copyRefDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyRefDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n \r\n Properties mod = getModification(copyRefDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyRefDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included reference \"+\r\n copyRefDef.getName()+\" from class \"+refDef.getOwner().getName()); \r\n }\r\n copyRefDef.applyModifications(mod);\r\n }\r\n return copyRefDef;\r\n }", "public void setFrustum(float[] frustum)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.setFrustum(frustum[0], frustum[3], frustum[1], frustum[4], frustum[2], frustum[5]);\n setFrustum(projMatrix);\n }", "public void setPadding(float padding, Layout.Axis axis) {\n OrientedLayout layout = null;\n switch(axis) {\n case X:\n layout = mShiftLayout;\n break;\n case Y:\n layout = mShiftLayout;\n break;\n case Z:\n layout = mStackLayout;\n break;\n }\n if (layout != null) {\n if (!equal(layout.getDividerPadding(axis), padding)) {\n layout.setDividerPadding(padding, axis);\n\n if (layout.getOrientationAxis() == axis) {\n requestLayout();\n }\n }\n }\n\n }", "public static String replaceParameters(final InputStream stream) {\n String content = IOUtil.asStringPreservingNewLines(stream);\n return resolvePlaceholders(content);\n }", "private static void parseStencil(JSONObject modelJSON,\n Shape current) throws JSONException {\n // get stencil type\n if (modelJSON.has(\"stencil\")) {\n JSONObject stencil = modelJSON.getJSONObject(\"stencil\");\n // TODO other attributes of stencil\n String stencilString = \"\";\n if (stencil.has(\"id\")) {\n stencilString = stencil.getString(\"id\");\n }\n current.setStencil(new StencilType(stencilString));\n }\n }" ]
Return the entity of a resource @param resource the resource @param <T> the type of the resource's entity @param <R> the resource type @return the resource's entity
[ "public static <T, R extends Resource<T>> T getEntity(R resource) {\n return resource.getEntity();\n }" ]
[ "public Date getPreviousWorkFinish(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToPreviousWorkFinish(cal);\n return cal.getTime();\n }", "public void useNewRESTServiceWithOldClient() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/new-rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n \n // The outgoing old Customer data needs to be transformed for \n // the new service to understand it and the response from the new service\n // needs to be transformed for this old client to understand it.\n ClientConfiguration config = WebClient.getConfig(customerService);\n addTransformInterceptors(config.getInInterceptors(),\n config.getOutInterceptors(),\n false);\n \n \n System.out.println(\"Using new RESTful CustomerService with old Client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old to New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old to New REST\");\n printOldCustomerDetails(customer);\n }", "public static sslcertlink[] get(nitro_service service) throws Exception{\n\t\tsslcertlink obj = new sslcertlink();\n\t\tsslcertlink[] response = (sslcertlink[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private static void parseChildShapes(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"childShapes\")) {\n ArrayList<Shape> childShapes = new ArrayList<Shape>();\n\n JSONArray childShapeObject = modelJSON.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapeObject.length(); i++) {\n childShapes.add(getShapeWithId(childShapeObject.getJSONObject(i).getString(\"resourceId\"),\n shapes));\n }\n if (childShapes.size() > 0) {\n for (Shape each : childShapes) {\n each.setParent(current);\n }\n current.setChildShapes(childShapes);\n }\n ;\n }\n }", "public void setProgressBackgroundColor(int colorRes) {\n mCircleView.setBackgroundColor(colorRes);\n mProgress.setBackgroundColor(getResources().getColor(colorRes));\n }", "private Table buildTable(CmsSqlConsoleResults results) {\n\n IndexedContainer container = new IndexedContainer();\n int numCols = results.getColumns().size();\n for (int c = 0; c < numCols; c++) {\n container.addContainerProperty(Integer.valueOf(c), results.getColumnType(c), null);\n }\n int r = 0;\n for (List<Object> row : results.getData()) {\n Item item = container.addItem(Integer.valueOf(r));\n for (int c = 0; c < numCols; c++) {\n item.getItemProperty(Integer.valueOf(c)).setValue(row.get(c));\n }\n r += 1;\n }\n Table table = new Table();\n table.setContainerDataSource(container);\n for (int c = 0; c < numCols; c++) {\n String col = (results.getColumns().get(c));\n table.setColumnHeader(Integer.valueOf(c), col);\n }\n table.setWidth(\"100%\");\n table.setHeight(\"100%\");\n table.setColumnCollapsingAllowed(true);\n return table;\n }", "private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation,\n ModelNode host) {\n final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR));\n if (realAddress.size() == 0 && COMPOSITE.equals(operation.get(OP).asString())) {\n //We have a composite operation resulting from a transformation to redeploy affected deployments\n //See redeploying deployments affected by an overlay.\n ModelNode serverOp = operation.clone();\n Map<ServerIdentity, Operations.CompositeOperationBuilder> composite = new HashMap<>();\n for (ModelNode step : serverOp.get(STEPS).asList()) {\n ModelNode newStep = step.clone();\n String groupName = PathAddress.pathAddress(step.get(OP_ADDR)).getElement(0).getValue();\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n Set<ServerIdentity> servers = getServersForGroup(groupName, host, localHostName, serverProxies);\n for(ServerIdentity server : servers) {\n if(!composite.containsKey(server)) {\n composite.put(server, Operations.CompositeOperationBuilder.create());\n }\n composite.get(server).addStep(newStep);\n }\n if(!servers.isEmpty()) {\n newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());\n }\n }\n if(!composite.isEmpty()) {\n Map<Set<ServerIdentity>, ModelNode> result = new HashMap<>();\n for(Entry<ServerIdentity, Operations.CompositeOperationBuilder> entry : composite.entrySet()) {\n result.put(Collections.singleton(entry.getKey()), entry.getValue().build().getOperation());\n }\n return result;\n }\n return Collections.emptyMap();\n }\n final Set<ServerIdentity> allServers = getAllRunningServers(host, localHostName, serverProxies);\n return Collections.singletonMap(allServers, operation.clone());\n }", "private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }", "public void bootstrap() throws Exception {\n final HostRunningModeControl runningModeControl = environment.getRunningModeControl();\n final ControlledProcessState processState = new ControlledProcessState(true);\n shutdownHook.setControlledProcessState(processState);\n ServiceTarget target = serviceContainer.subTarget();\n ControlledProcessStateService controlledProcessStateService = ControlledProcessStateService.addService(target, processState).getValue();\n RunningStateJmx.registerMBean(controlledProcessStateService, null, runningModeControl, false);\n final HostControllerService hcs = new HostControllerService(environment, runningModeControl, authCode, processState);\n target.addService(HostControllerService.HC_SERVICE_NAME, hcs).install();\n }" ]
Logs all properties
[ "public void print() {\n Iterator<String> iter = getKeys();\n while (iter.hasNext()) {\n String key = iter.next();\n log.info(key + \" = \" + getRawString(key));\n }\n }" ]
[ "protected String getBasePath(String rootPath) {\r\n\r\n if (rootPath.endsWith(INHERITANCE_CONFIG_FILE_NAME)) {\r\n return rootPath.substring(0, rootPath.length() - INHERITANCE_CONFIG_FILE_NAME.length());\r\n }\r\n return rootPath;\r\n }", "private void readProjectProperties(Project project) throws MPXJException\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n\n properties.setCompany(project.getCompany());\n properties.setManager(project.getManager());\n properties.setName(project.getName());\n properties.setStartDate(getDateTime(project.getProjectStart()));\n }", "public static base_response update(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser updateresource = new systemuser();\n\t\tupdateresource.username = resource.username;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.externalauth = resource.externalauth;\n\t\tupdateresource.promptstring = resource.promptstring;\n\t\tupdateresource.timeout = resource.timeout;\n\t\treturn updateresource.update_resource(client);\n\t}", "public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) {\n assertNumericArgument(timeout, true);\n this.requestTimeout = unit.toMillis(timeout);\n return this;\n }", "public ManageableCollection getCollectionByQuery(Class collectionClass, Query query)\n throws PersistenceBrokerException\n {\n return referencesBroker.getCollectionByQuery(collectionClass, query, false);\n }", "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(required = false) String friendlyName) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n // make sure client with this name does not already exist\n if (null != clientService.findClientFromFriendlyName(profileId, friendlyName)) {\n \tthrow new Exception(\"Cannot add client. Friendly name already in use.\");\n }\n \n Client client = clientService.add(profileId);\n\n // set friendly name if it was specified\n if (friendlyName != null) {\n clientService.setFriendlyName(profileId, client.getUUID(), friendlyName);\n client.setFriendlyName(friendlyName);\n }\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", client);\n return valueHash;\n }", "public void startScenario( Class<?> testClass, Method method, List<NamedArgument> arguments ) {\n listener.scenarioStarted( testClass, method, arguments );\n\n if( method.isAnnotationPresent( Pending.class ) ) {\n Pending annotation = method.getAnnotation( Pending.class );\n\n if( annotation.failIfPass() ) {\n failIfPass();\n } else if( !annotation.executeSteps() ) {\n methodInterceptor.disableMethodExecution();\n executeLifeCycleMethods = false;\n }\n suppressExceptions = true;\n } else if( method.isAnnotationPresent( NotImplementedYet.class ) ) {\n NotImplementedYet annotation = method.getAnnotation( NotImplementedYet.class );\n\n if( annotation.failIfPass() ) {\n failIfPass();\n } else if( !annotation.executeSteps() ) {\n methodInterceptor.disableMethodExecution();\n executeLifeCycleMethods = false;\n }\n suppressExceptions = true;\n }\n\n }", "public static final int getInt(InputStream is) throws IOException\n {\n byte[] data = new byte[4];\n is.read(data);\n return getInt(data, 0);\n }", "@RequestMapping(value = \"api/edit/repeatNumber\", method = RequestMethod.POST)\n public\n @ResponseBody\n String updateRepeatNumber(Model model, int newNum, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n logger.info(\"want to update repeat number of path_id={}, to newNum={}\", path_id, newNum);\n editService.updateRepeatNumber(newNum, path_id, clientUUID);\n return null;\n }" ]
Checks if the categoryfolder setting needs to be updated. @return true if the categoryfolder setting needs to be updated
[ "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 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 static boolean isDouble(CharSequence self) {\n try {\n Double.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "protected void addPoint(double time, RandomVariable value, boolean isParameter) {\n\t\tsynchronized (rationalFunctionInterpolationLazyInitLock) {\n\t\t\tif(interpolationEntity == InterpolationEntity.LOG_OF_VALUE_PER_TIME && time == 0) {\n\t\t\t\tboolean containsOne = false; int index=0;\n\t\t\t\tfor(int i = 0; i< value.size(); i++){if(value.get(i)==1.0) {containsOne = true; index=i; break;}}\n\t\t\t\tif(containsOne && isParameter == false) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new IllegalArgumentException(\"The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index\" + index + \").\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tRandomVariable interpolationEntityValue = interpolationEntityFromValue(value, time);\n\n\t\t\tint index = getTimeIndex(time);\n\t\t\tif(index >= 0) {\n\t\t\t\tif(points.get(index).value == interpolationEntityValue) {\n\t\t\t\t\treturn;\t\t\t// Already in list\n\t\t\t\t} else if(isParameter) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new RuntimeException(\"Trying to add a value for a time for which another value already exists.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Insert the new point, retain ordering.\n\t\t\t\tPoint point = new Point(time, interpolationEntityValue, isParameter);\n\t\t\t\tpoints.add(-index-1, point);\n\n\t\t\t\tif(isParameter) {\n\t\t\t\t\t// Add this point also to the list of parameters\n\t\t\t\t\tint parameterIndex = getParameterIndex(time);\n\t\t\t\t\tif(parameterIndex >= 0) {\n\t\t\t\t\t\tnew RuntimeException(\"CurveFromInterpolationPoints inconsistent.\");\n\t\t\t\t\t}\n\t\t\t\t\tpointsBeingParameters.add(-parameterIndex-1, point);\n\t\t\t\t}\n\t\t\t}\n\t\t\trationalFunctionInterpolation = null;\n\t\t\tcurveCacheReference = null;\n\t\t}\n\t}", "private TaskField getTaskField(int field)\n {\n TaskField result = MPPTaskField14.getInstance(field);\n\n if (result != null)\n {\n switch (result)\n {\n case START_TEXT:\n {\n result = TaskField.START;\n break;\n }\n\n case FINISH_TEXT:\n {\n result = TaskField.FINISH;\n break;\n }\n\n case DURATION_TEXT:\n {\n result = TaskField.DURATION;\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n return result;\n }", "public boolean containsNonZeroHosts(IPAddressSection other) {\n\t\tif(!other.isPrefixed()) {\n\t\t\treturn contains(other);\n\t\t}\n\t\tint otherPrefixLength = other.getNetworkPrefixLength();\n\t\tif(otherPrefixLength == other.getBitCount()) {\n\t\t\treturn contains(other);\n\t\t}\n\t\treturn containsNonZeroHostsImpl(other, otherPrefixLength);\n\t}", "public static cmppolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_policybinding_binding obj = new cmppolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_policybinding_binding response[] = (cmppolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public int getHistoryCount(int profileId, String clientUUID, HashMap<String, String[]> searchFilter) {\n int count = 0;\n Statement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n\n sqlQuery += \";\";\n\n logger.info(\"Query: {}\", sqlQuery);\n\n query = sqlConnection.createStatement();\n results = query.executeQuery(sqlQuery);\n if (results.next()) {\n count = results.getInt(1);\n }\n query.close();\n } catch (Exception e) {\n\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 return count;\n }", "public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {\n if (nodeList == null || nodeList.getLength() == 0) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }", "public TFuture<JsonResponse<AdvertiseResponse>> advertise() {\n\n final AdvertiseRequest advertiseRequest = new AdvertiseRequest();\n advertiseRequest.addService(service, 0);\n\n // TODO: options for hard fail, retries etc.\n final JsonRequest<AdvertiseRequest> request = new JsonRequest.Builder<AdvertiseRequest>(\n HYPERBAHN_SERVICE_NAME,\n HYPERBAHN_ADVERTISE_ENDPOINT\n )\n .setBody(advertiseRequest)\n .setTimeout(REQUEST_TIMEOUT)\n .setRetryLimit(4)\n .build();\n\n final TFuture<JsonResponse<AdvertiseResponse>> future = hyperbahnChannel.send(request);\n future.addCallback(new TFutureCallback<JsonResponse<AdvertiseResponse>>() {\n @Override\n public void onResponse(JsonResponse<AdvertiseResponse> response) {\n if (response.isError()) {\n logger.error(\"Failed to advertise to Hyperbahn: {} - {}\",\n response.getError().getErrorType(),\n response.getError().getMessage());\n }\n\n if (destroyed.get()) {\n return;\n }\n\n scheduleAdvertise();\n }\n });\n\n return future;\n }" ]
Return a licenses view of the targeted module @param moduleId String @return List<DbLicense>
[ "public List<DbLicense> getModuleLicenses(final String moduleId,\n final LicenseMatcher licenseMatcher) {\n final DbModule module = getModule(moduleId);\n\n final List<DbLicense> licenses = new ArrayList<>();\n final FiltersHolder filters = new FiltersHolder();\n final ArtifactHandler artifactHandler = new ArtifactHandler(repositoryHandler, licenseMatcher);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n licenses.addAll(artifactHandler.getArtifactLicenses(gavc, filters));\n }\n\n return licenses;\n }" ]
[ "private void RunScript(InteractiveObject interactiveObject, String functionName, Object[] parameters) {\n boolean complete = false;\n if ( V8JavaScriptEngine) {\n GVRJavascriptV8File gvrJavascriptV8File = interactiveObject.getScriptObject().getGVRJavascriptV8File();\n String paramString = \"var params =[\";\n for (int i = 0; i < parameters.length; i++ ) {\n paramString += (parameters[i] + \", \");\n }\n paramString = paramString.substring(0, (paramString.length()-2)) + \"];\";\n\n final GVRJavascriptV8File gvrJavascriptV8FileFinal = gvrJavascriptV8File;\n final InteractiveObject interactiveObjectFinal = interactiveObject;\n final String functionNameFinal = functionName;\n final Object[] parametersFinal = parameters;\n final String paramStringFinal = paramString;\n gvrContext.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n RunScriptThread (gvrJavascriptV8FileFinal, interactiveObjectFinal, functionNameFinal, parametersFinal, paramStringFinal);\n }\n });\n } // end V8JavaScriptEngine\n else {\n // Mozilla Rhino engine\n GVRJavascriptScriptFile gvrJavascriptFile = interactiveObject.getScriptObject().getGVRJavascriptScriptFile();\n\n complete = gvrJavascriptFile.invokeFunction(functionName, parameters);\n if (complete) {\n // The JavaScript (JS) ran. Now get the return\n // values (saved as X3D data types such as SFColor)\n // stored in 'localBindings'.\n // Then call SetResultsFromScript() to set the GearVR values\n Bindings localBindings = gvrJavascriptFile.getLocalBindings();\n SetResultsFromScript(interactiveObject, localBindings);\n } else {\n Log.e(TAG, \"Error in SCRIPT node '\" + interactiveObject.getScriptObject().getName() +\n \"' running Rhino Engine JavaScript function '\" + functionName + \"'\");\n }\n }\n }", "private static X509Certificate getReqSigCert(Message message) {\n\t\tList<WSHandlerResult> results = \n CastUtils.cast((List<?>)\n message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));\n\n if (results == null) {\n \treturn null;\n }\n \n /*\n\t\t * Scan the results for a matching actor. Use results only if the\n\t\t * receiving Actor and the sending Actor match.\n\t\t */\n\t\tfor (WSHandlerResult rResult : results) {\n\t\t\tList<WSSecurityEngineResult> wsSecEngineResults = rResult\n\t\t\t\t\t.getResults();\n\t\t\t/*\n\t\t\t * Scan the results for the first Signature action. Use the\n\t\t\t * certificate of this Signature to set the certificate for the\n\t\t\t * encryption action :-).\n\t\t\t */\n\t\t\tfor (WSSecurityEngineResult wser : wsSecEngineResults) {\n\t\t\t\tInteger actInt = (Integer) wser\n\t\t\t\t\t\t.get(WSSecurityEngineResult.TAG_ACTION);\n\t\t\t\tif (actInt.intValue() == WSConstants.SIGN) {\n\t\t\t\t\treturn (X509Certificate) wser\n\t\t\t\t\t\t\t.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher cancelPendingRequests() {\n if (pendingRequests.size() != 0) {\n for (int i = 0; i < pendingRequests.size(); i++) {\n int reqId = pendingRequests.keyAt(i);\n Request r = pendingRequests.valueAt(i);\n if (!r.isFinished() && !r.isCancelled()) {\n cancelRequest(r, reqId);\n }\n }\n }\n return this;\n }", "public void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs);\n recordSyncOpTimeNs(null, opTimeNs);\n } else {\n this.syncOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }", "public synchronized Widget measureChild(final int dataIndex, boolean calculateOffset) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"measureChild dataIndex = %d\", dataIndex);\n\n Widget widget = mContainer.get(dataIndex);\n if (widget != null) {\n synchronized (mMeasuredChildren) {\n mMeasuredChildren.add(dataIndex);\n }\n }\n return widget;\n }", "public static CombinedInterceptorAndDecoratorStackMethodHandler peekIfNotEmpty() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n return null;\n }\n return stack.peek();\n }", "public RandomVariable getValues(double evaluationTime, LIBORMarketModel model) {\n\t\tif(evaluationTime > 0) {\n\t\t\tthrow new RuntimeException(\"Forward start evaluation currently not supported.\");\n\t\t}\n\n\t\t// Fetch the covariance model of the model\n\t\tLIBORCovarianceModel covarianceModel = model.getCovarianceModel();\n\n\t\t// We sum over all forward rates\n\t\tint numberOfComponents = covarianceModel.getLiborPeriodDiscretization().getNumberOfTimeSteps();\n\n\t\t// Accumulator\n\t\tRandomVariable\tintegratedLIBORCurvature\t= new RandomVariableFromDoubleArray(0.0);\n\t\tfor(int componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) {\n\n\t\t\t// Integrate from 0 up to the fixing of the rate\n\t\t\tdouble timeEnd\t\t= covarianceModel.getLiborPeriodDiscretization().getTime(componentIndex);\n\t\t\tint timeEndIndex\t= covarianceModel.getTimeDiscretization().getTimeIndex(timeEnd);\n\n\t\t\t// If timeEnd is not in the time discretization we get timeEndIndex = -insertionPoint-1. In that case, we use the index prior to the insertionPoint\n\t\t\tif(timeEndIndex < 0) {\n\t\t\t\ttimeEndIndex = -timeEndIndex - 2;\n\t\t\t}\n\n\t\t\t// Sum squared second derivative of the variance for all components at this time step\n\t\t\tRandomVariable integratedLIBORCurvatureCurrentRate = new RandomVariableFromDoubleArray(0.0);\n\t\t\tfor(int timeIndex = 0; timeIndex < timeEndIndex-2; timeIndex++) {\n\t\t\t\tdouble timeStep1\t= covarianceModel.getTimeDiscretization().getTimeStep(timeIndex);\n\t\t\t\tdouble timeStep2\t= covarianceModel.getTimeDiscretization().getTimeStep(timeIndex+1);\n\n\t\t\t\tRandomVariable covarianceLeft\t\t= covarianceModel.getCovariance(timeIndex+0, componentIndex, componentIndex, null);\n\t\t\t\tRandomVariable covarianceCenter\t= covarianceModel.getCovariance(timeIndex+1, componentIndex, componentIndex, null);\n\t\t\t\tRandomVariable covarianceRight\t\t= covarianceModel.getCovariance(timeIndex+2, componentIndex, componentIndex, null);\n\n\t\t\t\t// Calculate second derivative\n\t\t\t\tRandomVariable curvatureSquared = covarianceRight.sub(covarianceCenter.mult(2.0)).add(covarianceLeft);\n\t\t\t\tcurvatureSquared = curvatureSquared.div(timeStep1 * timeStep2);\n\n\t\t\t\t// Take square\n\t\t\t\tcurvatureSquared = curvatureSquared.squared();\n\n\t\t\t\t// Integrate over time\n\t\t\t\tintegratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.add(curvatureSquared.mult(timeStep1));\n\t\t\t}\n\n\t\t\t// Empty intervall - skip\n\t\t\tif(timeEnd == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Average over time\n\t\t\tintegratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.div(timeEnd);\n\n\t\t\t// Take square root\n\t\t\tintegratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.sqrt();\n\n\t\t\t// Take max over all forward rates\n\t\t\tintegratedLIBORCurvature = integratedLIBORCurvature.add(integratedLIBORCurvatureCurrentRate);\n\t\t}\n\n\t\tintegratedLIBORCurvature = integratedLIBORCurvature.div(numberOfComponents);\n\t\treturn integratedLIBORCurvature.sub(tolerance).floor(0.0);\n\t}", "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 PhotoList<Photo> getContactsPhotos(int count, boolean justFriends, boolean singlePhoto, boolean includeSelf) 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_CONTACTS_PHOTOS);\r\n\r\n if (count > 0) {\r\n parameters.put(\"count\", Integer.toString(count));\r\n }\r\n if (justFriends) {\r\n parameters.put(\"just_friends\", \"1\");\r\n }\r\n if (singlePhoto) {\r\n parameters.put(\"single_photo\", \"1\");\r\n }\r\n if (includeSelf) {\r\n parameters.put(\"include_self\", \"1\");\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 NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n photos.setPage(\"1\");\r\n photos.setPages(\"1\");\r\n photos.setPerPage(\"\" + photoNodes.getLength());\r\n photos.setTotal(\"\" + photoNodes.getLength());\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }" ]
Find the current active layout. @param phoenixProject phoenix project data @return current active layout
[ "private Layout getActiveLayout(Project phoenixProject)\n {\n //\n // Start with the first layout we find\n //\n Layout activeLayout = phoenixProject.getLayouts().getLayout().get(0);\n\n //\n // If this isn't active, find one which is... and if none are,\n // we'll just use the first.\n //\n if (!activeLayout.isActive().booleanValue())\n {\n for (Layout layout : phoenixProject.getLayouts().getLayout())\n {\n if (layout.isActive().booleanValue())\n {\n activeLayout = layout;\n break;\n }\n }\n }\n\n return activeLayout;\n }" ]
[ "public static AnalysisResult fakeSuccess() {\n return new AnalysisResult(null, new Extensions(Collections.emptyMap(), Collections.emptyMap(),\n Collections.emptyMap(), Collections.emptyMap()));\n }", "public void transform(DataPipe cr) {\n Map<String, String> map = cr.getDataMap();\n\n for (String key : map.keySet()) {\n String value = map.get(key);\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n map.put(key, String.valueOf(ran));\n } else if (value.equals(\"#{divideBy2}\")) {\n String i = map.get(\"var_out_V3\");\n String result = String.valueOf(Integer.valueOf(i) / 2);\n map.put(key, result);\n }\n }\n }", "protected boolean determineFeatureState(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, boolean defaultState) {\n final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration());\n final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue);\n final Object value = expression.execute(context);\n if (value != null) {\n return isFeatureActive(value.toString());\n }\n else {\n return defaultState;\n }\n }", "public void get( int row , int col , Complex_F64 output ) {\n ops.get(mat,row,col,output);\n }", "public Set<String> getSupportedUriSchemes() {\n Set<String> schemes = new HashSet<>();\n\n for (ConfigFileLoaderPlugin loaderPlugin: this.getLoaderPlugins()) {\n schemes.add(loaderPlugin.getUriScheme());\n }\n\n return schemes;\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}", "public static <T extends CharSequence> T eachMatch(T self, CharSequence regex, @ClosureParams(value=FromString.class, options={\"List<String>\",\"String[]\"}) Closure closure) {\n eachMatch(self.toString(), regex.toString(), closure);\n return self;\n }", "@Override\n public boolean parseAndValidateRequest() {\n boolean result = false;\n if(!super.parseAndValidateRequest() || !hasVectorClock(this.isVectorClockOptional)\n || !hasContentLength() || !hasContentType()) {\n result = false;\n } else {\n result = true;\n }\n\n return result;\n }", "public Weld extensions(Extension... extensions) {\n this.extensions.clear();\n for (Extension extension : extensions) {\n addExtension(extension);\n }\n return this;\n }" ]
Read the header from the Phoenix file. @param stream input stream @return raw header data
[ "private String readHeaderString(BufferedInputStream stream) throws IOException\n {\n int bufferSize = 100;\n stream.mark(bufferSize);\n byte[] buffer = new byte[bufferSize];\n stream.read(buffer);\n Charset charset = CharsetHelper.UTF8;\n String header = new String(buffer, charset);\n int prefixIndex = header.indexOf(\"PPX!!!!|\");\n int suffixIndex = header.indexOf(\"|!!!!XPP\");\n\n if (prefixIndex != 0 || suffixIndex == -1)\n {\n throw new IOException(\"File format not recognised\");\n }\n\n int skip = suffixIndex + 9;\n stream.reset();\n stream.skip(skip);\n\n return header.substring(prefixIndex + 8, suffixIndex);\n }" ]
[ "public static boolean hasPermission(Permission permission) {\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n try {\n security.checkPermission(permission);\n } catch (java.security.AccessControlException e) {\n return false;\n }\n }\n return true;\n }", "public static void deleteSilentlyRecursively(final Path path) {\n if (path != null) {\n try {\n deleteRecursively(path);\n } catch (IOException ioex) {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(ioex, path);\n }\n }\n }", "protected MethodVisitor makeDelegateCall(final String name, final String desc, final String signature, final String[] exceptions, final int accessFlags) {\n MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions);\n mv.visitVarInsn(ALOAD, 0); // load this\n mv.visitFieldInsn(GETFIELD, proxyName, DELEGATE_OBJECT_FIELD, BytecodeHelper.getTypeDescription(delegateClass)); // load delegate\n // using InvokerHelper to allow potential intercepted calls\n int size;\n mv.visitLdcInsn(name); // method name\n Type[] args = Type.getArgumentTypes(desc);\n BytecodeHelper.pushConstant(mv, args.length);\n mv.visitTypeInsn(ANEWARRAY, \"java/lang/Object\");\n size = 6;\n int idx = 1;\n for (int i = 0; i < args.length; i++) {\n Type arg = args[i];\n mv.visitInsn(DUP);\n BytecodeHelper.pushConstant(mv, i);\n // primitive types must be boxed\n if (isPrimitive(arg)) {\n mv.visitIntInsn(getLoadInsn(arg), idx);\n String wrappedType = getWrappedClassDescriptor(arg);\n mv.visitMethodInsn(INVOKESTATIC, wrappedType, \"valueOf\", \"(\" + arg.getDescriptor() + \")L\" + wrappedType + \";\", false);\n } else {\n mv.visitVarInsn(ALOAD, idx); // load argument i\n }\n size = Math.max(size, 5+registerLen(arg));\n idx += registerLen(arg);\n mv.visitInsn(AASTORE); // store value into array\n }\n mv.visitMethodInsn(INVOKESTATIC, \"org/codehaus/groovy/runtime/InvokerHelper\", \"invokeMethod\", \"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;\", false);\n unwrapResult(mv, desc);\n mv.visitMaxs(size, registerLen(args) + 1);\n\n return mv;\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 static Trajectory resample(Trajectory t, int n){\n\t\tTrajectory t1 = new Trajectory(2);\n\t\t\n\t\tfor(int i = 0; i < t.size(); i=i+n){\n\t\t\tt1.add(t.get(i));\n\t\t}\n\t\t\n\t\treturn t1;\n\t}", "private void postTraversalProcessing() {\n\t\tint nc1 = treeSize;\n\t\tinfo[KR] = new int[leafCount];\n\t\tinfo[RKR] = new int[leafCount];\n\n\t\tint lc = leafCount;\n\t\tint i = 0;\n\n\t\t// compute left-most leaf descendants\n\t\t// go along the left-most path, remember each node and assign to it the path's\n\t\t// leaf\n\t\t// compute right-most leaf descendants (in reversed postorder)\n\t\tfor (i = 0; i < treeSize; i++) {\n\t\t\tif (paths[LEFT][i] == -1) {\n\t\t\t\tinfo[POST2_LLD][i] = i;\n\t\t\t} else {\n\t\t\t\tinfo[POST2_LLD][i] = info[POST2_LLD][paths[LEFT][i]];\n\t\t\t}\n\t\t\tif (paths[RIGHT][i] == -1) {\n\t\t\t\tinfo[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =\n\t\t\t\t\t\t(treeSize - 1 - info[POST2_PRE][i]);\n\t\t\t} else {\n\t\t\t\tinfo[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =\n\t\t\t\t\t\tinfo[RPOST2_RLD][treeSize - 1\n\t\t\t\t\t\t\t\t- info[POST2_PRE][paths[RIGHT][i]]];\n\t\t\t}\n\t\t}\n\n\t\t// compute key root nodes\n\t\t// compute reversed key root nodes (in revrsed postorder)\n\t\tboolean[] visited = new boolean[nc1];\n\t\tboolean[] visitedR = new boolean[nc1];\n\t\tArrays.fill(visited, false);\n\t\tint k = lc - 1;\n\t\tint kR = lc - 1;\n\t\tfor (i = nc1 - 1; i >= 0; i--) {\n\t\t\tif (!visited[info[POST2_LLD][i]]) {\n\t\t\t\tinfo[KR][k] = i;\n\t\t\t\tvisited[info[POST2_LLD][i]] = true;\n\t\t\t\tk--;\n\t\t\t}\n\t\t\tif (!visitedR[info[RPOST2_RLD][i]]) {\n\t\t\t\tinfo[RKR][kR] = i;\n\t\t\t\tvisitedR[info[RPOST2_RLD][i]] = true;\n\t\t\t\tkR--;\n\t\t\t}\n\t\t}\n\n\t\t// compute minimal key roots for every subtree\n\t\t// compute minimal reversed key roots for every subtree (in reversed postorder)\n\t\tint parent = -1;\n\t\tint parentR = -1;\n\t\tfor (i = 0; i < leafCount; i++) {\n\t\t\tparent = info[KR][i];\n\t\t\twhile (parent > -1 && info[POST2_MIN_KR][parent] == -1) {\n\t\t\t\tinfo[POST2_MIN_KR][parent] = i;\n\t\t\t\tparent = info[POST2_PARENT][parent];\n\t\t\t}\n\t\t\tparentR = info[RKR][i];\n\t\t\twhile (parentR > -1 && info[RPOST2_MIN_RKR][parentR] == -1) {\n\t\t\t\tinfo[RPOST2_MIN_RKR][parentR] = i;\n\t\t\t\tparentR =\n\t\t\t\t\t\tinfo[POST2_PARENT][info[RPOST2_POST][parentR]]; // get parent's postorder\n\t\t\t\tif (parentR > -1) {\n\t\t\t\t\tparentR = treeSize - 1 - info[POST2_PRE][parentR]; // if parent exists get its\n\t\t\t\t\t// rev. postorder\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "@Override\n public void put(ByteArray keyBytes, Versioned<byte[]> valueBytes, byte[] transforms)\n throws VoldemortException {\n // acquire write lock\n writeLock.lock();\n try {\n String key = ByteUtils.getString(keyBytes.get(), \"UTF-8\");\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n\n Versioned<Object> valueObject = convertStringToObject(key, value);\n\n this.put(key, valueObject);\n } finally {\n writeLock.unlock();\n }\n }", "public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) {\r\n String[] coVariables = action.getCoVariables().split(\",\");\r\n int n = Integer.valueOf(action.getN());\n\r\n List<Map<String, String>> newPossibleStateList = new ArrayList<>();\n\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n Map<String, String[]> variableDomains = new HashMap<>();\r\n Map<String, String> defaultVariableValues = new HashMap<>();\r\n for (String variable : coVariables) {\r\n String variableMetaInfo = possibleState.get(variable);\r\n String[] variableDomain = variableMetaInfo.split(\",\");\r\n variableDomains.put(variable, variableDomain);\r\n defaultVariableValues.put(variable, variableDomain[0]);\r\n }\n\r\n List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains);\r\n for (Map<String, String> nWiseCombination : nWiseCombinations) {\r\n Map<String, String> newPossibleState = new HashMap<>(possibleState);\r\n newPossibleState.putAll(defaultVariableValues);\r\n newPossibleState.putAll(nWiseCombination);\r\n newPossibleStateList.add(newPossibleState);\r\n }\r\n }\n\r\n return newPossibleStateList;\r\n }", "public static ClassNode getWrapper(ClassNode cn) {\n cn = cn.redirect();\n if (!isPrimitiveType(cn)) return cn;\n if (cn==boolean_TYPE) {\n return Boolean_TYPE;\n } else if (cn==byte_TYPE) {\n return Byte_TYPE;\n } else if (cn==char_TYPE) {\n return Character_TYPE;\n } else if (cn==short_TYPE) {\n return Short_TYPE;\n } else if (cn==int_TYPE) {\n return Integer_TYPE;\n } else if (cn==long_TYPE) {\n return Long_TYPE;\n } else if (cn==float_TYPE) {\n return Float_TYPE;\n } else if (cn==double_TYPE) {\n return Double_TYPE;\n } else if (cn==VOID_TYPE) {\n return void_WRAPPER_TYPE;\n }\n else {\n return cn;\n }\n }" ]
Use this API to fetch all the autoscaleprofile resources that are configured on netscaler.
[ "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 ItemRequest<CustomField> update(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"PUT\");\n }", "static Locale getLocale(PageContext pageContext, String name) {\r\n\r\n Locale loc = null;\r\n\r\n Object obj = javax.servlet.jsp.jstl.core.Config.find(pageContext, name);\r\n if (obj != null) {\r\n if (obj instanceof Locale) {\r\n loc = (Locale)obj;\r\n } else {\r\n loc = SetLocaleSupport.parseLocale((String)obj);\r\n }\r\n }\r\n\r\n return loc;\r\n }", "private ArrayList<RunListener> instantiateRunListeners() throws Exception {\n ArrayList<RunListener> instances = new ArrayList<>();\n\n if (runListeners != null) {\n for (String className : Arrays.asList(runListeners.split(\",\"))) {\n instances.add((RunListener) this.instantiate(className).newInstance());\n }\n }\n\n return instances;\n }", "public static void closeWithWarning(Closeable c) {\n if (c != null) {\n try {\n c.close();\n } catch (IOException e) {\n LOG.warning(\"Caught exception during close(): \" + e);\n }\n }\n }", "public void setStatusBarColor(int statusBarColor) {\n if (mBuilder.mScrimInsetsLayout != null) {\n mBuilder.mScrimInsetsLayout.setInsetForeground(statusBarColor);\n mBuilder.mScrimInsetsLayout.getView().invalidate();\n }\n }", "public static BufferedImage createImage(ImageProducer producer) {\n\t\tPixelGrabber pg = new PixelGrabber(producer, 0, 0, -1, -1, null, 0, 0);\n\t\ttry {\n\t\t\tpg.grabPixels();\n\t\t} catch (InterruptedException e) {\n\t\t\tthrow new RuntimeException(\"Image fetch interrupted\");\n\t\t}\n\t\tif ((pg.status() & ImageObserver.ABORT) != 0)\n\t\t\tthrow new RuntimeException(\"Image fetch aborted\");\n\t\tif ((pg.status() & ImageObserver.ERROR) != 0)\n\t\t\tthrow new RuntimeException(\"Image fetch error\");\n\t\tBufferedImage p = new BufferedImage(pg.getWidth(), pg.getHeight(), BufferedImage.TYPE_INT_ARGB);\n\t\tp.setRGB(0, 0, pg.getWidth(), pg.getHeight(), (int[])pg.getPixels(), 0, pg.getWidth());\n\t\treturn p;\n\t}", "private Double getPercentage(Number number)\n {\n Double result = null;\n\n if (number != null)\n {\n result = Double.valueOf(number.doubleValue() / 100);\n }\n\n return result;\n }", "private static String get(Properties p, String key, String defaultValue, Set<String> used){\r\n String rtn = p.getProperty(key, defaultValue);\r\n used.add(key);\r\n return rtn;\r\n }", "public NodeInfo getNode(String name) {\n final URI uri = uriWithPath(\"./nodes/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, NodeInfo.class);\n }" ]
Plots the MSD curve for trajectory t. @param t List of trajectories @param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds @param lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds
[ "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax) {\n\t\treturn getMSDLineChart(t, lagMin, lagMax, new MeanSquaredDisplacmentFeature(t,\n\t\t\t\tlagMin));\n\t}" ]
[ "public boolean matches(PathAddress address) {\n if (address == null) {\n return false;\n }\n if (equals(address)) {\n return true;\n }\n if (size() != address.size()) {\n return false;\n }\n for (int i = 0; i < size(); i++) {\n PathElement pe = getElement(i);\n PathElement other = address.getElement(i);\n if (!pe.matches(other)) {\n // Could be a multiTarget with segments\n if (pe.isMultiTarget() && !pe.isWildcard()) {\n boolean matched = false;\n for (String segment : pe.getSegments()) {\n if (segment.equals(other.getValue())) {\n matched = true;\n break;\n }\n }\n if (!matched) {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n return true;\n }", "public static nstrafficdomain_bridgegroup_binding[] get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Map<Integer, Row> createWorkPatternMap(List<Row> rows)\n {\n Map<Integer, Row> map = new HashMap<Integer, Row>();\n for (Row row : rows)\n {\n map.put(row.getInteger(\"WORK_PATTERNID\"), row);\n }\n return map;\n }", "@Override\n public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener,\n Throwable error) {\n //listener.getLogger().println(\"[MavenDependenciesRecorder] mojo: \" + mojo.getClass() + \":\" + mojo.getGoal());\n //listener.getLogger().println(\"[MavenDependenciesRecorder] dependencies: \" + pom.getArtifacts());\n recordMavenDependencies(pom.getArtifacts());\n return true;\n }", "private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"classes.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\t// Add direct subclass information:\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Integer superClass : classEntry.getValue().directSuperClasses) {\n\t\t\t\t\tthis.classRecords.get(superClass).nonemptyDirectSubclasses\n\t\t\t\t\t\t\t.add(classEntry.getKey().toString());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint count = 0;\n\t\t\tint countNoLabel = 0;\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (classEntry.getValue().label == null) {\n\t\t\t\t\tcountNoLabel++;\n\t\t\t\t}\n\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + classEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, classEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" class items.\");\n\t\t\tSystem.out.println(\" -- class items with missing label: \"\n\t\t\t\t\t+ countNoLabel);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "private static String wordShapeDan2Bio(String s, Collection<String> knownLCWords) {\r\n if (containsGreekLetter(s)) {\r\n return wordShapeDan2(s, knownLCWords) + \"-GREEK\";\r\n } else {\r\n return wordShapeDan2(s, knownLCWords);\r\n }\r\n }", "public void setNamespace(String prefix, String namespaceURI) {\n ensureNotNull(\"Prefix\", prefix);\n ensureNotNull(\"Namespace URI\", namespaceURI);\n\n namespaces.put(prefix, namespaceURI);\n }", "public String getHiveExecutionEngine() {\n String executionEngine = hiveConfSystemOverride.get(HiveConf.ConfVars.HIVE_EXECUTION_ENGINE.varname);\n return executionEngine == null ? HiveConf.ConfVars.HIVE_EXECUTION_ENGINE.getDefaultValue() : executionEngine;\n }", "public final ProcessorDependencyGraph getProcessorGraph() {\n if (this.processorGraph == null) {\n synchronized (this) {\n if (this.processorGraph == null) {\n final Map<String, Class<?>> attcls = new HashMap<>();\n for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {\n attcls.put(attribute.getKey(), attribute.getValue().getValueType());\n }\n this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);\n }\n }\n }\n return this.processorGraph;\n }" ]
Retrieve a calendar exception which applies to this date. @param date target date @return calendar exception, or null if none match this date
[ "public ProjectCalendarException getException(Date date)\n {\n ProjectCalendarException exception = null;\n\n // We're working with expanded exceptions, which includes any recurring exceptions\n // expanded into individual entries.\n populateExpandedExceptions();\n if (!m_expandedExceptions.isEmpty())\n {\n sortExceptions();\n\n int low = 0;\n int high = m_expandedExceptions.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarException midVal = m_expandedExceptions.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getFromDate(), midVal.getToDate(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n exception = midVal;\n break;\n }\n }\n }\n }\n\n if (exception == null && getParent() != null)\n {\n // Check base calendar as well for an exception.\n exception = getParent().getException(date);\n }\n return (exception);\n }" ]
[ "static ReadMasterDomainModelUtil readMasterDomainResourcesForInitialConnect(final Transformers transformers,\n final Transformers.TransformationInputs transformationInputs,\n final Transformers.ResourceIgnoredTransformationRegistry ignoredTransformationRegistry,\n final Resource domainRoot) throws OperationFailedException {\n\n Resource transformedResource = transformers.transformRootResource(transformationInputs, domainRoot, ignoredTransformationRegistry);\n ReadMasterDomainModelUtil util = new ReadMasterDomainModelUtil();\n util.describedResources = util.describeAsNodeList(PathAddress.EMPTY_ADDRESS, transformedResource, false);\n return util;\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 DynamicReportBuilder setColspan(int colNumber, int colQuantity, String colspanTitle) {\n this.setColspan(colNumber, colQuantity, colspanTitle, null);\n\n return this;\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 String setClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = null;\n\n try {\n classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, \"enterprise\", metadata);\n } catch (BoxAPIException e) {\n if (e.getResponseCode() == 409) {\n metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType);\n classification = this.updateMetadata(metadata);\n } else {\n throw e;\n }\n }\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }", "public static vpnvserver_vpnnexthopserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_vpnnexthopserver_binding obj = new vpnvserver_vpnnexthopserver_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_vpnnexthopserver_binding response[] = (vpnvserver_vpnnexthopserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static List<RebalanceTaskInfo> filterTaskPlanWithStores(List<RebalanceTaskInfo> existingPlanList,\n List<StoreDefinition> storeDefs) {\n List<RebalanceTaskInfo> plans = Lists.newArrayList();\n List<String> storeNames = StoreDefinitionUtils.getStoreNames(storeDefs);\n\n for(RebalanceTaskInfo existingPlan: existingPlanList) {\n RebalanceTaskInfo info = RebalanceTaskInfo.create(existingPlan.toJsonString());\n\n // Filter the plans only for stores given\n HashMap<String, List<Integer>> storeToPartitions = info.getStoreToPartitionIds();\n\n HashMap<String, List<Integer>> newStoreToPartitions = Maps.newHashMap();\n for(String storeName: storeNames) {\n if(storeToPartitions.containsKey(storeName))\n newStoreToPartitions.put(storeName, storeToPartitions.get(storeName));\n }\n info.setStoreToPartitionList(newStoreToPartitions);\n plans.add(info);\n }\n return plans;\n }", "public static <T> boolean containsAny(Collection<T> collection, Collection<T> toCheck){\r\n for(T c: toCheck){\r\n if(collection.contains(c))\r\n return true;\r\n }\r\n return false;\r\n \r\n }" ]
Converts a tab delimited string into an object with given fields Requires the object has public access for the specified fields @param objClass Class of object to be created @param str string to convert @param delimiterPattern delimiter @param fieldNames fieldnames @param <T> type to return @return Object created from string
[ "public static <T> T columnStringToObject(Class<?> objClass, String str, Pattern delimiterPattern, String[] fieldNames)\r\n throws InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException\r\n {\r\n String[] fields = delimiterPattern.split(str);\r\n T item = ErasureUtils.<T>uncheckedCast(objClass.newInstance());\r\n for (int i = 0; i < fields.length; i++) {\r\n try {\r\n Field field = objClass.getDeclaredField(fieldNames[i]);\r\n field.set(item, fields[i]);\r\n } catch (IllegalAccessException ex) {\r\n Method method = objClass.getDeclaredMethod(\"set\" + StringUtils.capitalize(fieldNames[i]), String.class);\r\n method.invoke(item, fields[i]);\r\n }\r\n }\r\n return item;\r\n }" ]
[ "private static void reallyValidatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager, Set<Object> dependencyPath, Set<Bean<?>> validatedBeans) {\n // see if we have already seen this bean in the dependency path\n if (dependencyPath.contains(bean)) {\n // create a list that shows the path to the bean\n List<Object> realDependencyPath = new ArrayList<Object>(dependencyPath);\n realDependencyPath.add(bean);\n throw ValidatorLogger.LOG.pseudoScopedBeanHasCircularReferences(WeldCollections.toMultiRowString(realDependencyPath));\n }\n if (validatedBeans.contains(bean)) {\n return;\n }\n dependencyPath.add(bean);\n for (InjectionPoint injectionPoint : bean.getInjectionPoints()) {\n if (!injectionPoint.isDelegate()) {\n dependencyPath.add(injectionPoint);\n validatePseudoScopedInjectionPoint(injectionPoint, beanManager, dependencyPath, validatedBeans);\n dependencyPath.remove(injectionPoint);\n }\n }\n if (bean instanceof DecorableBean<?>) {\n final List<Decorator<?>> decorators = Reflections.<DecorableBean<?>>cast(bean).getDecorators();\n if (!decorators.isEmpty()) {\n for (final Decorator<?> decorator : decorators) {\n reallyValidatePseudoScopedBean(decorator, beanManager, dependencyPath, validatedBeans);\n }\n }\n }\n if (bean instanceof AbstractProducerBean<?, ?, ?> && !(bean instanceof EEResourceProducerField<?, ?>)) {\n AbstractProducerBean<?, ?, ?> producer = (AbstractProducerBean<?, ?, ?>) bean;\n if (!beanManager.isNormalScope(producer.getDeclaringBean().getScope()) && !producer.getAnnotated().isStatic()) {\n reallyValidatePseudoScopedBean(producer.getDeclaringBean(), beanManager, dependencyPath, validatedBeans);\n }\n }\n validatedBeans.add(bean);\n dependencyPath.remove(bean);\n }", "public void build(Set<Bean<?>> beans) {\n\n if (isBuilt()) {\n throw new IllegalStateException(\"BeanIdentifier index is already built!\");\n }\n\n if (beans.isEmpty()) {\n index = new BeanIdentifier[0];\n reverseIndex = Collections.emptyMap();\n indexHash = 0;\n indexBuilt.set(true);\n return;\n }\n\n List<BeanIdentifier> tempIndex = new ArrayList<BeanIdentifier>(beans.size());\n\n for (Bean<?> bean : beans) {\n if (bean instanceof CommonBean<?>) {\n tempIndex.add(((CommonBean<?>) bean).getIdentifier());\n } else if (bean instanceof PassivationCapable) {\n tempIndex.add(new StringBeanIdentifier(((PassivationCapable) bean).getId()));\n }\n }\n\n Collections.sort(tempIndex, new Comparator<BeanIdentifier>() {\n @Override\n public int compare(BeanIdentifier o1, BeanIdentifier o2) {\n return o1.asString().compareTo(o2.asString());\n }\n });\n\n index = tempIndex.toArray(new BeanIdentifier[tempIndex.size()]);\n\n ImmutableMap.Builder<BeanIdentifier, Integer> builder = ImmutableMap.builder();\n for (int i = 0; i < index.length; i++) {\n builder.put(index[i], i);\n }\n reverseIndex = builder.build();\n\n indexHash = Arrays.hashCode(index);\n\n if(BootstrapLogger.LOG.isDebugEnabled()) {\n BootstrapLogger.LOG.beanIdentifierIndexBuilt(getDebugInfo());\n }\n indexBuilt.set(true);\n }", "public boolean needMerge(@NotNull final BasePage left, @NotNull final BasePage right) {\n final int leftSize = left.getSize();\n final int rightSize = right.getSize();\n return leftSize == 0 || rightSize == 0 ||\n leftSize + rightSize <= (((isDupTree(left) ? getDupPageMaxSize() : getPageMaxSize()) * 7) >> 3);\n }", "private static void readAndAddDocumentsFromStream(\n final SolrClient client,\n final String lang,\n final InputStream is,\n final List<SolrInputDocument> documents,\n final boolean closeStream) {\n\n final BufferedReader br = new BufferedReader(new InputStreamReader(is));\n\n try {\n String line = br.readLine();\n while (null != line) {\n\n final SolrInputDocument document = new SolrInputDocument();\n // Each field is named after the schema \"entry_xx\" where xx denotes\n // the two digit language code. See the file spellcheck/conf/schema.xml.\n document.addField(\"entry_\" + lang, line);\n documents.add(document);\n\n // Prevent OutOfMemoryExceptions ...\n if (documents.size() >= MAX_LIST_SIZE) {\n addDocuments(client, documents, false);\n documents.clear();\n }\n\n line = br.readLine();\n }\n } catch (IOException e) {\n LOG.error(\"Could not read spellcheck dictionary from input stream.\");\n } catch (SolrServerException e) {\n LOG.error(\"Error while adding documents to Solr server. \");\n } finally {\n try {\n if (closeStream) {\n br.close();\n }\n } catch (Exception e) {\n // Nothing to do here anymore ....\n }\n }\n }", "public Story storyOfPath(Configuration configuration, String storyPath) {\n String storyAsText = configuration.storyLoader().loadStoryAsText(storyPath);\n return configuration.storyParser().parseStory(storyAsText, storyPath);\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 RelatedTagsList getRelated(String tag) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_RELATED);\n\n parameters.put(\"tag\", tag);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element tagsElement = response.getPayload();\n\n RelatedTagsList tags = new RelatedTagsList();\n tags.setSource(tagsElement.getAttribute(\"source\"));\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag t = new Tag();\n t.setValue(XMLUtilities.getValue(tagElement));\n tags.add(t);\n }\n return tags;\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 }", "private int bestSurroundingSet(int index, int length, int... valid) {\r\n int option1 = set[index - 1];\r\n if (index + 1 < length) {\r\n // we have two options to check\r\n int option2 = set[index + 1];\r\n if (contains(valid, option1) && contains(valid, option2)) {\r\n return Math.min(option1, option2);\r\n } else if (contains(valid, option1)) {\r\n return option1;\r\n } else if (contains(valid, option2)) {\r\n return option2;\r\n } else {\r\n return valid[0];\r\n }\r\n } else {\r\n // we only have one option to check\r\n if (contains(valid, option1)) {\r\n return option1;\r\n } else {\r\n return valid[0];\r\n }\r\n }\r\n }" ]
Return fallback if first string is null or empty
[ "public static String defaultString(final String str, final String fallback) {\n return isNullOrEmpty(str) ? fallback : str;\n }" ]
[ "private void calculateSCL(double[] x) {\r\n //System.out.println(\"Checking at: \"+x[0]+\" \"+x[1]+\" \"+x[2]);\r\n value = 0.0;\r\n Arrays.fill(derivative, 0.0);\r\n double[] sums = new double[numClasses];\r\n double[] probs = new double[numClasses];\r\n double[] counts = new double[numClasses];\r\n Arrays.fill(counts, 0.0);\r\n for (int d = 0; d < data.length; d++) {\r\n // if (d == testMin) {\r\n // d = testMax - 1;\r\n // continue;\r\n // }\r\n int[] features = data[d];\r\n // activation\r\n Arrays.fill(sums, 0.0);\r\n for (int c = 0; c < numClasses; c++) {\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n sums[c] += x[i];\r\n }\r\n }\r\n // expectation (slower routine replaced by fast way)\r\n // double total = Double.NEGATIVE_INFINITY;\r\n // for (int c=0; c<numClasses; c++) {\r\n // total = SloppyMath.logAdd(total, sums[c]);\r\n // }\r\n double total = ArrayMath.logSum(sums);\r\n int ld = labels[d];\r\n for (int c = 0; c < numClasses; c++) {\r\n probs[c] = Math.exp(sums[c] - total);\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n derivative[i] += probs[ld] * probs[c];\r\n }\r\n }\r\n // observed\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], labels[d]);\r\n derivative[i] -= probs[ld];\r\n }\r\n value -= probs[ld];\r\n }\r\n // priors\r\n if (true) {\r\n for (int i = 0; i < x.length; i++) {\r\n double k = 1.0;\r\n double w = x[i];\r\n value += k * w * w / 2.0;\r\n derivative[i] += k * w;\r\n }\r\n }\r\n }", "protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n boolean needsCommit = false;\r\n long result = 0;\r\n /*\r\n arminw:\r\n use the associated broker instance, check if broker was in tx or\r\n we need to commit used connection.\r\n */\r\n PersistenceBroker targetBroker = getBrokerForClass();\r\n if(!targetBroker.isInTransaction())\r\n {\r\n targetBroker.beginTransaction();\r\n needsCommit = true;\r\n }\r\n try\r\n {\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n /*\r\n if 0 was returned we assume that the stored procedure\r\n did not work properly.\r\n */\r\n if (result == 0)\r\n {\r\n throw new SequenceManagerException(\"No incremented value retrieved\");\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n // maybe the sequence was not created\r\n log.info(\"Could not grab next key, message was \" + e.getMessage() +\r\n \" - try to write a new sequence entry to database\");\r\n try\r\n {\r\n // on create, make sure to get the max key for the table first\r\n long maxKey = SequenceManagerHelper.getMaxForExtent(targetBroker, field);\r\n createSequence(targetBroker, field, sequenceName, maxKey);\r\n }\r\n catch (Exception e1)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n throw new SequenceManagerException(eol + \"Could not grab next id, failed with \" + eol +\r\n e.getMessage() + eol + \"Creation of new sequence failed with \" +\r\n eol + e1.getMessage() + eol, e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id although a sequence seems to exist\", e);\r\n }\r\n }\r\n }\r\n finally\r\n {\r\n if(targetBroker != null && needsCommit)\r\n {\r\n targetBroker.commitTransaction();\r\n }\r\n }\r\n return result;\r\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 }", "protected InternalHttpResponse sendInternalRequest(HttpRequest request) {\n InternalHttpResponder responder = new InternalHttpResponder();\n httpResourceHandler.handle(request, responder);\n return responder.getResponse();\n }", "private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "private void processClassMethods(XMLStreamWriter writer, Class<?> aClass, Set<Method> methodSet) throws XMLStreamException\n {\n Method[] methods = aClass.getDeclaredMethods();\n for (Method method : methods)\n {\n if (!methodSet.contains(method) && Modifier.isPublic(method.getModifiers()) && !Modifier.isInterface(method.getModifiers()))\n {\n if (Modifier.isStatic(method.getModifiers()))\n {\n // TODO Handle static methods here\n }\n else\n {\n String name = method.getName();\n String methodSignature = createMethodSignature(method);\n String fullJavaName = aClass.getCanonicalName() + \".\" + name + methodSignature;\n\n if (!ignoreMethod(fullJavaName))\n {\n //\n // Hide the original method\n //\n writer.writeStartElement(\"method\");\n writer.writeAttribute(\"name\", name);\n writer.writeAttribute(\"sig\", methodSignature);\n\n writer.writeStartElement(\"attribute\");\n writer.writeAttribute(\"type\", \"System.ComponentModel.EditorBrowsableAttribute\");\n writer.writeAttribute(\"sig\", \"(Lcli.System.ComponentModel.EditorBrowsableState;)V\");\n writer.writeStartElement(\"parameter\");\n writer.writeCharacters(\"Never\");\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndElement();\n\n //\n // Create a wrapper method\n //\n name = name.toUpperCase().charAt(0) + name.substring(1);\n\n writer.writeStartElement(\"method\");\n writer.writeAttribute(\"name\", name);\n writer.writeAttribute(\"sig\", methodSignature);\n writer.writeAttribute(\"modifiers\", \"public\");\n\n writer.writeStartElement(\"body\");\n\n for (int index = 0; index <= method.getParameterTypes().length; index++)\n {\n if (index < 4)\n {\n writer.writeEmptyElement(\"ldarg_\" + index);\n }\n else\n {\n writer.writeStartElement(\"ldarg_s\");\n writer.writeAttribute(\"argNum\", Integer.toString(index));\n writer.writeEndElement();\n }\n }\n\n writer.writeStartElement(\"callvirt\");\n writer.writeAttribute(\"class\", aClass.getName());\n writer.writeAttribute(\"name\", method.getName());\n writer.writeAttribute(\"sig\", methodSignature);\n writer.writeEndElement();\n\n if (!method.getReturnType().getName().equals(\"void\"))\n {\n writer.writeEmptyElement(\"ldnull\");\n writer.writeEmptyElement(\"pop\");\n }\n writer.writeEmptyElement(\"ret\");\n writer.writeEndElement();\n writer.writeEndElement();\n\n /*\n * The private method approach doesn't work... so\n * 3. Add EditorBrowsableAttribute (Never) to original methods\n * 4. Generate C Sharp and VB variants of the DLL to avid case-sensitivity issues\n * 5. Implement static method support?\n <attribute type=\"System.ComponentModel.EditorBrowsableAttribute\" sig=\"(Lcli.System.ComponentModel.EditorBrowsableState;)V\">\n 914 <parameter>Never</parameter>\n 915 </attribute>\n */\n\n m_responseList.add(fullJavaName);\n }\n }\n }\n }\n }", "public void setValue(Vector3f scale) {\n mX = scale.x;\n mY = scale.y;\n mZ = scale.z;\n }", "private static String loadUA(ClassLoader loader, String filename){\n String ua = \"cloudant-http\";\n String version = \"unknown\";\n final InputStream propStream = loader.getResourceAsStream(filename);\n final Properties properties = new Properties();\n try {\n if (propStream != null) {\n try {\n properties.load(propStream);\n } finally {\n propStream.close();\n }\n }\n ua = properties.getProperty(\"user.agent.name\", ua);\n version = properties.getProperty(\"user.agent.version\", version);\n } catch (IOException e) {\n // Swallow exception and use default values.\n }\n\n return String.format(Locale.ENGLISH, \"%s/%s\", ua,version);\n }", "public final void warn(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.WARN, pObject, null);\r\n\t}" ]
Gets the date time str. @param d the d @return the date time str
[ "public static String getDateTimeStr(Date d) {\n if (d == null)\n return \"\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSSZ\");\n // 20140315 test will problem +0000\n return sdf.format(d);\n }" ]
[ "public static nslimitidentifier_stats[] get(nitro_service service) throws Exception{\n\t\tnslimitidentifier_stats obj = new nslimitidentifier_stats();\n\t\tnslimitidentifier_stats[] response = (nslimitidentifier_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "Path resolveBaseDir(final String name, final String dirName) {\n final String currentDir = SecurityActions.getPropertyPrivileged(name);\n if (currentDir == null) {\n return jbossHomeDir.resolve(dirName);\n }\n return Paths.get(currentDir);\n }", "public static void main(String[] args) {\r\n\r\n String[] s = {\"there once was a man\", \"this one is a manic\", \"hey there\", \"there once was a mane\", \"once in a manger.\", \"where is one match?\", \"Jo3seph Smarr!\", \"Joseph R Smarr\"};\r\n for (int i = 0; i < 8; i++) {\r\n for (int j = 0; j < 8; j++) {\r\n System.out.println(\"s1: \" + s[i]);\r\n System.out.println(\"s2: \" + s[j]);\r\n System.out.println(\"edit distance: \" + editDistance(s[i], s[j]));\r\n System.out.println(\"LCS: \" + longestCommonSubstring(s[i], s[j]));\r\n System.out.println(\"LCCS: \" + longestCommonContiguousSubstring(s[i], s[j]));\r\n System.out.println();\r\n }\r\n }\r\n }", "public void setKeywords(final List<String> keywords) {\n StringBuilder builder = new StringBuilder();\n for (String keyword: keywords) {\n if (builder.length() > 0) {\n builder.append(',');\n }\n builder.append(keyword.trim());\n }\n this.keywords = Optional.of(builder.toString());\n }", "private GVRCursorController getUniqueControllerId(int deviceId) {\n GVRCursorController controller = controllerIds.get(deviceId);\n if (controller != null) {\n return controller;\n }\n return null;\n }", "public void setVariable(String name, Object value) {\n if (variables == null)\n variables = new LinkedHashMap();\n variables.put(name, value);\n }", "private double getExpectedProbability(double x)\n {\n double y = 1 / (standardDeviation * Math.sqrt(Math.PI * 2));\n double z = -(Math.pow(x - mean, 2) / (2 * Math.pow(standardDeviation, 2)));\n return y * Math.exp(z);\n }", "private void populateContainer(FieldType field, byte[] values, byte[] descriptions)\n {\n CustomField config = m_container.getCustomField(field);\n CustomFieldLookupTable table = config.getLookupTable();\n\n List<Object> descriptionList = convertType(DataType.STRING, descriptions);\n List<Object> valueList = convertType(field.getDataType(), values);\n for (int index = 0; index < descriptionList.size(); index++)\n {\n CustomFieldValueItem item = new CustomFieldValueItem(Integer.valueOf(0));\n item.setDescription((String) descriptionList.get(index));\n if (index < valueList.size())\n {\n item.setValue(valueList.get(index));\n }\n table.add(item);\n }\n }", "public static Cluster getCluster(ZkClient zkClient) {\n Cluster cluster = new Cluster();\n List<String> nodes = getChildrenParentMayNotExist(zkClient, BrokerIdsPath);\n for (String node : nodes) {\n final String brokerInfoString = readData(zkClient, BrokerIdsPath + \"/\" + node);\n cluster.add(Broker.createBroker(Integer.valueOf(node), brokerInfoString));\n }\n return cluster;\n }" ]