query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Creates a simple, annotation defined Enterprise Web Bean using the annotations specified on type
@param <T> The type
@param beanManager the current manager
@param type the AnnotatedType to use
@return An Enterprise Web Bean | [
"public static <T> SessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager, EnhancedAnnotatedType<T> type) {\n return new SessionBeanImpl<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifier(type, ejbDescriptor)), beanManager);\n }"
] | [
"public static int getId(Context context, String id) {\n final String defType;\n if (id.startsWith(\"R.\")) {\n int dot = id.indexOf('.', 2);\n defType = id.substring(2, dot);\n } else {\n defType = \"drawable\";\n }\n\n Log.d(TAG, \"getId(): id: %s, extracted type: %s\", id, defType);\n return getId(context, id, defType);\n }",
"protected final void verify() {\n collectInitialisers();\n verifyCandidates();\n verifyInitialisers();\n collectPossibleInitialValues();\n verifyPossibleInitialValues();\n collectEffectiveAssignmentInstructions();\n verifyEffectiveAssignmentInstructions();\n collectAssignmentGuards();\n verifyAssignmentGuards();\n end();\n }",
"public static sslpolicylabel[] get(nitro_service service) throws Exception{\n\t\tsslpolicylabel obj = new sslpolicylabel();\n\t\tsslpolicylabel[] response = (sslpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public final void fatal(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.FATAL, pObject, null);\r\n\t}",
"protected String statusMsg(final String queue, final Job job) throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setQueue(queue);\n status.setPayload(job);\n return ObjectMapperFactory.get().writeValueAsString(status);\n }",
"public static Document removeTags(Document dom, String tagName) {\n NodeList list;\n try {\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n\n while (list.getLength() > 0) {\n Node sc = list.item(0);\n\n if (sc != null) {\n sc.getParentNode().removeChild(sc);\n }\n\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n }\n } catch (XPathExpressionException e) {\n LOGGER.error(\"Error while removing tag \" + tagName, e);\n }\n\n return dom;\n\n }",
"public static gslbservice[] get(nitro_service service) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tgslbservice[] response = (gslbservice[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void prepareModel(DescriptorRepository model)\r\n {\r\n TreeMap result = new TreeMap();\r\n\r\n for (Iterator it = model.getDescriptorTable().values().iterator(); it.hasNext();)\r\n {\r\n ClassDescriptor classDesc = (ClassDescriptor)it.next();\r\n\r\n if (classDesc.getFullTableName() == null)\r\n {\r\n // not mapped to a database table\r\n continue;\r\n }\r\n\r\n String elementName = getElementName(classDesc);\r\n Table mappedTable = getTableFor(elementName);\r\n Map columnsMap = getColumnsFor(elementName);\r\n Map requiredAttributes = getRequiredAttributes(elementName);\r\n List classDescs = getClassDescriptorsMappingTo(elementName);\r\n\r\n if (mappedTable == null)\r\n {\r\n mappedTable = _schema.findTable(classDesc.getFullTableName());\r\n if (mappedTable == null)\r\n {\r\n continue;\r\n }\r\n columnsMap = new TreeMap();\r\n requiredAttributes = new HashMap();\r\n classDescs = new ArrayList();\r\n _elementToTable.put(elementName, mappedTable);\r\n _elementToClassDescriptors.put(elementName, classDescs);\r\n _elementToColumnMap.put(elementName, columnsMap);\r\n _elementToRequiredAttributesMap.put(elementName, requiredAttributes);\r\n }\r\n classDescs.add(classDesc);\r\n extractAttributes(classDesc, mappedTable, columnsMap, requiredAttributes);\r\n }\r\n extractIndirectionTables(model, _schema);\r\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 }"
] |
Looks for sequences of integer lists and combine them into one big sequence | [
"protected void parseCombineIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int numFound = 0;\n\n TokenList.Token start = null;\n TokenList.Token end = null;\n\n while( t != null ) {\n if( t.getType() == Type.VARIABLE && (isVariableInteger(t) ||\n t.getVariable().getType() == VariableType.INTEGER_SEQUENCE )) {\n if( numFound == 0 ) {\n numFound = 1;\n start = end = t;\n } else {\n numFound++;\n end = t;\n }\n } else if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n numFound = 0;\n } else {\n numFound = 0;\n }\n t = t.next;\n }\n\n if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n }\n }"
] | [
"public static Set<String> commaDelimitedListToSet(String str) {\n Set<String> set = new TreeSet<String>();\n String[] tokens = commaDelimitedListToStringArray(str);\n Collections.addAll(set, tokens);\n return set;\n }",
"public Task<Void> sendResetPasswordEmail(@NonNull final String email) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n sendResetPasswordEmailInternal(email);\n return null;\n }\n });\n }",
"public static boolean isRowsLinearIndependent( DMatrixRMaj A )\n {\n // LU decomposition\n LUDecomposition<DMatrixRMaj> lu = DecompositionFactory_DDRM.lu(A.numRows,A.numCols);\n if( lu.inputModified() )\n A = A.copy();\n\n if( !lu.decompose(A))\n throw new RuntimeException(\"Decompositon failed?\");\n\n // if they are linearly independent it should not be singular\n return !lu.isSingular();\n }",
"private static void verifyJUnit4Present() {\n try {\n Class<?> clazz = Class.forName(\"org.junit.runner.Description\");\n if (!Serializable.class.isAssignableFrom(clazz)) {\n JvmExit.halt(SlaveMain.ERR_OLD_JUNIT);\n }\n } catch (ClassNotFoundException e) {\n JvmExit.halt(SlaveMain.ERR_NO_JUNIT);\n }\n }",
"public static boolean compareAnnotatedParameters(AnnotatedParameter<?> p1, AnnotatedParameter<?> p2) {\n return compareAnnotatedCallable(p1.getDeclaringCallable(), p2.getDeclaringCallable()) && p1.getPosition() == p2.getPosition() && compareAnnotated(p1, p2);\n }",
"public void setFrustum(float fovy, float aspect, float znear, float zfar)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.perspective((float) Math.toRadians(fovy), aspect, znear, zfar);\n setFrustum(projMatrix);\n }",
"public EndpointOverride getPath(int pathId, String clientUUID, String[] filters) throws Exception {\n EndpointOverride endpoint = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID + \"=\" + pathId + \";\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n results = statement.executeQuery();\n\n if (results.next()) {\n endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return endpoint;\n }",
"@SuppressWarnings(\"WeakerAccess\")\n protected boolean isJettyWithJMX(ClassLoaderLeakPreventor preventor) {\n final ClassLoader classLoader = preventor.getClassLoader();\n try {\n // If package org.eclipse.jetty is found, we may be running under jetty\n if (classLoader.getResource(\"org/eclipse/jetty\") == null) {\n return false;\n }\n\n Class.forName(\"org.eclipse.jetty.jmx.MBeanContainer\", false, classLoader.getParent()); // JMX enabled?\n Class.forName(\"org.eclipse.jetty.webapp.WebAppContext\", false, classLoader.getParent());\n }\n catch(Exception ex) { // For example ClassNotFoundException\n return false;\n }\n \n // Seems we are running in Jetty with JMX enabled\n return true;\n }",
"public static base_response unset(nitro_service client, clusterinstance resource, String[] args) throws Exception{\n\t\tclusterinstance unsetresource = new clusterinstance();\n\t\tunsetresource.clid = resource.clid;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] |
Return a list of 'Files' of downloaded or uploaded files. Filters build files without local and remote paths.
@param buildFilesStream - Stream of build Artifacts or Dependencies.
@return - List of build files. | [
"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 }"
] | [
"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 }",
"@Override\n\tpublic String toCanonicalString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.canonicalString) == null) {\n\t\t\tstringCache.canonicalString = result = toNormalizedString(IPv6StringCache.canonicalParams);\n\t\t}\n\t\treturn result;\n\t}",
"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 CmsXmlContent unmarshalXmlContent(CmsFile file) throws CmsXmlException {\n\n CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);\n content.setAutoCorrectionEnabled(true);\n content.correctXmlStructure(m_cms);\n\n return content;\n }",
"public static void changeSign(DMatrixSparseCSC A , DMatrixSparseCSC B ) {\n if( A != B ) {\n B.copyStructure(A);\n }\n\n for (int i = 0; i < A.nz_length; i++) {\n B.nz_values[i] = -A.nz_values[i];\n }\n }",
"public void deleteIndex(String indexName, String designDocId, String type) {\n assertNotEmpty(indexName, \"indexName\");\n assertNotEmpty(designDocId, \"designDocId\");\n assertNotNull(type, \"type\");\n if (!designDocId.startsWith(\"_design\")) {\n designDocId = \"_design/\" + designDocId;\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").path(designDocId)\n .path(type).path(indexName).build();\n InputStream response = null;\n try {\n HttpConnection connection = Http.DELETE(uri);\n response = client.couchDbClient.executeToInputStream(connection);\n getResponse(response, Response.class, client.getGson());\n } finally {\n close(response);\n }\n }",
"public static IntRange GetRange( int[] values, double percent ){\n int total = 0, n = values.length;\n\n // for all values\n for ( int i = 0; i < n; i++ )\n {\n // accumalate total\n total += values[i];\n }\n\n int min, max, hits;\n int h = (int) ( total * ( percent + ( 1 - percent ) / 2 ) );\n\n // get range min value\n for ( min = 0, hits = total; min < n; min++ )\n {\n hits -= values[min];\n if ( hits < h )\n break;\n }\n // get range max value\n for ( max = n - 1, hits = total; max >= 0; max-- )\n {\n hits -= values[max];\n if ( hits < h )\n break;\n }\n return new IntRange( min, max );\n }",
"@Override\n public final Integer optInt(final String key, final Integer defaultValue) {\n Integer result = optInt(key);\n return result == null ? defaultValue : result;\n }",
"public void setKnotType(int n, int type) {\n\t\tknotTypes[n] = (byte)((knotTypes[n] & ~COLOR_MASK) | type);\n\t\trebuildGradient();\n\t}"
] |
Creates a field map for tasks.
@param props props data | [
"public void createTaskFieldMap(Props props)\n {\n byte[] fieldMapData = null;\n for (Integer key : TASK_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultTaskData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }"
] | [
"public BoxStoragePolicy.Info getInfo(String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = STORAGE_POLICY_WITH_ID_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(),\n this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Info(response.getJSON());\n }",
"private synchronized HostServerGroupEffect getMappableDomainEffect(PathAddress address, String key,\n Map<String, Set<String>> map, Resource root) {\n if (requiresMapping) {\n map(root);\n requiresMapping = false;\n }\n Set<String> mapped = map.get(key);\n return mapped != null ? HostServerGroupEffect.forDomain(address, mapped)\n : HostServerGroupEffect.forUnassignedDomain(address);\n }",
"public void disableAllOverrides(int pathID, String clientUUID) {\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 \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ? \"\n );\n statement.setInt(1, pathID);\n statement.setString(2, clientUUID);\n statement.execute();\n statement.close();\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 }",
"private static JSONObject parseTarget(Shape target) throws JSONException {\n JSONObject targetObject = new JSONObject();\n\n targetObject.put(\"resourceId\",\n target.getResourceId().toString());\n\n return targetObject;\n }",
"protected MappedPreparedStmt<T, ID> prepareStatement(Long limit, boolean cacheStore) throws SQLException {\n\t\tList<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();\n\t\tString statement = buildStatementString(argList);\n\t\tArgumentHolder[] selectArgs = argList.toArray(new ArgumentHolder[argList.size()]);\n\t\tFieldType[] resultFieldTypes = getResultFieldTypes();\n\t\tFieldType[] argFieldTypes = new FieldType[argList.size()];\n\t\tfor (int selectC = 0; selectC < selectArgs.length; selectC++) {\n\t\t\targFieldTypes[selectC] = selectArgs[selectC].getFieldType();\n\t\t}\n\t\tif (!type.isOkForStatementBuilder()) {\n\t\t\tthrow new IllegalStateException(\"Building a statement from a \" + type + \" statement is not allowed\");\n\t\t}\n\t\treturn new MappedPreparedStmt<T, ID>(dao, tableInfo, statement, argFieldTypes, resultFieldTypes, selectArgs,\n\t\t\t\t(databaseType.isLimitSqlSupported() ? null : limit), type, cacheStore);\n\t}",
"public static String getValue(Element element) {\r\n if (element != null) {\r\n Node dataNode = element.getFirstChild();\r\n if (dataNode != null) {\r\n return ((Text) dataNode).getData();\r\n }\r\n }\r\n return null;\r\n }",
"public void insert(Platform platform, Database model, int batchSize) throws SQLException\r\n {\r\n if (batchSize <= 1)\r\n {\r\n for (Iterator it = _beans.iterator(); it.hasNext();)\r\n {\r\n platform.insert(model, (DynaBean)it.next());\r\n }\r\n }\r\n else\r\n {\r\n for (int startIdx = 0; startIdx < _beans.size(); startIdx += batchSize)\r\n {\r\n platform.insert(model, _beans.subList(startIdx, startIdx + batchSize));\r\n }\r\n }\r\n }",
"public static base_response save(nitro_service client) throws Exception {\n\t\tnsconfig saveresource = new nsconfig();\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}",
"public static void generateJRXML(DynamicReport dr, LayoutManager layoutManager, Map _parameters, String xmlEncoding, OutputStream outputStream) throws JRException {\n JasperReport jr = generateJasperReport(dr, layoutManager, _parameters);\n if (xmlEncoding == null)\n xmlEncoding = DEFAULT_XML_ENCODING;\n JRXmlWriter.writeReport(jr, outputStream, xmlEncoding);\n }"
] |
This method extracts predecessor data from an MSPDI file.
@param task Task data | [
"private void readPredecessors(Project.Tasks.Task task)\n {\n Integer uid = task.getUID();\n if (uid != null)\n {\n Task currTask = m_projectFile.getTaskByUniqueID(uid);\n if (currTask != null)\n {\n for (Project.Tasks.Task.PredecessorLink link : task.getPredecessorLink())\n {\n readPredecessor(currTask, link);\n }\n }\n }\n }"
] | [
"public void reset() {\n\t\tCrawlSession session = context.getSession();\n\t\tif (crawlpath != null) {\n\t\t\tsession.addCrawlPath(crawlpath);\n\t\t}\n\t\tList<StateVertex> onURLSetTemp = new ArrayList<>();\n\t\tif (stateMachine != null)\n\t\t\tonURLSetTemp = stateMachine.getOnURLSet();\n\t\tstateMachine = new StateMachine(graphProvider.get(), crawlRules.getInvariants(), plugins,\n\t\t\t\tstateComparator, onURLSetTemp);\n\t\tcontext.setStateMachine(stateMachine);\n\t\tcrawlpath = new CrawlPath();\n\t\tcontext.setCrawlPath(crawlpath);\n\t\tbrowser.handlePopups();\n\t\tbrowser.goToUrl(url);\n\t\t// Checks the landing page for URL and sets the current page accordingly\n\t\tcheckOnURLState();\n\t\tplugins.runOnUrlLoadPlugins(context);\n\t\tcrawlDepth.set(0);\n\t}",
"@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }",
"protected Collection provideStateManagers(Collection pojos)\r\n {\r\n \tPersistenceCapable pc;\r\n \tint [] fieldNums;\r\n \tIterator iter = pojos.iterator();\r\n \tCollection result = new ArrayList();\r\n \t\r\n \twhile (iter.hasNext())\r\n \t{\r\n \t\t// obtain a StateManager\r\n \t\tpc = (PersistenceCapable) iter.next();\r\n \t\tIdentity oid = new Identity(pc, broker);\r\n \t\tStateManagerInternal smi = pmi.getStateManager(oid, pc.getClass()); \r\n \t\t\r\n \t\t// fetch attributes into StateManager\r\n\t\t\tJDOClass jdoClass = Helper.getJDOClass(pc.getClass());\r\n\t\t\tfieldNums = jdoClass.getManagedFieldNumbers();\r\n\r\n\t\t\tFieldManager fm = new OjbFieldManager(pc, broker);\r\n\t\t\tsmi.replaceFields(fieldNums, fm);\r\n\t\t\tsmi.retrieve();\r\n\t\t\t\r\n\t\t\t// get JDO PersistencecCapable instance from SM and add it to result collection\r\n\t\t\tObject instance = smi.getObject();\r\n\t\t\tresult.add(instance);\r\n \t}\r\n \treturn result; \r\n\t}",
"public static <IN extends CoreMap> CRFClassifier<IN> getJarClassifier(String resourceName, Properties props) {\r\n CRFClassifier<IN> crf = new CRFClassifier<IN>();\r\n crf.loadJarClassifier(resourceName, props);\r\n return crf;\r\n }",
"@UiHandler(\"m_dateList\")\r\n void dateListValueChange(ValueChangeEvent<SortedSet<Date>> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setDates(event.getValue());\r\n }\r\n }",
"void writeNoValueRestriction(RdfWriter rdfWriter, String propertyUri,\n\t\t\tString rangeUri, String subject) throws RDFHandlerException {\n\n\t\tResource bnodeSome = rdfWriter.getFreshBNode();\n\t\trdfWriter.writeTripleValueObject(subject, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_CLASS);\n\t\trdfWriter.writeTripleValueObject(subject, RdfWriter.OWL_COMPLEMENT_OF,\n\t\t\t\tbnodeSome);\n\t\trdfWriter.writeTripleValueObject(bnodeSome, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_RESTRICTION);\n\t\trdfWriter.writeTripleUriObject(bnodeSome, RdfWriter.OWL_ON_PROPERTY,\n\t\t\t\tpropertyUri);\n\t\trdfWriter.writeTripleUriObject(bnodeSome,\n\t\t\t\tRdfWriter.OWL_SOME_VALUES_FROM, rangeUri);\n\t}",
"String getStatus(CmsUser user, boolean disabled, boolean newUser) {\n\n if (disabled) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_0);\n }\n if (newUser) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_0);\n }\n if (OpenCms.getLoginManager().isUserTempDisabled(user.getName())) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_UNLOCK_USER_STATUS_0);\n }\n if (isUserPasswordReset(user)) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_0);\n }\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_ACTIVE_0);\n }",
"@UiHandler(\"m_atNumber\")\r\n void onWeekOfMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekOfMonth(event.getValue());\r\n }\r\n }",
"public static <T> T getBundle(final Class<T> type) {\n return doPrivileged(new PrivilegedAction<T>() {\n public T run() {\n final Locale locale = Locale.getDefault();\n final String lang = locale.getLanguage();\n final String country = locale.getCountry();\n final String variant = locale.getVariant();\n\n Class<? extends T> bundleClass = null;\n if (variant != null && !variant.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, country, variant), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null && country != null && !country.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, country, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null && lang != null && !lang.isEmpty()) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", lang, null, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n // ignore\n }\n if (bundleClass == null) try {\n bundleClass = Class.forName(join(type.getName(), \"$bundle\", null, null, null), true, type.getClassLoader()).asSubclass(type);\n } catch (ClassNotFoundException e) {\n throw new IllegalArgumentException(\"Invalid bundle \" + type + \" (implementation not found)\");\n }\n final Field field;\n try {\n field = bundleClass.getField(\"INSTANCE\");\n } catch (NoSuchFieldException e) {\n throw new IllegalArgumentException(\"Bundle implementation \" + bundleClass + \" has no instance field\");\n }\n try {\n return type.cast(field.get(null));\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Bundle implementation \" + bundleClass + \" could not be instantiated\", e);\n }\n }\n });\n }"
] |
Returns all the URL that should be inside the classpath. This includes the jar itself if any.
@throws JqmPayloadException | [
"private URL[] getClasspath(JobInstance ji, JobRunnerCallback cb) throws JqmPayloadException\n {\n switch (ji.getJD().getPathType())\n {\n case MAVEN:\n return mavenResolver.resolve(ji);\n case MEMORY:\n return new URL[0];\n case FS:\n default:\n return fsResolver.getLibraries(ji.getNode(), ji.getJD());\n }\n }"
] | [
"public int addKey(String key) {\n JdkUtils.requireNonNull(key);\n int nextIndex = keys.size();\n final Integer mapIndex = JdkUtils.putIfAbsent(keys, key, nextIndex);\n return mapIndex == null ? nextIndex : mapIndex;\n }",
"private void addSubMatrixVariables(List<TokenList.Token> inputs, List<Variable> variables) {\n for (int i = 0; i < inputs.size(); i++) {\n TokenList.Token t = inputs.get(i);\n if( t.getType() != Type.VARIABLE )\n throw new ParseError(\"Expected variables only in sub-matrix input, not \"+t.getType());\n Variable v = t.getVariable();\n if( v.getType() == VariableType.INTEGER_SEQUENCE || isVariableInteger(t) ) {\n variables.add(v);\n } else {\n throw new ParseError(\"Expected an integer, integer sequence, or array range to define a submatrix\");\n }\n }\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 List<CmsUser> getVisibleUser() {\n\n if (!m_fullyLoaded) {\n return m_users;\n }\n if (size() == m_users.size()) {\n return m_users;\n }\n List<CmsUser> directs = new ArrayList<CmsUser>();\n for (CmsUser user : m_users) {\n if (!m_indirects.contains(user)) {\n directs.add(user);\n }\n }\n return directs;\n }",
"public static base_response convert(nitro_service client, sslpkcs8 resource) throws Exception {\n\t\tsslpkcs8 convertresource = new sslpkcs8();\n\t\tconvertresource.pkcs8file = resource.pkcs8file;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.keyform = resource.keyform;\n\t\tconvertresource.password = resource.password;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}",
"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}",
"public static dnsview[] get(nitro_service service, String viewname[]) throws Exception{\n\t\tif (viewname !=null && viewname.length>0) {\n\t\t\tdnsview response[] = new dnsview[viewname.length];\n\t\t\tdnsview obj[] = new dnsview[viewname.length];\n\t\t\tfor (int i=0;i<viewname.length;i++) {\n\t\t\t\tobj[i] = new dnsview();\n\t\t\t\tobj[i].set_viewname(viewname[i]);\n\t\t\t\tresponse[i] = (dnsview) 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 detect(final String... packageNames) throws IOException {\n final String[] pkgNameFilter = new String[packageNames.length];\n for (int i = 0; i < pkgNameFilter.length; ++i) {\n pkgNameFilter[i] = packageNames[i].replace('.', '/');\n if (!pkgNameFilter[i].endsWith(\"/\")) {\n pkgNameFilter[i] = pkgNameFilter[i].concat(\"/\");\n }\n }\n final Set<File> files = new HashSet<>();\n final ClassLoader loader = Thread.currentThread().getContextClassLoader();\n for (final String packageName : pkgNameFilter) {\n final Enumeration<URL> resourceEnum = loader.getResources(packageName);\n while (resourceEnum.hasMoreElements()) {\n final URL url = resourceEnum.nextElement();\n if (\"file\".equals(url.getProtocol())) {\n final File dir = toFile(url);\n if (dir.isDirectory()) {\n files.add(dir);\n } else {\n throw new AssertionError(\"Not a recognized file URL: \" + url);\n }\n } else {\n final File jarFile = toFile(openJarURLConnection(url).getJarFileURL());\n if (jarFile.isFile()) {\n files.add(jarFile);\n } else {\n throw new AssertionError(\"Not a File: \" + jarFile);\n }\n }\n }\n }\n if (DEBUG) {\n print(\"Files to scan: %s\", files);\n }\n if (!files.isEmpty()) {\n // see http://shipilev.net/blog/2016/arrays-wisdom-ancients/#_conclusion\n detect(new ClassFileIterator(files.toArray(new File[0]), pkgNameFilter));\n }\n }",
"public CollectionRequest<Task> findByTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }"
] |
Declares additional internal data structures. | [
"@Override\n public void setExpectedMaxSize( int numRows , int numCols ) {\n super.setExpectedMaxSize(numRows,numCols);\n\n // if the matrix that is being decomposed is smaller than the block we really don't\n // see the B matrix.\n if( numRows < blockWidth)\n B = new DMatrixRMaj(0,0);\n else\n B = new DMatrixRMaj(blockWidth,maxWidth);\n\n chol = new CholeskyBlockHelper_DDRM(blockWidth);\n }"
] | [
"private void ensureReferencedPKs(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException\r\n {\r\n String targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);\r\n ClassDescriptorDef targetClassDef = modelDef.getClass(targetClassName);\r\n\r\n ensurePKsFromHierarchy(targetClassDef);\r\n }",
"public static Info rand( 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(\"rand-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 RandomMatrices_DDRM.fillUniform(output.matrix, 0,1,manager.getRandom());\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }",
"private void ensurePrecisionAndScale(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, null);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, null);\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION))\r\n {\r\n String defaultPrecision = JdbcTypeHelper.getDefaultPrecisionFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultPrecision != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no precision setting though its jdbc type requires it (in most databases); using default precision of \"+defaultPrecision);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, defaultPrecision);\r\n }\r\n else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, \"1\");\r\n }\r\n }\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))\r\n {\r\n String defaultScale = JdbcTypeHelper.getDefaultScaleFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultScale != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no scale setting though its jdbc type requires it (in most databases); using default scale of \"+defaultScale);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, defaultScale);\r\n }\r\n else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION) || fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION))\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, \"0\");\r\n }\r\n }\r\n }",
"private static List<CmsCategory> getCategories(CmsObject cms, CmsResource resource) {\n\n if ((null != resource) && (null != cms)) {\n try {\n return CmsCategoryService.getInstance().readResourceCategories(cms, resource);\n } catch (CmsException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return new ArrayList<CmsCategory>(0);\n }",
"public String getString(Integer id, Integer type)\n {\n return (getString(m_meta.getOffset(id, type)));\n }",
"public void deleteProduct(final String name) {\n final DbProduct dbProduct = getProduct(name);\n repositoryHandler.deleteProduct(dbProduct.getName());\n }",
"public static void addOverrideToPath() throws Exception {\n Client client = new Client(\"ProfileName\", false);\n\n // Use the fully qualified name for a plugin override.\n client.addMethodToResponseOverride(\"Test Path\", \"com.groupon.odo.sample.Common.delay\");\n\n // The third argument is the ordinal - the nth instance of this override added to this path\n // The final arguments count and type are determined by the override. \"delay\" used in this sample\n // has a single int argument - # of milliseconds delay to simulate\n client.setMethodArguments(\"Test Path\", \"com.groupon.odo.sample.Common.delay\", 1, \"100\");\n }",
"public DynamicReport build() {\n\n if (built) {\n throw new DJBuilderException(\"DynamicReport already built. Cannot use more than once.\");\n } else {\n built = true;\n }\n\n report.setOptions(options);\n if (!globalVariablesGroup.getFooterVariables().isEmpty() || !globalVariablesGroup.getHeaderVariables().isEmpty() || !globalVariablesGroup.getVariables().isEmpty() || hasPercentageColumn()) {\n report.getColumnsGroups().add(0, globalVariablesGroup);\n }\n\n createChartGroups();\n\n addGlobalCrosstabs();\n\n addSubreportsToGroups();\n\n concatenateReports();\n\n report.setAutoTexts(autoTexts);\n return report;\n }",
"public static protocolhttpband[] get(nitro_service service, protocolhttpband_args args) throws Exception{\n\t\tprotocolhttpband obj = new protocolhttpband();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tprotocolhttpband[] response = (protocolhttpband[])obj.get_resources(service, option);\n\t\treturn response;\n\t}"
] |
Prints command-line help menu. | [
"public static void printHelp(PrintStream stream) {\n stream.println();\n stream.println(\"Voldemort Admin Tool Async-Job Commands\");\n stream.println(\"---------------------------------------\");\n stream.println(\"list Get async job list from nodes.\");\n stream.println(\"stop Stop async jobs on one node.\");\n stream.println();\n stream.println(\"To get more information on each command,\");\n stream.println(\"please try \\'help async-job <command-name>\\'.\");\n stream.println();\n }"
] | [
"private static String firstFoundTableName(PersistenceBroker brokerForClass, ClassDescriptor cld)\r\n {\r\n String name = null;\r\n if (!cld.isInterface() && cld.getFullTableName() != null)\r\n {\r\n return cld.getFullTableName();\r\n }\r\n if (cld.isExtent())\r\n {\r\n Collection extentClasses = cld.getExtentClasses();\r\n for (Iterator iterator = extentClasses.iterator(); iterator.hasNext();)\r\n {\r\n name = firstFoundTableName(brokerForClass, brokerForClass.getClassDescriptor((Class) iterator.next()));\r\n // System.out.println(\"## \" + cld.getClassNameOfObject()+\" - name: \"+name);\r\n if (name != null) break;\r\n }\r\n }\r\n return name;\r\n }",
"private PersistenceBrokerException createException(final Exception ex, String message, final Object objectToIdentify, Class topLevelClass, Class realClass, Object[] pks)\r\n {\r\n final String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer msg = new StringBuffer();\r\n if(message == null)\r\n {\r\n msg.append(\"Unexpected error: \");\r\n }\r\n else\r\n {\r\n msg.append(message).append(\" :\");\r\n }\r\n if(topLevelClass != null) msg.append(eol).append(\"objectTopLevelClass=\").append(topLevelClass.getName());\r\n if(realClass != null) msg.append(eol).append(\"objectRealClass=\").append(realClass.getName());\r\n if(pks != null) msg.append(eol).append(\"pkValues=\").append(ArrayUtils.toString(pks));\r\n if(objectToIdentify != null) msg.append(eol).append(\"object to identify: \").append(objectToIdentify);\r\n if(ex != null)\r\n {\r\n // add causing stack trace\r\n Throwable rootCause = ExceptionUtils.getRootCause(ex);\r\n if(rootCause != null)\r\n {\r\n msg.append(eol).append(\"The root stack trace is --> \");\r\n String rootStack = ExceptionUtils.getStackTrace(rootCause);\r\n msg.append(eol).append(rootStack);\r\n }\r\n\r\n return new PersistenceBrokerException(msg.toString(), ex);\r\n }\r\n else\r\n {\r\n return new PersistenceBrokerException(msg.toString());\r\n }\r\n }",
"private static void filter(String filename, String filtername) throws Exception\n {\n ProjectFile project = new UniversalProjectReader().read(filename);\n Filter filter = project.getFilters().getFilterByName(filtername);\n\n if (filter == null)\n {\n displayAvailableFilters(project);\n }\n else\n {\n System.out.println(filter);\n System.out.println();\n\n if (filter.isTaskFilter())\n {\n processTaskFilter(project, filter);\n }\n else\n {\n processResourceFilter(project, filter);\n }\n }\n }",
"private String parameter(Options opt, Parameter p[]) {\n\tStringBuilder par = new StringBuilder(1000);\n\tfor (int i = 0; i < p.length; i++) {\n\t par.append(p[i].name() + typeAnnotation(opt, p[i].type()));\n\t if (i + 1 < p.length)\n\t\tpar.append(\", \");\n\t}\n\treturn par.toString();\n }",
"private void createTasks(ChildTaskContainer parent, String parentName, List<Row> rows)\n {\n for (Row row : rows)\n {\n boolean rowIsBar = (row.getInteger(\"BARID\") != null);\n\n //\n // Don't export hammock tasks.\n //\n if (rowIsBar && row.getChildRows().isEmpty())\n {\n continue;\n }\n\n Task task = parent.addTask();\n\n //\n // Do we have a bar, task, or milestone?\n //\n if (rowIsBar)\n {\n //\n // If the bar only has one child task, we skip it and add the task directly\n //\n if (skipBar(row))\n {\n populateLeaf(row.getString(\"NAMH\"), row.getChildRows().get(0), task);\n }\n else\n {\n populateBar(row, task);\n createTasks(task, task.getName(), row.getChildRows());\n }\n }\n else\n {\n populateLeaf(parentName, row, task);\n }\n\n m_eventManager.fireTaskReadEvent(task);\n }\n }",
"private 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 void growInternal(int amount ) {\n int tmp[] = new int[ data.length + amount ];\n\n System.arraycopy(data,0,tmp,0,data.length);\n this.data = tmp;\n }",
"public final void notifyContentItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= contentItemCount || toPosition >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \"\n + toPosition + \" is not within the position bounds for content items [0 - \" + (contentItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition + headerItemCount, toPosition + headerItemCount);\n }",
"public String getSample(int line, int column, Janitor janitor) {\n String sample = null;\n String text = source.getLine(line, janitor);\n\n if (text != null) {\n if (column > 0) {\n String marker = Utilities.repeatString(\" \", column - 1) + \"^\";\n\n if (column > 40) {\n int start = column - 30 - 1;\n int end = (column + 10 > text.length() ? text.length() : column + 10 - 1);\n sample = \" \" + text.substring(start, end) + Utilities.eol() + \" \" +\n marker.substring(start, marker.length());\n } else {\n sample = \" \" + text + Utilities.eol() + \" \" + marker;\n }\n } else {\n sample = text;\n }\n }\n\n return sample;\n }"
] |
Use this API to update nsrpcnode. | [
"public static base_response update(nitro_service client, nsrpcnode resource) throws Exception {\n\t\tnsrpcnode updateresource = new nsrpcnode();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.srcip = resource.srcip;\n\t\tupdateresource.secure = resource.secure;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"public static long count(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding();\n\t\tobj.set_vservername(vservername);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslvserver_sslciphersuite_binding response[] = (sslvserver_sslciphersuite_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 File getTargetFile(final MiscContentItem item) {\n final State state = this.state;\n if (state == State.NEW || state == State.ROLLBACK_ONLY) {\n return getTargetFile(miscTargetRoot, item);\n } else {\n throw new IllegalStateException(); // internal wrong usage, no i18n\n }\n }",
"public List<Pair<int[][][], int[]>> documentsToDataAndLabelsList(Collection<List<IN>> documents) {\r\n int numDatums = 0;\r\n\r\n List<Pair<int[][][], int[]>> docList = new ArrayList<Pair<int[][][], int[]>>();\r\n for (List<IN> doc : documents) {\r\n Pair<int[][][], int[]> docPair = documentToDataAndLabels(doc);\r\n docList.add(docPair);\r\n numDatums += doc.size();\r\n }\r\n\r\n System.err.println(\"numClasses: \" + classIndex.size() + ' ' + classIndex);\r\n System.err.println(\"numDocuments: \" + docList.size());\r\n System.err.println(\"numDatums: \" + numDatums);\r\n System.err.println(\"numFeatures: \" + featureIndex.size());\r\n return docList;\r\n }",
"public static boolean isTrait(final ClassNode cNode) {\n return cNode!=null\n && ((cNode.isInterface() && !cNode.getAnnotations(TRAIT_CLASSNODE).isEmpty())\n || isAnnotatedWithTrait(cNode));\n }",
"public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deployment = entities.stream()\n .filter(hm -> hm instanceof Deployment)\n .map(hm -> (Deployment) hm)\n .map(rc -> rc.getMetadata().getName()).findFirst();\n\n deployment.ifPresent(name -> this.applicationName = name);\n }\n }",
"public String convertToPrefixLength() throws AddressStringException {\n\t\tIPAddress address = toAddress();\n\t\tInteger prefix;\n\t\tif(address == null) {\n\t\t\tif(isPrefixOnly()) {\n\t\t\t\tprefix = getNetworkPrefixLength();\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} else {\n\t\t\tprefix = address.getBlockMaskPrefixLength(true);\n\t\t\tif(prefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn IPAddressSegment.toUnsignedString(prefix, 10, \n\t\t\t\tnew StringBuilder(IPAddressSegment.toUnsignedStringLength(prefix, 10) + 1).append(IPAddress.PREFIX_LEN_SEPARATOR)).toString();\n\t}",
"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 }",
"public static int rank( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n int N = svd.numberOfSingularValues();\n double sv[] = svd.getSingularValues();\n\n double threshold = singularThreshold(sv,N);\n int count = 0;\n for (int i = 0; i < sv.length; i++) {\n if( sv[i] >= threshold ) {\n count++;\n }\n }\n return count;\n }",
"public LogSegment getLastView() {\n List<LogSegment> views = getView();\n return views.get(views.size() - 1);\n }"
] |
Convert any number class to array of integer.
@param <T> Type.
@param array Array.
@return Integer array. | [
"public static <T extends Number> int[] asArray(final T... array) {\n int[] b = new int[array.length];\n for (int i = 0; i < b.length; i++) {\n b[i] = array[i].intValue();\n }\n return b;\n }"
] | [
"public Collection getReaders(Object obj)\r\n {\r\n \tcheckTimedOutLocks();\r\n Identity oid = new Identity(obj,getBroker());\r\n return getReaders(oid);\r\n }",
"public final SimpleFeatureCollection treatStringAsURL(final Template template, final String geoJsonUrl)\n throws IOException {\n URL url;\n try {\n url = FileUtils.testForLegalFileUrl(template.getConfiguration(), new URL(geoJsonUrl));\n } catch (MalformedURLException e) {\n return null;\n }\n\n final String geojsonString;\n if (url.getProtocol().equalsIgnoreCase(\"file\")) {\n geojsonString = IOUtils.toString(url, Constants.DEFAULT_CHARSET.name());\n } else {\n geojsonString = URIUtils.toString(this.httpRequestFactory, url);\n }\n\n return treatStringAsGeoJson(geojsonString);\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 }",
"private void populateResourceAssignmentWorkgroupFields(Record record, ResourceAssignmentWorkgroupFields workgroup) throws MPXJException\n {\n workgroup.setMessageUniqueID(record.getString(0));\n workgroup.setConfirmed(NumberHelper.getInt(record.getInteger(1)) == 1);\n workgroup.setResponsePending(NumberHelper.getInt(record.getInteger(1)) == 1);\n workgroup.setUpdateStart(record.getDateTime(3));\n workgroup.setUpdateFinish(record.getDateTime(4));\n workgroup.setScheduleID(record.getString(5));\n }",
"public static boolean ensureJedisConnection(final Jedis jedis) {\n final boolean jedisOK = testJedisConnection(jedis);\n if (!jedisOK) {\n try {\n jedis.quit();\n } catch (Exception e) {\n } // Ignore\n try {\n jedis.disconnect();\n } catch (Exception e) {\n } // Ignore\n jedis.connect();\n }\n return jedisOK;\n }",
"public static String padOrTrim(String str, int num) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n int leng = str.length();\r\n if (leng < num) {\r\n StringBuilder sb = new StringBuilder(str);\r\n for (int i = 0; i < num - leng; i++) {\r\n sb.append(' ');\r\n }\r\n return sb.toString();\r\n } else if (leng > num) {\r\n return str.substring(0, num);\r\n } else {\r\n return str;\r\n }\r\n }",
"public Reply getReplyInfo(String topicId, String replyId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REPLIES_GET_INFO);\r\n parameters.put(\"topic_id\", topicId);\r\n parameters.put(\"reply_id\", replyId);\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 replyElement = response.getPayload();\r\n\r\n return parseReply(replyElement);\r\n }",
"public Info changeMessage(String newMessage) {\n Info newInfo = new Info();\n newInfo.setMessage(newMessage);\n\n URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(newInfo.getPendingChanges());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonResponse = JsonObject.readFrom(response.getJSON());\n\n return new Info(jsonResponse);\n }",
"public static base_responses export(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata exportresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texportresources[i] = new appfwlearningdata();\n\t\t\t\texportresources[i].profilename = resources[i].profilename;\n\t\t\t\texportresources[i].securitycheck = resources[i].securitycheck;\n\t\t\t\texportresources[i].target = resources[i].target;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, exportresources,\"export\");\n\t\t}\n\t\treturn result;\n\t}"
] |
Allows direct access to the Undertow.Builder for custom configuration
@param serverConfigurationFunction the serverConfigurationFunction | [
"public ProteusApplication setServerConfigurationFunction(Function<Undertow.Builder, Undertow.Builder> serverConfigurationFunction)\n {\n this.serverConfigurationFunction = serverConfigurationFunction;\n return this;\n }"
] | [
"private void listGreetings(String guestbookName) throws DatastoreException {\n Query.Builder query = Query.newBuilder();\n query.addKindBuilder().setName(GREETING_KIND);\n query.setFilter(makeFilter(KEY_PROPERTY, PropertyFilter.Operator.HAS_ANCESTOR,\n makeValue(makeKey(GUESTBOOK_KIND, guestbookName))));\n query.addOrder(makeOrder(DATE_PROPERTY, PropertyOrder.Direction.DESCENDING));\n\n List<Entity> greetings = runQuery(query.build());\n if (greetings.size() == 0) {\n System.out.println(\"no greetings in \" + guestbookName);\n }\n for (Entity greeting : greetings) {\n Map<String, Value> propertyMap = greeting.getProperties();\n System.out.println(\n DatastoreHelper.toDate(propertyMap.get(DATE_PROPERTY)) + \": \" +\n DatastoreHelper.getString(propertyMap.get(USER_PROPERTY)) + \" says \" +\n DatastoreHelper.getString(propertyMap.get(MESSAGE_PROPERTY)));\n }\n }",
"@Override\n public void close() throws VoldemortException {\n logger.debug(\"Close called for read-only store.\");\n this.fileModificationLock.writeLock().lock();\n\n try {\n if(isOpen) {\n this.isOpen = false;\n fileSet.close();\n } else {\n logger.debug(\"Attempt to close already closed store \" + getName());\n }\n } finally {\n this.fileModificationLock.writeLock().unlock();\n }\n }",
"public static @Nullable CleverTapAPI getInstance(Context context) throws CleverTapMetaDataNotFoundException, CleverTapPermissionsNotSatisfied {\n // For Google Play Store/Android Studio tracking\n sdkVersion = BuildConfig.SDK_VERSION_STRING;\n return getDefaultInstance(context);\n }",
"public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) {\n return getSharedItem(api, sharedLink, null);\n }",
"public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deployment = entities.stream()\n .filter(hm -> hm instanceof Deployment)\n .map(hm -> (Deployment) hm)\n .map(rc -> rc.getMetadata().getName()).findFirst();\n\n deployment.ifPresent(name -> this.applicationName = name);\n }\n }",
"protected Boolean getIgnoreReleaseDate() {\n\n Boolean isIgnoreReleaseDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_RELEASE_DATE);\n return (null == isIgnoreReleaseDate) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreReleaseDate())\n : isIgnoreReleaseDate;\n }",
"public boolean hasProperties(Set<PropertyKey> keys) {\n for (PropertyKey key : keys) {\n if (null == getProperty(key.m_key)) {\n return false;\n }\n }\n \n return true;\n }",
"private void writeFinalResults() {\n\t\t// Print a final report:\n\t\tprintStatus();\n\n\t\t// Store property counts in files:\n\t\twritePropertyStatisticsToFile(this.itemStatistics,\n\t\t\t\t\"item-property-counts.csv\");\n\t\twritePropertyStatisticsToFile(this.propertyStatistics,\n\t\t\t\t\"property-property-counts.csv\");\n\n\t\t// Store site link statistics in file:\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"site-link-counts.csv\"))) {\n\n\t\t\tout.println(\"Site key,Site links\");\n\t\t\tfor (Entry<String, Integer> entry : this.siteLinkStatistics\n\t\t\t\t\t.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\n\t\t// Store term statistics in file:\n\t\twriteTermStatisticsToFile(this.itemStatistics, \"item-term-counts.csv\");\n\t\twriteTermStatisticsToFile(this.propertyStatistics,\n\t\t\t\t\"property-term-counts.csv\");\n\t}",
"public static base_responses add(nitro_service client, cmppolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcmppolicylabel addresources[] = new cmppolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cmppolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Prints dependencies recovered from the methods of a class. A
dependency is inferred only if another relation between the two
classes is not already in the graph.
@param classes | [
"public void printInferredDependencies(ClassDoc c) {\n\tif (hidden(c))\n\t return;\n\n\tOptions opt = optionProvider.getOptionsFor(c);\n\tSet<Type> types = new HashSet<Type>();\n\t// harvest method return and parameter types\n\tfor (MethodDoc method : filterByVisibility(c.methods(false), opt.inferDependencyVisibility)) {\n\t types.add(method.returnType());\n\t for (Parameter parameter : method.parameters()) {\n\t\ttypes.add(parameter.type());\n\t }\n\t}\n\t// and the field types\n\tif (!opt.inferRelationships) {\n\t for (FieldDoc field : filterByVisibility(c.fields(false), opt.inferDependencyVisibility)) {\n\t\ttypes.add(field.type());\n\t }\n\t}\n\t// see if there are some type parameters\n\tif (c.asParameterizedType() != null) {\n\t ParameterizedType pt = c.asParameterizedType();\n\t types.addAll(Arrays.asList(pt.typeArguments()));\n\t}\n\t// see if type parameters extend something\n\tfor(TypeVariable tv: c.typeParameters()) {\n\t if(tv.bounds().length > 0 )\n\t\ttypes.addAll(Arrays.asList(tv.bounds()));\n\t}\n\n\t// and finally check for explicitly imported classes (this\n\t// assumes there are no unused imports...)\n\tif (opt.useImports)\n\t types.addAll(Arrays.asList(importedClasses(c)));\n\n\t// compute dependencies\n\tfor (Type type : types) {\n\t // skip primitives and type variables, as well as dependencies\n\t // on the source class\n\t if (type.isPrimitive() || type instanceof WildcardType || type instanceof TypeVariable\n\t\t || c.toString().equals(type.asClassDoc().toString()))\n\t\tcontinue;\n\n\t // check if the destination is excluded from inference\n\t ClassDoc fc = type.asClassDoc();\n\t if (hidden(fc))\n\t\tcontinue;\n\t \n\t // check if source and destination are in the same package and if we are allowed\n\t // to infer dependencies between classes in the same package\n\t if(!opt.inferDepInPackage && c.containingPackage().equals(fc.containingPackage()))\n\t\tcontinue;\n\n\t // if source and dest are not already linked, add a dependency\n\t RelationPattern rp = getClassInfo(c, true).getRelation(fc.toString());\n\t if (rp == null || rp.matchesOne(new RelationPattern(RelationDirection.OUT))) {\n\t\trelation(opt, RelationType.DEPEND, c, fc, \"\", \"\", \"\");\n\t }\n\t \n\t}\n }"
] | [
"public void forAllTables(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _torqueModel.getTables(); it.hasNext(); )\r\n {\r\n _curTableDef = (TableDef)it.next();\r\n generate(template);\r\n }\r\n _curTableDef = null;\r\n }",
"public CrosstabBuilder setRowStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {\r\n\t\tcrosstab.setRowHeaderStyle(headerStyle);\r\n\t\tcrosstab.setRowTotalheaderStyle(totalHeaderStyle);\r\n\t\tcrosstab.setRowTotalStyle(totalStyle);\r\n\t\treturn this;\r\n\t}",
"private <T> T request(ClientRequest<T> delegate, String operationName) {\n long startTimeMs = -1;\n long startTimeNs = -1;\n\n if(logger.isDebugEnabled()) {\n startTimeMs = System.currentTimeMillis();\n }\n ClientRequestExecutor clientRequestExecutor = pool.checkout(destination);\n String debugMsgStr = \"\";\n\n startTimeNs = System.nanoTime();\n\n BlockingClientRequest<T> blockingClientRequest = null;\n try {\n blockingClientRequest = new BlockingClientRequest<T>(delegate, timeoutMs);\n clientRequestExecutor.addClientRequest(blockingClientRequest,\n timeoutMs,\n System.nanoTime() - startTimeNs);\n\n boolean awaitResult = blockingClientRequest.await();\n\n if(awaitResult == false) {\n blockingClientRequest.timeOut();\n }\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"success\";\n\n return blockingClientRequest.getResult();\n } catch(InterruptedException e) {\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"unreachable: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e);\n } catch(UnreachableStoreException e) {\n clientRequestExecutor.close();\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"failure: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e.getCause());\n } finally {\n if(blockingClientRequest != null && !blockingClientRequest.isComplete()) {\n // close the executor if we timed out\n clientRequestExecutor.close();\n }\n // Record operation time\n long opTimeNs = Utils.elapsedTimeNs(startTimeNs, System.nanoTime());\n if(stats != null) {\n stats.recordSyncOpTimeNs(destination, opTimeNs);\n }\n if(logger.isDebugEnabled()) {\n logger.debug(\"Sync request end, type: \"\n + operationName\n + \" requestRef: \"\n + System.identityHashCode(delegate)\n + \" totalTimeNs: \"\n + opTimeNs\n + \" start time: \"\n + startTimeMs\n + \" end time: \"\n + System.currentTimeMillis()\n + \" client:\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalAddress()\n + \":\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalPort()\n + \" server: \"\n + clientRequestExecutor.getSocketChannel()\n .socket()\n .getRemoteSocketAddress() + \" outcome: \"\n + debugMsgStr);\n }\n\n pool.checkin(destination, clientRequestExecutor);\n }\n }",
"public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }",
"public String getAccuracyDescription(int numDigits) {\r\n NumberFormat nf = NumberFormat.getNumberInstance();\r\n nf.setMaximumFractionDigits(numDigits);\r\n Triple<Double, Integer, Integer> accu = getAccuracyInfo();\r\n return nf.format(accu.first()) + \" (\" + accu.second() + \"/\" + (accu.second() + accu.third()) + \")\";\r\n }",
"public static Predicate is(final String sql) {\n return new Predicate() {\n public String toSql() {\n return sql;\n }\n public void init(AbstractSqlCreator creator) {\n }\n };\n }",
"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 byte[] getThumbnail(ThumbnailFileType fileType, int minWidth, int minHeight, int maxWidth, int maxHeight) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"min_width\", minWidth);\n builder.appendParam(\"min_height\", minHeight);\n builder.appendParam(\"max_width\", maxWidth);\n builder.appendParam(\"max_height\", maxHeight);\n\n URLTemplate template;\n if (fileType == ThumbnailFileType.PNG) {\n template = GET_THUMBNAIL_PNG_TEMPLATE;\n } else if (fileType == ThumbnailFileType.JPG) {\n template = GET_THUMBNAIL_JPG_TEMPLATE;\n } else {\n throw new BoxAPIException(\"Unsupported thumbnail file type\");\n }\n URL url = template.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n ByteArrayOutputStream thumbOut = new ByteArrayOutputStream();\n InputStream body = response.getBody();\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = body.read(buffer);\n while (n != -1) {\n thumbOut.write(buffer, 0, n);\n n = body.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Error reading thumbnail bytes from response body\", e);\n } finally {\n response.disconnect();\n }\n\n return thumbOut.toByteArray();\n }",
"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 }"
] |
Use this API to fetch the statistics of all protocoludp_stats resources that are configured on netscaler. | [
"public static protocoludp_stats get(nitro_service service) throws Exception{\n\t\tprotocoludp_stats obj = new protocoludp_stats();\n\t\tprotocoludp_stats[] response = (protocoludp_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}"
] | [
"public void process(DMatrixSparseCSC A , int parent[], int post[], int counts[] ) {\n if( counts.length < A.numCols )\n throw new IllegalArgumentException(\"counts must be at least of length A.numCols\");\n\n initialize(A);\n\n int delta[] = counts;\n findFirstDescendant(parent, post, delta);\n\n if( ata ) {\n init_ata(post);\n }\n for (int i = 0; i < n; i++)\n w[ancestor+i] = i;\n\n int[] ATp = At.col_idx; int []ATi = At.nz_rows;\n\n for (int k = 0; k < n; k++) {\n int j = post[k];\n if( parent[j] != -1 )\n delta[parent[j]]--; // j is not a root\n for (int J = HEAD(k,j); J != -1; J = NEXT(J)) {\n for (int p = ATp[J]; p < ATp[J+1]; p++) {\n int i = ATi[p];\n int q = isLeaf(i,j);\n if( jleaf >= 1)\n delta[j]++;\n if( jleaf == 2 )\n delta[q]--;\n }\n }\n if( parent[j] != -1 )\n w[ancestor+j] = parent[j];\n }\n\n // sum up delta's of each child\n for ( int j = 0; j < n; j++) {\n if( parent[j] != -1)\n counts[parent[j]] += counts[j];\n }\n }",
"public static vpnvserver_aaapreauthenticationpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_aaapreauthenticationpolicy_binding response[] = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void postConstruct(GeoService geoService, DtoConverterService converterService) throws GeomajasException {\n\t\tif (null == layerInfo) {\n\t\t\tlayerInfo = new RasterLayerInfo();\n\t\t}\n\t\tlayerInfo.setCrs(TiledRasterLayerService.MERCATOR);\n\t\tcrs = geoService.getCrs2(TiledRasterLayerService.MERCATOR);\n\t\tlayerInfo.setTileWidth(tileSize);\n\t\tlayerInfo.setTileHeight(tileSize);\n\t\tBbox bbox = new Bbox(-TiledRasterLayerService.HALF_EQUATOR_IN_METERS,\n\t\t\t\t-TiledRasterLayerService.HALF_EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS,\n\t\t\t\tTiledRasterLayerService.EQUATOR_IN_METERS);\n\t\tlayerInfo.setMaxExtent(bbox);\n\t\tmaxBounds = converterService.toInternal(bbox);\n\n\t\tresolutions = new double[maxZoomLevel + 1];\n\t\tdouble powerOfTwo = 1;\n\t\tfor (int zoomLevel = 0; zoomLevel <= maxZoomLevel; zoomLevel++) {\n\t\t\tdouble resolution = (TiledRasterLayerService.EQUATOR_IN_METERS) / (tileSize * powerOfTwo);\n\t\t\tresolutions[zoomLevel] = resolution;\n\t\t\tpowerOfTwo *= 2;\n\t\t}\n\t}",
"private FieldDescriptor getFldFromJoin(TableAlias aTableAlias, String aColName)\r\n {\r\n FieldDescriptor fld = null;\r\n\r\n // Search Join Structure for attribute\r\n if (aTableAlias.joins != null)\r\n {\r\n Iterator itr = aTableAlias.joins.iterator();\r\n while (itr.hasNext())\r\n {\r\n Join join = (Join) itr.next();\r\n ClassDescriptor cld = join.right.cld;\r\n\r\n if (cld != null)\r\n {\r\n fld = cld.getFieldDescriptorByName(aColName);\r\n if (fld != null)\r\n {\r\n break;\r\n }\r\n\r\n }\r\n }\r\n }\r\n return fld;\r\n }",
"public <T> T getNodeMetaData(Object key) {\n if (metaDataMap == null) {\n return (T) null;\n }\n return (T) metaDataMap.get(key);\n }",
"public static String replaceFullRequestContent(\n String requestContentTemplate, String replacementString) {\n return (requestContentTemplate.replace(\n PcConstants.COMMAND_VAR_DEFAULT_REQUEST_CONTENT,\n replacementString));\n }",
"public static Chart getMSDLineWithPowerModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double a, double D) {\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] = 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^alpha\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"private Set<String> populateTableNames(String url) throws SQLException\n {\n Set<String> tableNames = new HashSet<String>();\n Connection connection = null;\n ResultSet rs = null;\n\n try\n {\n connection = DriverManager.getConnection(url);\n DatabaseMetaData dmd = connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tableNames.add(rs.getString(\"TABLE_NAME\").toUpperCase());\n }\n }\n\n finally\n {\n if (rs != null)\n {\n rs.close();\n }\n\n if (connection != null)\n {\n connection.close();\n }\n }\n\n return tableNames;\n }",
"protected int readShort(InputStream is) throws IOException\n {\n byte[] data = new byte[2];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getShort(data, 0));\n }"
] |
Sets a custom configuration attribute.
@param attributeName the attribute name. Names starting with
{@link #JDBC_PROPERTY_NAME_PREFIX} will be used (without the prefix) by the
ConnectionFactory when creating connections from DriverManager
(not used for external DataSource connections). Names starting with
{@link #DBCP_PROPERTY_NAME_PREFIX} to Commons DBCP (if used, also without prefix).
@param attributeValue the attribute value | [
"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 }"
] | [
"boolean processUnstable() {\n boolean change = !unstable;\n if (change) { // Only once until the process is removed. A process is unstable until removed.\n unstable = true;\n HostControllerLogger.ROOT_LOGGER.managedServerUnstable(serverName);\n }\n return change;\n }",
"@Override public void setUniqueID(Integer uniqueID)\n {\n ProjectFile parent = getParentFile();\n\n if (m_uniqueID != null)\n {\n parent.getCalendars().unmapUniqueID(m_uniqueID);\n }\n\n parent.getCalendars().mapUniqueID(uniqueID, this);\n\n m_uniqueID = uniqueID;\n }",
"public void logWarning(final String message) {\n messageQueue.add(new LogEntry() {\n @Override\n public String getMessage() {\n return message;\n }\n });\n }",
"public void setSourceUrl(String newUrl, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVERS +\n \" SET \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newUrl);\n statement.setInt(2, id);\n statement.executeUpdate();\n statement.close();\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 }",
"private void checkReferenceForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef classDef;\r\n ReferenceDescriptorDef refDef;\r\n\r\n for (Iterator it = modelDef.getClasses(); it.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)it.next();\r\n for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)\r\n {\r\n refDef = (ReferenceDescriptorDef)refIt.next();\r\n if (!refDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n checkReferenceForeignkeys(modelDef, refDef);\r\n }\r\n }\r\n }\r\n }",
"public int getVertices(double[] coords) {\n for (int i = 0; i < numVertices; i++) {\n Point3d pnt = pointBuffer[vertexPointIndices[i]].pnt;\n coords[i * 3 + 0] = pnt.x;\n coords[i * 3 + 1] = pnt.y;\n coords[i * 3 + 2] = pnt.z;\n }\n return numVertices;\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 }",
"public static void sendMimeMessage(MimeMessage mimeMessage) {\r\n try {\r\n Transport.send(mimeMessage);\r\n } catch (MessagingException e) {\r\n throw new IllegalStateException(\"Can not send message \" + mimeMessage, e);\r\n }\r\n }",
"@VisibleForTesting\n protected static Dimension getSize(\n final ScalebarAttributeValues scalebarParams,\n final ScaleBarRenderSettings settings, final Dimension maxLabelSize) {\n final float width;\n final float height;\n if (scalebarParams.getOrientation().isHorizontal()) {\n width = 2 * settings.getPadding()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getLeftLabelMargin() + settings.getRightLabelMargin();\n height = 2 * settings.getPadding()\n + settings.getBarSize() + settings.getLabelDistance()\n + Label.getRotatedHeight(maxLabelSize, scalebarParams.getLabelRotation());\n } else {\n width = 2 * settings.getPadding()\n + settings.getLabelDistance() + settings.getBarSize()\n + Label.getRotatedWidth(maxLabelSize, scalebarParams.getLabelRotation());\n height = 2 * settings.getPadding()\n + settings.getTopLabelMargin()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getBottomLabelMargin();\n }\n return new Dimension((int) Math.ceil(width), (int) Math.ceil(height));\n }"
] |
Extracts the bindingId from a Server.
@param server
@return | [
"private static String getBindingId(Server server) {\n Endpoint ep = server.getEndpoint();\n BindingInfo bi = ep.getBinding().getBindingInfo();\n return bi.getBindingId();\n }"
] | [
"private static <T, ID> void addDropTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, boolean logDetails) {\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\tdatabaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter);\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"dropping table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"DROP TABLE \");\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(' ');\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t}",
"private CmsFavInfo createFavInfo(CmsFavoriteEntry entry) throws CmsException {\n\n String title = \"\";\n String subtitle = \"\";\n CmsFavInfo result = new CmsFavInfo(entry);\n CmsObject cms = A_CmsUI.getCmsObject();\n String project = getProject(cms, entry);\n String site = getSite(cms, entry);\n try {\n CmsUUID idToLoad = entry.getDetailId() != null ? entry.getDetailId() : entry.getStructureId();\n CmsResource resource = cms.readResource(idToLoad, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n CmsResourceUtil resutil = new CmsResourceUtil(cms, resource);\n switch (entry.getType()) {\n case explorerFolder:\n title = CmsStringUtil.isEmpty(resutil.getTitle())\n ? CmsResource.getName(resource.getRootPath())\n : resutil.getTitle();\n break;\n case page:\n title = resutil.getTitle();\n break;\n }\n subtitle = resource.getRootPath();\n CmsResourceIcon icon = result.getResourceIcon();\n icon.initContent(resutil, CmsResource.STATE_UNCHANGED, false, false);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n result.getTopLine().setValue(title);\n result.getBottomLine().setValue(subtitle);\n result.getProjectLabel().setValue(project);\n result.getSiteLabel().setValue(site);\n\n return result;\n\n }",
"public static String encodeScheme(String scheme, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(scheme, encoding, HierarchicalUriComponents.Type.SCHEME);\n\t}",
"public byte[] serialize() throws PersistenceBrokerException\r\n {\r\n // Identity is serialized and written to an ObjectOutputStream\r\n // This ObjectOutputstream is compressed by a GZIPOutputStream\r\n // and finally written to a ByteArrayOutputStream.\r\n // the resulting byte[] is returned\r\n try\r\n {\r\n final ByteArrayOutputStream bao = new ByteArrayOutputStream();\r\n final GZIPOutputStream gos = new GZIPOutputStream(bao);\r\n final ObjectOutputStream oos = new ObjectOutputStream(gos);\r\n oos.writeObject(this);\r\n oos.close();\r\n gos.close();\r\n bao.close();\r\n return bao.toByteArray();\r\n }\r\n catch (Exception ignored)\r\n {\r\n throw new PersistenceBrokerException(ignored);\r\n }\r\n }",
"public static Result get(XmlFileModel key)\n {\n String cacheKey = getKey(key);\n\n Result result = null;\n CacheDocument reference = map.get(cacheKey);\n\n if (reference == null)\n return new Result(false, null);\n\n if (reference.parseFailure)\n return new Result(true, null);\n\n Document document = reference.getDocument();\n if (document == null)\n LOG.info(\"Cache miss on XML document: \" + cacheKey);\n\n return new Result(false, document);\n }",
"public void init(Configuration configuration) {\n if (devMode && reload && !listeningToDispatcher) {\n // this is the only way I found to be able to get added to to\n // ConfigurationProvider list\n // listening to events in Dispatcher\n listeningToDispatcher = true;\n Dispatcher.addDispatcherListener(this);\n }\n }",
"private static void computeBadByteSkipArray(byte[] pattern, int[] badByteArray) {\n for (int a = 0; a < ALPHABET_SIZE; a++) {\n badByteArray[a] = pattern.length;\n }\n\n for (int j = 0; j < pattern.length - 1; j++) {\n badByteArray[pattern[j] - Byte.MIN_VALUE] = pattern.length - j - 1;\n }\n }",
"private StepFormatter.Formatting<?, ?> getFormatting( Annotation[] annotations, Set<Class<?>> visitedTypes,\n Annotation originalAnnotation, String parameterName ) {\n List<StepFormatter.Formatting<?, ?>> foundFormatting = Lists.newArrayList();\n Table tableAnnotation = null;\n for( Annotation annotation : annotations ) {\n try {\n if( annotation instanceof Format ) {\n Format arg = (Format) annotation;\n foundFormatting.add( new StepFormatter.ArgumentFormatting( ReflectionUtil.newInstance( arg.value() ), arg.args() ) );\n } else if( annotation instanceof Table ) {\n tableAnnotation = (Table) annotation;\n } else if( annotation instanceof AnnotationFormat ) {\n AnnotationFormat arg = (AnnotationFormat) annotation;\n foundFormatting.add( new StepFormatter.ArgumentFormatting(\n new StepFormatter.AnnotationBasedFormatter( arg.value().newInstance(), originalAnnotation ) ) );\n } else {\n Class<? extends Annotation> annotationType = annotation.annotationType();\n if( !visitedTypes.contains( annotationType ) ) {\n visitedTypes.add( annotationType );\n StepFormatter.Formatting<?, ?> formatting = getFormatting( annotationType.getAnnotations(), visitedTypes,\n annotation, parameterName );\n if( formatting != null ) {\n foundFormatting.add( formatting );\n }\n }\n }\n } catch( Exception e ) {\n throw Throwables.propagate( e );\n }\n }\n\n if( foundFormatting.size() > 1 ) {\n Formatting<?, ?> innerFormatting = Iterables.getLast( foundFormatting );\n foundFormatting.remove( innerFormatting );\n\n ChainedFormatting<?> chainedFormatting = new StepFormatter.ChainedFormatting<Object>( (ObjectFormatter<Object>) innerFormatting );\n for( StepFormatter.Formatting<?, ?> formatting : Lists.reverse( foundFormatting ) ) {\n chainedFormatting.addFormatting( (StepFormatter.Formatting<?, String>) formatting );\n }\n\n foundFormatting.clear();\n foundFormatting.add( chainedFormatting );\n }\n\n if( tableAnnotation != null ) {\n ObjectFormatter<?> objectFormatter = foundFormatting.isEmpty()\n ? DefaultFormatter.INSTANCE\n : foundFormatting.get( 0 );\n return getTableFormatting( annotations, parameterName, tableAnnotation, objectFormatter );\n }\n\n if( foundFormatting.isEmpty() ) {\n return null;\n }\n\n return foundFormatting.get( 0 );\n }",
"public static void shutdownDomain(final ModelControllerClient client, final int timeout) throws IOException, OperationExecutionException {\n // Note the following two operations used to shutdown a domain don't seem to work well in a composite operation.\n // The operation occasionally sees a java.util.concurrent.CancellationException because the operation client\n // is likely closed before the AsyncFuture.get() is complete. Using a non-composite operation doesn't seem to\n // have this issue.\n\n // First shutdown the servers\n final ModelNode stopServersOp = Operations.createOperation(\"stop-servers\");\n stopServersOp.get(\"blocking\").set(true);\n stopServersOp.get(\"timeout\").set(timeout);\n ModelNode response = client.execute(stopServersOp);\n if (!Operations.isSuccessfulOutcome(response)) {\n throw new OperationExecutionException(\"Failed to stop servers.\", stopServersOp, response);\n }\n\n // Now shutdown the host\n final ModelNode address = determineHostAddress(client);\n final ModelNode shutdownOp = Operations.createOperation(\"shutdown\", address);\n response = client.execute(shutdownOp);\n if (Operations.isSuccessfulOutcome(response)) {\n // Wait until the process has died\n while (true) {\n if (isDomainRunning(client, true)) {\n try {\n TimeUnit.MILLISECONDS.sleep(20L);\n } catch (InterruptedException e) {\n LOGGER.trace(\"Interrupted during sleep\", e);\n }\n } else {\n break;\n }\n }\n } else {\n throw new OperationExecutionException(\"Failed to shutdown host.\", shutdownOp, response);\n }\n }"
] |
Obtains the collection of server groups defined for a profile
@param model
@param profileId
@return
@throws Exception | [
"@RequestMapping(value = \"api/servergroup\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getServerGroups(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"search\", required = false) String search,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId);\n\n if (search != null) {\n Iterator<ServerGroup> iterator = serverGroups.iterator();\n while (iterator.hasNext()) {\n ServerGroup serverGroup = iterator.next();\n if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) {\n iterator.remove();\n }\n }\n }\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, \"servergroups\");\n return returnJson;\n }"
] | [
"public ManagementModelNode findNode(String address) {\n ManagementModelNode root = (ManagementModelNode)tree.getModel().getRoot();\n Enumeration<javax.swing.tree.TreeNode> allNodes = root.depthFirstEnumeration();\n while (allNodes.hasMoreElements()) {\n ManagementModelNode node = (ManagementModelNode)allNodes.nextElement();\n if (node.addressPath().equals(address)) return node;\n }\n\n return null;\n }",
"public Versioned<E> getVersionedById(int id) {\n Versioned<VListNode<E>> listNode = getListNode(id);\n if(listNode == null)\n throw new IndexOutOfBoundsException();\n return new Versioned<E>(listNode.getValue().getValue(), listNode.getVersion());\n }",
"public void mark() {\n final long currentTimeMillis = clock.currentTimeMillis();\n\n synchronized (queue) {\n if (queue.size() == capacity) {\n /*\n * we're all filled up already, let's dequeue the oldest\n * timestamp to make room for this new one.\n */\n queue.removeFirst();\n }\n queue.addLast(currentTimeMillis);\n }\n }",
"@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n // Calculate summaries.\n summaryListener.suiteSummary(e);\n\n Description suiteDescription = e.getDescription();\n String displayName = suiteDescription.getDisplayName();\n if (displayName.trim().isEmpty()) {\n junit4.log(\"Could not emit XML report for suite (null description).\", \n Project.MSG_WARN);\n return;\n }\n\n if (!suiteCounts.containsKey(displayName)) {\n suiteCounts.put(displayName, 1);\n } else {\n int newCount = suiteCounts.get(displayName) + 1;\n suiteCounts.put(displayName, newCount);\n if (!ignoreDuplicateSuites && newCount == 2) {\n junit4.log(\"Duplicate suite name used with XML reports: \"\n + displayName + \". This may confuse tools that process XML reports. \"\n + \"Set 'ignoreDuplicateSuites' to true to skip this message.\", Project.MSG_WARN);\n }\n displayName = displayName + \"-\" + newCount;\n }\n \n try {\n File reportFile = new File(dir, \"TEST-\" + displayName + \".xml\");\n RegistryMatcher rm = new RegistryMatcher();\n rm.bind(String.class, new XmlStringTransformer());\n Persister persister = new Persister(rm);\n persister.write(buildModel(e), reportFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize report for suite \"\n + displayName + \": \" + x.toString(), x, Project.MSG_WARN);\n }\n }",
"public void cleanup() {\n synchronized (_sslMap) {\n for (SslRelayOdo relay : _sslMap.values()) {\n if (relay.getHttpServer() != null && relay.isStarted()) {\n relay.getHttpServer().removeListener(relay);\n }\n }\n\n sslRelays.clear();\n }\n }",
"protected <T> T getDatamodelObjectFromResponse(JsonNode response, List<String> path, Class<T> targetClass) throws JsonProcessingException {\n\t\tif(response == null) {\n\t\t\tthrow new JsonMappingException(\"The API response is null\");\n\t\t}\n\t\tJsonNode currentNode = response;\n\t\tfor(String field : path) {\n\t\t\tif (!currentNode.has(field)) {\n\t\t\t\tthrow new JsonMappingException(\"Field '\"+field+\"' not found in API response.\");\n\t\t\t}\n\t\t\tcurrentNode = currentNode.path(field);\n\t\t}\n\t\treturn mapper.treeToValue(currentNode, targetClass);\n\t}",
"public void setDefaultInterval(long defaultInterval) {\n \tif(defaultInterval <= 0) {\n \t\tLOG.severe(\"collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is \" + defaultInterval);\n \t\tthrow new IllegalArgumentException(\"collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is \" + defaultInterval);\n \t}\n this.defaultInterval = defaultInterval;\n }",
"public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {\n\t\tif (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {\n\t\t\tGenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\tGenericBeanDefinition def = new GenericBeanDefinition();\n\t\t\tdef.setBeanClassName(genericInfo.getClassName());\n\t\t\tif (genericInfo.getPropertyValues() != null) {\n\t\t\t\tMutablePropertyValues propertyValues = new MutablePropertyValues();\n\t\t\t\tfor (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {\n\t\t\t\t\tBeanMetadataElementInfo info = entry.getValue();\n\t\t\t\t\tpropertyValues.add(entry.getKey(), toInternal(info));\n\t\t\t\t}\n\t\t\t\tdef.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {\n\t\t\tObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\treturn createBeanDefinitionByIntrospection(objectInfo.getObject());\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to internal of \" + beanDefinitionInfo.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}",
"public void delete(Object element, boolean testForEquality) {\r\n\tint index = indexOfFromTo(element, 0, size-1, testForEquality);\r\n\tif (index>=0) removeFromTo(index,index);\r\n}"
] |
This method takes the textual version of a priority
and returns an appropriate instance of this class. Note that unrecognised
values are treated as medium priority.
@param locale target locale
@param priority text version of the priority
@return Priority class instance | [
"public static Priority getInstance(Locale locale, String priority)\n {\n int index = DEFAULT_PRIORITY_INDEX;\n\n if (priority != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(locale, LocaleData.PRIORITY_TYPES);\n for (int loop = 0; loop < priorityTypes.length; loop++)\n {\n if (priorityTypes[loop].equalsIgnoreCase(priority) == true)\n {\n index = loop;\n break;\n }\n }\n }\n\n return (Priority.getInstance((index + 1) * 100));\n }"
] | [
"public static MapBounds adjustBoundsToScaleAndMapSize(\n final GenericMapAttributeValues mapValues,\n final Rectangle paintArea,\n final MapBounds bounds,\n final double dpi) {\n MapBounds newBounds = bounds;\n if (mapValues.isUseNearestScale()) {\n newBounds = newBounds.adjustBoundsToNearestScale(\n mapValues.getZoomLevels(),\n mapValues.getZoomSnapTolerance(),\n mapValues.getZoomLevelSnapStrategy(),\n mapValues.getZoomSnapGeodetic(),\n paintArea, dpi);\n }\n\n newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));\n\n if (mapValues.isUseAdjustBounds()) {\n newBounds = newBounds.adjustedEnvelope(paintArea);\n }\n return newBounds;\n }",
"public HttpConnection setRequestBody(final String input) {\n try {\n final byte[] inputBytes = input.getBytes(\"UTF-8\");\n return setRequestBody(inputBytes);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n }\n }",
"public static boolean validate(Statement stmt) {\n try {\n Connection conn = stmt.getConnection();\n if (conn == null)\n return false;\n\n if (!conn.isClosed() && conn.isValid(10))\n return true;\n\n stmt.close();\n conn.close();\n } catch (SQLException e) {\n // this may well fail. that doesn't matter. we're just making an\n // attempt to clean up, and if we can't, that's just too bad.\n }\n return false;\n }",
"public static String createResource(\n CmsObject cmsObject,\n String newLink,\n Locale locale,\n String sitePath,\n String modelFileName,\n String mode,\n String postCreateHandler) {\n\n String[] newLinkParts = newLink.split(\"\\\\|\");\n String rootPath = newLinkParts[1];\n String typeName = newLinkParts[2];\n CmsFile modelFile = null;\n if (StringUtils.equalsIgnoreCase(mode, CmsEditorConstants.MODE_COPY)) {\n try {\n modelFile = cmsObject.readFile(sitePath);\n } catch (CmsException e) {\n LOG.warn(\n \"The resource at path\" + sitePath + \"could not be read. Thus it can not be used as model file.\",\n e);\n }\n }\n CmsADEConfigData adeConfig = OpenCms.getADEManager().lookupConfiguration(cmsObject, rootPath);\n CmsResourceTypeConfig typeConfig = adeConfig.getResourceType(typeName);\n CmsResource newElement = null;\n try {\n CmsObject cmsClone = cmsObject;\n if ((locale != null) && !cmsObject.getRequestContext().getLocale().equals(locale)) {\n // in case the content locale does not match the request context locale, use a clone cms with the appropriate locale\n cmsClone = OpenCms.initCmsObject(cmsObject);\n cmsClone.getRequestContext().setLocale(locale);\n }\n newElement = typeConfig.createNewElement(cmsClone, modelFile, rootPath);\n CmsPair<String, String> handlerParameter = I_CmsCollectorPostCreateHandler.splitClassAndConfig(\n postCreateHandler);\n I_CmsCollectorPostCreateHandler handler = A_CmsResourceCollector.getPostCreateHandler(\n handlerParameter.getFirst());\n handler.onCreate(cmsClone, cmsClone.readFile(newElement), modelFile != null, handlerParameter.getSecond());\n } catch (CmsException e) {\n LOG.error(\"Could not create resource.\", e);\n }\n return newElement == null ? null : cmsObject.getSitePath(newElement);\n }",
"public static base_response unset(nitro_service client, coparameter resource, String[] args) throws Exception{\n\t\tcoparameter unsetresource = new coparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n String dir = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean verbose = false;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_DIR)) {\n dir = (String) options.valueOf(AdminParserUtils.OPT_DIR);\n }\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n if(options.has(OPT_VERBOSE)) {\n verbose = true;\n }\n\n // execute command\n File directory = AdminToolUtils.createDir(dir);\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {\n metaKeys = Lists.newArrayList();\n for(Object key: MetadataStore.METADATA_KEYS) {\n metaKeys.add((String) key);\n }\n }\n\n doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose);\n }",
"protected String parseOptionalStringValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n return value.getStringValue(null);\n }\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 }",
"protected void updateNorms( int j ) {\n boolean foundNegative = false;\n for( int col = j; col < numCols; col++ ) {\n double e = dataQR[col][j-1];\n double v = normsCol[col] -= e*e;\n\n if( v < 0 ) {\n foundNegative = true;\n break;\n }\n }\n\n // if a negative sum has been found then clearly too much precision has been lost\n // and it should recompute the column norms from scratch\n if( foundNegative ) {\n for( int col = j; col < numCols; col++ ) {\n double u[] = dataQR[col];\n double actual = 0;\n for( int i=j; i < numRows; i++ ) {\n double v = u[i];\n actual += v*v;\n }\n normsCol[col] = actual;\n }\n }\n }"
] |
Return the discount factor within a given model context for a given maturity.
@param model The model used as a context (not required for this class).
@param maturity The maturity in terms of ACT/365 daycount form this curve reference date. Note that this parameter might get rescaled to a different time parameter.
@see net.finmath.marketdata.model.curves.DiscountCurveInterface#getDiscountFactor(net.finmath.marketdata.model.AnalyticModelInterface, double) | [
"@Override\n\tpublic double getDiscountFactor(AnalyticModelInterface model, double maturity)\n\t{\n\t\t// Change time scale\n\t\tmaturity *= timeScaling;\n\n\t\tdouble beta1\t= parameter[0];\n\t\tdouble beta2\t= parameter[1];\n\t\tdouble beta3\t= parameter[2];\n\t\tdouble beta4\t= parameter[3];\n\t\tdouble tau1\t\t= parameter[4];\n\t\tdouble tau2\t\t= parameter[5];\n\n\t\tdouble x1 = tau1 > 0 ? FastMath.exp(-maturity/tau1) : 0.0;\n\t\tdouble x2 = tau2 > 0 ? FastMath.exp(-maturity/tau2) : 0.0;\n\n\t\tdouble y1 = tau1 > 0 ? (maturity > 0.0 ? (1.0-x1)/maturity*tau1 : 1.0) : 0.0;\n\t\tdouble y2 = tau2 > 0 ? (maturity > 0.0 ? (1.0-x2)/maturity*tau2 : 1.0) : 0.0;\n\n\t\tdouble zeroRate = beta1 + beta2 * y1 + beta3 * (y1-x1) + beta4 * (y2-x2);\n\n\t\treturn Math.exp(- zeroRate * maturity);\n\t}"
] | [
"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 static base_response Import(nitro_service client, application resource) throws Exception {\n\t\tapplication Importresource = new application();\n\t\tImportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\tImportresource.appname = resource.appname;\n\t\tImportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"public static DMatrixRMaj identity(int numRows , int numCols )\n {\n DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);\n\n int small = numRows < numCols ? numRows : numCols;\n\n for( int i = 0; i < small; i++ ) {\n ret.set(i,i,1.0);\n }\n\n return ret;\n }",
"private void attachMeta(final JSONObject o, final Context context) {\n // Memory consumption\n try {\n o.put(\"mc\", Utils.getMemoryConsumption());\n } catch (Throwable t) {\n // Ignore\n }\n\n // Attach the network type\n try {\n o.put(\"nt\", Utils.getCurrentNetworkType(context));\n } catch (Throwable t) {\n // Ignore\n }\n }",
"private void writeCustomField(CustomField field) throws IOException\n {\n if (field.getAlias() != null)\n {\n m_writer.writeStartObject(null);\n m_writer.writeNameValuePair(\"field_type_class\", field.getFieldType().getFieldTypeClass().name().toLowerCase());\n m_writer.writeNameValuePair(\"field_type\", field.getFieldType().name().toLowerCase());\n m_writer.writeNameValuePair(\"field_alias\", field.getAlias());\n m_writer.writeEndObject();\n }\n }",
"private Field getFieldRecursive(Class c, String name) throws NoSuchFieldException\r\n {\r\n try\r\n {\r\n return c.getDeclaredField(name);\r\n }\r\n catch (NoSuchFieldException e)\r\n {\r\n // if field could not be found in the inheritance hierarchy, signal error\r\n if ((c == Object.class) || (c.getSuperclass() == null) || c.isInterface())\r\n {\r\n throw e;\r\n }\r\n // if field could not be found in class c try in superclass\r\n else\r\n {\r\n return getFieldRecursive(c.getSuperclass(), name);\r\n }\r\n }\r\n }",
"@Override\n\tprotected final void subAppend(final LoggingEvent event) {\n\t\tif (event instanceof ScheduledFileRollEvent) {\n\t\t\t// the scheduled append() call has been made by a different thread\n\t\t\tsynchronized (this) {\n\t\t\t\tif (this.closed) {\n\t\t\t\t\t// just consume the event\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.rollFile(event);\n\t\t\t}\n\t\t} else if (event instanceof FileRollEvent) {\n\t\t\t// definitely want to avoid rolling here whilst a file roll event is still being handled\n\t\t\tsuper.subAppend(event);\n\t\t} else {\n\n\t\t\tif(event instanceof FoundationLof4jLoggingEvent){\n\t\t\t\tFoundationLof4jLoggingEvent foundationLof4jLoggingEvent = (FoundationLof4jLoggingEvent)event;\n\t\t\t\tfoundationLof4jLoggingEvent.setAppenderName(this.getName());\n\t\t\t}\n\t\t\t\n\t\t\tthis.rollFile(event);\n\t\t\tsuper.subAppend(event);\n\t\t}\n\t}",
"public static Interface get(nitro_service service, String id) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tobj.set_id(id);\n\t\tInterface response = (Interface) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static gslbservice_stats get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice_stats response = (gslbservice_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] |
Read a single calendar exception.
@param bc parent calendar
@param exception exception data | [
"private void readException(ProjectCalendar bc, Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n Date fromDate = exception.getTimePeriod().getFromDate();\n Date toDate = exception.getTimePeriod().getToDate();\n\n // Vico Schedule Planner seems to write start and end dates to FromTime and ToTime\n // rather than FromDate and ToDate. This is plain wrong, and appears to be ignored by MS Project\n // so we will ignore it too!\n if (fromDate != null && toDate != null)\n {\n ProjectCalendarException bce = bc.addCalendarException(fromDate, toDate);\n bce.setName(exception.getName());\n readRecurringData(bce, exception);\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = exception.getWorkingTimes();\n if (times != null)\n {\n List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> time = times.getWorkingTime();\n for (Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime period : time)\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n bce.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }\n }"
] | [
"public static String takeWhile(GString self, @ClosureParams(value=SimpleType.class, options=\"char\") Closure condition) {\n return (String) takeWhile(self.toString(), condition);\n }",
"private Set<HttpMethod> getHttpMethods(Method method) {\n Set<HttpMethod> httpMethods = new HashSet<>();\n\n if (method.isAnnotationPresent(GET.class)) {\n httpMethods.add(HttpMethod.GET);\n }\n if (method.isAnnotationPresent(PUT.class)) {\n httpMethods.add(HttpMethod.PUT);\n }\n if (method.isAnnotationPresent(POST.class)) {\n httpMethods.add(HttpMethod.POST);\n }\n if (method.isAnnotationPresent(DELETE.class)) {\n httpMethods.add(HttpMethod.DELETE);\n }\n\n return Collections.unmodifiableSet(httpMethods);\n }",
"private static void checkSorted(int[] sorted) {\r\n for (int i = 0; i < sorted.length-1; i++) {\r\n if (sorted[i] > sorted[i+1]) {\r\n throw new RuntimeException(\"input must be sorted!\");\r\n }\r\n }\r\n }",
"private org.apache.tools.ant.types.Path resolveFiles(org.apache.tools.ant.types.Path path) {\n org.apache.tools.ant.types.Path cloned = new org.apache.tools.ant.types.Path(getProject());\n for (String location : path.list()) {\n cloned.createPathElement().setLocation(new File(location));\n }\n return cloned;\n }",
"public List<String> parseMethodList(String methods) {\n\n String[] methodArray = StringUtils.delimitedListToStringArray(methods, \",\");\n\n List<String> methodList = new ArrayList<String>();\n\n for (String methodName : methodArray) {\n methodList.add(methodName.trim());\n }\n return methodList;\n }",
"protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }",
"public static void validateInterimFinalCluster(final Cluster interimCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(interimCluster, finalCluster);\n validateClusterZonesSame(interimCluster, finalCluster);\n validateClusterNodeCounts(interimCluster, finalCluster);\n validateClusterNodeState(interimCluster, finalCluster);\n return;\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}",
"protected static void writeErrorResponse(final Channel channel, final ManagementRequestHeader header, final Throwable error) throws IOException {\n final ManagementResponseHeader response = ManagementResponseHeader.create(header, error);\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }"
] |
Deletes a product from the database
@param name String | [
"public void deleteProduct(final String name) {\n final DbProduct dbProduct = getProduct(name);\n repositoryHandler.deleteProduct(dbProduct.getName());\n }"
] | [
"public double distanceFrom(LatLong end) {\n\n double dLat = (end.getLatitude() - getLatitude()) * Math.PI / 180;\n double dLon = (end.getLongitude() - getLongitude()) * Math.PI / 180;\n\n double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)\n + Math.cos(getLatitude() * Math.PI / 180)\n * Math.cos(end.getLatitude() * Math.PI / 180)\n * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n\n double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n double d = EarthRadiusMeters * c;\n return d;\n }",
"public Collection<Group> getPublicGroups(String userId) throws FlickrException {\r\n List<Group> groups = new ArrayList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_GROUPS);\r\n\r\n parameters.put(\"user_id\", userId);\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 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 group.setAdmin(\"1\".equals(groupElement.getAttribute(\"admin\")));\r\n group.setEighteenPlus(groupElement.getAttribute(\"eighteenplus\").equals(\"0\") ? false : true);\r\n groups.add(group);\r\n }\r\n return groups;\r\n }",
"private String normalizePath(String scriptPath) {\n StringBuilder builder = new StringBuilder(scriptPath.length() + 1);\n if (scriptPath.startsWith(\"/\")) {\n builder.append(scriptPath.substring(1));\n } else {\n builder.append(scriptPath);\n }\n if (!scriptPath.endsWith(\"/\")) {\n builder.append(\"/\");\n }\n return builder.toString();\n }",
"public Map<String, String> resolve(Map<String, String> config) {\n config = resolveSystemEnvironmentVariables(config);\n config = resolveSystemDefaultSetup(config);\n config = resolveDockerInsideDocker(config);\n config = resolveDownloadDockerMachine(config);\n config = resolveAutoStartDockerMachine(config);\n config = resolveDefaultDockerMachine(config);\n config = resolveServerUriByOperativeSystem(config);\n config = resolveServerIp(config);\n config = resolveTlsVerification(config);\n return config;\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 }",
"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 BMatrixRMaj randomBinary(int numRow , int numCol , Random rand ) {\n BMatrixRMaj mat = new BMatrixRMaj(numRow,numCol);\n\n setRandomB(mat, rand);\n\n return mat;\n }",
"public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {\n\n org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(\n currentModule.groupId, currentModule.artifactId);\n\n Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap();\n for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) {\n modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName(\n entry.getKey().groupId, entry.getKey().artifactId), entry.getValue());\n }\n\n org.jfrog.build.extractor.maven.transformer.PomTransformer transformer =\n new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl,\n failOnSnapshot);\n\n return transformer.transform(pomFile);\n }",
"public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\n }"
] |
Return any feedback messages and errors that were generated - but
suppressed - during the interpolation process. Since unresolvable
expressions will be left in the source string as-is, this feedback is
optional, and will only be useful for debugging interpolation problems.
@return a {@link List} that may be interspersed with {@link String} and
{@link Throwable} instances. | [
"public List getFeedback()\n\t {\n\t List<?> messages = new ArrayList();\n\t for ( ValueSource vs : valueSources )\n\t {\n\t List feedback = vs.getFeedback();\n\t if ( feedback != null && !feedback.isEmpty() )\n\t {\n\t messages.addAll( feedback );\n\t }\n\t }\n\n\t return messages;\n\t }"
] | [
"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 static void append(Path self, Object text) throws IOException {\n Writer writer = null;\n try {\n writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.defaultCharset());\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }",
"private void bubbleUpNodeTable(DAGraph<DataT, NodeT> from, LinkedList<String> path) {\n if (path.contains(from.rootNode.key())) {\n path.push(from.rootNode.key()); // For better error message\n throw new IllegalStateException(\"Detected circular dependency: \" + StringUtils.join(path, \" -> \"));\n }\n path.push(from.rootNode.key());\n for (DAGraph<DataT, NodeT> to : from.parentDAGs) {\n this.merge(from.nodeTable, to.nodeTable);\n this.bubbleUpNodeTable(to, path);\n }\n path.pop();\n }",
"private String formatPriority(Priority value)\n {\n String result = null;\n\n if (value != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(m_locale, LocaleData.PRIORITY_TYPES);\n int priority = value.getValue();\n if (priority < Priority.LOWEST)\n {\n priority = Priority.LOWEST;\n }\n else\n {\n if (priority > Priority.DO_NOT_LEVEL)\n {\n priority = Priority.DO_NOT_LEVEL;\n }\n }\n\n priority /= 100;\n\n result = priorityTypes[priority - 1];\n }\n\n return (result);\n }",
"public static base_responses delete(nitro_service client, String ipv6address[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ipv6address != null && ipv6address.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[ipv6address.length];\n\t\t\tfor (int i=0;i<ipv6address.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = ipv6address[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void setModelByText(String model) {\r\n try {\r\n InputStream is = new ByteArrayInputStream(model.getBytes());\r\n this.model = SCXMLParser.parse(new InputSource(is), null, customActionsFromTagExtensions());\r\n this.setStateMachine(this.model);\r\n } catch (IOException | SAXException | ModelException e) {\r\n e.printStackTrace();\r\n }\r\n }",
"public String toStringByValue() {\r\n\tIntArrayList theKeys = new IntArrayList();\r\n\tkeysSortedByValue(theKeys);\r\n\r\n\tStringBuffer buf = new StringBuffer();\r\n\tbuf.append(\"[\");\r\n\tint maxIndex = theKeys.size() - 1;\r\n\tfor (int i = 0; i <= maxIndex; i++) {\r\n\t\tint key = theKeys.get(i);\r\n\t buf.append(String.valueOf(key));\r\n\t\tbuf.append(\"->\");\r\n\t buf.append(String.valueOf(get(key)));\r\n\t\tif (i < maxIndex) buf.append(\", \");\r\n\t}\r\n\tbuf.append(\"]\");\r\n\treturn buf.toString();\r\n}",
"public static base_response add(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile addresource = new autoscaleprofile();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.url = resource.url;\n\t\taddresource.apikey = resource.apikey;\n\t\taddresource.sharedsecret = resource.sharedsecret;\n\t\treturn addresource.add_resource(client);\n\t}",
"protected boolean hasTimeStampHeader() {\n String originTime = request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS);\n boolean result = false;\n if(originTime != null) {\n try {\n // TODO: remove the originTime field from request header,\n // because coordinator should not accept the request origin time\n // from the client.. In this commit, we only changed\n // \"this.parsedRequestOriginTimeInMs\" from\n // \"Long.parseLong(originTime)\" to current system time,\n // The reason that we did not remove the field from request\n // header right now, is because this commit is a quick fix for\n // internal performance test to be available as soon as\n // possible.\n\n this.parsedRequestOriginTimeInMs = System.currentTimeMillis();\n if(this.parsedRequestOriginTimeInMs < 0) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Origin time cannot be negative \");\n\n } else {\n result = true;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect origin time parameter. Cannot parse this to long: \"\n + originTime,\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect origin time parameter. Cannot parse this to long: \"\n + originTime);\n }\n } else {\n logger.error(\"Error when validating request. Missing origin time parameter.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing origin time parameter.\");\n }\n return result;\n }"
] |
Send a device found announcement to all registered listeners.
@param announcement the message announcing the new device | [
"private void deliverFoundAnnouncement(final DeviceAnnouncement announcement) {\n for (final DeviceAnnouncementListener listener : getDeviceAnnouncementListeners()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n listener.deviceFound(announcement);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device found announcement to listener\", t);\n }\n }\n });\n }\n }"
] | [
"public void removeHoursFromDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = null;\n }",
"protected FieldDescriptor resolvePayloadField(Message message) {\n for (FieldDescriptor field : message.getDescriptorForType().getFields()) {\n if (message.hasField(field)) {\n return field;\n }\n }\n\n throw new RuntimeException(\"No payload found in message \" + message);\n }",
"public static boolean isSafe(Expression expression) {\r\n if (expression instanceof MethodCallExpression) {\r\n return ((MethodCallExpression) expression).isSafe();\r\n }\r\n if (expression instanceof PropertyExpression) {\r\n return ((PropertyExpression) expression).isSafe();\r\n }\r\n return false;\r\n }",
"public ManageableCollection getCollectionByQuery(Class collectionClass, Query query)\n throws PersistenceBrokerException\n {\n return referencesBroker.getCollectionByQuery(collectionClass, query, false);\n }",
"public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name,\n CreateUserParams params) {\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"login\", login);\n requestJSON.add(\"name\", name);\n\n if (params != null) {\n if (params.getRole() != null) {\n requestJSON.add(\"role\", params.getRole().toJSONValue());\n }\n\n if (params.getStatus() != null) {\n requestJSON.add(\"status\", params.getStatus().toJSONValue());\n }\n\n requestJSON.add(\"language\", params.getLanguage());\n requestJSON.add(\"is_sync_enabled\", params.getIsSyncEnabled());\n requestJSON.add(\"job_title\", params.getJobTitle());\n requestJSON.add(\"phone\", params.getPhone());\n requestJSON.add(\"address\", params.getAddress());\n requestJSON.add(\"space_amount\", params.getSpaceAmount());\n requestJSON.add(\"can_see_managed_users\", params.getCanSeeManagedUsers());\n requestJSON.add(\"timezone\", params.getTimezone());\n requestJSON.add(\"is_exempt_from_device_limits\", params.getIsExemptFromDeviceLimits());\n requestJSON.add(\"is_exempt_from_login_verification\", params.getIsExemptFromLoginVerification());\n requestJSON.add(\"is_platform_access_only\", params.getIsPlatformAccessOnly());\n requestJSON.add(\"external_app_user_id\", params.getExternalAppUserId());\n }\n\n URL url = USERS_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxUser createdUser = new BoxUser(api, responseJSON.get(\"id\").asString());\n return createdUser.new Info(responseJSON);\n }",
"protected NodeData createBodyStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"background-color\", tf.createColor(255, 255, 255)));\n return ret;\n }",
"private static void listHierarchy(Task task, String indent)\n {\n for (Task child : task.getChildTasks())\n {\n System.out.println(indent + \"Task: \" + child.getName() + \"\\t\" + child.getStart() + \"\\t\" + child.getFinish());\n listHierarchy(child, indent + \" \");\n }\n }",
"public static boolean isAssignableFrom(TypeReference<?> from, TypeReference<?> to) {\n\t\tif (from == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (to.equals(from)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (to.getType() instanceof Class) {\n\t\t\treturn to.getRawType().isAssignableFrom(from.getRawType());\n\t\t} else if (to.getType() instanceof ParameterizedType) {\n\t\t\treturn isAssignableFrom(from.getType(), (ParameterizedType) to\n\t\t\t\t\t.getType(), new HashMap<String, Type>());\n\t\t} else if (to.getType() instanceof GenericArrayType) {\n\t\t\treturn to.getRawType().isAssignableFrom(from.getRawType())\n\t\t\t\t\t&& isAssignableFrom(from.getType(), (GenericArrayType) to\n\t\t\t\t\t\t\t.getType());\n\t\t} else {\n\t\t\tthrow new AssertionError(\"Unexpected Type : \" + to);\n\t\t}\n\t}",
"public InetSocketAddress getMulticastSocketAddress() {\n if (multicastAddress == null) {\n throw MESSAGES.noMulticastBinding(name);\n }\n return new InetSocketAddress(multicastAddress, multicastPort);\n }"
] |
Locates the services in the context classloader of the current thread.
@param serviceType the type of the services to locate
@param <X> the type of the service
@return the service type loader | [
"public static <X> ServiceTypeLoader<X> load(Class<X> serviceType) {\n return load(serviceType, Thread.currentThread().getContextClassLoader());\n }"
] | [
"public static String getDumpFileDirectoryName(\n\t\t\tDumpContentType dumpContentType, String dateStamp) {\n\t\treturn dumpContentType.toString().toLowerCase() + \"-\" + dateStamp;\n\t}",
"@Override\n public int getShadowSize() {\n\tElement shadowElement = shadow.getElement();\n\tshadowElement.setScrollTop(10000);\n\treturn shadowElement.getScrollTop();\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 }",
"public static boolean isEasterSunday(LocalDate date) {\n\t\tint y = date.getYear();\n\t\tint a = y % 19;\n\t\tint b = y / 100;\n\t\tint c = y % 100;\n\t\tint d = b / 4;\n\t\tint e = b % 4;\n\t\tint f = (b + 8) / 25;\n\t\tint g = (b - f + 1) / 3;\n\t\tint h = (19 * a + b - d - g + 15) % 30;\n\t\tint i = c / 4;\n\t\tint k = c % 4;\n\t\tint l = (32 + 2 * e + 2 * i - h - k) % 7;\n\t\tint m = (a + 11 * h + 22 * l) / 451;\n\t\tint easterSundayMonth\t= (h + l - 7 * m + 114) / 31;\n\t\tint easterSundayDay\t\t= ((h + l - 7 * m + 114) % 31) + 1;\n\n\t\tint month = date.getMonthValue();\n\t\tint day = date.getDayOfMonth();\n\n\t\treturn (easterSundayMonth == month) && (easterSundayDay == day);\n\t}",
"private String applyFilters(String methodName) {\n if (filters.isEmpty()) {\n return methodName;\n }\n\n Reader in = new StringReader(methodName);\n for (TokenFilter tf : filters) {\n in = tf.chain(in);\n }\n\n try {\n return CharStreams.toString(in);\n } catch (IOException e) {\n junit4.log(\"Could not apply filters to \" + methodName + \n \": \" + Throwables.getStackTraceAsString(e), Project.MSG_WARN);\n return methodName;\n }\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 static String getCountryCodeAndCheckDigit(final String iban) {\n return iban.substring(COUNTRY_CODE_INDEX,\n COUNTRY_CODE_INDEX + COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH);\n }",
"public synchronized void start() throws Exception {\n if (state == State.RUNNING) {\n LOG.debug(\"Ignore start() call on HTTP service {} since it has already been started.\", serviceName);\n return;\n }\n if (state != State.NOT_STARTED) {\n if (state == State.STOPPED) {\n throw new IllegalStateException(\"Cannot start the HTTP service \"\n + serviceName + \" again since it has been stopped\");\n }\n throw new IllegalStateException(\"Cannot start the HTTP service \"\n + serviceName + \" because it was failed earlier\");\n }\n\n try {\n LOG.info(\"Starting HTTP Service {} at address {}\", serviceName, bindAddress);\n channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);\n resourceHandler.init(handlerContext);\n eventExecutorGroup = createEventExecutorGroup(execThreadPoolSize);\n bootstrap = createBootstrap(channelGroup);\n Channel serverChannel = bootstrap.bind(bindAddress).sync().channel();\n channelGroup.add(serverChannel);\n\n bindAddress = (InetSocketAddress) serverChannel.localAddress();\n\n LOG.debug(\"Started HTTP Service {} at address {}\", serviceName, bindAddress);\n state = State.RUNNING;\n } catch (Throwable t) {\n // Release resources if there is any failure\n channelGroup.close().awaitUninterruptibly();\n try {\n if (bootstrap != null) {\n shutdownExecutorGroups(0, 5, TimeUnit.SECONDS,\n bootstrap.config().group(), bootstrap.config().childGroup(), eventExecutorGroup);\n } else {\n shutdownExecutorGroups(0, 5, TimeUnit.SECONDS, eventExecutorGroup);\n }\n } catch (Throwable t2) {\n t.addSuppressed(t2);\n }\n state = State.FAILED;\n throw t;\n }\n }",
"public static void handleDomainOperationResponseStreams(final OperationContext context,\n final ModelNode responseNode,\n final List<OperationResponse.StreamEntry> streams) {\n\n if (responseNode.hasDefined(RESPONSE_HEADERS)) {\n ModelNode responseHeaders = responseNode.get(RESPONSE_HEADERS);\n // Strip out any stream header as the header created by this process is what counts\n responseHeaders.remove(ATTACHED_STREAMS);\n if (responseHeaders.asInt() == 0) {\n responseNode.remove(RESPONSE_HEADERS);\n }\n }\n\n for (OperationResponse.StreamEntry streamEntry : streams) {\n context.attachResultStream(streamEntry.getUUID(), streamEntry.getMimeType(), streamEntry.getStream());\n }\n }"
] |
Modifies the belief referenced by bName parameter.
@param bName
- the name of the belief to update.
@param value
- the new value for the belief | [
"private void setBelief(String bName, Object value) {\n introspector.setBeliefValue(this.getLocalName(), bName, value, null);\n }"
] | [
"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 }",
"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 boolean isExit() {\n if (currentRow > finalRow) { //request new block of work\n String newBlock = this.sendRequestSync(\"this/request/block\");\n LineCountManager.LineCountBlock block = new LineCountManager.LineCountBlock(0, 0);\n\n if (newBlock.contains(\"exit\")) {\n getExitFlag().set(true);\n makeReport(true);\n return true;\n } else {\n block.buildFromResponse(newBlock);\n }\n\n currentRow = block.getStart();\n finalRow = block.getStop();\n } else { //report the number of lines written\n makeReport(false);\n\n if (exit.get()) {\n getExitFlag().set(true);\n return true;\n }\n }\n\n return false;\n }",
"protected Method resolveTargetMethod(Message message,\n FieldDescriptor payloadField) {\n Method targetMethod = fieldToMethod.get(payloadField);\n\n if (targetMethod == null) {\n // look up and cache target method; this block is called only once\n // per target method, so synchronized is ok\n synchronized (this) {\n targetMethod = fieldToMethod.get(payloadField);\n if (targetMethod == null) {\n String name = payloadField.getName();\n for (Method method : service.getClass().getMethods()) {\n if (method.getName().equals(name)) {\n try {\n method.setAccessible(true);\n } catch (Exception ex) {\n log.log(Level.SEVERE,\"Error accessing RPC method\",ex);\n }\n\n targetMethod = method;\n fieldToMethod.put(payloadField, targetMethod);\n break;\n }\n }\n }\n }\n }\n\n if (targetMethod != null) {\n return targetMethod;\n } else {\n throw new RuntimeException(\"No matching method found by the name '\"\n + payloadField.getName() + \"'\");\n }\n }",
"public static XMLStreamException unexpectedEndElement(final XMLExtendedStreamReader reader) {\n return ControllerLogger.ROOT_LOGGER.unexpectedEndElement(reader.getName(), reader.getLocation());\n }",
"public String toDecodedString(final java.net.URI uri) {\n final String scheme = uri.getScheme();\n final String part = uri.getSchemeSpecificPart();\n if ((scheme == null)) {\n return part;\n }\n return ((scheme + \":\") + part);\n }",
"private void readFile(InputStream is) throws IOException\n {\n StreamHelper.skip(is, 64);\n int index = 64;\n\n ArrayList<Integer> offsetList = new ArrayList<Integer>();\n List<String> nameList = new ArrayList<String>();\n\n while (true)\n {\n byte[] table = new byte[32];\n is.read(table);\n index += 32;\n\n int offset = PEPUtility.getInt(table, 0);\n offsetList.add(Integer.valueOf(offset));\n if (offset == 0)\n {\n break;\n }\n\n nameList.add(PEPUtility.getString(table, 5).toUpperCase());\n }\n\n StreamHelper.skip(is, offsetList.get(0).intValue() - index);\n\n for (int offsetIndex = 1; offsetIndex < offsetList.size() - 1; offsetIndex++)\n {\n String name = nameList.get(offsetIndex - 1);\n Class<? extends Table> tableClass = TABLE_CLASSES.get(name);\n if (tableClass == null)\n {\n tableClass = Table.class;\n }\n\n Table table;\n try\n {\n table = tableClass.newInstance();\n }\n\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n m_tables.put(name, table);\n table.read(is);\n }\n }",
"public void update(int width, int height, int sampleCount) {\n if (capturing) {\n throw new IllegalStateException(\"Cannot update backing texture while capturing\");\n }\n\n this.width = width;\n this.height = height;\n\n if (sampleCount == 0)\n captureTexture = new GVRRenderTexture(getGVRContext(), width, height);\n else\n captureTexture = new GVRRenderTexture(getGVRContext(), width, height, sampleCount);\n\n setRenderTexture(captureTexture);\n readBackBuffer = new int[width * height];\n }",
"final void waitForSizeQueue(final int queueSize) {\n synchronized (this.queue) {\n while (this.queue.size() > queueSize) {\n try {\n this.queue.wait(250L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n this.queue.notifyAll();\n }\n }"
] |
Inject members into this instance and register the services afterwards.
@see #getGuiceModule()
@see #registerInRegistry(boolean)
@since 2.1 | [
"public void registerServices(boolean force) {\n\t\tInjector injector = Guice.createInjector(getGuiceModule());\n\t\tinjector.injectMembers(this);\n\t\tregisterInRegistry(force);\n\t}"
] | [
"public void commit() {\n if (directory == null)\n return;\n\n try {\n if (reader != null)\n reader.close();\n\n // it turns out that IndexWriter.optimize actually slows\n // searches down, because it invalidates the cache. therefore\n // not calling it any more.\n // http://www.searchworkings.org/blog/-/blogs/uwe-says%3A-is-your-reader-atomic\n // iwriter.optimize();\n\n iwriter.commit();\n openSearchers();\n } catch (IOException e) {\n throw new DukeException(e);\n }\n }",
"private void addChildrenForGroupsNode(I_CmsOuTreeType type, String ouItem) {\n\n try {\n // Cut of type-specific prefix from ouItem with substring()\n List<CmsGroup> groups = m_app.readGroupsForOu(m_cms, ouItem.substring(1), type, false);\n for (CmsGroup group : groups) {\n Pair<String, CmsUUID> key = Pair.of(type.getId(), group.getId());\n Item groupItem = m_treeContainer.addItem(key);\n if (groupItem == null) {\n groupItem = getItem(key);\n }\n groupItem.getItemProperty(PROP_SID).setValue(group.getId());\n groupItem.getItemProperty(PROP_NAME).setValue(getIconCaptionHTML(group, CmsOuTreeType.GROUP));\n groupItem.getItemProperty(PROP_TYPE).setValue(type);\n setChildrenAllowed(key, false);\n m_treeContainer.setParent(key, ouItem);\n }\n } catch (CmsException e) {\n LOG.error(\"Can not read group\", e);\n }\n }",
"public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story) throws Throwable {\n run(configuration, candidateSteps, story, MetaFilter.EMPTY);\n }",
"private <T> CoreRemoteMongoCollection<T> getRemoteCollection(\n final MongoNamespace namespace,\n final Class<T> resultClass\n ) {\n return remoteClient\n .getDatabase(namespace.getDatabaseName())\n .getCollection(namespace.getCollectionName(), resultClass);\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 }",
"public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret,\n String token) {\n targetOauth = new JsonObject();\n this.consumerSecret = consumerSecret;\n this.consumerKey = consumerKey;\n this.tokenSecret = tokenSecret;\n this.token = token;\n return this;\n }",
"public static base_response add(nitro_service client, nspbr6 resource) throws Exception {\n\t\tnspbr6 addresource = new nspbr6();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\taddresource.action = resource.action;\n\t\taddresource.srcipv6 = resource.srcipv6;\n\t\taddresource.srcipop = resource.srcipop;\n\t\taddresource.srcipv6val = resource.srcipv6val;\n\t\taddresource.srcport = resource.srcport;\n\t\taddresource.srcportop = resource.srcportop;\n\t\taddresource.srcportval = resource.srcportval;\n\t\taddresource.destipv6 = resource.destipv6;\n\t\taddresource.destipop = resource.destipop;\n\t\taddresource.destipv6val = resource.destipv6val;\n\t\taddresource.destport = resource.destport;\n\t\taddresource.destportop = resource.destportop;\n\t\taddresource.destportval = resource.destportval;\n\t\taddresource.srcmac = resource.srcmac;\n\t\taddresource.protocol = resource.protocol;\n\t\taddresource.protocolnumber = resource.protocolnumber;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.Interface = resource.Interface;\n\t\taddresource.priority = resource.priority;\n\t\taddresource.state = resource.state;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.nexthop = resource.nexthop;\n\t\taddresource.nexthopval = resource.nexthopval;\n\t\taddresource.nexthopvlan = resource.nexthopvlan;\n\t\treturn addresource.add_resource(client);\n\t}",
"public <T extends Widget & Checkable> void clearChecks() {\n List<T> children = getCheckableChildren();\n for (T c : children) {\n c.setChecked(false);\n }\n }",
"public static Range toRange(Span span) {\n return new Range(toKey(span.getStart()), span.isStartInclusive(), toKey(span.getEnd()),\n span.isEndInclusive());\n }"
] |
Returns a licenses regarding its Id and a fake on if no license exist with such an Id
@param licenseId String
@return License | [
"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 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 }",
"public void setBufferedImage(BufferedImage img) {\n image = img;\n width = img.getWidth();\n height = img.getHeight();\n updateColorArray();\n }",
"public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }",
"public void setSchema(String schema)\n {\n if (schema.charAt(schema.length() - 1) != '.')\n {\n schema = schema + '.';\n }\n m_schema = schema;\n }",
"public static <ResultT> PollingState<ResultT> createFromJSONString(String serializedPollingState) {\n ObjectMapper mapper = initMapper(new ObjectMapper());\n PollingState<ResultT> pollingState;\n try {\n pollingState = mapper.readValue(serializedPollingState, PollingState.class);\n } catch (IOException exception) {\n throw new RuntimeException(exception);\n }\n return pollingState;\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public Color segmentColor(final int segment, final boolean front) {\n final ByteBuffer bytes = getData();\n if (isColor) {\n final int base = segment * 6;\n final int backHeight = segmentHeight(segment, false);\n if (backHeight == 0) {\n return Color.BLACK;\n }\n final int maxLevel = front? 255 : 191;\n final int red = Util.unsign(bytes.get(base + 3)) * maxLevel / backHeight;\n final int green = Util.unsign(bytes.get(base + 4)) * maxLevel / backHeight;\n final int blue = Util.unsign(bytes.get(base + 5)) * maxLevel / backHeight;\n return new Color(red, green, blue);\n } else {\n final int intensity = getData().get(segment * 2 + 1) & 0x07;\n return (intensity >= 5) ? INTENSE_COLOR : NORMAL_COLOR;\n }\n }",
"public static netbridge_vlan_binding[] get(nitro_service service, String name) throws Exception{\n\t\tnetbridge_vlan_binding obj = new netbridge_vlan_binding();\n\t\tobj.set_name(name);\n\t\tnetbridge_vlan_binding response[] = (netbridge_vlan_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void writeBufferedValsToStorage() {\n List<Versioned<byte[]>> obsoleteVals = storageEngine.multiVersionPut(currBufferedKey,\n currBufferedVals);\n // log Obsolete versions in debug mode\n if(logger.isDebugEnabled() && obsoleteVals.size() > 0) {\n logger.debug(\"updateEntries (Streaming multi-version-put) rejected these versions as obsolete : \"\n + StoreUtils.getVersions(obsoleteVals) + \" for key \" + currBufferedKey);\n }\n currBufferedVals = new ArrayList<Versioned<byte[]>>(VALS_BUFFER_EXPECTED_SIZE);\n }",
"@VisibleForTesting\n protected static double getNearestNiceValue(\n final double value, final DistanceUnit scaleUnit, final boolean lockUnits) {\n DistanceUnit bestUnit = bestUnit(scaleUnit, value, lockUnits);\n double factor = scaleUnit.convertTo(1.0, bestUnit);\n\n // nearest power of 10 lower than value\n int digits = (int) Math.floor((Math.log(value * factor) / Math.log(10)));\n double pow10 = Math.pow(10, digits);\n\n // ok, find first character\n double firstChar = value * factor / pow10;\n\n // right, put it into the correct bracket\n int barLen;\n if (firstChar >= 10.0) {\n barLen = 10;\n } else if (firstChar >= 5.0) {\n barLen = 5;\n } else if (firstChar >= 2.0) {\n barLen = 2;\n } else {\n barLen = 1;\n }\n\n // scale it up the correct power of 10\n return barLen * pow10 / factor;\n }"
] |
Use this API to unset the properties of rnatparam resource.
Properties that need to be unset are specified in args array. | [
"public static base_response unset(nitro_service client, rnatparam resource, String[] args) throws Exception{\n\t\trnatparam unsetresource = new rnatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] | [
"public void setColorRange(int firstIndex, int lastIndex, int color) {\n\t\tfor (int i = firstIndex; i <= lastIndex; i++)\n\t\t\tmap[i] = color;\n\t}",
"public static String getArtifactoryPluginVersion() {\n String pluginsSortName = \"artifactory\";\n //Validates Jenkins existence because in some jobs the Jenkins instance is unreachable\n if (Jenkins.getInstance() != null\n && Jenkins.getInstance().getPlugin(pluginsSortName) != null\n && Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper() != null) {\n return Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper().getVersion();\n }\n return \"\";\n }",
"public String putProperty(String key,\n String value) {\n return this.getProperties().put(key,\n value);\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 }",
"private Path getPath(PropertyWriter writer, JsonStreamContext sc) {\n LinkedList<PathElement> elements = new LinkedList<>();\n\n if (sc != null) {\n elements.add(new PathElement(writer.getName(), sc.getCurrentValue()));\n sc = sc.getParent();\n }\n\n while (sc != null) {\n if (sc.getCurrentName() != null && sc.getCurrentValue() != null) {\n elements.addFirst(new PathElement(sc.getCurrentName(), sc.getCurrentValue()));\n }\n sc = sc.getParent();\n }\n\n return new Path(elements);\n }",
"@SuppressWarnings(\"unchecked\")\n\tpublic <S extends IPAddressPartConfiguredString<T, P>> SQLStringMatcher<T, P, S> getNetworkStringMatcher(boolean isEntireAddress, IPAddressSQLTranslator translator) {\n\t\treturn new SQLStringMatcher<T, P, S>((S) this, isEntireAddress, translator);\n\t}",
"private Duration getDuration(String value)\n {\n Duration result = null;\n\n if (value != null && value.length() != 0)\n {\n double seconds = getLong(value);\n double hours = seconds / (60 * 60);\n double days = hours / 8;\n\n if (days < 1)\n {\n result = Duration.getInstance(hours, TimeUnit.HOURS);\n }\n else\n {\n double durationDays = hours / 8;\n result = Duration.getInstance(durationDays, TimeUnit.DAYS);\n }\n }\n\n return (result);\n }",
"public void update(short number) {\n byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_SHORT];\n ByteUtils.writeShort(numberInBytes, number, 0);\n update(numberInBytes);\n }",
"public List<DbComment> getComments(String entityId, String entityType) {\n return repositoryHandler.getComments(entityId, entityType);\n }"
] |
Discard the changes. | [
"void rollback() {\n if (publishedFullRegistry == null) {\n return;\n }\n writeLock.lock();\n try {\n publishedFullRegistry.readLock.lock();\n try {\n clear(true);\n copy(publishedFullRegistry, this);\n modified = false;\n } finally {\n publishedFullRegistry.readLock.unlock();\n }\n } finally {\n writeLock.unlock();\n }\n }"
] | [
"public static double normP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return normF(A);\n } else {\n return inducedP2(A);\n }\n }",
"private void renderThumbnail(Video video) {\n Picasso.with(getContext()).cancelRequest(thumbnail);\n Picasso.with(getContext())\n .load(video.getThumbnail())\n .placeholder(R.drawable.placeholder)\n .into(thumbnail);\n }",
"public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException {\n\t\tlog.debug(\"clipTile before {}\", tile);\n\t\tList<InternalFeature> orgFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tGeometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping.\n\t\tfor (InternalFeature feature : orgFeatures) {\n\t\t\t// clip feature if necessary\n\t\t\tif (exceedsScreenDimensions(feature, scale)) {\n\t\t\t\tlog.debug(\"feature {} exceeds screen dimensions\", feature);\n\t\t\t\tInternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone();\n\t\t\t\ttile.setClipped(true);\n\t\t\t\tvectorFeature.setClipped(true);\n\t\t\t\tif (null == maxScreenBbox) {\n\t\t\t\t\tmaxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin));\n\t\t\t\t}\n\t\t\t\tGeometry clipped = maxScreenBbox.intersection(feature.getGeometry());\n\t\t\t\tvectorFeature.setClippedGeometry(clipped);\n\t\t\t\ttile.addFeature(vectorFeature);\n\t\t\t} else {\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t\tlog.debug(\"clipTile after {}\", tile);\n\t}",
"public void run(Configuration configuration, InjectableStepsFactory stepsFactory, Story story, MetaFilter filter,\n State beforeStories) throws Throwable {\n RunContext context = new RunContext(configuration, stepsFactory, story.getPath(), filter);\n if (beforeStories != null) {\n context.stateIs(beforeStories);\n }\n Map<String, String> storyParameters = new HashMap<>();\n run(context, story, storyParameters);\n }",
"public static int forceCleanup(Thread t)\n {\n int i = 0;\n for (Map.Entry<ConnectionPool, Set<ConnPair>> e : conns.entrySet())\n {\n for (ConnPair c : e.getValue())\n {\n if (c.thread.equals(t))\n {\n try\n {\n // This will in turn remove it from the static Map.\n c.conn.getHandler().invoke(c.conn, Connection.class.getMethod(\"close\"), null);\n }\n catch (Throwable e1)\n {\n e1.printStackTrace();\n }\n i++;\n }\n }\n }\n return i;\n }",
"public void handle(HttpRequest request, HttpResponder responder) {\n if (urlRewriter != null) {\n try {\n request.setUri(URI.create(request.uri()).normalize().toString());\n if (!urlRewriter.rewrite(request, responder)) {\n return;\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\",\n t.getMessage()));\n LOG.error(\"Exception thrown during rewriting of uri {}\", request.uri(), t);\n return;\n }\n }\n\n try {\n String path = URI.create(request.uri()).normalize().getPath();\n\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations\n = patternRouter.getDestinations(path);\n\n PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination =\n getMatchedDestination(routableDestinations, request.method(), path);\n\n if (matchedDestination != null) {\n //Found a httpresource route to it.\n HttpResourceModel httpResourceModel = matchedDestination.getDestination();\n\n // Call preCall method of handler hooks.\n boolean terminated = false;\n HandlerInfo info = new HandlerInfo(httpResourceModel.getMethod().getDeclaringClass().getName(),\n httpResourceModel.getMethod().getName());\n for (HandlerHook hook : handlerHooks) {\n if (!hook.preCall(request, responder, info)) {\n // Terminate further request processing if preCall returns false.\n terminated = true;\n break;\n }\n }\n\n // Call httpresource method\n if (!terminated) {\n // Wrap responder to make post hook calls.\n responder = new WrappedHttpResponder(responder, handlerHooks, request, info);\n if (httpResourceModel.handle(request, responder, matchedDestination.getGroupNameValues()).isStreaming()) {\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Body Consumer not supported for internalHttpResponder: %s\",\n request.uri()));\n }\n }\n } else if (routableDestinations.size() > 0) {\n //Found a matching resource but could not find the right HttpMethod so return 405\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n } else {\n responder.sendString(HttpResponseStatus.NOT_FOUND, String.format(\"Problem accessing: %s. Reason: Not Found\",\n request.uri()));\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\", t.getMessage()));\n LOG.error(\"Exception thrown during request processing for uri {}\", request.uri(), t);\n }\n }",
"public <A extends Collection<? super ResultT>> A into(final A target) {\n forEach(new Block<ResultT>() {\n @Override\n public void apply(@Nonnull final ResultT t) {\n target.add(t);\n }\n });\n return target;\n }",
"static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException {\n AzureAsyncOperation asyncOperation = null;\n String rawString = null;\n if (response.body() != null) {\n try {\n rawString = response.body().string();\n asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class);\n } catch (IOException exception) {\n // Exception will be handled below\n } finally {\n response.body().close();\n }\n }\n if (asyncOperation == null || asyncOperation.status() == null) {\n throw new CloudException(\"polling response does not contain a valid body: \" + rawString, response);\n }\n else {\n asyncOperation.rawString = rawString;\n }\n return asyncOperation;\n }",
"private List<UDFAssignmentType> writeUDFType(FieldTypeClass type, FieldContainer mpxj)\n {\n List<UDFAssignmentType> out = new ArrayList<UDFAssignmentType>();\n for (CustomField cf : m_sortedCustomFieldsList)\n {\n FieldType fieldType = cf.getFieldType();\n if (fieldType != null && type == fieldType.getFieldTypeClass())\n {\n Object value = mpxj.getCachedValue(fieldType);\n if (FieldTypeHelper.valueIsNotDefault(fieldType, value))\n {\n UDFAssignmentType udf = m_factory.createUDFAssignmentType();\n udf.setTypeObjectId(FieldTypeHelper.getFieldID(fieldType));\n setUserFieldValue(udf, fieldType.getDataType(), value);\n out.add(udf);\n }\n }\n }\n return out;\n }"
] |
Calculate the actual bit length of the proposed binary string. | [
"private static int getBinaryLength(int version, QrMode[] inputModeUnoptimized, int[] inputData, boolean gs1, int eciMode) {\n\n int i, j;\n QrMode currentMode;\n int inputLength = inputModeUnoptimized.length;\n int count = 0;\n int alphaLength;\n int percent = 0;\n\n // ZINT NOTE: in Zint, this call modifies the input mode array directly; here, we leave\n // the original array alone so that subsequent binary length checks don't irrevocably\n // optimize the mode array for the wrong QR Code version\n QrMode[] inputMode = applyOptimisation(version, inputModeUnoptimized);\n\n currentMode = QrMode.NULL;\n\n if (gs1) {\n count += 4;\n }\n\n if (eciMode != 3) {\n count += 12;\n }\n\n for (i = 0; i < inputLength; i++) {\n if (inputMode[i] != currentMode) {\n count += 4;\n switch (inputMode[i]) {\n case KANJI:\n count += tribus(version, 8, 10, 12);\n count += (blockLength(i, inputMode) * 13);\n break;\n case BINARY:\n count += tribus(version, 8, 16, 16);\n for (j = i; j < (i + blockLength(i, inputMode)); j++) {\n if (inputData[j] > 0xff) {\n count += 16;\n } else {\n count += 8;\n }\n }\n break;\n case ALPHANUM:\n count += tribus(version, 9, 11, 13);\n alphaLength = blockLength(i, inputMode);\n // In alphanumeric mode % becomes %%\n if (gs1) {\n for (j = i; j < (i + alphaLength); j++) { // TODO: need to do this only if in GS1 mode? or is the other code wrong? https://sourceforge.net/p/zint/tickets/104/#227b\n if (inputData[j] == '%') {\n percent++;\n }\n }\n }\n alphaLength += percent;\n switch (alphaLength % 2) {\n case 0:\n count += (alphaLength / 2) * 11;\n break;\n case 1:\n count += ((alphaLength - 1) / 2) * 11;\n count += 6;\n break;\n }\n break;\n case NUMERIC:\n count += tribus(version, 10, 12, 14);\n switch (blockLength(i, inputMode) % 3) {\n case 0:\n count += (blockLength(i, inputMode) / 3) * 10;\n break;\n case 1:\n count += ((blockLength(i, inputMode) - 1) / 3) * 10;\n count += 4;\n break;\n case 2:\n count += ((blockLength(i, inputMode) - 2) / 3) * 10;\n count += 7;\n break;\n }\n break;\n }\n currentMode = inputMode[i];\n }\n }\n\n return count;\n }"
] | [
"public boolean setCurrentPage(final int page) {\n Log.d(TAG, \"setPageId pageId = %d\", page);\n return (page >= 0 && page < getCheckableCount()) && check(page);\n }",
"private void addHandlerInitializerMethod(ClassFile proxyClassType, ClassMethod staticConstructor) throws Exception {\n ClassMethod classMethod = proxyClassType.addMethod(AccessFlag.PRIVATE, INIT_MH_METHOD_NAME, BytecodeUtils.VOID_CLASS_DESCRIPTOR, LJAVA_LANG_OBJECT);\n final CodeAttribute b = classMethod.getCodeAttribute();\n b.aload(0);\n StaticMethodInformation methodInfo = new StaticMethodInformation(INIT_MH_METHOD_NAME, new Class[] { Object.class }, void.class,\n classMethod.getClassFile().getName());\n invokeMethodHandler(classMethod, methodInfo, false, DEFAULT_METHOD_RESOLVER, staticConstructor);\n b.checkcast(MethodHandler.class);\n b.putfield(classMethod.getClassFile().getName(), METHOD_HANDLER_FIELD_NAME, DescriptorUtils.makeDescriptor(MethodHandler.class));\n b.returnInstruction();\n BeanLogger.LOG.createdMethodHandlerInitializerForDecoratorProxy(getBeanType());\n\n }",
"public synchronized Object next() throws NoSuchElementException\r\n {\r\n try\r\n {\r\n if (!isHasCalledCheck())\r\n {\r\n hasNext();\r\n }\r\n setHasCalledCheck(false);\r\n if (getHasNext())\r\n {\r\n Object obj = getObjectFromResultSet();\r\n m_current_row++;\r\n\r\n // Invoke events on PersistenceBrokerAware instances and listeners\r\n // set target object\r\n if (!disableLifeCycleEvents)\r\n {\r\n getAfterLookupEvent().setTarget(obj);\r\n getBroker().fireBrokerEvent(getAfterLookupEvent());\r\n getAfterLookupEvent().setTarget(null);\r\n } \r\n return obj;\r\n }\r\n else\r\n {\r\n throw new NoSuchElementException(\"inner hasNext was false\");\r\n }\r\n }\r\n catch (ResourceClosedException ex)\r\n {\r\n autoReleaseDbResources();\r\n throw ex;\r\n }\r\n catch (NoSuchElementException ex)\r\n {\r\n autoReleaseDbResources();\r\n logger.error(\"Error while iterate ResultSet for query \" + m_queryObject, ex);\r\n throw new NoSuchElementException(\"Could not obtain next object: \" + ex.getMessage());\r\n }\r\n }",
"protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException {\n Class c = this.findLoadedClass(name);\n if (c != null) return c;\n c = (Class) customClasses.get(name);\n if (c != null) return c;\n\n try {\n c = oldFindClass(name);\n } catch (ClassNotFoundException cnfe) {\n // IGNORE\n }\n if (c == null) c = super.loadClass(name, resolve);\n\n if (resolve) resolveClass(c);\n\n return c;\n }",
"public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }",
"@SuppressWarnings(\"unchecked\")\n public static <T extends Serializable> T makeClone(T from) {\n return (T) SerializationUtils.clone(from);\n }",
"public Object copy(final Object obj, PersistenceBroker broker)\r\n\t\t\tthrows ObjectCopyException\r\n\t{\r\n\t\tObjectOutputStream oos = null;\r\n\t\tObjectInputStream ois = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tfinal ByteArrayOutputStream bos = new ByteArrayOutputStream();\r\n\t\t\toos = new ObjectOutputStream(bos);\r\n\t\t\t// serialize and pass the object\r\n\t\t\toos.writeObject(obj);\r\n\t\t\toos.flush();\r\n\t\t\tfinal ByteArrayInputStream bin =\r\n\t\t\t\t\tnew ByteArrayInputStream(bos.toByteArray());\r\n\t\t\tois = new ObjectInputStream(bin);\r\n\t\t\t// return the new object\r\n\t\t\treturn ois.readObject();\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tthrow new ObjectCopyException(e);\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tif (oos != null)\r\n\t\t\t\t{\r\n\t\t\t\t\toos.close();\r\n\t\t\t\t}\r\n\t\t\t\tif (ois != null)\r\n\t\t\t\t{\r\n\t\t\t\t\tois.close();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (IOException ioe)\r\n\t\t\t{\r\n\t\t\t\t// ignore\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) {\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size());\n for(Integer serverId: serverIds) {\n clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue));\n }\n return new VectorClock(clockEntries, timestamp);\n }",
"public void setSessionTimeout(int timeout) {\n ((ZKBackend) getBackend()).setSessionTimeout(timeout);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Locator session timeout set to: \" + timeout);\n }\n }"
] |
Retrieves the timephased breakdown of cost.
@return timephased cost | [
"public List<TimephasedCost> getTimephasedCost()\n {\n if (m_timephasedCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedWork != null && m_timephasedWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedCost = getTimephasedCostMultipleRates(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n else\n {\n m_timephasedCost = getTimephasedCostSingleRate(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedCost = getTimephasedCostFixedAmount();\n }\n\n }\n return m_timephasedCost;\n }"
] | [
"public static base_response clear(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig clearresource = new nsconfig();\n\t\tclearresource.force = resource.force;\n\t\tclearresource.level = resource.level;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"private void writeAvailability(Project.Resources.Resource xml, Resource mpx)\n {\n AvailabilityPeriods periods = m_factory.createProjectResourcesResourceAvailabilityPeriods();\n xml.setAvailabilityPeriods(periods);\n List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();\n for (Availability availability : mpx.getAvailability())\n {\n AvailabilityPeriod period = m_factory.createProjectResourcesResourceAvailabilityPeriodsAvailabilityPeriod();\n list.add(period);\n DateRange range = availability.getRange();\n\n period.setAvailableFrom(range.getStart());\n period.setAvailableTo(range.getEnd());\n period.setAvailableUnits(DatatypeConverter.printUnits(availability.getUnits()));\n }\n }",
"public void write(WritableByteChannel channel) throws IOException {\n logger.debug(\"Writing> {}\", this);\n for (Field field : fields) {\n field.write(channel);\n }\n }",
"public Range<Dyno> listDynos(String appName) {\n return connection.execute(new DynoList(appName), apiKey);\n }",
"private void reInitLayoutElements() {\n\n m_panel.clear();\n for (CmsCheckBox cb : m_checkBoxes) {\n m_panel.add(setStyle(m_onlyLabels ? new Label(cb.getText()) : cb));\n }\n }",
"public static DMatrix2 extractColumn( DMatrix2x2 a , int column , DMatrix2 out ) {\n if( out == null) out = new DMatrix2();\n switch( column ) {\n case 0:\n out.a1 = a.a11;\n out.a2 = a.a21;\n break;\n case 1:\n out.a1 = a.a12;\n out.a2 = a.a22;\n break;\n default:\n throw new IllegalArgumentException(\"Out of bounds column. column = \"+column);\n }\n return out;\n }",
"public static Polygon calculateBounds(final MapfishMapContext context) {\n double rotation = context.getRootContext().getRotation();\n ReferencedEnvelope env = context.getRootContext().toReferencedEnvelope();\n\n Coordinate centre = env.centre();\n AffineTransform rotateInstance = AffineTransform.getRotateInstance(rotation, centre.x, centre.y);\n\n double[] dstPts = new double[8];\n double[] srcPts = {\n env.getMinX(), env.getMinY(), env.getMinX(), env.getMaxY(),\n env.getMaxX(), env.getMaxY(), env.getMaxX(), env.getMinY()\n };\n\n rotateInstance.transform(srcPts, 0, dstPts, 0, 4);\n\n return new GeometryFactory().createPolygon(new Coordinate[]{\n new Coordinate(dstPts[0], dstPts[1]), new Coordinate(dstPts[2], dstPts[3]),\n new Coordinate(dstPts[4], dstPts[5]), new Coordinate(dstPts[6], dstPts[7]),\n new Coordinate(dstPts[0], dstPts[1])\n });\n }",
"public static Cluster swapRandomPartitionsWithinZone(final Cluster nextCandidateCluster,\n final int zoneId) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n Random r = new Random();\n\n List<Integer> nodeIdsInZone = new ArrayList<Integer>(nextCandidateCluster.getNodeIdsInZone(zoneId));\n\n if(nodeIdsInZone.size() == 0) {\n return returnCluster;\n }\n\n // Select random stealer node\n int stealerNodeOffset = r.nextInt(nodeIdsInZone.size());\n Integer stealerNodeId = nodeIdsInZone.get(stealerNodeOffset);\n\n // Select random stealer partition\n List<Integer> stealerPartitions = returnCluster.getNodeById(stealerNodeId)\n .getPartitionIds();\n if(stealerPartitions.size() == 0) {\n return nextCandidateCluster;\n }\n int stealerPartitionOffset = r.nextInt(stealerPartitions.size());\n int stealerPartitionId = stealerPartitions.get(stealerPartitionOffset);\n\n // Select random donor node\n List<Integer> donorNodeIds = new ArrayList<Integer>();\n donorNodeIds.addAll(nodeIdsInZone);\n donorNodeIds.remove(stealerNodeId);\n\n if(donorNodeIds.isEmpty()) { // No donor nodes!\n return returnCluster;\n }\n int donorIdOffset = r.nextInt(donorNodeIds.size());\n Integer donorNodeId = donorNodeIds.get(donorIdOffset);\n\n // Select random donor partition\n List<Integer> donorPartitions = returnCluster.getNodeById(donorNodeId).getPartitionIds();\n int donorPartitionOffset = r.nextInt(donorPartitions.size());\n int donorPartitionId = donorPartitions.get(donorPartitionOffset);\n\n return swapPartitions(returnCluster,\n stealerNodeId,\n stealerPartitionId,\n donorNodeId,\n donorPartitionId);\n }",
"public int compareTo(WordTag wordTag) { \r\n int first = (word != null ? word().compareTo(wordTag.word()) : 0);\r\n if(first != 0)\r\n return first;\r\n else {\r\n if (tag() == null) {\r\n if (wordTag.tag() == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return tag().compareTo(wordTag.tag());\r\n }\r\n }"
] |
Gets the URL of the service with the given name that has been created during the current session.
@param name to return its URL
@return URL of the service. | [
"public Optional<URL> getServiceUrl(String name) {\n Service service = client.services().inNamespace(namespace).withName(name).get();\n return service != null ? createUrlForService(service) : Optional.empty();\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n private static void parseProperties(JSONObject modelJSON,\n Shape current,\n Boolean keepGlossaryLink) throws JSONException {\n if (modelJSON.has(\"properties\")) {\n JSONObject propsObject = modelJSON.getJSONObject(\"properties\");\n Iterator<String> keys = propsObject.keys();\n Pattern pattern = Pattern.compile(jsonPattern);\n\n while (keys.hasNext()) {\n StringBuilder result = new StringBuilder();\n int lastIndex = 0;\n String key = keys.next();\n String value = propsObject.getString(key);\n\n if (!keepGlossaryLink) {\n Matcher matcher = pattern.matcher(value);\n while (matcher.find()) {\n String id = matcher.group(1);\n current.addGlossaryIds(id);\n String text = matcher.group(2);\n result.append(text);\n lastIndex = matcher.end();\n }\n result.append(value.substring(lastIndex));\n value = result.toString();\n }\n\n current.putProperty(key,\n value);\n }\n }\n }",
"public void deleteIndex(String indexName, String designDocId, String type) {\n assertNotEmpty(indexName, \"indexName\");\n assertNotEmpty(designDocId, \"designDocId\");\n assertNotNull(type, \"type\");\n if (!designDocId.startsWith(\"_design\")) {\n designDocId = \"_design/\" + designDocId;\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").path(designDocId)\n .path(type).path(indexName).build();\n InputStream response = null;\n try {\n HttpConnection connection = Http.DELETE(uri);\n response = client.couchDbClient.executeToInputStream(connection);\n getResponse(response, Response.class, client.getGson());\n } finally {\n close(response);\n }\n }",
"public static base_responses add(nitro_service client, tmtrafficaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\ttmtrafficaction addresources[] = new tmtrafficaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new tmtrafficaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].apptimeout = resources[i].apptimeout;\n\t\t\t\taddresources[i].sso = resources[i].sso;\n\t\t\t\taddresources[i].formssoaction = resources[i].formssoaction;\n\t\t\t\taddresources[i].persistentcookie = resources[i].persistentcookie;\n\t\t\t\taddresources[i].initiatelogout = resources[i].initiatelogout;\n\t\t\t\taddresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\taddresources[i].samlssoprofile = resources[i].samlssoprofile;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private boolean tryCustomErrorPage(CmsObject cms, HttpServletRequest req, HttpServletResponse res, int errorCode) {\n\n String siteRoot = OpenCms.getSiteManager().matchRequest(req).getSiteRoot();\n CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);\n if (site != null) {\n // store current site root and URI\n String currentSiteRoot = cms.getRequestContext().getSiteRoot();\n String currentUri = cms.getRequestContext().getUri();\n try {\n if (site.getErrorPage() != null) {\n String rootPath = site.getErrorPage();\n if (loadCustomErrorPage(cms, req, res, rootPath)) {\n return true;\n }\n }\n String rootPath = CmsStringUtil.joinPaths(siteRoot, \"/.errorpages/handle\" + errorCode + \".html\");\n if (loadCustomErrorPage(cms, req, res, rootPath)) {\n return true;\n }\n } finally {\n cms.getRequestContext().setSiteRoot(currentSiteRoot);\n cms.getRequestContext().setUri(currentUri);\n }\n }\n return false;\n }",
"private void startInvertedColors() {\n if (managerFeatures.getInvertedColors().isInverted()) {\n managerFeatures.getInvertedColors().turnOff(mGvrContext.getMainScene());\n } else {\n managerFeatures.getInvertedColors().turnOn(mGvrContext.getMainScene());\n }\n }",
"public AsciiTable setPaddingTop(int paddingTop) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public String getRelativePath() {\n final StringBuilder builder = new StringBuilder();\n for(final String p : path) {\n builder.append(p).append(\"/\");\n }\n builder.append(getName());\n return builder.toString();\n }",
"VersionExcludeData getVersionIgnoreData(int major, int minor, int micro) {\n VersionExcludeData result = registry.get(new VersionKey(major, minor, micro));\n if (result == null) {\n result = registry.get(new VersionKey(major, minor, null));\n }\n return result;\n }",
"private void checkReferenceForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef classDef;\r\n ReferenceDescriptorDef refDef;\r\n\r\n for (Iterator it = modelDef.getClasses(); it.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)it.next();\r\n for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)\r\n {\r\n refDef = (ReferenceDescriptorDef)refIt.next();\r\n if (!refDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n checkReferenceForeignkeys(modelDef, refDef);\r\n }\r\n }\r\n }\r\n }"
] |
Returns an entry of kind snippet with the given proposal and label and the prefix from the context, or null if the proposal is not valid.
@since 2.16 | [
"public ContentAssistEntry createSnippet(final String proposal, final String label, final ContentAssistContext context) {\n final Procedure1<ContentAssistEntry> _function = (ContentAssistEntry it) -> {\n it.setLabel(label);\n };\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_SNIPPET, _function);\n }"
] | [
"public void updateStructure()\n {\n if (size() > 1)\n {\n Collections.sort(this);\n m_projectFile.getChildTasks().clear();\n\n Task lastTask = null;\n int lastLevel = -1;\n boolean autoWbs = m_projectFile.getProjectConfig().getAutoWBS();\n boolean autoOutlineNumber = m_projectFile.getProjectConfig().getAutoOutlineNumber();\n\n for (Task task : this)\n {\n task.clearChildTasks();\n Task parent = null;\n if (!task.getNull())\n {\n int level = NumberHelper.getInt(task.getOutlineLevel());\n\n if (lastTask != null)\n {\n if (level == lastLevel || task.getNull())\n {\n parent = lastTask.getParentTask();\n level = lastLevel;\n }\n else\n {\n if (level > lastLevel)\n {\n parent = lastTask;\n }\n else\n {\n while (level <= lastLevel)\n {\n parent = lastTask.getParentTask();\n\n if (parent == null)\n {\n break;\n }\n\n lastLevel = NumberHelper.getInt(parent.getOutlineLevel());\n lastTask = parent;\n }\n }\n }\n }\n\n lastTask = task;\n lastLevel = level;\n\n if (autoWbs || task.getWBS() == null)\n {\n task.generateWBS(parent);\n }\n\n if (autoOutlineNumber)\n {\n task.generateOutlineNumber(parent);\n }\n }\n\n if (parent == null)\n {\n m_projectFile.getChildTasks().add(task);\n }\n else\n {\n parent.addChildTask(task);\n }\n }\n }\n }",
"public static String changeFirstLetterToLowerCase(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toLowerCase(a);\n return new String(letras);\n }",
"public void deleteIndex(String indexName, String designDocId, String type) {\n assertNotEmpty(indexName, \"indexName\");\n assertNotEmpty(designDocId, \"designDocId\");\n assertNotNull(type, \"type\");\n if (!designDocId.startsWith(\"_design\")) {\n designDocId = \"_design/\" + designDocId;\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").path(designDocId)\n .path(type).path(indexName).build();\n InputStream response = null;\n try {\n HttpConnection connection = Http.DELETE(uri);\n response = client.couchDbClient.executeToInputStream(connection);\n getResponse(response, Response.class, client.getGson());\n } finally {\n close(response);\n }\n }",
"public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) {\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final DependencyReport report = new DependencyReport(moduleId);\n final List<String> done = new ArrayList<String>();\n for(final DbModule submodule: DataUtils.getAllSubmodules(module)){\n done.add(submodule.getId());\n }\n\n addModuleToReport(report, module, filters, done, 1);\n\n return report;\n }",
"public V internalNonBlockingGet(K key) throws Exception {\n Pool<V> resourcePool = getResourcePoolForKey(key);\n return attemptNonBlockingCheckout(key, resourcePool);\n }",
"synchronized JSONObject fetchEvents(Table table, final int limit) {\n final String tName = table.getName();\n Cursor cursor = null;\n String lastId = null;\n\n final JSONArray events = new JSONArray();\n\n //noinspection TryFinallyCanBeTryWithResources\n try {\n final SQLiteDatabase db = dbHelper.getReadableDatabase();\n cursor = db.rawQuery(\"SELECT * FROM \" + tName +\n \" ORDER BY \" + KEY_CREATED_AT + \" ASC LIMIT \" + limit, null);\n\n\n while (cursor.moveToNext()) {\n if (cursor.isLast()) {\n lastId = cursor.getString(cursor.getColumnIndex(\"_id\"));\n }\n try {\n final JSONObject j = new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA)));\n events.put(j);\n } catch (final JSONException e) {\n // Ignore\n }\n }\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Could not fetch records out of database \" + tName + \".\", e);\n lastId = null;\n } finally {\n dbHelper.close();\n if (cursor != null) {\n cursor.close();\n }\n }\n\n if (lastId != null) {\n try {\n final JSONObject ret = new JSONObject();\n ret.put(lastId, events);\n return ret;\n } catch (JSONException e) {\n // ignore\n }\n }\n\n return null;\n }",
"private boolean validate(CmsFavoriteEntry entry) {\n\n try {\n String siteRoot = entry.getSiteRoot();\n if (!m_okSiteRoots.contains(siteRoot)) {\n m_rootCms.readResource(siteRoot);\n m_okSiteRoots.add(siteRoot);\n }\n CmsUUID project = entry.getProjectId();\n if (!m_okProjects.contains(project)) {\n m_cms.readProject(project);\n m_okProjects.add(project);\n }\n for (CmsUUID id : Arrays.asList(entry.getDetailId(), entry.getStructureId())) {\n if ((id != null) && !m_okStructureIds.contains(id)) {\n m_cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n m_okStructureIds.add(id);\n }\n }\n return true;\n\n } catch (Exception e) {\n LOG.info(\"Favorite entry validation failed: \" + e.getLocalizedMessage(), e);\n return false;\n }\n\n }",
"public static boolean respondsTo(Object object, String methodName) {\r\n MetaClass metaClass = DefaultGroovyMethods.getMetaClass(object);\r\n if (!metaClass.respondsTo(object, methodName).isEmpty()) {\r\n return true;\r\n }\r\n Map properties = DefaultGroovyMethods.getProperties(object);\r\n return properties.containsKey(methodName);\r\n }",
"public Response remove(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.remove(ensureDesignPrefix(id), rev);\r\n\r\n }"
] |
Returns the query string currently in the text field.
@return the query string | [
"@NonNull public CharSequence getQuery() {\n if (searchView != null) {\n return searchView.getQuery();\n } else if (supportView != null) {\n return supportView.getQuery();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }"
] | [
"private void setTempoMaster(DeviceUpdate newMaster) {\n DeviceUpdate oldMaster = tempoMaster.getAndSet(newMaster);\n if ((newMaster == null && oldMaster != null) ||\n (newMaster != null && ((oldMaster == null) || !newMaster.getAddress().equals(oldMaster.getAddress())))) {\n // This is a change in master, so report it to any registered listeners\n deliverMasterChangedAnnouncement(newMaster);\n }\n }",
"public static base_responses update(nitro_service client, responderpolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tresponderpolicy updateresources[] = new responderpolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new responderpolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].undefaction = resources[i].undefaction;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].logaction = resources[i].logaction;\n\t\t\t\tupdateresources[i].appflowaction = resources[i].appflowaction;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public EventBus emit(String event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }",
"@Override\n public Scenario<GIVEN, WHEN, THEN> startScenario( String description ) {\n super.startScenario( description );\n return this;\n\n }",
"private Charset getCharset()\n {\n Charset result = m_charset;\n if (result == null)\n {\n // We default to CP1252 as this seems to be the most common encoding\n result = m_encoding == null ? CharsetHelper.CP1252 : Charset.forName(m_encoding);\n }\n return result;\n }",
"private String applyFilters(String methodName) {\n if (filters.isEmpty()) {\n return methodName;\n }\n\n Reader in = new StringReader(methodName);\n for (TokenFilter tf : filters) {\n in = tf.chain(in);\n }\n\n try {\n return CharStreams.toString(in);\n } catch (IOException e) {\n junit4.log(\"Could not apply filters to \" + methodName + \n \": \" + Throwables.getStackTraceAsString(e), Project.MSG_WARN);\n return methodName;\n }\n }",
"@RequestMapping(value = \"api/servergroup\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getServerGroups(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"search\", required = false) String search,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId);\n\n if (search != null) {\n Iterator<ServerGroup> iterator = serverGroups.iterator();\n while (iterator.hasNext()) {\n ServerGroup serverGroup = iterator.next();\n if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) {\n iterator.remove();\n }\n }\n }\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, \"servergroups\");\n return returnJson;\n }",
"public static void calculateLegendInformation(List<? extends BaseModel> _Models, float _StartX, float _EndX, Paint _Paint) {\n float textMargin = Utils.dpToPx(10.f);\n float lastX = _StartX;\n\n // calculate the legend label positions and check if there is enough space to display the label,\n // if not the label will not be shown\n for (BaseModel model : _Models) {\n if (!model.isIgnore()) {\n Rect textBounds = new Rect();\n RectF legendBounds = model.getLegendBounds();\n\n _Paint.getTextBounds(model.getLegendLabel(), 0, model.getLegendLabel().length(), textBounds);\n model.setTextBounds(textBounds);\n\n float centerX = legendBounds.centerX();\n float centeredTextPos = centerX - (textBounds.width() / 2);\n float textStartPos = centeredTextPos - textMargin;\n\n // check if the text is too big to fit on the screen\n if (centeredTextPos + textBounds.width() > _EndX - textMargin) {\n model.setShowLabel(false);\n } else {\n // check if the current legend label overrides the label before\n // if the label overrides the label before, the current label will not be shown.\n // If not the label will be shown and the label position is calculated\n if (textStartPos < lastX) {\n if (lastX + textMargin < legendBounds.left) {\n model.setLegendLabelPosition((int) (lastX + textMargin));\n model.setShowLabel(true);\n lastX = lastX + textMargin + textBounds.width();\n } else {\n model.setShowLabel(false);\n }\n } else {\n model.setShowLabel(true);\n model.setLegendLabelPosition((int) centeredTextPos);\n lastX = centerX + (textBounds.width() / 2);\n }\n }\n }\n }\n\n }",
"public static CoordinateReferenceSystem parseProjection(\n final String projection, final Boolean longitudeFirst) {\n try {\n if (longitudeFirst == null) {\n return CRS.decode(projection);\n } else {\n return CRS.decode(projection, longitudeFirst);\n }\n } catch (NoSuchAuthorityCodeException e) {\n throw new RuntimeException(projection + \" was not recognized as a crs code\", e);\n } catch (FactoryException e) {\n throw new RuntimeException(\"Error occurred while parsing: \" + projection, e);\n }\n }"
] |
Groups the current element according to the value
@param answer the map containing the results
@param element the element to be placed
@param value the value according to which the element will be placed
@since 1.5.0 | [
"protected static <K, T> void groupAnswer(final Map<K, List<T>> answer, T element, K value) {\n if (answer.containsKey(value)) {\n answer.get(value).add(element);\n } else {\n List<T> groupedElements = new ArrayList<T>();\n groupedElements.add(element);\n answer.put(value, groupedElements);\n }\n }"
] | [
"public static BoxRetentionPolicyAssignment.Info createAssignmentToMetadata(BoxAPIConnection api,\r\n String policyID,\r\n String templateID,\r\n MetadataFieldFilter... filter) {\r\n JsonObject assignTo = new JsonObject().add(\"type\", TYPE_METADATA).add(\"id\", templateID);\r\n JsonArray filters = null;\r\n if (filter.length > 0) {\r\n filters = new JsonArray();\r\n for (MetadataFieldFilter f : filter) {\r\n filters.add(f.getJsonObject());\r\n }\r\n }\r\n return createAssignment(api, policyID, assignTo, filters);\r\n }",
"public static aaagroup_vpntrafficpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_vpntrafficpolicy_binding obj = new aaagroup_vpntrafficpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_vpntrafficpolicy_binding response[] = (aaagroup_vpntrafficpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public 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 InstalledIdentity load(final File jbossHome, final ProductConfig productConfig, final File... repoRoots) throws IOException {\n final InstalledImage installedImage = installedImage(jbossHome);\n return load(installedImage, productConfig, Arrays.<File>asList(repoRoots), Collections.<File>emptyList());\n }",
"public static int NextPowerOf2(int x) {\r\n --x;\r\n x |= x >> 1;\r\n x |= x >> 2;\r\n x |= x >> 4;\r\n x |= x >> 8;\r\n x |= x >> 16;\r\n return ++x;\r\n }",
"@SuppressWarnings(\"unchecked\")\n public void setVars(final Map<String, ? extends Object> vars) {\n this.vars = (Map<String, Object>)vars;\n }",
"public static appfwhtmlerrorpage get(nitro_service service, options option) throws Exception{\n\t\tappfwhtmlerrorpage obj = new appfwhtmlerrorpage();\n\t\tappfwhtmlerrorpage[] response = (appfwhtmlerrorpage[])obj.get_resources(service,option);\n\t\treturn response[0];\n\t}",
"public ItemRequest<Story> delete(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"DELETE\");\n }",
"public static HttpConnection connect(String requestMethod,\n URL url,\n String contentType) {\n return new HttpConnection(requestMethod, url, contentType);\n }"
] |
Create a new GP entry in the database. No commit performed. | [
"public static GlobalParameter create(DbConn cnx, String key, String value)\n {\n QueryResult r = cnx.runUpdate(\"globalprm_insert\", key, value);\n GlobalParameter res = new GlobalParameter();\n res.id = r.getGeneratedId();\n res.key = key;\n res.value = value;\n return res;\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 void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"life-expectancies.csv\"))) {\n\n\t\t\tfor (int i = 0; i < lifeSpans.length; i++) {\n\t\t\t\tif (peopleCount[i] != 0) {\n\t\t\t\t\tout.println(i + \",\" + (double) lifeSpans[i]\n\t\t\t\t\t\t\t/ peopleCount[i] + \",\" + peopleCount[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"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 List<Formation> listFormation(String appName) {\n return connection.execute(new FormationList(appName), apiKey);\n }",
"private void writeResource(Resource record) throws IOException\n {\n m_buffer.setLength(0);\n\n //\n // Write the resource record\n //\n int[] fields = m_resourceModel.getModel();\n\n m_buffer.append(MPXConstants.RESOURCE_RECORD_NUMBER);\n for (int loop = 0; loop < fields.length; loop++)\n {\n int mpxFieldType = fields[loop];\n if (mpxFieldType == -1)\n {\n break;\n }\n\n ResourceField resourceField = MPXResourceField.getMpxjField(mpxFieldType);\n Object value = record.getCachedValue(resourceField);\n value = formatType(resourceField.getDataType(), value);\n\n m_buffer.append(m_delimiter);\n m_buffer.append(format(value));\n }\n\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n\n //\n // Write the resource notes\n //\n String notes = record.getNotes();\n if (notes.length() != 0)\n {\n writeNotes(MPXConstants.RESOURCE_NOTES_RECORD_NUMBER, notes);\n }\n\n //\n // Write the resource calendar\n //\n if (record.getResourceCalendar() != null)\n {\n writeCalendar(record.getResourceCalendar());\n }\n\n m_eventManager.fireResourceWrittenEvent(record);\n }",
"public static final Date parseDate(String value)\n {\n Date result = null;\n\n try\n {\n if (value != null && !value.isEmpty())\n {\n result = DATE_FORMAT.get().parse(value);\n }\n }\n catch (ParseException ex)\n {\n // Ignore\n }\n\n return result;\n }",
"private static String wordShapeDan1(String s) {\r\n boolean digit = true;\r\n boolean upper = true;\r\n boolean lower = true;\r\n boolean mixed = true;\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (!Character.isDigit(c)) {\r\n digit = false;\r\n }\r\n if (!Character.isLowerCase(c)) {\r\n lower = false;\r\n }\r\n if (!Character.isUpperCase(c)) {\r\n upper = false;\r\n }\r\n if ((i == 0 && !Character.isUpperCase(c)) || (i >= 1 && !Character.isLowerCase(c))) {\r\n mixed = false;\r\n }\r\n }\r\n if (digit) {\r\n return \"ALL-DIGITS\";\r\n }\r\n if (upper) {\r\n return \"ALL-UPPER\";\r\n }\r\n if (lower) {\r\n return \"ALL-LOWER\";\r\n }\r\n if (mixed) {\r\n return \"MIXED-CASE\";\r\n }\r\n return \"OTHER\";\r\n }",
"public B partialFilterSelector(Selector selector) {\n instance.def.selector = Helpers.getJsonObjectFromSelector(selector);\n return returnThis();\n }",
"@JsonAnySetter\n public void setUnknownField(final String name, final Object value) {\n this.unknownFields.put(name, value);\n }"
] |
Checks the preconditions for creating a new LMinMax processor.
@param min
the minimum value (inclusive)
@param max
the maximum value (inclusive)
@throws IllegalArgumentException
if {@code max < min} | [
"private static void checkPreconditions(final long min, final long max) {\n\t\tif( max < min ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"max (%d) should not be < min (%d)\", max, min));\n\t\t}\n\t}"
] | [
"private void onScrollImpl(final Vector3Axis offset, final LayoutScroller.OnScrollListener listener) {\n if (!isScrolling()) {\n mScroller = new ScrollingProcessor(offset, listener);\n mScroller.scroll();\n }\n }",
"public <T> InternalEjbDescriptor<T> get(String beanName) {\n return cast(ejbByName.get(beanName));\n }",
"protected <T, A> ActiveOperation<T, A> getActiveOperation(final ManagementRequestHeader header) {\n return getActiveOperation(header.getBatchId());\n }",
"public static base_responses unset(nitro_service client, String sitename[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite unsetresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tunsetresources[i] = new gslbsite();\n\t\t\t\tunsetresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"@Inline(value = \"$1.remove($2)\", statementExpression = true)\n\tpublic static <K, V> V operator_remove(Map<K, V> map, K key) {\n\t\treturn map.remove(key);\n\t}",
"public List<I_CmsEditableGroupRow> getRows() {\n\n List<I_CmsEditableGroupRow> result = Lists.newArrayList();\n for (Component component : m_container) {\n if (component instanceof I_CmsEditableGroupRow) {\n result.add((I_CmsEditableGroupRow)component);\n }\n }\n return result;\n }",
"public static void writeDocumentToFile(Document document,\n String filePathname, String method, int indent)\n throws TransformerException, IOException {\n\n Transformer transformer = TransformerFactory.newInstance()\n .newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n transformer.setOutputProperty(OutputKeys.METHOD, method);\n\n transformer.transform(new DOMSource(document), new StreamResult(\n new FileOutputStream(filePathname)));\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 registerRequirement(RuntimeRequirementRegistration requirement) {\n assert writeLock.isHeldByCurrentThread();\n CapabilityId dependentId = requirement.getDependentId();\n if (!capabilities.containsKey(dependentId)) {\n throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(),\n dependentId.getScope().getName());\n }\n Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap =\n requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements;\n\n Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId);\n if (dependents == null) {\n dependents = new HashMap<>();\n requirementMap.put(dependentId, dependents);\n }\n RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName());\n if (existing == null) {\n dependents.put(requirement.getRequiredName(), requirement);\n } else {\n existing.addRegistrationPoint(requirement.getOldestRegistrationPoint());\n }\n modified = true;\n }"
] |
Inserts the result of the migration into the migration table
@param migration the migration that was executed
@param wasSuccessful indicates if the migration was successful or not | [
"private void logMigration(DbMigration migration, boolean wasSuccessful) {\n BoundStatement boundStatement = logMigrationStatement.bind(wasSuccessful, migration.getVersion(),\n migration.getScriptName(), migration.getMigrationScript(), new Date());\n session.execute(boundStatement);\n }"
] | [
"public void setEnterpriseCost(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_COST, index), value);\n }",
"public Stats getPhotosetStats(String photosetId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTOSET_STATS, \"photoset_id\", photosetId, date);\n }",
"private static void addCacheDetailsEntry(SlotReference slot, ZipOutputStream zos, WritableByteChannel channel) throws IOException {\n // Record the details of the media being cached, to make it easier to recognize now that we can.\n MediaDetails details = MetadataFinder.getInstance().getMediaDetailsFor(slot);\n if (details != null) {\n zos.putNextEntry(new ZipEntry(CACHE_DETAILS_ENTRY));\n Util.writeFully(details.getRawBytes(), channel);\n }\n }",
"private String escapeString(String value)\n {\n m_buffer.setLength(0);\n m_buffer.append('\"');\n for (int index = 0; index < value.length(); index++)\n {\n char c = value.charAt(index);\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\\\\\"\");\n break;\n }\n\n case '\\\\':\n {\n m_buffer.append(\"\\\\\\\\\");\n break;\n }\n\n case '/':\n {\n m_buffer.append(\"\\\\/\");\n break;\n }\n\n case '\\b':\n {\n m_buffer.append(\"\\\\b\");\n break;\n }\n\n case '\\f':\n {\n m_buffer.append(\"\\\\f\");\n break;\n }\n\n case '\\n':\n {\n m_buffer.append(\"\\\\n\");\n break;\n }\n\n case '\\r':\n {\n m_buffer.append(\"\\\\r\");\n break;\n }\n\n case '\\t':\n {\n m_buffer.append(\"\\\\t\");\n break;\n }\n\n default:\n {\n // Append if it's not a control character (0x00 to 0x1f)\n if (c > 0x1f)\n {\n m_buffer.append(c);\n }\n break;\n }\n }\n }\n m_buffer.append('\"');\n return m_buffer.toString();\n }",
"public void setPromoted(final boolean promoted) {\n this.promoted = promoted;\n\n for (final Artifact artifact : artifacts) {\n artifact.setPromoted(promoted);\n }\n\n for (final Module suModule : submodules) {\n suModule.setPromoted(promoted);\n }\n }",
"public static appfwsignatures get(nitro_service service, String name) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tobj.set_name(name);\n\t\tappfwsignatures response = (appfwsignatures) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public boolean isValidStore(String name) {\n readLock.lock();\n try {\n if(this.storeNames.contains(name)) {\n return true;\n }\n return false;\n } finally {\n readLock.unlock();\n }\n }",
"private static EventEnumType convertEventType(org.talend.esb.sam.common.event.EventTypeEnum eventType) {\n if (eventType == null) {\n return null;\n }\n return EventEnumType.valueOf(eventType.name());\n }",
"public static base_response update(nitro_service client, gslbservice resource) throws Exception {\n\t\tgslbservice updateresource = new gslbservice();\n\t\tupdateresource.servicename = resource.servicename;\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.publicip = resource.publicip;\n\t\tupdateresource.publicport = resource.publicport;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.sitepersistence = resource.sitepersistence;\n\t\tupdateresource.siteprefix = resource.siteprefix;\n\t\tupdateresource.maxclient = resource.maxclient;\n\t\tupdateresource.healthmonitor = resource.healthmonitor;\n\t\tupdateresource.maxbandwidth = resource.maxbandwidth;\n\t\tupdateresource.downstateflush = resource.downstateflush;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.viewname = resource.viewname;\n\t\tupdateresource.viewip = resource.viewip;\n\t\tupdateresource.monthreshold = resource.monthreshold;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.monitor_name_svc = resource.monitor_name_svc;\n\t\tupdateresource.hashid = resource.hashid;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.appflowlog = resource.appflowlog;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Used to populate Map with given annotations
@param annotations initial value for annotations | [
"private void populateAnnotations(Collection<Annotation> annotations) {\n for (Annotation each : annotations) {\n this.annotations.put(each.annotationType(), each);\n }\n }"
] | [
"public String getXmlFormatted(Map<String, String> dataMap) {\r\n StringBuilder sb = new StringBuilder();\r\n for (String var : outTemplate) {\r\n sb.append(appendXmlStartTag(var));\r\n sb.append(dataMap.get(var));\r\n sb.append(appendXmlEndingTag(var));\r\n }\r\n return sb.toString();\r\n }",
"protected void load()\r\n {\r\n // properties file may be set as a System property.\r\n // if no property is set take default name.\r\n String fn = System.getProperty(OJB_PROPERTIES_FILE, OJB_PROPERTIES_FILE);\r\n setFilename(fn);\r\n super.load();\r\n\r\n // default repository & connection descriptor file\r\n repositoryFilename = getString(\"repositoryFile\", OJB_METADATA_FILE);\r\n\r\n // object cache class\r\n objectCacheClass = getClass(\"ObjectCacheClass\", ObjectCacheDefaultImpl.class, ObjectCache.class);\r\n\r\n // load PersistentField Class\r\n persistentFieldClass =\r\n getClass(\"PersistentFieldClass\", PersistentFieldDirectImpl.class, PersistentField.class);\r\n\r\n // load PersistenceBroker Class\r\n persistenceBrokerClass =\r\n getClass(\"PersistenceBrokerClass\", PersistenceBrokerImpl.class, PersistenceBroker.class);\r\n\r\n // load ListProxy Class\r\n listProxyClass = getClass(\"ListProxyClass\", ListProxyDefaultImpl.class);\r\n\r\n // load SetProxy Class\r\n setProxyClass = getClass(\"SetProxyClass\", SetProxyDefaultImpl.class);\r\n\r\n // load CollectionProxy Class\r\n collectionProxyClass = getClass(\"CollectionProxyClass\", CollectionProxyDefaultImpl.class);\r\n\r\n // load IndirectionHandler Class\r\n indirectionHandlerClass =\r\n getClass(\"IndirectionHandlerClass\", IndirectionHandlerJDKImpl.class, IndirectionHandler.class);\r\n \r\n // load ProxyFactory Class\r\n proxyFactoryClass =\r\n getClass(\"ProxyFactoryClass\", ProxyFactoryJDKImpl.class, ProxyFactory.class);\r\n\r\n // load configuration for ImplicitLocking parameter:\r\n useImplicitLocking = getBoolean(\"ImplicitLocking\", false);\r\n\r\n // load configuration for LockAssociations parameter:\r\n lockAssociationAsWrites = (getString(\"LockAssociations\", \"WRITE\").equalsIgnoreCase(\"WRITE\"));\r\n\r\n // load OQL Collection Class\r\n oqlCollectionClass = getClass(\"OqlCollectionClass\", DListImpl.class, ManageableCollection.class);\r\n\r\n // set the limit for IN-sql , -1 for no limits\r\n sqlInLimit = getInteger(\"SqlInLimit\", -1);\r\n\r\n //load configuration for PB pool\r\n maxActive = getInteger(PoolConfiguration.MAX_ACTIVE,\r\n PoolConfiguration.DEFAULT_MAX_ACTIVE);\r\n maxIdle = getInteger(PoolConfiguration.MAX_IDLE,\r\n PoolConfiguration.DEFAULT_MAX_IDLE);\r\n maxWait = getLong(PoolConfiguration.MAX_WAIT,\r\n PoolConfiguration.DEFAULT_MAX_WAIT);\r\n timeBetweenEvictionRunsMillis = getLong(PoolConfiguration.TIME_BETWEEN_EVICTION_RUNS_MILLIS,\r\n PoolConfiguration.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);\r\n minEvictableIdleTimeMillis = getLong(PoolConfiguration.MIN_EVICTABLE_IDLE_TIME_MILLIS,\r\n PoolConfiguration.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);\r\n whenExhaustedAction = getByte(PoolConfiguration.WHEN_EXHAUSTED_ACTION,\r\n PoolConfiguration.DEFAULT_WHEN_EXHAUSTED_ACTION);\r\n\r\n useSerializedRepository = getBoolean(\"useSerializedRepository\", false);\r\n }",
"public EndpointOverride getPath(int pathId, String clientUUID, String[] filters) throws Exception {\n EndpointOverride endpoint = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID + \"=\" + pathId + \";\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n results = statement.executeQuery();\n\n if (results.next()) {\n endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return endpoint;\n }",
"public boolean isValidStore(String name) {\n readLock.lock();\n try {\n if(this.storeNames.contains(name)) {\n return true;\n }\n return false;\n } finally {\n readLock.unlock();\n }\n }",
"public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationAlongPath(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {document.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n getJSObject().eval(r.toString());\n \n }",
"public static FormValidation validateEmails(String emails) {\n if (!Strings.isNullOrEmpty(emails)) {\n String[] recipients = StringUtils.split(emails, \" \");\n for (String email : recipients) {\n FormValidation validation = validateInternetAddress(email);\n if (validation != FormValidation.ok()) {\n return validation;\n }\n }\n }\n return FormValidation.ok();\n }",
"protected List<Integer> cancelAllActiveOperations() {\n final List<Integer> operations = new ArrayList<Integer>();\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n activeOperation.asyncCancel(false);\n operations.add(activeOperation.getOperationId());\n }\n return operations;\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 static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {\n if (cNode.isInterface()) return;\n boolean isItselfTrait = Traits.isTrait(cNode);\n SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);\n if (isItselfTrait) {\n checkTraitAllowed(cNode, unit);\n return;\n }\n if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {\n List<ClassNode> traits = findTraits(cNode);\n for (ClassNode trait : traits) {\n TraitHelpersTuple helpers = Traits.findHelpers(trait);\n applyTrait(trait, cNode, helpers);\n superCallTransformer.visitClass(cNode);\n if (unit!=null) {\n ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());\n collector.visitClass(cNode);\n }\n }\n }\n }"
] |
Print a task type.
@param value TaskType instance
@return task type value | [
"public static final String printTaskType(TaskType value)\n {\n return (Integer.toString(value == null ? TaskType.FIXED_UNITS.getValue() : value.getValue()));\n }"
] | [
"public QueryBuilder<T, ID> join(QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException {\n\t\taddJoinInfo(JoinType.INNER, null, null, joinedQueryBuilder, JoinWhereOperation.AND);\n\t\treturn this;\n\t}",
"public static Broker createBroker(int id, String brokerInfoString) {\n String[] brokerInfo = brokerInfoString.split(\":\");\n String creator = brokerInfo[0].replace('#', ':');\n String hostname = brokerInfo[1].replace('#', ':');\n String port = brokerInfo[2];\n boolean autocreated = Boolean.valueOf(brokerInfo.length > 3 ? brokerInfo[3] : \"true\");\n return new Broker(id, creator, hostname, Integer.parseInt(port), autocreated);\n }",
"public int sum() {\n int total = 0;\n int N = getNumElements();\n for (int i = 0; i < N; i++) {\n if( data[i] )\n total += 1;\n }\n return total;\n }",
"public static <T> FastEvent<T> of(Class<T> type, BeanManagerImpl manager, ObserverNotifier notifier, Annotation... qualifiers) {\n ResolvedObservers<T> resolvedObserverMethods = notifier.<T> resolveObserverMethods(type, qualifiers);\n if (resolvedObserverMethods.isMetadataRequired()) {\n EventMetadata metadata = new EventMetadataImpl(type, null, qualifiers);\n CurrentEventMetadata metadataService = manager.getServices().get(CurrentEventMetadata.class);\n return new FastEventWithMetadataPropagation<T>(resolvedObserverMethods, metadata, metadataService);\n } else {\n return new FastEvent<T>(resolvedObserverMethods);\n }\n }",
"@SuppressWarnings(\"unchecked\")\n public static <T> T convert(Object fromValue, Class<T> toType) throws TypeCastException {\n return convert(fromValue, toType, (String) null);\n }",
"public List<Set<String>> makeNWiseTuples(String[] variables, int nWise) {\r\n List<Set<String>> completeTuples = new ArrayList<>();\r\n makeNWiseTuplesHelper(completeTuples, variables, 0, new HashSet<String>(), nWise);\n\r\n return completeTuples;\r\n }",
"public int checkIn() {\n\n try {\n synchronized (STATIC_LOCK) {\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, false));\n CmsObject cms = getCmsObject();\n if (cms != null) {\n return checkInInternal();\n } else {\n m_logStream.println(\"No CmsObject given. Did you call init() first?\");\n return -1;\n }\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return -2;\n }\n }",
"public boolean setCustomResponse(String pathValue, String requestType, String customData) {\n try {\n JSONObject path = getPathFromEndpoint(pathValue, requestType);\n if (path == null) {\n String pathName = pathValue;\n createPath(pathName, pathValue, requestType);\n path = getPathFromEndpoint(pathValue, requestType);\n }\n String pathId = path.getString(\"pathId\");\n resetResponseOverride(pathId);\n setCustomResponse(pathId, customData);\n return toggleResponseOverride(pathId, true);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"private static boolean matches(@Nonnull final Pattern pattern, @Nonnull final CharSequence chars) {\n\t\treturn pattern.matcher(chars).matches();\n\t}"
] |
Adds an additional site link to the constructed document.
@param title
the title of the linked page
@param siteKey
identifier of the site, e.g., "enwiki"
@param badges
one or more badges | [
"public ItemDocumentBuilder withSiteLink(String title, String siteKey,\n\t\t\tItemIdValue... badges) {\n\t\twithSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges)));\n\t\treturn this;\n\t}"
] | [
"public static double[] singularValues( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n double sv[] = svd.getSingularValues();\n Arrays.sort(sv,0,svd.numberOfSingularValues());\n\n // change the ordering to ascending\n for (int i = 0; i < sv.length/2; i++) {\n double tmp = sv[i];\n sv[i] = sv[sv.length-i-1];\n sv[sv.length-i-1] = tmp;\n }\n\n return sv;\n }",
"@SuppressWarnings(\"unchecked\") private boolean isFieldPopulated(Task task, TaskField field)\n {\n boolean result = false;\n if (field != null)\n {\n Object value = task.getCachedValue(field);\n switch (field)\n {\n case PREDECESSORS:\n case SUCCESSORS:\n {\n result = value != null && !((List<Relation>) value).isEmpty();\n break;\n }\n\n default:\n {\n result = value != null;\n break;\n }\n }\n }\n return result;\n }",
"public static cachepolicylabel[] get(nitro_service service) throws Exception{\n\t\tcachepolicylabel obj = new cachepolicylabel();\n\t\tcachepolicylabel[] response = (cachepolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Photoset getInfo(String photosetId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\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 photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photosetElement.getAttribute(\"owner\"));\r\n photoset.setOwner(owner);\r\n\r\n Photo primaryPhoto = new Photo();\r\n primaryPhoto.setId(photosetElement.getAttribute(\"primary\"));\r\n primaryPhoto.setSecret(photosetElement.getAttribute(\"secret\")); // TODO verify that this is the secret for the photo\r\n primaryPhoto.setServer(photosetElement.getAttribute(\"server\")); // TODO verify that this is the server for the photo\r\n primaryPhoto.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n // TODO remove secret/server/farm from photoset?\r\n // It's rather related to the primaryPhoto, then to the photoset itself.\r\n photoset.setSecret(photosetElement.getAttribute(\"secret\"));\r\n photoset.setServer(photosetElement.getAttribute(\"server\"));\r\n photoset.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPhotoCount(photosetElement.getAttribute(\"count_photos\"));\r\n photoset.setVideoCount(Integer.parseInt(photosetElement.getAttribute(\"count_videos\")));\r\n photoset.setViewCount(Integer.parseInt(photosetElement.getAttribute(\"count_views\")));\r\n photoset.setCommentCount(Integer.parseInt(photosetElement.getAttribute(\"count_comments\")));\r\n photoset.setDateCreate(photosetElement.getAttribute(\"date_create\"));\r\n photoset.setDateUpdate(photosetElement.getAttribute(\"date_update\"));\r\n\r\n photoset.setIsCanComment(\"1\".equals(photosetElement.getAttribute(\"can_comment\")));\r\n\r\n photoset.setTitle(XMLUtilities.getChildValue(photosetElement, \"title\"));\r\n photoset.setDescription(XMLUtilities.getChildValue(photosetElement, \"description\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n return photoset;\r\n }",
"protected <T, A> ActiveOperation<T, A> getActiveOperation(final ManagementRequestHeader header) {\n return getActiveOperation(header.getBatchId());\n }",
"public Set<String> rangeByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (lexRange.hasLimit()) {\n return jedis.zrangeByLex(getKey(), lexRange.from(), lexRange.to(), lexRange.offset(), lexRange.count());\n } else {\n return jedis.zrangeByLex(getKey(), lexRange.from(), lexRange.to());\n }\n }\n });\n }",
"private void initPatternControllers() {\r\n\r\n m_patternControllers.put(PatternType.NONE, new CmsPatternPanelNoneController());\r\n m_patternControllers.put(PatternType.DAILY, new CmsPatternPanelDailyController(m_model, this));\r\n m_patternControllers.put(PatternType.WEEKLY, new CmsPatternPanelWeeklyController(m_model, this));\r\n m_patternControllers.put(PatternType.MONTHLY, new CmsPatternPanelMonthlyController(m_model, this));\r\n m_patternControllers.put(PatternType.YEARLY, new CmsPatternPanelYearlyController(m_model, this));\r\n // m_patternControllers.put(PatternType.INDIVIDUAL, new CmsPatternPanelIndividualController(m_model, this));\r\n }",
"private void setMaxMin(IntervalRBTreeNode<T> n) {\n n.min = n.left;\n n.max = n.right;\n if (n.leftChild != null) {\n n.min = Math.min(n.min, n.leftChild.min);\n n.max = Math.max(n.max, n.leftChild.max);\n }\n if (n.rightChild != null) {\n n.min = Math.min(n.min, n.rightChild.min);\n n.max = Math.max(n.max, n.rightChild.max);\n }\n }",
"public void commandContinuationRequest()\r\n throws ProtocolException {\r\n try {\r\n output.write('+');\r\n output.write(' ');\r\n output.write('O');\r\n output.write('K');\r\n output.write('\\r');\r\n output.write('\\n');\r\n output.flush();\r\n } catch (IOException e) {\r\n throw new ProtocolException(\"Unexpected exception in sending command continuation request.\", e);\r\n }\r\n }"
] |
Loads the localization for the current locale from a bundle of type xmlvfsbundle.
It assumes, the content has already been unmarshalled before.
@param locale the locale for which the localization should be loaded | [
"private void loadLocalizationFromXmlBundle(Locale locale) {\n\n CmsXmlContentValueSequence messages = m_xmlBundle.getValueSequence(\"Message\", locale);\n SortedProperties props = new SortedProperties();\n if (null != messages) {\n for (I_CmsXmlContentValue msg : messages.getValues()) {\n String msgpath = msg.getPath();\n props.put(\n m_xmlBundle.getStringValue(m_cms, msgpath + \"/Key\", locale),\n m_xmlBundle.getStringValue(m_cms, msgpath + \"/Value\", locale));\n }\n }\n m_localizations.put(locale, props);\n }"
] | [
"private int calculateRowHeaderMaxWidth(DJCrosstabColumn crosstabColumn) {\n\t\tint auxWidth = 0;\n\t\tboolean firstTime = true;\n\t\tList<DJCrosstabColumn> auxList = new ArrayList<DJCrosstabColumn>(djcross.getColumns());\n\t\tCollections.reverse(auxList);\n\t\tfor (DJCrosstabColumn col : auxList) {\n\t\t\tif (col.equals(crosstabColumn)){\n\t\t\t\tif (auxWidth == 0)\n\t\t\t\t\tauxWidth = col.getWidth();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (firstTime){\n\t\t\t\tauxWidth += col.getWidth();\n\t\t\t\tfirstTime = false;\n\t\t\t}\n\t\t\tif (col.isShowTotals()) {\n\t\t\t\tauxWidth += col.getWidth();\n\t\t\t}\n\t\t}\n\t\treturn auxWidth;\n\t}",
"public void transformPose(Matrix4f trans)\n {\n Bone bone = mBones[0];\n\n bone.LocalMatrix.set(trans);\n bone.WorldMatrix.set(trans);\n bone.Changed = WORLD_POS | WORLD_ROT;\n mNeedSync = true;\n sync();\n }",
"public Map<String, Integer> getAggregateResultCountSummary() {\n\n Map<String, Integer> summaryMap = new LinkedHashMap<String, Integer>();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n summaryMap.put(entry.getKey(), entry.getValue().size());\n }\n\n return summaryMap;\n }",
"public void printInferredDependencies(ClassDoc c) {\n\tif (hidden(c))\n\t return;\n\n\tOptions opt = optionProvider.getOptionsFor(c);\n\tSet<Type> types = new HashSet<Type>();\n\t// harvest method return and parameter types\n\tfor (MethodDoc method : filterByVisibility(c.methods(false), opt.inferDependencyVisibility)) {\n\t types.add(method.returnType());\n\t for (Parameter parameter : method.parameters()) {\n\t\ttypes.add(parameter.type());\n\t }\n\t}\n\t// and the field types\n\tif (!opt.inferRelationships) {\n\t for (FieldDoc field : filterByVisibility(c.fields(false), opt.inferDependencyVisibility)) {\n\t\ttypes.add(field.type());\n\t }\n\t}\n\t// see if there are some type parameters\n\tif (c.asParameterizedType() != null) {\n\t ParameterizedType pt = c.asParameterizedType();\n\t types.addAll(Arrays.asList(pt.typeArguments()));\n\t}\n\t// see if type parameters extend something\n\tfor(TypeVariable tv: c.typeParameters()) {\n\t if(tv.bounds().length > 0 )\n\t\ttypes.addAll(Arrays.asList(tv.bounds()));\n\t}\n\n\t// and finally check for explicitly imported classes (this\n\t// assumes there are no unused imports...)\n\tif (opt.useImports)\n\t types.addAll(Arrays.asList(importedClasses(c)));\n\n\t// compute dependencies\n\tfor (Type type : types) {\n\t // skip primitives and type variables, as well as dependencies\n\t // on the source class\n\t if (type.isPrimitive() || type instanceof WildcardType || type instanceof TypeVariable\n\t\t || c.toString().equals(type.asClassDoc().toString()))\n\t\tcontinue;\n\n\t // check if the destination is excluded from inference\n\t ClassDoc fc = type.asClassDoc();\n\t if (hidden(fc))\n\t\tcontinue;\n\t \n\t // check if source and destination are in the same package and if we are allowed\n\t // to infer dependencies between classes in the same package\n\t if(!opt.inferDepInPackage && c.containingPackage().equals(fc.containingPackage()))\n\t\tcontinue;\n\n\t // if source and dest are not already linked, add a dependency\n\t RelationPattern rp = getClassInfo(c, true).getRelation(fc.toString());\n\t if (rp == null || rp.matchesOne(new RelationPattern(RelationDirection.OUT))) {\n\t\trelation(opt, RelationType.DEPEND, c, fc, \"\", \"\", \"\");\n\t }\n\t \n\t}\n }",
"@SuppressWarnings(\"unchecked\") public Relation addPredecessor(Task targetTask, RelationType type, Duration lag)\n {\n //\n // Ensure that we have a valid lag duration\n //\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n //\n // Retrieve the list of predecessors\n //\n List<Relation> predecessorList = (List<Relation>) getCachedValue(TaskField.PREDECESSORS);\n\n //\n // Ensure that there is only one predecessor relationship between\n // these two tasks.\n //\n Relation predecessorRelation = null;\n Iterator<Relation> iter = predecessorList.iterator();\n while (iter.hasNext() == true)\n {\n predecessorRelation = iter.next();\n if (predecessorRelation.getTargetTask() == targetTask)\n {\n if (predecessorRelation.getType() != type || predecessorRelation.getLag().compareTo(lag) != 0)\n {\n predecessorRelation = null;\n }\n break;\n }\n predecessorRelation = null;\n }\n\n //\n // If necessary, create a new predecessor relationship\n //\n if (predecessorRelation == null)\n {\n predecessorRelation = new Relation(this, targetTask, type, lag);\n predecessorList.add(predecessorRelation);\n }\n\n //\n // Retrieve the list of successors\n //\n List<Relation> successorList = (List<Relation>) targetTask.getCachedValue(TaskField.SUCCESSORS);\n\n //\n // Ensure that there is only one successor relationship between\n // these two tasks.\n //\n Relation successorRelation = null;\n iter = successorList.iterator();\n while (iter.hasNext() == true)\n {\n successorRelation = iter.next();\n if (successorRelation.getTargetTask() == this)\n {\n if (successorRelation.getType() != type || successorRelation.getLag().compareTo(lag) != 0)\n {\n successorRelation = null;\n }\n break;\n }\n successorRelation = null;\n }\n\n //\n // If necessary, create a new successor relationship\n //\n if (successorRelation == null)\n {\n successorRelation = new Relation(targetTask, this, type, lag);\n successorList.add(successorRelation);\n }\n\n return (predecessorRelation);\n }",
"public static String getClassName(Class<?> c) {\n String name = c.getName();\n return name.substring(name.lastIndexOf('.') + 1, name.length());\n }",
"public static String printUUID(UUID guid)\n {\n return guid == null ? null : \"{\" + guid.toString().toUpperCase() + \"}\";\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 }",
"private Envelope getBoundsLocal(Filter filter) throws LayerException {\n\t\ttry {\n\t\t\tSession session = getSessionFactory().getCurrentSession();\n\t\t\tCriteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());\n\t\t\tCriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);\n\t\t\tCriterion c = (Criterion) filter.accept(visitor, criteria);\n\t\t\tif (c != null) {\n\t\t\t\tcriteria.add(c);\n\t\t\t}\n\t\t\tcriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\t\t\tList<?> features = criteria.list();\n\t\t\tEnvelope bounds = new Envelope();\n\t\t\tfor (Object f : features) {\n\t\t\t\tEnvelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();\n\t\t\t\tif (!geomBounds.isNull()) {\n\t\t\t\t\tbounds.expandToInclude(geomBounds);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bounds;\n\t\t} catch (HibernateException he) {\n\t\t\tthrow new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()\n\t\t\t\t\t.getDataSourceName(), filter.toString());\n\t\t}\n\t}"
] |
Tests correctness. | [
"protected static void statistics(int from, int to) {\r\n\t// check that primes contain no accidental errors\r\n\tfor (int i=0; i<primeCapacities.length-1; i++) {\r\n\t\tif (primeCapacities[i] >= primeCapacities[i+1]) throw new RuntimeException(\"primes are unsorted or contain duplicates; detected at \"+i+\"@\"+primeCapacities[i]);\r\n\t}\r\n\t\r\n\tdouble accDeviation = 0.0;\r\n\tdouble maxDeviation = - 1.0;\r\n\r\n\tfor (int i=from; i<=to; i++) {\r\n\t\tint primeCapacity = nextPrime(i);\r\n\t\t//System.out.println(primeCapacity);\r\n\t\tdouble deviation = (primeCapacity - i) / (double)i;\r\n\t\t\r\n\t\tif (deviation > maxDeviation) {\r\n\t\t\tmaxDeviation = deviation;\r\n\t\t\tSystem.out.println(\"new maxdev @\"+i+\"@dev=\"+maxDeviation);\r\n\t\t}\r\n\r\n\t\taccDeviation += deviation;\r\n\t}\r\n\tlong width = 1 + (long)to - (long)from;\r\n\t\r\n\tdouble meanDeviation = accDeviation/width;\r\n\tSystem.out.println(\"Statistics for [\"+ from + \",\"+to+\"] are as follows\");\r\n\tSystem.out.println(\"meanDeviation = \"+(float)meanDeviation*100+\" %\");\r\n\tSystem.out.println(\"maxDeviation = \"+(float)maxDeviation*100+\" %\");\r\n}"
] | [
"public CustomHeadersInterceptor addHeaderMap(Map<String, String> headers) {\n for (Map.Entry<String, String> header : headers.entrySet()) {\n this.headers.put(header.getKey(), Collections.singletonList(header.getValue()));\n }\n return this;\n }",
"public void addArtifact(final Artifact artifact) {\n if (!artifacts.contains(artifact)) {\n if (promoted) {\n artifact.setPromoted(promoted);\n }\n\n artifacts.add(artifact);\n }\n }",
"public static float gain(float a, float b) {\n/*\n\t\tfloat p = (float)Math.log(1.0 - b) / (float)Math.log(0.5);\n\n\t\tif (a < .001)\n\t\t\treturn 0.0f;\n\t\telse if (a > .999)\n\t\t\treturn 1.0f;\n\t\tif (a < 0.5)\n\t\t\treturn (float)Math.pow(2 * a, p) / 2;\n\t\telse\n\t\t\treturn 1.0f - (float)Math.pow(2 * (1. - a), p) / 2;\n*/\n\t\tfloat c = (1.0f/b-2.0f) * (1.0f-2.0f*a);\n\t\tif (a < 0.5)\n\t\t\treturn a/(c+1.0f);\n\t\telse\n\t\t\treturn (c-a)/(c-1.0f);\n\t}",
"public boolean isPrivate() {\n\t\t// refer to RFC 1918\n // 10/8 prefix\n // 172.16/12 prefix (172.16.0.0 – 172.31.255.255)\n // 192.168/16 prefix\n\t\tIPv4AddressSegment seg0 = getSegment(0);\n\t\tIPv4AddressSegment seg1 = getSegment(1);\n\t\treturn seg0.matches(10)\n\t\t\t|| seg0.matches(172) && seg1.matchesWithPrefixMask(16, 4)\n\t\t\t|| seg0.matches(192) && seg1.matches(168);\n\t}",
"@Override\n public void close() throws VoldemortException {\n logger.debug(\"Close called for read-only store.\");\n this.fileModificationLock.writeLock().lock();\n\n try {\n if(isOpen) {\n this.isOpen = false;\n fileSet.close();\n } else {\n logger.debug(\"Attempt to close already closed store \" + getName());\n }\n } finally {\n this.fileModificationLock.writeLock().unlock();\n }\n }",
"private static BundleCapability getExportedPackage(BundleContext context, String packageName) {\n List<BundleCapability> packages = new ArrayList<BundleCapability>();\n for (Bundle bundle : context.getBundles()) {\n BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);\n for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) {\n String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);\n if (pName.equalsIgnoreCase(packageName)) {\n packages.add(packageCapability);\n }\n }\n }\n\n Version max = Version.emptyVersion;\n BundleCapability maxVersion = null;\n for (BundleCapability aPackage : packages) {\n Version version = (Version) aPackage.getAttributes().get(\"version\");\n if (max.compareTo(version) <= 0) {\n max = version;\n maxVersion = aPackage;\n }\n }\n\n return maxVersion;\n }",
"public synchronized boolean tryDelegateSlop(Node node) {\n if(asyncCallbackShouldSendhint) {\n return false;\n } else {\n slopDestinations.put(node, true);\n return true;\n }\n }",
"public static ClientBuilder account(String account) {\n logger.config(\"Account: \" + account);\n return ClientBuilder.url(\n convertStringToURL(String.format(\"https://%s.cloudant.com\", account)));\n }",
"public Map<Integer, List<Row>> createTimeEntryMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"TIME_ENTRYID\");\n List<Row> list = map.get(workPatternID);\n if (list == null)\n {\n list = new LinkedList<Row>();\n map.put(workPatternID, list);\n }\n list.add(row);\n }\n return map;\n }"
] |
Returns the link for the given workplace resource.
This should only be used for resources under /system or /shared.<p<
@param cms the current OpenCms user context
@param resourceName the resource to generate the online link for
@param forceSecure forces the secure server prefix
@return the link for the given resource | [
"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 }"
] | [
"public List<Integer> getPathOrder(int profileId) {\n ArrayList<Integer> pathOrder = new ArrayList<Integer>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \"\n + Constants.DB_TABLE_PATH + \" WHERE \"\n + Constants.GENERIC_PROFILE_ID + \" = ? \"\n + \" ORDER BY \" + Constants.PATH_PROFILE_PATH_ORDER + \" ASC\"\n );\n queryStatement.setInt(1, profileId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n pathOrder.add(results.getInt(Constants.GENERIC_ID));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n logger.info(\"pathOrder = {}\", pathOrder);\n return pathOrder;\n }",
"public static SPIProviderResolver getInstance(ClassLoader cl)\n {\n SPIProviderResolver resolver = (SPIProviderResolver)ServiceLoader.loadService(SPIProviderResolver.class.getName(), DEFAULT_SPI_PROVIDER_RESOLVER, cl);\n return resolver;\n }",
"public synchronized void addShutdownListener(ShutdownListener listener) {\n if (state == CLOSED) {\n listener.handleCompleted();\n } else {\n listeners.add(listener);\n }\n }",
"public String findPlatformFor(String jdbcSubProtocol, String jdbcDriver)\r\n {\r\n String platform = (String)jdbcSubProtocolToPlatform.get(jdbcSubProtocol);\r\n\r\n if (platform == null)\r\n {\r\n platform = (String)jdbcDriverToPlatform.get(jdbcDriver);\r\n }\r\n return platform;\r\n }",
"public boolean shouldCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, cacheIdentifiers) || checkSuffixes(uri, cacheSuffixes);\n\t}",
"public void addColumnIsNull(String column)\r\n {\r\n\t\t// PAW\r\n\t\t//SelectionCriteria c = ValueCriteria.buildNullCriteria(column, getAlias());\r\n\t\tSelectionCriteria c = ValueCriteria.buildNullCriteria(column, getUserAlias(column));\r\n c.setTranslateAttribute(false);\r\n addSelectionCriteria(c);\r\n }",
"public Filter geoSearch(String value) {\n GeopositionComparator comp = (GeopositionComparator) prop.getComparator();\n double dist = comp.getMaxDistance();\n double degrees = DistanceUtils.dist2Degrees(dist, DistanceUtils.EARTH_MEAN_RADIUS_KM * 1000.0);\n Shape circle = spatialctx.makeCircle(parsePoint(value), degrees);\n SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);\n return strategy.makeFilter(args);\n }",
"public static final UUID getUUID(InputStream is) throws IOException\n {\n byte[] data = new byte[16];\n is.read(data);\n\n long long1 = 0;\n long1 |= ((long) (data[3] & 0xFF)) << 56;\n long1 |= ((long) (data[2] & 0xFF)) << 48;\n long1 |= ((long) (data[1] & 0xFF)) << 40;\n long1 |= ((long) (data[0] & 0xFF)) << 32;\n long1 |= ((long) (data[5] & 0xFF)) << 24;\n long1 |= ((long) (data[4] & 0xFF)) << 16;\n long1 |= ((long) (data[7] & 0xFF)) << 8;\n long1 |= ((long) (data[6] & 0xFF)) << 0;\n\n long long2 = 0;\n long2 |= ((long) (data[8] & 0xFF)) << 56;\n long2 |= ((long) (data[9] & 0xFF)) << 48;\n long2 |= ((long) (data[10] & 0xFF)) << 40;\n long2 |= ((long) (data[11] & 0xFF)) << 32;\n long2 |= ((long) (data[12] & 0xFF)) << 24;\n long2 |= ((long) (data[13] & 0xFF)) << 16;\n long2 |= ((long) (data[14] & 0xFF)) << 8;\n long2 |= ((long) (data[15] & 0xFF)) << 0;\n\n return new UUID(long1, long2);\n }",
"public void ifDoesntHaveMemberTag(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean result = false;\r\n\r\n if (getCurrentField() != null) {\r\n if (!hasTag(attributes, FOR_FIELD)) {\r\n result = true;\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (!hasTag(attributes, FOR_METHOD)) {\r\n result = true;\r\n generate(template);\r\n }\r\n }\r\n if (!result) {\r\n String error = attributes.getProperty(\"error\");\r\n\r\n if (error != null) {\r\n getEngine().print(error);\r\n }\r\n }\r\n }"
] |
As already described, but if separator is not null, then objects
such as TaggedWord
@param separator The string used to separate Word and Tag
in TaggedWord, etc | [
"public static <T> String listToString(List<T> list, final boolean justValue,\r\n final String separator) {\r\n StringBuilder s = new StringBuilder();\r\n for (Iterator<T> wordIterator = list.iterator(); wordIterator.hasNext();) {\r\n T o = wordIterator.next();\r\n s.append(wordToString(o, justValue, separator));\r\n if (wordIterator.hasNext()) {\r\n s.append(' ');\r\n }\r\n }\r\n return s.toString();\r\n }"
] | [
"public Collection<EmailAlias> getEmailAliases() {\n URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n Collection<EmailAlias> emailAliases = new ArrayList<EmailAlias>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject emailAliasJSON = value.asObject();\n emailAliases.add(new EmailAlias(emailAliasJSON));\n }\n\n return emailAliases;\n }",
"protected void postDestroyConnection(ConnectionHandle handle){\r\n\t\tConnectionPartition partition = handle.getOriginatingPartition();\r\n\r\n\t\tif (this.finalizableRefQueue != null && handle.getInternalConnection() != null){ //safety\r\n\t\t\tthis.finalizableRefs.remove(handle.getInternalConnection());\r\n\t\t\t//\t\t\tassert o != null : \"Did not manage to remove connection from finalizable ref queue\";\r\n\t\t}\r\n\r\n\t\tpartition.updateCreatedConnections(-1);\r\n\t\tpartition.setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization\r\n\r\n\r\n\t\t// \"Destroying\" for us means: don't put it back in the pool.\r\n\t\tif (handle.getConnectionHook() != null){\r\n\t\t\thandle.getConnectionHook().onDestroy(handle);\r\n\t\t}\r\n\r\n\t}",
"@Override\n public boolean supportsNativeRotation() {\n return this.params.useNativeAngle &&\n (this.params.serverType == WmsLayerParam.ServerType.MAPSERVER ||\n this.params.serverType == WmsLayerParam.ServerType.GEOSERVER);\n }",
"protected boolean isStoredProcedure(String sql)\r\n {\r\n /*\r\n Stored procedures start with\r\n {?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n or\r\n {call <procedure-name>[<arg1>,<arg2>, ...]}\r\n but also statements with white space like\r\n { ?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n are possible.\r\n */\r\n int k = 0, i = 0;\r\n char c;\r\n while(k < 3 && i < sql.length())\r\n {\r\n c = sql.charAt(i);\r\n if(c != ' ')\r\n {\r\n switch (k)\r\n {\r\n case 0:\r\n if(c != '{') return false;\r\n break;\r\n case 1:\r\n if(c != '?' && c != 'c') return false;\r\n break;\r\n case 2:\r\n if(c != '=' && c != 'a') return false;\r\n break;\r\n }\r\n k++;\r\n }\r\n i++;\r\n }\r\n return true;\r\n }",
"private void readResources()\n {\n for (MapRow row : getTable(\"RTAB\"))\n {\n Resource resource = m_projectFile.addResource();\n setFields(RESOURCE_FIELDS, row, resource);\n m_eventManager.fireResourceReadEvent(resource);\n // TODO: Correctly handle calendar\n }\n }",
"@Override\n\tpublic boolean exists() {\n\t\ttry {\n\t\t\tInputStream inputStream = this.assetManager.open(this.fileName);\n\t\t\tif (inputStream != null) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\treturn false;\n\t\t}\n\t}",
"@Override\n public ArtifactoryResponse restCall(ArtifactoryRequest artifactoryRequest) throws IOException {\n HttpRequestBase httpRequest;\n\n String requestPath = \"/\" + artifactoryRequest.getApiUrl();\n ContentType contentType = Util.getContentType(artifactoryRequest.getRequestType());\n\n String queryPath = \"\";\n if (!artifactoryRequest.getQueryParams().isEmpty()) {\n queryPath = Util.getQueryPath(\"?\", artifactoryRequest.getQueryParams());\n }\n\n switch (artifactoryRequest.getMethod()) {\n case GET:\n httpRequest = new HttpGet();\n\n break;\n\n case POST:\n httpRequest = new HttpPost();\n setEntity((HttpPost)httpRequest, artifactoryRequest.getBody(), contentType);\n\n break;\n\n case PUT:\n httpRequest = new HttpPut();\n setEntity((HttpPut)httpRequest, artifactoryRequest.getBody(), contentType);\n\n break;\n\n case DELETE:\n httpRequest = new HttpDelete();\n\n break;\n\n case PATCH:\n httpRequest = new HttpPatch();\n setEntity((HttpPatch)httpRequest, artifactoryRequest.getBody(), contentType);\n break;\n\n case OPTIONS:\n httpRequest = new HttpOptions();\n break;\n\n default:\n throw new IllegalArgumentException(\"Unsupported request method.\");\n }\n\n httpRequest.setURI(URI.create(url + requestPath + queryPath));\n addAccessTokenHeaderIfNeeded(httpRequest);\n\n if (contentType != null) {\n httpRequest.setHeader(\"Content-type\", contentType.getMimeType());\n }\n\n Map<String, String> headers = artifactoryRequest.getHeaders();\n for (String key : headers.keySet()) {\n httpRequest.setHeader(key, headers.get(key));\n }\n\n HttpResponse httpResponse = httpClient.execute(httpRequest);\n return new ArtifactoryResponseImpl(httpResponse);\n }",
"GVRShader makeTemplate(Class<? extends GVRShader> id, GVRContext ctx)\n {\n try\n {\n Constructor<? extends GVRShader> maker = id.getDeclaredConstructor(GVRContext.class);\n return maker.newInstance(ctx);\n }\n catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex)\n {\n try\n {\n Constructor<? extends GVRShader> maker = id.getDeclaredConstructor();\n return maker.newInstance();\n }\n catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex2)\n {\n ctx.getEventManager().sendEvent(ctx, IErrorEvents.class, \"onError\", new Object[] {ex2.getMessage(), this});\n return null;\n }\n }\n }",
"public void setTargetBytecode(String version) {\n if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) {\n this.targetBytecode = version;\n }\n }"
] |
Creates a method signature.
@param method Method instance
@return method signature | [
"private String createMethodSignature(Method method)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(\"(\");\n for (Class<?> type : method.getParameterTypes())\n {\n sb.append(getTypeString(type));\n }\n sb.append(\")\");\n Class<?> type = method.getReturnType();\n if (type.getName().equals(\"void\"))\n {\n sb.append(\"V\");\n }\n else\n {\n sb.append(getTypeString(type));\n }\n return sb.toString();\n }"
] | [
"protected static void captureSystemStreams(boolean captureOut, boolean captureErr){\r\n if(captureOut){\r\n System.setOut(new RedwoodPrintStream(STDOUT, realSysOut));\r\n }\r\n if(captureErr){\r\n System.setErr(new RedwoodPrintStream(STDERR, realSysErr));\r\n }\r\n }",
"public static base_responses export(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata exportresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texportresources[i] = new appfwlearningdata();\n\t\t\t\texportresources[i].profilename = resources[i].profilename;\n\t\t\t\texportresources[i].securitycheck = resources[i].securitycheck;\n\t\t\t\texportresources[i].target = resources[i].target;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, exportresources,\"export\");\n\t\t}\n\t\treturn result;\n\t}",
"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 static void block(DMatrix1Row A , DMatrix1Row A_tran ,\n final int blockLength )\n {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int blockHeight = Math.min( blockLength , A.numRows - i);\n\n int indexSrc = i*A.numCols;\n int indexDst = i;\n\n for( int j = 0; j < A.numCols; j += blockLength ) {\n int blockWidth = Math.min( blockLength , A.numCols - j);\n\n// int indexSrc = i*A.numCols + j;\n// int indexDst = j*A_tran.numCols + i;\n\n int indexSrcEnd = indexSrc + blockWidth;\n// for( int l = 0; l < blockWidth; l++ , indexSrc++ ) {\n for( ; indexSrc < indexSrcEnd; indexSrc++ ) {\n int rowSrc = indexSrc;\n int rowDst = indexDst;\n int end = rowDst + blockHeight;\n// for( int k = 0; k < blockHeight; k++ , rowSrc += A.numCols ) {\n for( ; rowDst < end; rowSrc += A.numCols ) {\n // faster to write in sequence than to read in sequence\n A_tran.data[ rowDst++ ] = A.data[ rowSrc ];\n }\n indexDst += A_tran.numCols;\n }\n }\n }\n }",
"public <T> T get(URI uri, Class<T> classType) {\n HttpConnection connection = Http.GET(uri);\n InputStream response = executeToInputStream(connection);\n try {\n return getResponse(response, classType, getGson());\n } finally {\n close(response);\n }\n }",
"private void injectAdditionalStyles() {\n\n try {\n Collection<String> stylesheets = OpenCms.getWorkplaceAppManager().getAdditionalStyleSheets();\n for (String stylesheet : stylesheets) {\n A_CmsUI.get().getPage().addDependency(new Dependency(Type.STYLESHEET, stylesheet));\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }",
"public static transformpolicy[] get(nitro_service service) throws Exception{\n\t\ttransformpolicy obj = new transformpolicy();\n\t\ttransformpolicy[] response = (transformpolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Set<RateType> getRateTypes() {\n @SuppressWarnings(\"unchecked\")\n Set<RateType> rateSet = get(KEY_RATE_TYPES, Set.class);\n if (rateSet == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(rateSet);\n }",
"public void performImplicitSingleStep(double scale , double lambda , boolean byAngle) {\n createBulge(x1,lambda,scale,byAngle);\n\n for( int i = x1; i < x2-1 && bulge != 0.0; i++ ) {\n removeBulgeLeft(i,true);\n if( bulge == 0 )\n break;\n removeBulgeRight(i);\n }\n\n if( bulge != 0 )\n removeBulgeLeft(x2-1,false);\n\n incrementSteps();\n }"
] |
Iterate RMI Targets Map and remove entries loaded by protected ClassLoader | [
"@SuppressWarnings(\"WeakerAccess\")\n protected void clearRmiTargetsMap(ClassLoaderLeakPreventor preventor, Map<?, ?> rmiTargetsMap) {\n try {\n final Field cclField = preventor.findFieldOfClass(\"sun.rmi.transport.Target\", \"ccl\");\n preventor.debug(\"Looping \" + rmiTargetsMap.size() + \" RMI Targets to find leaks\");\n for(Iterator<?> iter = rmiTargetsMap.values().iterator(); iter.hasNext(); ) {\n Object target = iter.next(); // sun.rmi.transport.Target\n ClassLoader ccl = (ClassLoader) cclField.get(target);\n if(preventor.isClassLoaderOrChild(ccl)) {\n preventor.warn(\"Removing RMI Target: \" + target);\n iter.remove();\n }\n }\n }\n catch (Exception ex) {\n preventor.error(ex);\n }\n }"
] | [
"private String joinElements(int length)\n {\n StringBuilder sb = new StringBuilder();\n for (int index = 0; index < length; index++)\n {\n sb.append(m_elements.get(index));\n }\n return sb.toString();\n }",
"public static autoscaleprofile[] get(nitro_service service) throws Exception{\n\t\tautoscaleprofile obj = new autoscaleprofile();\n\t\tautoscaleprofile[] response = (autoscaleprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void onDrawFrame(float frameTime) {\n final GVRSceneObject owner = getOwnerObject();\n if (owner == null) {\n return;\n }\n\n final int size = mRanges.size();\n final GVRTransform t = getGVRContext().getMainScene().getMainCameraRig().getCenterCamera().getTransform();\n\n for (final Object[] range : mRanges) {\n ((GVRSceneObject)range[1]).setEnable(false);\n }\n\n for (int i = size - 1; i >= 0; --i) {\n final Object[] range = mRanges.get(i);\n final GVRSceneObject child = (GVRSceneObject) range[1];\n if (child.getParent() != owner) {\n Log.w(TAG, \"the scene object for distance greater than \" + range[0] + \" is not a child of the owner; skipping it\");\n continue;\n }\n\n final float[] values = child.getBoundingVolumeRawValues();\n mCenter.set(values[0], values[1], values[2], 1.0f);\n mVector.set(t.getPositionX(), t.getPositionY(), t.getPositionZ(), 1.0f);\n\n mVector.sub(mCenter);\n mVector.negate();\n\n float distance = mVector.dot(mVector);\n\n if (distance >= (Float) range[0]) {\n child.setEnable(true);\n break;\n }\n }\n }",
"@Override\r\n public boolean containsKey(Object key) {\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n Object value = deltaMap.get(key);\r\n if (value == null) {\r\n return originalMap.containsKey(key);\r\n }\r\n if (value == removedValue) {\r\n return false;\r\n }\r\n return true;\r\n }",
"public void setManyToOneAttribute(String name, AssociationValue value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new ManyToOneAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\n\t}",
"private void processCalendarData(ProjectCalendar calendar, List<ResultSetRow> calendarData)\n {\n for (ResultSetRow row : calendarData)\n {\n processCalendarData(calendar, row);\n }\n }",
"private static RemoteWebDriver buildRemoteWebDriver(String hubUrl) {\n\t\tDesiredCapabilities capabilities = new DesiredCapabilities();\n\t\tcapabilities.setPlatform(Platform.ANY);\n\t\tURL url;\n\t\ttry {\n\t\t\turl = new URL(hubUrl);\n\t\t} catch (MalformedURLException e) {\n\t\t\tLOGGER.error(\"The given hub url of the remote server is malformed can not continue!\",\n\t\t\t\t\te);\n\t\t\treturn null;\n\t\t}\n\t\tHttpCommandExecutor executor = null;\n\t\ttry {\n\t\t\texecutor = new HttpCommandExecutor(url);\n\t\t} catch (Exception e) {\n\t\t\t// TODO Stefan; refactor this catch, this will definitely result in\n\t\t\t// NullPointers, why\n\t\t\t// not throw RuntimeException direct?\n\t\t\tLOGGER.error(\n\t\t\t\t\t\"Received unknown exception while creating the \"\n\t\t\t\t\t\t\t+ \"HttpCommandExecutor, can not continue!\",\n\t\t\t\t\te);\n\t\t\treturn null;\n\t\t}\n\t\treturn new RemoteWebDriver(executor, capabilities);\n\t}",
"private boolean contentEqualsUnchecked(byte[] bytes, int offset, int len) {\n if (length != len) {\n return false;\n }\n\n return compareToUnchecked(bytes, offset, len) == 0;\n }",
"public void setLargePayloadSupportEnabled(AmazonS3 s3, String s3BucketName) {\n\t\tif (s3 == null || s3BucketName == null) {\n\t\t\tString errorMessage = \"S3 client and/or S3 bucket name cannot be null.\";\n\t\t\tLOG.error(errorMessage);\n\t\t\tthrow new AmazonClientException(errorMessage);\n\t\t}\n\t\tif (isLargePayloadSupportEnabled()) {\n\t\t\tLOG.warn(\"Large-payload support is already enabled. Overwriting AmazonS3Client and S3BucketName.\");\n\t\t}\n\t\tthis.s3 = s3;\n\t\tthis.s3BucketName = s3BucketName;\n\t\tlargePayloadSupport = true;\n\t\tLOG.info(\"Large-payload support enabled.\");\n\t}"
] |
Use this API to fetch all the nsfeature resources that are configured on netscaler. | [
"public static nsfeature get(nitro_service service) throws Exception{\n\t\tnsfeature obj = new nsfeature();\n\t\tnsfeature[] response = (nsfeature[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] | [
"private boolean isForGerritHost(HttpRequest request) {\n if (!(request instanceof HttpRequestWrapper)) return false;\n HttpRequest originalRequest = ((HttpRequestWrapper) request).getOriginal();\n if (!(originalRequest instanceof HttpRequestBase)) return false;\n URI uri = ((HttpRequestBase) originalRequest).getURI();\n URI authDataUri = URI.create(authData.getHost());\n if (uri == null || uri.getHost() == null) return false;\n boolean hostEquals = uri.getHost().equals(authDataUri.getHost());\n boolean portEquals = uri.getPort() == authDataUri.getPort();\n return hostEquals && portEquals;\n }",
"static void undoChanges(final PatchEntry entry, final PatchContentLoader loader) {\n final List<ContentModification> modifications = new ArrayList<ContentModification>(entry.rollbackActions);\n for (final ContentModification modification : modifications) {\n final ContentItem item = modification.getItem();\n if (item.getContentType() != ContentType.MISC) {\n // Skip modules and bundles they should be removed as part of the {@link FinalizeCallback}\n continue;\n }\n final PatchingTaskDescription description = new PatchingTaskDescription(entry.applyPatchId, modification, loader, false, false, false);\n try {\n final PatchingTask task = PatchingTask.Factory.create(description, entry);\n task.execute(entry);\n } catch (Exception e) {\n PatchLogger.ROOT_LOGGER.failedToUndoChange(item.toString());\n }\n }\n }",
"@UiHandler(\"m_atNumber\")\r\n void onWeekOfMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekOfMonth(event.getValue());\r\n }\r\n }",
"public <T extends Widget & Checkable> List<T> getCheckedWidgets() {\n List<T> checked = new ArrayList<>();\n\n for (Widget c : getChildren()) {\n if (c instanceof Checkable && ((Checkable) c).isChecked()) {\n checked.add((T) c);\n }\n }\n\n return checked;\n }",
"protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {\n for (MethodNode method : mopCalls) {\n String name = getMopMethodName(method, useThis);\n Parameter[] parameters = method.getParameters();\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());\n MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);\n controller.setMethodVisitor(mv);\n mv.visitVarInsn(ALOAD, 0);\n int newRegister = 1;\n OperandStack operandStack = controller.getOperandStack();\n for (Parameter parameter : parameters) {\n ClassNode type = parameter.getType();\n operandStack.load(parameter.getType(), newRegister);\n // increment to next register, double/long are using two places\n newRegister++;\n if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++;\n }\n operandStack.remove(parameters.length);\n ClassNode declaringClass = method.getDeclaringClass();\n // JDK 8 support for default methods in interfaces\n // this should probably be strenghtened when we support the A.super.foo() syntax\n int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL;\n mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE);\n BytecodeHelper.doReturn(mv, method.getReturnType());\n mv.visitMaxs(0, 0);\n mv.visitEnd();\n controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);\n }\n }",
"static String toFormattedString(final String iban) {\n final StringBuilder ibanBuffer = new StringBuilder(iban);\n final int length = ibanBuffer.length();\n\n for (int i = 0; i < length / 4; i++) {\n ibanBuffer.insert((i + 1) * 4 + i, ' ');\n }\n\n return ibanBuffer.toString().trim();\n }",
"@Deprecated\n public static PersistentResourceXMLBuilder decorator(final String elementName) {\n return new PersistentResourceXMLBuilder(PathElement.pathElement(elementName), null).setDecoratorGroup(elementName);\n }",
"@PrefMetadata(type = CmsElementViewPreference.class)\n public String getElementView() {\n\n return m_settings.getAdditionalPreference(CmsElementViewPreference.PREFERENCE_NAME, false);\n }",
"public HomekitRoot createBridge(\n HomekitAuthInfo authInfo,\n String label,\n String manufacturer,\n String model,\n String serialNumber)\n throws IOException {\n HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo);\n root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer));\n return root;\n }"
] |
Checks whether a user account can be locked because of inactivity.
@param cms the CMS context
@param user the user to check
@return true if the user may be locked after being inactive for too long | [
"public boolean canLockBecauseOfInactivity(CmsObject cms, CmsUser user) {\n\n return !user.isManaged()\n && !user.isWebuser()\n && !OpenCms.getDefaultUsers().isDefaultUser(user.getName())\n && !OpenCms.getRoleManager().hasRole(cms, user.getName(), CmsRole.ROOT_ADMIN);\n }"
] | [
"public static List<GVRAtlasInformation> loadAtlasInformation(InputStream ins) {\n try {\n int size = ins.available();\n byte[] buffer = new byte[size];\n\n ins.read(buffer);\n\n return loadAtlasInformation(new JSONArray(new String(buffer, \"UTF-8\")));\n } catch (JSONException je) {\n je.printStackTrace();\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n\n return null;\n }",
"public Project dependsOnArtifact(Artifact artifact)\n {\n Project project = new Project();\n project.setArtifact(artifact); \n project.setInputVariablesName(inputVarName);\n return project;\n }",
"public final boolean hasReturnValues()\r\n {\r\n if (this.hasReturnValue())\r\n {\r\n return true;\r\n }\r\n else\r\n {\r\n // TODO: We may be able to 'pre-calculate' the results\r\n // of this loop by just checking arguments as they are added\r\n // The only problem is that the 'isReturnedbyProcedure' property\r\n // can be modified once the argument is added to this procedure.\r\n // If that occurs, then 'pre-calculated' results will be inacccurate.\r\n Iterator iter = this.getArguments().iterator();\r\n while (iter.hasNext())\r\n {\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();\r\n if (arg.getIsReturnedByProcedure())\r\n {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }",
"private QueueCursor updateCursorForDBObject(JSONObject dbObject, QueueCursor cursor) {\n\n if (dbObject == null) return cursor;\n\n Iterator<String> keys = dbObject.keys();\n if (keys.hasNext()) {\n String key = keys.next();\n cursor.setLastId(key);\n try {\n cursor.setData(dbObject.getJSONArray(key));\n } catch (JSONException e) {\n cursor.setLastId(null);\n cursor.setData(null);\n }\n }\n\n return cursor;\n }",
"public static Date getDateFromConciseStr(String str) {\n\n Date d = null;\n if (str == null || str.isEmpty())\n return null;\n\n try {\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyyMMddHHmmssSSSZ\");\n\n d = sdf.parse(str);\n } catch (Exception ex) {\n logger.error(ex + \"Exception while converting string to date : \"\n + str);\n }\n\n return d;\n }",
"private ModelNode addLocalHost(final ModelNode address, final List<ModelNode> operationList, final String hostName) {\n\n String resolvedHost = hostName != null ? hostName : defaultHostControllerName;\n\n // All further operations should modify the newly added host so the address passed in is updated.\n address.add(HOST, resolvedHost);\n\n // Add a step to setup the ManagementResourceRegistrations for the root host resource\n final ModelNode hostAddOp = new ModelNode();\n hostAddOp.get(OP).set(HostAddHandler.OPERATION_NAME);\n hostAddOp.get(OP_ADDR).set(address);\n\n operationList.add(hostAddOp);\n\n // Add a step to store the HC name\n ModelNode nameValue = hostName == null ? new ModelNode() : new ModelNode(hostName);\n final ModelNode writeName = Util.getWriteAttributeOperation(address, NAME, nameValue);\n operationList.add(writeName);\n return hostAddOp;\n }",
"public Script getScript(int id) {\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE id = ?\"\n );\n statement.setInt(1, id);\n results = statement.executeQuery();\n if (results.next()) {\n return scriptFromSQLResult(results);\n }\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 (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return null;\n }",
"private void readTasks(Project plannerProject) throws MPXJException\n {\n Tasks tasks = plannerProject.getTasks();\n if (tasks != null)\n {\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readTask(null, task);\n }\n\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readPredecessors(task);\n }\n }\n\n m_projectFile.updateStructure();\n }",
"public SerialMessage getNoMoreInformationMessage() {\r\n\t\tlogger.debug(\"Creating new message for application command WAKE_UP_NO_MORE_INFORMATION for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessagePriority.Low);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t2, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) WAKE_UP_NO_MORE_INFORMATION };\r\n \tresult.setMessagePayload(newPayload);\r\n\r\n \treturn result;\r\n\t}"
] |
A Maven stub is a Maven Project for which we have found information, but the project has not yet been located
within the input application. If we have found an application of the same GAV within the input app, we should
fill out this stub instead of creating a new one. | [
"private MavenProjectModel getMavenStubProject(MavenProjectService mavenProjectService, String groupId, String artifactId, String version)\n {\n Iterable<MavenProjectModel> mavenProjectModels = mavenProjectService.findByGroupArtifactVersion(groupId, artifactId, version);\n if (!mavenProjectModels.iterator().hasNext())\n {\n return null;\n }\n for (MavenProjectModel mavenProjectModel : mavenProjectModels)\n {\n if (mavenProjectModel.getRootFileModel() == null)\n {\n // this is a stub... we can fill it in with details\n return mavenProjectModel;\n }\n }\n return null;\n }"
] | [
"public List<TimephasedCost> getTimephasedCost()\n {\n if (m_timephasedCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedWork != null && m_timephasedWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedCost = getTimephasedCostMultipleRates(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n else\n {\n m_timephasedCost = getTimephasedCostSingleRate(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedCost = getTimephasedCostFixedAmount();\n }\n\n }\n return m_timephasedCost;\n }",
"public Iterable<BoxGroupMembership.Info> getAllMemberships(String ... fields) {\n final QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new Iterable<BoxGroupMembership.Info>() {\n public Iterator<BoxGroupMembership.Info> iterator() {\n URL url = USER_MEMBERSHIPS_URL_TEMPLATE.buildWithQuery(\n BoxUser.this.getAPI().getBaseURL(), builder.toString(), BoxUser.this.getID());\n return new BoxGroupMembershipIterator(BoxUser.this.getAPI(), url);\n }\n };\n }",
"public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deployment = entities.stream()\n .filter(hm -> hm instanceof Deployment)\n .map(hm -> (Deployment) hm)\n .map(rc -> rc.getMetadata().getName()).findFirst();\n\n deployment.ifPresent(name -> this.applicationName = name);\n }\n }",
"public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\n }",
"public void setGlobal(int pathId, Boolean global) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_GLOBAL + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setBoolean(1, global);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public void setChildren(List<PrintComponent<?>> children) {\n\t\tthis.children = children;\n\t\t// needed for Json unmarshall !!!!\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.setParent(this);\n\t\t}\n\t}",
"@Modified(id = \"exporterServices\")\n void modifiedExporterService(ServiceReference<ExporterService> serviceReference) {\n try {\n exportersManager.modified(serviceReference);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.error(\"The ServiceProperty \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" of the ExporterService \"\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 exportersManager.removeLinks(serviceReference);\n return;\n }\n if (exportersManager.matched(serviceReference)) {\n exportersManager.updateLinks(serviceReference);\n } else {\n exportersManager.removeLinks(serviceReference);\n }\n }",
"public void increasePriority(int overrideId, int ordinal, int pathId, String clientUUID) {\n logger.info(\"Increase priority\");\n\n int origPriority = -1;\n int newPriority = -1;\n int origId = 0;\n int newId = 0;\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n results = null;\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n statement.setInt(1, pathId);\n statement.setString(2, clientUUID);\n results = statement.executeQuery();\n\n int ordinalCount = 0;\n while (results.next()) {\n if (results.getInt(Constants.ENABLED_OVERRIDES_OVERRIDE_ID) == overrideId) {\n ordinalCount++;\n if (ordinalCount == ordinal) {\n origPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n origId = results.getInt(Constants.GENERIC_ID);\n break;\n }\n }\n newPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n newId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n // update priorities\n if (origPriority != -1 && newPriority != -1) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, origPriority);\n statement.setInt(2, newId);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, newPriority);\n statement.setInt(2, origId);\n statement.executeUpdate();\n }\n } catch (Exception e) {\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"@Override protected Class getPrototypeClass(Video content) {\n Class prototypeClass;\n if (content.isFavorite()) {\n prototypeClass = FavoriteVideoRenderer.class;\n } else if (content.isLive()) {\n prototypeClass = LiveVideoRenderer.class;\n } else {\n prototypeClass = LikeVideoRenderer.class;\n }\n return prototypeClass;\n }"
] |
Updates the file metadata.
@param metadata the new metadata values.
@return the metadata returned from the server. | [
"public Metadata updateMetadata(Metadata metadata) {\n String scope;\n if (metadata.getScope().equals(Metadata.GLOBAL_METADATA_SCOPE)) {\n scope = Metadata.GLOBAL_METADATA_SCOPE;\n } else {\n scope = Metadata.ENTERPRISE_METADATA_SCOPE;\n }\n\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(),\n scope, metadata.getTemplateName());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n request.addHeader(\"Content-Type\", \"application/json-patch+json\");\n request.setBody(metadata.getPatch());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }"
] | [
"public void setMatrix(int[] matrix) {\n\t\tthis.matrix = matrix;\n\t\tsum = 0;\n\t\tfor (int i = 0; i < matrix.length; i++)\n\t\t\tsum += matrix[i];\n\t}",
"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}",
"public static MapBounds adjustBoundsToScaleAndMapSize(\n final GenericMapAttributeValues mapValues,\n final Rectangle paintArea,\n final MapBounds bounds,\n final double dpi) {\n MapBounds newBounds = bounds;\n if (mapValues.isUseNearestScale()) {\n newBounds = newBounds.adjustBoundsToNearestScale(\n mapValues.getZoomLevels(),\n mapValues.getZoomSnapTolerance(),\n mapValues.getZoomLevelSnapStrategy(),\n mapValues.getZoomSnapGeodetic(),\n paintArea, dpi);\n }\n\n newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));\n\n if (mapValues.isUseAdjustBounds()) {\n newBounds = newBounds.adjustedEnvelope(paintArea);\n }\n return newBounds;\n }",
"public final void notifyHeaderItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newHeaderItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (newHeaderItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart, itemCount);\n }",
"public void logAttributeWarning(PathAddress address, String message, String attribute) {\n logAttributeWarning(address, null, message, attribute);\n }",
"public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case REQUEST_PERMISSIONS_CODE:\n if (listener != null) {\n boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;\n listener.onPermissionResult(granted);\n }\n break;\n default:\n // Ignored\n }\n }",
"private ServerBootstrap createBootstrap(final ChannelGroup channelGroup) throws Exception {\n EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-boss-thread-%d\"));\n EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-worker-thread-%d\"));\n ServerBootstrap bootstrap = new ServerBootstrap();\n bootstrap\n .group(bossGroup, workerGroup)\n .channel(NioServerSocketChannel.class)\n .childHandler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel ch) throws Exception {\n channelGroup.add(ch);\n\n ChannelPipeline pipeline = ch.pipeline();\n if (sslHandlerFactory != null) {\n // Add SSLHandler if SSL is enabled\n pipeline.addLast(\"ssl\", sslHandlerFactory.create(ch.alloc()));\n }\n pipeline.addLast(\"codec\", new HttpServerCodec());\n pipeline.addLast(\"compressor\", new HttpContentCompressor());\n pipeline.addLast(\"chunkedWriter\", new ChunkedWriteHandler());\n pipeline.addLast(\"keepAlive\", new HttpServerKeepAliveHandler());\n pipeline.addLast(\"router\", new RequestRouter(resourceHandler, httpChunkLimit, sslHandlerFactory != null));\n if (eventExecutorGroup == null) {\n pipeline.addLast(\"dispatcher\", new HttpDispatcher());\n } else {\n pipeline.addLast(eventExecutorGroup, \"dispatcher\", new HttpDispatcher());\n }\n\n if (pipelineModifier != null) {\n pipelineModifier.modify(pipeline);\n }\n }\n });\n\n for (Map.Entry<ChannelOption, Object> entry : channelConfigs.entrySet()) {\n bootstrap.option(entry.getKey(), entry.getValue());\n }\n for (Map.Entry<ChannelOption, Object> entry : childChannelConfigs.entrySet()) {\n bootstrap.childOption(entry.getKey(), entry.getValue());\n }\n\n return bootstrap;\n }",
"private void initializeSignProperties() {\n if (!signPackage && !signChanges) {\n return;\n }\n\n if (key != null && keyring != null && passphrase != null) {\n return;\n }\n\n Map<String, String> properties =\n readPropertiesFromActiveProfiles(signCfgPrefix, KEY, KEYRING, PASSPHRASE);\n\n key = lookupIfEmpty(key, properties, KEY);\n keyring = lookupIfEmpty(keyring, properties, KEYRING);\n passphrase = decrypt(lookupIfEmpty(passphrase, properties, PASSPHRASE));\n\n if (keyring == null) {\n try {\n keyring = Utils.guessKeyRingFile().getAbsolutePath();\n console.info(\"Located keyring at \" + keyring);\n } catch (FileNotFoundException e) {\n console.warn(e.getMessage());\n }\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}"
] |
Obtains a International Fixed local date-time from another date-time object.
@param temporal the date-time object to convert, not null
@return the International Fixed local date-time, not null
@throws DateTimeException if unable to create the date-time | [
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<InternationalFixedDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<InternationalFixedDate>) super.localDateTime(temporal);\n }"
] | [
"protected String consumeWord(ImapRequestLineReader request,\n CharacterValidator validator)\n throws ProtocolException {\n StringBuilder atom = new StringBuilder();\n\n char next = request.nextWordChar();\n while (!isWhitespace(next)) {\n if (validator.isValid(next)) {\n atom.append(next);\n request.consume();\n } else {\n throw new ProtocolException(\"Invalid character: '\" + next + '\\'');\n }\n next = request.nextChar();\n }\n return atom.toString();\n }",
"protected EObject forceCreateModelElementAndSet(Action action, EObject value) {\n \tEObject result = semanticModelBuilder.create(action.getType().getClassifier());\n \tsemanticModelBuilder.set(result, action.getFeature(), value, null /* ParserRule */, currentNode);\n \tinsertCompositeNode(action);\n \tassociateNodeWithAstElement(currentNode, result);\n \treturn result;\n }",
"protected void modify(Transaction t) {\n try {\n this.lock.writeLock().lock();\n t.perform();\n } finally {\n this.lock.writeLock().unlock();\n }\n }",
"public static RouteInfo of(ActionContext context) {\n H.Method m = context.req().method();\n String path = context.req().url();\n RequestHandler handler = context.handler();\n if (null == handler) {\n handler = UNKNOWN_HANDLER;\n }\n return new RouteInfo(m, path, handler);\n }",
"protected String extractHeaderComment( File xmlFile )\n throws MojoExecutionException\n {\n\n try\n {\n SAXParser parser = SAXParserFactory.newInstance().newSAXParser();\n SaxHeaderCommentHandler handler = new SaxHeaderCommentHandler();\n parser.setProperty( \"http://xml.org/sax/properties/lexical-handler\", handler );\n parser.parse( xmlFile, handler );\n return handler.getHeaderComment();\n }\n catch ( Exception e )\n {\n throw new MojoExecutionException( \"Failed to parse XML from \" + xmlFile, e );\n }\n }",
"public static BoxStoragePolicyAssignment.Info getAssignmentForTarget(final BoxAPIConnection api,\n String resolvedForType, String resolvedForID) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"resolved_for_type\", resolvedForType)\n .appendParam(\"resolved_for_id\", resolvedForID);\n URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api,\n response.getJsonObject().get(\"entries\").asArray().get(0).asObject().get(\"id\").asString());\n BoxStoragePolicyAssignment.Info info = storagePolicyAssignment.new\n Info(response.getJsonObject().get(\"entries\").asArray().get(0).asObject());\n\n return info;\n }",
"public void useOldRESTService() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using old RESTful CustomerService with old client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old REST\");\n printOldCustomerDetails(customer);\n }",
"@JmxOperation\n public String stopAsyncOperation(int requestId) {\n try {\n stopOperation(requestId);\n } catch(VoldemortException e) {\n return e.getMessage();\n }\n\n return \"Stopping operation \" + requestId;\n }",
"public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }"
] |
Calculates the size based constraint width and height if present, otherwise from children sizes. | [
"public void calculateSize(PdfContext context) {\n\t\tfloat width = 0;\n\t\tfloat height = 0;\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.calculateSize(context);\n\t\t\tfloat cw = child.getBounds().getWidth() + 2 * child.getConstraint().getMarginX();\n\t\t\tfloat ch = child.getBounds().getHeight() + 2 * child.getConstraint().getMarginY();\n\t\t\tswitch (getConstraint().getFlowDirection()) {\n\t\t\t\tcase LayoutConstraint.FLOW_NONE:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_X:\n\t\t\t\t\twidth += cw;\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_Y:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight += ch;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unknown flow direction \" + getConstraint().getFlowDirection());\n\t\t\t}\n\t\t}\n\t\tif (getConstraint().getWidth() != 0) {\n\t\t\twidth = getConstraint().getWidth();\n\t\t}\n\t\tif (getConstraint().getHeight() != 0) {\n\t\t\theight = getConstraint().getHeight();\n\t\t}\n\t\tsetBounds(new Rectangle(0, 0, width, height));\n\t}"
] | [
"public byte[] getByteArray(int offset)\n {\n byte[] result = null;\n\n if (offset > 0 && offset < m_data.length)\n {\n int nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n int itemSize = MPPUtility.getInt(m_data, offset);\n offset += 4;\n\n if (itemSize > 0 && itemSize < m_data.length)\n {\n int blockRemainingSize = 28;\n\n if (nextBlockOffset != -1 || itemSize <= blockRemainingSize)\n {\n int itemRemainingSize = itemSize;\n result = new byte[itemSize];\n int resultOffset = 0;\n\n while (nextBlockOffset != -1)\n {\n MPPUtility.getByteArray(m_data, offset, blockRemainingSize, result, resultOffset);\n resultOffset += blockRemainingSize;\n offset += blockRemainingSize;\n itemRemainingSize -= blockRemainingSize;\n\n if (offset != nextBlockOffset)\n {\n offset = nextBlockOffset;\n }\n\n nextBlockOffset = MPPUtility.getInt(m_data, offset);\n offset += 4;\n blockRemainingSize = 32;\n }\n\n MPPUtility.getByteArray(m_data, offset, itemRemainingSize, result, resultOffset);\n }\n }\n }\n\n return (result);\n }",
"public BlockHeader read(byte[] buffer, int offset, int postHeaderSkipBytes)\n {\n m_offset = offset;\n\n System.arraycopy(buffer, m_offset, m_header, 0, 8);\n m_offset += 8;\n\n int nameLength = FastTrackUtility.getInt(buffer, m_offset);\n m_offset += 4;\n\n if (nameLength < 1 || nameLength > 255)\n {\n throw new UnexpectedStructureException();\n }\n\n m_name = new String(buffer, m_offset, nameLength, CharsetHelper.UTF16LE);\n m_offset += nameLength;\n\n m_columnType = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_flags = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_skip = new byte[postHeaderSkipBytes];\n System.arraycopy(buffer, m_offset, m_skip, 0, postHeaderSkipBytes);\n m_offset += postHeaderSkipBytes;\n\n return this;\n }",
"public Client findClient(String clientUUID, Integer profileId) throws Exception {\n Client client = null;\n /* ERROR CODE: 500 WHEN TRYING TO DELETE A SERVER GROUP.\n THIS APPEARS TO BE BECAUSE CLIENT UUID IS NULL.\n */\n /* CODE ADDED TO PREVENT NULL POINTERS. */\n if (clientUUID == null) {\n clientUUID = \"\";\n }\n\n // first see if the clientUUID is actually a uuid.. it might be a friendlyName and need conversion\n /* A UUID IS A UNIVERSALLY UNIQUE IDENTIFIER. */\n if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) != 0 &&\n !clientUUID.matches(\"[\\\\w]{8}-[\\\\w]{4}-[\\\\w]{4}-[\\\\w]{4}-[\\\\w]{12}\")) {\n Client tmpClient = this.findClientFromFriendlyName(profileId, clientUUID);\n\n // if we can't find a client then fall back to the default ID\n if (tmpClient == null) {\n clientUUID = Constants.PROFILE_CLIENT_DEFAULT_ID;\n } else {\n return tmpClient;\n }\n }\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = ?\";\n\n if (profileId != null) {\n queryString += \" AND \" + Constants.GENERIC_PROFILE_ID + \"=?\";\n }\n\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n if (profileId != null) {\n statement.setInt(2, profileId);\n }\n\n results = statement.executeQuery();\n if (results.next()) {\n client = this.getClientFromResultSet(results);\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return client;\n }",
"public boolean matches(HostName host) {\n\t\tif(this == host) {\n\t\t\treturn true;\n\t\t}\n\t\tif(isValid()) {\n\t\t\tif(host.isValid()) {\n\t\t\t\tif(isAddressString()) {\n\t\t\t\t\treturn host.isAddressString()\n\t\t\t\t\t\t\t&& asAddressString().equals(host.asAddressString())\n\t\t\t\t\t\t\t&& Objects.equals(getPort(), host.getPort())\n\t\t\t\t\t\t\t&& Objects.equals(getService(), host.getService());\n\t\t\t\t}\n\t\t\t\tif(host.isAddressString()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tString thisHost = parsedHost.getHost();\n\t\t\t\tString otherHost = host.parsedHost.getHost();\n\t\t\t\tif(!thisHost.equals(otherHost)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn Objects.equals(parsedHost.getEquivalentPrefixLength(), host.parsedHost.getEquivalentPrefixLength()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getMask(), host.parsedHost.getMask()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getPort(), host.parsedHost.getPort()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getService(), host.parsedHost.getService());\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\treturn !host.isValid() && toString().equals(host.toString());\n\t}",
"public static Organization unserializeOrganization(final String organization) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(organization, Organization.class);\n }",
"private Collection<TestClassResults> flattenResults(List<ISuite> suites)\n {\n Map<IClass, TestClassResults> flattenedResults = new HashMap<IClass, TestClassResults>();\n for (ISuite suite : suites)\n {\n for (ISuiteResult suiteResult : suite.getResults().values())\n {\n // Failed and skipped configuration methods are treated as test failures.\n organiseByClass(suiteResult.getTestContext().getFailedConfigurations().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedConfigurations().getAllResults(), flattenedResults);\n // Successful configuration methods are not included.\n \n organiseByClass(suiteResult.getTestContext().getFailedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getPassedTests().getAllResults(), flattenedResults);\n }\n }\n return flattenedResults.values();\n }",
"public InsertBuilder set(String column, String value) {\n columns.add(column);\n values.add(value);\n return this;\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 ModelNode createBootUpdates(final String serverName, final ModelNode domainModel, final ModelNode hostModel,\n final DomainController domainController, final ExpressionResolver expressionResolver) {\n final ManagedServerOperationsFactory factory = new ManagedServerOperationsFactory(serverName, domainModel,\n hostModel, domainController, expressionResolver);\n\n\n return factory.getBootUpdates();\n }"
] |
Stores template parameters for OpenShiftAssistantTemplate.
@param name template parameter name
@param value template parameter value | [
"public OpenShiftAssistantTemplate parameter(String name, String value) {\n parameterValues.put(name, value);\n return this;\n }"
] | [
"public void postConstruct(GeoService geoService, DtoConverterService converterService) throws GeomajasException {\n\t\tif (null == layerInfo) {\n\t\t\tlayerInfo = new RasterLayerInfo();\n\t\t}\n\t\tlayerInfo.setCrs(TiledRasterLayerService.MERCATOR);\n\t\tcrs = geoService.getCrs2(TiledRasterLayerService.MERCATOR);\n\t\tlayerInfo.setTileWidth(tileSize);\n\t\tlayerInfo.setTileHeight(tileSize);\n\t\tBbox bbox = new Bbox(-TiledRasterLayerService.HALF_EQUATOR_IN_METERS,\n\t\t\t\t-TiledRasterLayerService.HALF_EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS,\n\t\t\t\tTiledRasterLayerService.EQUATOR_IN_METERS);\n\t\tlayerInfo.setMaxExtent(bbox);\n\t\tmaxBounds = converterService.toInternal(bbox);\n\n\t\tresolutions = new double[maxZoomLevel + 1];\n\t\tdouble powerOfTwo = 1;\n\t\tfor (int zoomLevel = 0; zoomLevel <= maxZoomLevel; zoomLevel++) {\n\t\t\tdouble resolution = (TiledRasterLayerService.EQUATOR_IN_METERS) / (tileSize * powerOfTwo);\n\t\t\tresolutions[zoomLevel] = resolution;\n\t\t\tpowerOfTwo *= 2;\n\t\t}\n\t}",
"private 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 double[] getRegressionCoefficients(RandomVariable value) {\n\t\tif(basisFunctions.length == 0) {\n\t\t\treturn new double[] { };\n\t\t}\n\t\telse if(basisFunctions.length == 1) {\n\t\t\t/*\n\t\t\t * Regression with one basis function is just a projection on that vector. <b,x>/<b,b>\n\t\t\t */\n\t\t\treturn new double[] { value.mult(basisFunctions[0]).getAverage() / basisFunctions[0].squared().getAverage() };\n\t\t}\n\t\telse if(basisFunctions.length == 2) {\n\t\t\t/*\n\t\t\t * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD)\n\t\t\t */\n\t\t\tdouble a = basisFunctions[0].squared().getAverage();\n\t\t\tdouble b = basisFunctions[0].mult(basisFunctions[1]).average().squared().doubleValue();\n\t\t\tdouble c = b;\n\t\t\tdouble d = basisFunctions[1].squared().getAverage();\n\n\t\t\tdouble determinant = (a * d - b * c);\n\t\t\tif(determinant != 0) {\n\t\t\t\tdouble x = value.mult(basisFunctions[0]).getAverage();\n\t\t\t\tdouble y = value.mult(basisFunctions[1]).getAverage();\n\n\t\t\t\tdouble alpha0 = (d * x - b * y) / determinant;\n\t\t\t\tdouble alpha1 = (a * y - c * x) / determinant;\n\n\t\t\t\treturn new double[] { alpha0, alpha1 };\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * General case\n\t\t */\n\n\t\t// Build regression matrix\n\t\tdouble[][] BTB = new double[basisFunctions.length][basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tfor(int j=0; j<=i; j++) {\n\t\t\t\tdouble covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage();\n\t\t\t\tBTB[i][j] = covariance;\n\t\t\t\tBTB[j][i] = covariance;\n\t\t\t}\n\t\t}\n\n\t\tdouble[] BTX = new double[basisFunctions.length];\n\t\tfor(int i=0; i<basisFunctions.length; i++) {\n\t\t\tdouble covariance = basisFunctions[i].mult(value).getAverage();\n\t\t\tBTX[i] = covariance;\n\t\t}\n\n\t\treturn LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX);\n\t}",
"public void begin(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n data = new TimingData(key);\n executionInfo.put(key, data);\n }\n data.begin();\n }",
"public Where<T, ID> and() {\n\t\tManyClause clause = new ManyClause(pop(\"AND\"), ManyClause.AND_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}",
"@Override\n public void run() {\n try {\n threadContext.activate();\n // run the original thread\n runnable.run();\n } finally {\n threadContext.invalidate();\n threadContext.deactivate();\n }\n\n }",
"public void actionPerformed(java.awt.event.ActionEvent e)\r\n {\r\n System.out.println(\"Action Command: \" + e.getActionCommand());\r\n System.out.println(\"Action Params : \" + e.paramString());\r\n System.out.println(\"Action Source : \" + e.getSource());\r\n System.out.println(\"Action SrcCls : \" + e.getSource().getClass().getName());\r\n org.apache.ojb.broker.metadata.ClassDescriptor cld =\r\n new org.apache.ojb.broker.metadata.ClassDescriptor(rootNode.getRepository());\r\n // cld.setClassNameOfObject(\"New Class\");\r\n cld.setTableName(\"New Table\");\r\n rootNode.addClassDescriptor(cld);\r\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 }",
"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 }"
] |
This method is called to format a currency value.
@param value numeric value
@return currency value | [
"private String formatCurrency(Number value)\n {\n return (value == null ? null : m_formats.getCurrencyFormat().format(value));\n }"
] | [
"public void log(Level level, String msg) {\n\t\tlogIfEnabled(level, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}",
"protected void processDurationField(Row row)\n {\n processField(row, \"DUR_FIELD_ID\", \"DUR_REF_UID\", MPDUtility.getAdjustedDuration(m_project, row.getInt(\"DUR_VALUE\"), MPDUtility.getDurationTimeUnits(row.getInt(\"DUR_FMT\"))));\n }",
"public String toMixedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.mixedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.mixedString = result = toNormalizedString(IPv6StringCache.mixedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toMixedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"private void initAdapter()\n {\n Connection tmp = null;\n DatabaseMetaData meta = null;\n try\n {\n tmp = _ds.getConnection();\n meta = tmp.getMetaData();\n product = meta.getDatabaseProductName().toLowerCase();\n }\n catch (SQLException e)\n {\n throw new DatabaseException(\"Cannot connect to the database\", e);\n }\n finally\n {\n try\n {\n if (tmp != null)\n {\n tmp.close();\n }\n }\n catch (SQLException e)\n {\n // Nothing to do.\n }\n }\n\n DbAdapter newAdpt = null;\n for (String s : ADAPTERS)\n {\n try\n {\n Class<? extends DbAdapter> clazz = Db.class.getClassLoader().loadClass(s).asSubclass(DbAdapter.class);\n newAdpt = clazz.newInstance();\n if (newAdpt.compatibleWith(meta))\n {\n adapter = newAdpt;\n break;\n }\n }\n catch (Exception e)\n {\n throw new DatabaseException(\"Issue when loading database adapter named: \" + s, e);\n }\n }\n\n if (adapter == null)\n {\n throw new DatabaseException(\"Unsupported database! There is no JQM database adapter compatible with product name \" + product);\n }\n else\n {\n jqmlogger.info(\"Using database adapter {}\", adapter.getClass().getCanonicalName());\n }\n }",
"public static String getAt(GString text, Range range) {\n return getAt(text.toString(), range);\n }",
"private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {\n Map<String, Object> dataClone = new HashMap<String, Object>(data);\n dataClone.put(\"auth\", getAuthData());\n\n Map<String, String> payload = new HashMap<String, String>();\n payload.put(\"params\", jsonifyData(dataClone));\n\n if (transloadit.shouldSignRequest) {\n payload.put(\"signature\", getSignature(jsonifyData(dataClone)));\n }\n return payload;\n }",
"public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs);\n recordCheckoutTimeUs(null, checkoutTimeUs);\n } else {\n this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US);\n }\n }",
"public Collection<V> put(K key, Collection<V> collection) {\r\n return map.put(key, collection);\r\n }",
"public static final BigDecimal printCurrency(Number value)\n {\n return (value == null || value.doubleValue() == 0 ? null : new BigDecimal(value.doubleValue() * 100));\n }"
] |
Gets the publisher wrapped by the specofoed FlexiblePublisher.
@param publisher The FlexiblePublisher wrapping the publisher.
@param type The type of the publisher wrapped by the FlexiblePublisher.
@return The publisher object wrapped by the FlexiblePublisher.
Null is returned if the FlexiblePublisher does not wrap a publisher of the specified type.
@throws IllegalArgumentException In case publisher is not of type
{@link org.jenkins_ci.plugins.flexible_publish.FlexiblePublisher} | [
"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 }"
] | [
"synchronized public void completeTask(int taskId, int partitionStoresMigrated) {\n tasksInFlight.remove(taskId);\n\n numTasksCompleted++;\n numPartitionStoresMigrated += partitionStoresMigrated;\n\n updateProgressBar();\n }",
"public static final Object getObject(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return (bundle.getObject(key));\n }",
"public static <T extends HasWord> TokenizerFactory<T> factory(LexedTokenFactory<T> factory, String options) {\r\n return new PTBTokenizerFactory<T>(factory, options);\r\n\r\n }",
"public static void writeFlowId(Message message, String flowId) {\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n headers.put(FLOWID_HTTP_HEADER_NAME, Collections.singletonList(flowId));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' set to: \" + flowId);\n }\n }",
"synchronized void processFinished() {\n final InternalState required = this.requiredState;\n final InternalState state = this.internalState;\n // If the server was not stopped\n if(required == InternalState.STOPPED && state == InternalState.PROCESS_STOPPING) {\n finishTransition(InternalState.PROCESS_STOPPING, InternalState.PROCESS_STOPPED);\n } else {\n this.requiredState = InternalState.STOPPED;\n if ( !(internalSetState(getTransitionTask(InternalState.PROCESS_STOPPING), internalState, InternalState.PROCESS_STOPPING)\n && internalSetState(getTransitionTask(InternalState.PROCESS_REMOVING), internalState, InternalState.PROCESS_REMOVING)\n && internalSetState(getTransitionTask(InternalState.STOPPED), internalState, InternalState.STOPPED)) ){\n this.requiredState = InternalState.FAILED;\n internalSetState(null, internalState, InternalState.PROCESS_STOPPED);\n }\n }\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 void safeRevertWorkingCopy() {\n try {\n revertWorkingCopy();\n } catch (Exception e) {\n debuggingLogger.log(Level.FINE, \"Failed to revert working copy\", e);\n log(\"Failed to revert working copy: \" + e.getLocalizedMessage());\n Throwable cause = e.getCause();\n if (!(cause instanceof SVNException)) {\n return;\n }\n SVNException svnException = (SVNException) cause;\n if (svnException.getErrorMessage().getErrorCode() == SVNErrorCode.WC_LOCKED) {\n // work space locked attempt cleanup and try to revert again\n try {\n cleanupWorkingCopy();\n } catch (Exception unlockException) {\n debuggingLogger.log(Level.FINE, \"Failed to cleanup working copy\", e);\n log(\"Failed to cleanup working copy: \" + e.getLocalizedMessage());\n return;\n }\n\n try {\n revertWorkingCopy();\n } catch (Exception revertException) {\n log(\"Failed to revert working copy on the 2nd attempt: \" + e.getLocalizedMessage());\n }\n }\n }\n }",
"protected <T, A> ActiveOperation<T, A> removeActiveOperation(Integer id) {\n final ActiveOperation<T, A> removed = removeUnderLock(id);\n if(removed != null) {\n for(final Map.Entry<Integer, ActiveRequest<?, ?>> requestEntry : requests.entrySet()) {\n final ActiveRequest<?, ?> request = requestEntry.getValue();\n if(request.context == removed) {\n requests.remove(requestEntry.getKey());\n }\n }\n }\n return removed;\n }",
"public static boolean isCompleteZip(File file) throws IOException, NonScannableZipException {\n\n FileChannel channel = null;\n try {\n channel = new FileInputStream(file).getChannel();\n\n long size = channel.size();\n if (size < ENDLEN) { // Obvious case\n return false;\n }\n else if (validateEndRecord(file, channel, size - ENDLEN)) { // typical case where file is complete and end record has no comment\n return true;\n }\n\n // Either file is incomplete or the end of central directory record includes an arbitrary length comment\n // So, we have to scan backwards looking for an end of central directory record\n return scanForEndSig(file, channel);\n }\n finally {\n safeClose(channel);\n }\n }"
] |
Utility method to retrieve the previous working date finish time, given
a date and time as a starting point.
@param date date and time start point
@return date and time of previous work finish | [
"public Date getPreviousWorkFinish(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToPreviousWorkFinish(cal);\n return cal.getTime();\n }"
] | [
"@Override\n public void invert(DMatrixRBlock A_inv) {\n int M = Math.min(QR.numRows,QR.numCols);\n if( A_inv.numRows != M || A_inv.numCols != M )\n throw new IllegalArgumentException(\"A_inv must be square an have dimension \"+M);\n\n\n // Solve for A^-1\n // Q*R*A^-1 = I\n\n // Apply householder reflectors to the identity matrix\n // y = Q^T*I = Q^T\n MatrixOps_DDRB.setIdentity(A_inv);\n decomposer.applyQTran(A_inv);\n\n // Solve using upper triangular R matrix\n // R*A^-1 = y\n // A^-1 = R^-1*y\n TriangularSolver_DDRB.solve(QR.blockLength,true,\n new DSubmatrixD1(QR,0,M,0,M),new DSubmatrixD1(A_inv),false);\n }",
"public static aaagroup_vpntrafficpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_vpntrafficpolicy_binding obj = new aaagroup_vpntrafficpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_vpntrafficpolicy_binding response[] = (aaagroup_vpntrafficpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String getSolrRangeString(String from, String to) {\n\n // If a parameter is not initialized, use the asterisk '*' operator\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(from)) {\n from = \"*\";\n }\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(to)) {\n to = \"*\";\n }\n\n return String.format(\"[%s TO %s]\", from, to);\n }",
"private String getDateString(Date value)\n {\n Calendar cal = DateHelper.popCalendar(value);\n int year = cal.get(Calendar.YEAR);\n int month = cal.get(Calendar.MONTH) + 1;\n int day = cal.get(Calendar.DAY_OF_MONTH);\n DateHelper.pushCalendar(cal);\n \n StringBuilder sb = new StringBuilder(8);\n sb.append(m_fourDigitFormat.format(year));\n sb.append(m_twoDigitFormat.format(month));\n sb.append(m_twoDigitFormat.format(day));\n\n return (sb.toString());\n }",
"public T addContentModification(final ContentModification modification) {\n if (itemFilter.accepts(modification.getItem())) {\n internalAddModification(modification);\n }\n return returnThis();\n }",
"public void setValue(String constantValue)\r\n {\r\n this.fieldSource = SOURCE_VALUE;\r\n this.fieldRefName = null;\r\n this.returnedByProcedure = false;\r\n this.constantValue = constantValue;\r\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 boolean checkPrefixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.startsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken, Boolean serializeNulls) {\n LOG.debug(\"Factory call to instantiate class: \" + type.getName());\n RestClient restClient = new RefreshingRestClient();\n\n @SuppressWarnings(\"unchecked\")\n Class<T> concreteClass = (Class<T>) writerMap.get(type);\n\n if (concreteClass == null) {\n throw new UnsupportedOperationException(\"No implementation for requested interface found: \" + type.getName());\n }\n\n LOG.debug(\"got writer class: \" + concreteClass);\n try {\n Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class, OauthToken.class,\n RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class);\n return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient,\n connectTimeout, readTimeout, null, serializeNulls);\n } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {\n throw new UnsupportedOperationException(\"Unknown error instantiating the concrete API class: \" + type.getName(), e);\n }\n }"
] |
Determines if the queue identified by the given key is a delayed queue.
@param jedis
connection to Redis
@param key
the key that identifies a queue
@return true if the key identifies a delayed queue, false otherwise | [
"public static boolean isDelayedQueue(final Jedis jedis, final String key) {\n return ZSET.equalsIgnoreCase(jedis.type(key));\n }"
] | [
"public static sslservice[] get(nitro_service service, sslservice_args args) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsslservice[] response = (sslservice[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"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 }",
"VersionExcludeData getVersionIgnoreData(int major, int minor, int micro) {\n VersionExcludeData result = registry.get(new VersionKey(major, minor, micro));\n if (result == null) {\n result = registry.get(new VersionKey(major, minor, null));\n }\n return result;\n }",
"public static DMatrixRMaj insideSpan(DMatrixRMaj[] span , double min , double max , Random rand ) {\n DMatrixRMaj A = new DMatrixRMaj(span.length,1);\n\n DMatrixRMaj B = new DMatrixRMaj(span[0].getNumElements(),1);\n\n for( int i = 0; i < span.length; i++ ) {\n B.set(span[i]);\n double val = rand.nextDouble()*(max-min)+min;\n CommonOps_DDRM.scale(val,B);\n\n CommonOps_DDRM.add(A,B,A);\n\n }\n\n return A;\n }",
"public static base_responses update(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 updateresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsip6();\n\t\t\t\tupdateresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tupdateresources[i].td = resources[i].td;\n\t\t\t\tupdateresources[i].nd = resources[i].nd;\n\t\t\t\tupdateresources[i].icmp = resources[i].icmp;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t\tupdateresources[i].telnet = resources[i].telnet;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].gui = resources[i].gui;\n\t\t\t\tupdateresources[i].ssh = resources[i].ssh;\n\t\t\t\tupdateresources[i].snmp = resources[i].snmp;\n\t\t\t\tupdateresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\tupdateresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].map = resources[i].map;\n\t\t\t\tupdateresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\tupdateresources[i].hostroute = resources[i].hostroute;\n\t\t\t\tupdateresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\tupdateresources[i].metric = resources[i].metric;\n\t\t\t\tupdateresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\tupdateresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\tupdateresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void sendMessageToAgents(String[] agent_name, String msgtype,\n Object message_content, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }",
"public boolean hasMoreElements()\r\n {\r\n try\r\n {\r\n if (!hasCalledCheck)\r\n {\r\n hasCalledCheck = true;\r\n hasNext = resultSetAndStatment.m_rs.next();\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n LoggerFactory.getDefaultLogger().error(e);\r\n //releaseDbResources();\r\n hasNext = false;\r\n }\r\n finally\r\n {\r\n if(!hasNext)\r\n {\r\n releaseDbResources();\r\n }\r\n }\r\n return hasNext;\r\n }",
"public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.sql.Time(gc.getTime().getTime());\n }",
"public RedwoodConfiguration neatExit(){\r\n tasks.add(new Runnable() { public void run() {\r\n Runtime.getRuntime().addShutdownHook(new Thread(){\r\n @Override public void run(){ Redwood.stop(); }\r\n });\r\n }});\r\n return this;\r\n }"
] |
Retrieve the effective calendar for this task. If the task does not have
a specific calendar associated with it, fall back to using the default calendar
for the project.
@return ProjectCalendar instance | [
"public ProjectCalendar getEffectiveCalendar()\n {\n ProjectCalendar result = getCalendar();\n if (result == null)\n {\n result = getParentFile().getDefaultCalendar();\n }\n return result;\n }"
] | [
"public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength);\n recordResourceRequestQueueLength(null, queueLength);\n } else {\n this.resourceRequestQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }",
"public List<String> invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {\n MavenProject mavenProject = getMavenProject(f.getAbsolutePath());\n return mavenProject.getModel().getModules();\n }",
"private void readPage(byte[] buffer, Table table)\n {\n int magicNumber = getShort(buffer, 0);\n if (magicNumber == 0x4400)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, 0, 6, true, 16, \"\"));\n int recordSize = m_definition.getRecordSize();\n RowValidator rowValidator = m_definition.getRowValidator();\n String primaryKeyColumnName = m_definition.getPrimaryKeyColumnName();\n\n int index = 6;\n while (index + recordSize <= buffer.length)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, index, recordSize, true, 16, \"\"));\n int btrieveValue = getShort(buffer, index);\n if (btrieveValue != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n row.put(\"ROW_VERSION\", Integer.valueOf(btrieveValue));\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(index, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n if (rowValidator == null || rowValidator.validRow(row))\n {\n table.addRow(primaryKeyColumnName, row);\n }\n }\n index += recordSize;\n }\n }\n }",
"private void disableCertificateVerification()\n throws KeyManagementException, NoSuchAlgorithmException {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] { new CustomTrustManager() };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new SecureRandom());\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);\n final HostnameVerifier verifier = new HostnameVerifier() {\n @Override\n public boolean verify(final String hostname,\n final SSLSession session) {\n return true;\n }\n };\n\n HttpsURLConnection.setDefaultHostnameVerifier(verifier);\n }",
"protected void setBeanStore(BoundBeanStore beanStore) {\n if (beanStore == null) {\n this.beanStore.remove();\n } else {\n this.beanStore.set(beanStore);\n }\n }",
"public static Observable<byte[]> downloadFileAsync(String url, Retrofit retrofit) {\n FileService service = retrofit.create(FileService.class);\n Observable<ResponseBody> response = service.download(url);\n return response.map(new Func1<ResponseBody, byte[]>() {\n @Override\n public byte[] call(ResponseBody responseBody) {\n try {\n return responseBody.bytes();\n } catch (IOException e) {\n throw Exceptions.propagate(e);\n }\n }\n });\n }",
"public void map(Story story, MetaFilter metaFilter) {\n if (metaFilter.allow(story.getMeta())) {\n boolean allowed = false;\n for (Scenario scenario : story.getScenarios()) {\n // scenario also inherits meta from story\n Meta inherited = scenario.getMeta().inheritFrom(story.getMeta());\n if (metaFilter.allow(inherited)) {\n allowed = true;\n break;\n }\n }\n if (allowed) {\n add(metaFilter.asString(), story);\n }\n }\n }",
"@Override\n\tpublic String toNormalizedString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.normalizedString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.normalizedString = result = toNormalizedString(IPv6StringCache.normalizedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toNormalizedString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"private void mapText(String oldText, Map<String, String> replacements)\n {\n char c2 = 0;\n if (oldText != null && oldText.length() != 0 && !replacements.containsKey(oldText))\n {\n StringBuilder newText = new StringBuilder(oldText.length());\n for (int loop = 0; loop < oldText.length(); loop++)\n {\n char c = oldText.charAt(loop);\n if (Character.isUpperCase(c))\n {\n newText.append('X');\n }\n else\n {\n if (Character.isLowerCase(c))\n {\n newText.append('x');\n }\n else\n {\n if (Character.isDigit(c))\n {\n newText.append('0');\n }\n else\n {\n if (Character.isLetter(c))\n {\n // Handle other codepages etc. If possible find a way to\n // maintain the same code page as original.\n // E.g. replace with a character from the same alphabet.\n // This 'should' work for most cases\n if (c2 == 0)\n {\n c2 = c;\n }\n newText.append(c2);\n }\n else\n {\n newText.append(c);\n }\n }\n }\n }\n }\n\n replacements.put(oldText, newText.toString());\n }\n }"
] |
Retrieves the value of the given accessible field of the given receiver.
@param receiver the container of the field, not <code>null</code>
@param fieldName the field's name, not <code>null</code>
@return the value of the field
@throws NoSuchFieldException see {@link Class#getField(String)}
@throws SecurityException see {@link Class#getField(String)}
@throws IllegalAccessException see {@link Field#get(Object)}
@throws IllegalArgumentException see {@link Field#get(Object)} | [
"@SuppressWarnings(\"unchecked\")\n\t/* @Nullable */\n\tpublic <T> T get(Object receiver, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\t\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\treturn (T) f.get(receiver);\n\t}"
] | [
"private static void listHierarchy(ProjectFile file)\n {\n for (Task task : file.getChildTasks())\n {\n System.out.println(\"Task: \" + task.getName() + \"\\t\" + task.getStart() + \"\\t\" + task.getFinish());\n listHierarchy(task, \" \");\n }\n\n System.out.println();\n }",
"public static HashMap<String, String> getParameters(String query) {\n HashMap<String, String> params = new HashMap<String, String>();\n if (query == null || query.length() == 0) {\n return params;\n }\n\n String[] splitQuery = query.split(\"&\");\n for (String splitItem : splitQuery) {\n String[] items = splitItem.split(\"=\");\n\n if (items.length == 1) {\n params.put(items[0], \"\");\n } else {\n params.put(items[0], items[1]);\n }\n }\n\n return params;\n }",
"public static final Double getPercentage(byte[] data, int offset)\n {\n int value = MPPUtility.getShort(data, offset);\n Double result = null;\n if (value >= 0 && value <= 100)\n {\n result = NumberHelper.getDouble(value);\n }\n return result;\n }",
"public static String getStringProperty(String name, Map<String, String> map, String defaultValue) {\n if (map.containsKey(name) && Strings.isNotNullOrEmpty(map.get(name))) {\n defaultValue = map.get(name);\n }\n return getPropertyOrEnvironmentVariable(name, defaultValue);\n }",
"private void addMembers(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n if (!type.isInterface() && (type.getFields() != null)) {\r\n XField field;\r\n\r\n for (Iterator it = type.getFields().iterator(); it.hasNext(); ) {\r\n field = (XField)it.next();\r\n if (!field.isFinal() && !field.isStatic() && !field.isTransient()) {\r\n if (checkTagAndParam(field.getDoc(), tagName, paramName, paramValue)) {\r\n // already processed ?\r\n if (!members.containsKey(field.getName())) {\r\n memberNames.add(field.getName());\r\n members.put(field.getName(), field);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (type.getMethods() != null) {\r\n XMethod method;\r\n String propertyName;\r\n\r\n for (Iterator it = type.getMethods().iterator(); it.hasNext(); ) {\r\n method = (XMethod)it.next();\r\n if (!method.isConstructor() && !method.isNative() && !method.isStatic()) {\r\n if (checkTagAndParam(method.getDoc(), tagName, paramName, paramValue)) {\r\n if (MethodTagsHandler.isGetterMethod(method) || MethodTagsHandler.isSetterMethod(method)) {\r\n propertyName = MethodTagsHandler.getPropertyNameFor(method);\r\n if (!members.containsKey(propertyName)) {\r\n memberNames.add(propertyName);\r\n members.put(propertyName, method);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }",
"public void setStatusBarMessage(final String message)\r\n {\r\n // Guaranteed to return a non-null array\r\n Object[] listeners = listenerList.getListenerList();\r\n // Process the listeners last to first, notifying\r\n // those that are interested in this event\r\n for (int i = listeners.length-2; i>=0; i-=2) {\r\n if (listeners[i]==StatusMessageListener.class) \r\n {\r\n ((StatusMessageListener)listeners[i+1]).statusMessageReceived(message);\r\n } \r\n } \r\n }",
"public boolean shouldNotCache(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkContains(uri, noCacheIdentifiers) || checkSuffixes(uri, noCacheSuffixes);\n\t}",
"public String astring(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n switch (next) {\n case '\"':\n return consumeQuoted(request);\n case '{':\n return consumeLiteral(request);\n default:\n return atom(request);\n }\n }",
"public void alias( double value , String name ) {\n if( isReserved(name))\n throw new RuntimeException(\"Reserved word or contains a reserved character. '\"+name+\"'\");\n\n VariableDouble old = (VariableDouble)variables.get(name);\n if( old == null ) {\n variables.put(name, new VariableDouble(value));\n }else {\n old.value = value;\n }\n }"
] |
Get the property name of a method name. For example the property name of
setSomeValue would be someValue. Names not beginning with set or get are
not changed.
@param name The name to process
@return The property name | [
"public static String getPropertyName(String name) {\n if(name != null && (name.startsWith(\"get\") || name.startsWith(\"set\"))) {\n StringBuilder b = new StringBuilder(name);\n b.delete(0, 3);\n b.setCharAt(0, Character.toLowerCase(b.charAt(0)));\n return b.toString();\n } else {\n return name;\n }\n }"
] | [
"private Properties parseXML(Document doc, String sectionName) {\n\t\tint found = -1;\n\t\tProperties results = new Properties();\n\t\tNodeList config = null;\n\t\tif (sectionName == null){\n\t\t\tconfig = doc.getElementsByTagName(\"default-config\");\n\t\t\tfound = 0;\n\t\t} else {\n\t\t\tconfig = doc.getElementsByTagName(\"named-config\");\n\t\t\tif(config != null && config.getLength() > 0) {\n\t\t\t\tfor (int i = 0; i < config.getLength(); i++) {\n\t\t\t\t\tNode node = config.item(i);\n\t\t\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE ){\n\t\t\t\t\t\tNamedNodeMap attributes = node.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tNode name = attributes.getNamedItem(\"name\");\n\t\t\t\t\t\t\tif (name.getNodeValue().equalsIgnoreCase(sectionName)){\n\t\t\t\t\t\t\t\tfound = i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found == -1){\n\t\t\t\tconfig = null;\n\t\t\t\tlogger.warn(\"Did not find \"+sectionName+\" section in config file. Reverting to defaults.\");\n\t\t\t}\n\t\t}\n\n\t\tif(config != null && config.getLength() > 0) {\n\t\t\tNode node = config.item(found);\n\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE){\n\t\t\t\tElement elementEntry = (Element)node;\n\t\t\t\tNodeList childNodeList = elementEntry.getChildNodes();\n\t\t\t\tfor (int j = 0; j < childNodeList.getLength(); j++) {\n\t\t\t\t\tNode node_j = childNodeList.item(j);\n\t\t\t\t\tif (node_j.getNodeType() == Node.ELEMENT_NODE) {\n\t\t\t\t\t\tElement piece = (Element) node_j;\n\t\t\t\t\t\tNamedNodeMap attributes = piece.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tresults.put(attributes.item(0).getNodeValue(), piece.getTextContent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}",
"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}",
"public void process(File file) throws Exception\n {\n openLogFile();\n\n int blockIndex = 0;\n int length = (int) file.length();\n m_buffer = new byte[length];\n FileInputStream is = new FileInputStream(file);\n try\n {\n int bytesRead = is.read(m_buffer);\n if (bytesRead != length)\n {\n throw new RuntimeException(\"Read count different\");\n }\n }\n finally\n {\n is.close();\n }\n\n List<Integer> blocks = new ArrayList<Integer>();\n for (int index = 64; index < m_buffer.length - 11; index++)\n {\n if (matchPattern(PARENT_BLOCK_PATTERNS, index))\n {\n blocks.add(Integer.valueOf(index));\n }\n }\n\n int startIndex = 0;\n for (int endIndex : blocks)\n {\n int blockLength = endIndex - startIndex;\n readBlock(blockIndex, startIndex, blockLength);\n startIndex = endIndex;\n ++blockIndex;\n }\n\n int blockLength = m_buffer.length - startIndex;\n readBlock(blockIndex, startIndex, blockLength);\n\n closeLogFile();\n }",
"public static boolean setDefaultCustomResponse(String pathValue, String requestType, String customData) {\n try {\n JSONObject profile = getDefaultProfile();\n String profileName = profile.getString(\"name\");\n PathValueClient client = new PathValueClient(profileName, false);\n return client.setCustomResponse(pathValue, requestType, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public static <T> T mode(Collection<T> values) {\r\n Set<T> modes = modes(values);\r\n return modes.iterator().next();\r\n }",
"protected void runImportScript(CmsObject cms, CmsModule module) {\n\n LOG.info(\"Executing import script for module \" + module.getName());\n m_report.println(\n org.opencms.module.Messages.get().container(org.opencms.module.Messages.RPT_IMPORT_SCRIPT_HEADER_0),\n I_CmsReport.FORMAT_HEADLINE);\n String importScript = \"echo on\\n\" + module.getImportScript();\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n PrintStream out = new PrintStream(buffer);\n CmsShell shell = new CmsShell(cms, \"${user}@${project}:${siteroot}|${uri}>\", null, out, out);\n shell.execute(importScript);\n String outputString = buffer.toString();\n LOG.info(\"Shell output for import script was: \\n\" + outputString);\n m_report.println(\n org.opencms.module.Messages.get().container(\n org.opencms.module.Messages.RPT_IMPORT_SCRIPT_OUTPUT_1,\n outputString));\n }",
"public static Platform detect() throws UnsupportedPlatformException {\n String osArch = getProperty(\"os.arch\");\n String osName = getProperty(\"os.name\");\n\n for (Arch arch : Arch.values()) {\n if (arch.pattern.matcher(osArch).matches()) {\n for (OS os : OS.values()) {\n if (os.pattern.matcher(osName).matches()) {\n return new Platform(arch, os);\n }\n }\n }\n }\n\n String msg = String.format(\"Unsupported platform %s %s\", osArch, osName);\n throw new UnsupportedPlatformException(msg);\n }",
"public static spilloverpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy_lbvserver_binding obj = new spilloverpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy_lbvserver_binding response[] = (spilloverpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"static <K, V> PageMetadata<K, V> mergeTokenAndQueryParameters(String paginationToken, final\n ViewQueryParameters<K, V> initialParameters) {\n\n // Decode the base64 token into JSON\n String json = new String(Base64.decodeBase64(paginationToken), Charset.forName(\"UTF-8\"));\n\n // Get a suitable Gson, we need any adapter registered for the K key type\n Gson paginationTokenGson = getGsonWithKeyAdapter(initialParameters);\n\n // Deserialize the pagination token JSON, using the appropriate K, V types\n PaginationToken token = paginationTokenGson.fromJson(json, PaginationToken.class);\n\n // Create new query parameters using the initial ViewQueryParameters as a starting point.\n ViewQueryParameters<K, V> tokenPageParameters = initialParameters.copy();\n\n // Merge the values from the token into the new query parameters\n tokenPageParameters.descending = token.descending;\n tokenPageParameters.endkey = token.endkey;\n tokenPageParameters.endkey_docid = token.endkey_docid;\n tokenPageParameters.inclusive_end = token.inclusive_end;\n tokenPageParameters.startkey = token.startkey;\n tokenPageParameters.startkey_docid = token.startkey_docid;\n\n return new PageMetadata<K, V>(token.direction, token\n .pageNumber, tokenPageParameters);\n }"
] |
Part of the endOfRun process that needs the database. May be deferred if the database is not available. | [
"void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }"
] | [
"public final int getJdbcType()\r\n {\r\n switch (this.fieldSource)\r\n {\r\n case SOURCE_FIELD :\r\n return this.getFieldRef().getJdbcType().getType();\r\n case SOURCE_NULL :\r\n return java.sql.Types.NULL;\r\n case SOURCE_VALUE :\r\n return java.sql.Types.VARCHAR;\r\n default :\r\n return java.sql.Types.NULL;\r\n }\r\n }",
"protected void copyStream(File outputDirectory,\n InputStream stream,\n String targetFileName) throws IOException\n {\n File resourceFile = new File(outputDirectory, targetFileName);\n BufferedReader reader = null;\n Writer writer = null;\n try\n {\n reader = new BufferedReader(new InputStreamReader(stream, ENCODING));\n writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resourceFile), ENCODING));\n\n String line = reader.readLine();\n while (line != null)\n {\n writer.write(line);\n writer.write('\\n');\n line = reader.readLine();\n }\n writer.flush();\n }\n finally\n {\n if (reader != null)\n {\n reader.close();\n }\n if (writer != null)\n {\n writer.close();\n }\n }\n }",
"public static boolean isTrue(Expression expression) {\r\n if (expression == null) {\r\n return false;\r\n }\r\n if (expression instanceof PropertyExpression\r\n && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) {\r\n if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression\r\n && \"TRUE\".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) {\r\n return true;\r\n }\r\n }\r\n return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isTrueExpression()) ||\r\n \"Boolean.TRUE\".equals(expression.getText());\r\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 static base_responses delete(nitro_service client, dnsaaaarec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsaaaarec deleteresources[] = new dnsaaaarec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new dnsaaaarec();\n\t\t\t\tdeleteresources[i].hostname = resources[i].hostname;\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static InputStream getContentStream(String stringUrl) throws MalformedURLException, IOException {\n URL url = new URL(stringUrl);\n \n URLConnection urlConnection = url.openConnection();\n \n InputStream is = urlConnection.getInputStream();\n if (\"gzip\".equals(urlConnection.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n return is;\n }",
"public Version putWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n List<Versioned<V>> versionedValues;\n long startTime = System.currentTimeMillis();\n String keyHexString = \"\";\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"PUT requested for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + startTime\n + \" . Nested GET and PUT VERSION requests to follow ---\");\n }\n\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent put might be faster such that all the\n // steps might finish within the allotted time\n requestWrapper.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(requestWrapper);\n Versioned<V> versioned = getItemOrThrow(requestWrapper.getKey(), null, versionedValues);\n\n long endTime = System.currentTimeMillis();\n if(versioned == null)\n versioned = Versioned.value(requestWrapper.getRawValue(), new VectorClock());\n else\n versioned.setObject(requestWrapper.getRawValue());\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n long timeLeft = requestWrapper.getRoutingTimeoutInMs() - (endTime - startTime);\n if(timeLeft <= 0) {\n throw new StoreTimeoutException(\"PUT request timed out\");\n }\n CompositeVersionedPutVoldemortRequest<K, V> putVersionedRequestObject = new CompositeVersionedPutVoldemortRequest<K, V>(requestWrapper.getKey(),\n versioned,\n timeLeft);\n putVersionedRequestObject.setRequestOriginTimeInMs(requestWrapper.getRequestOriginTimeInMs());\n Version result = putVersionedWithCustomTimeout(putVersionedRequestObject);\n long endTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT response received for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + endTimeInMs);\n }\n return result;\n }",
"public PromotionEvaluationReport getModulePromotionReport(final String name, final String version) throws GrapesCommunicationException {\n return getModulePromotionReportRaw(name, version, false, PromotionEvaluationReport.class);\n }",
"@SuppressWarnings(\"unchecked\")\n private static Object resolveConflictWithResolver(\n final ConflictHandler conflictResolver,\n final BsonValue documentId,\n final ChangeEvent localEvent,\n final ChangeEvent remoteEvent\n ) {\n return conflictResolver.resolveConflict(\n documentId,\n localEvent,\n remoteEvent);\n }"
] |
Find all methods on classes under scanBase that are annotated with annotationClass.
@param scanBase Package to scan recursively, in dot notation (ie: org.jrugged...)
@param annotationClass Class of the annotation to search for
@return Set<Method> The set of all @{java.lang.reflect.Method}s having the annotation | [
"public Set<Method> findAnnotatedMethods(String scanBase, Class<? extends Annotation> annotationClass) {\n Set<BeanDefinition> filteredComponents = findCandidateBeans(scanBase, annotationClass);\n return extractAnnotatedMethods(filteredComponents, annotationClass);\n }"
] | [
"public static String join(Iterable<?> iterable, String separator) {\n if (iterable != null) {\n StringBuilder buf = new StringBuilder();\n Iterator<?> it = iterable.iterator();\n char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;\n while (it.hasNext()) {\n buf.append(it.next());\n if (it.hasNext()) {\n if (singleChar != 0) {\n // More efficient\n buf.append(singleChar);\n } else {\n buf.append(separator);\n }\n }\n }\n return buf.toString();\n } else {\n return \"\";\n }\n }",
"public void setAll() {\n\tshowAttributes = true;\n\tshowEnumerations = true;\n\tshowEnumConstants = true;\n\tshowOperations = true;\n\tshowConstructors = true;\n\tshowVisibility = true;\n\tshowType = true;\n }",
"public static <X> String createTypeId(AnnotatedType<X> annotatedType) {\n String id = createTypeId(annotatedType.getJavaClass(), annotatedType.getAnnotations(), annotatedType.getMethods(), annotatedType.getFields(), annotatedType.getConstructors());\n String hash = hash(id);\n MetadataLogger.LOG.tracef(\"Generated AnnotatedType id hash for %s: %s\", id, hash);\n return hash;\n }",
"static void addHeaders(HttpUriRequest httpRequest, HttpHeaders headers) {\n\t\tfor (Map.Entry<String, List<String>> entry : headers.entrySet()) {\n\t\t\tString headerName = entry.getKey();\n\t\t\tif (HttpHeaders.COOKIE.equalsIgnoreCase(headerName)) { // RFC 6265\n\t\t\t\tString headerValue = StringUtils.collectionToDelimitedString(entry.getValue(), \"; \");\n\t\t\t\thttpRequest.addHeader(headerName, headerValue);\n\t\t\t}\n\t\t\telse if (!HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) &&\n\t\t\t\t\t!HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)) {\n\t\t\t\tfor (String headerValue : entry.getValue()) {\n\t\t\t\t\thttpRequest.addHeader(headerName, headerValue);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"String urlDecode(String name, String encoding) throws UnsupportedEncodingException {\n return URLDecoder.decode(name, encoding);\n }",
"public PayloadBuilder category(final String category) {\n if (category != null) {\n aps.put(\"category\", category);\n } else {\n aps.remove(\"category\");\n }\n return this;\n }",
"private void addException(ProjectCalendar mpxjCalendar, net.sf.mpxj.ganttproject.schema.Date date)\n {\n String year = date.getYear();\n if (year == null || year.isEmpty())\n {\n // In order to process recurring exceptions using MPXJ, we need a start and end date\n // to constrain the number of dates we generate.\n // May need to pre-process the tasks in order to calculate a start and finish date.\n // TODO: handle recurring exceptions\n }\n else\n {\n Calendar calendar = DateHelper.popCalendar();\n calendar.set(Calendar.YEAR, Integer.parseInt(year));\n calendar.set(Calendar.MONTH, NumberHelper.getInt(date.getMonth()));\n calendar.set(Calendar.DAY_OF_MONTH, NumberHelper.getInt(date.getDate()));\n Date exceptionDate = calendar.getTime();\n DateHelper.pushCalendar(calendar);\n ProjectCalendarException exception = mpxjCalendar.addCalendarException(exceptionDate, exceptionDate);\n\n // TODO: not sure how NEUTRAL should be handled\n if (\"WORKING_DAY\".equals(date.getType()))\n {\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }",
"@SuppressWarnings(\"rawtypes\")\n\tprivate MailInboundChannelAdapterSpec getImapFlowBuilder(URLName urlName) {\n\t\treturn Mail.imapInboundAdapter(urlName.toString())\n\t\t\t\t.shouldMarkMessagesAsRead(this.properties.isMarkAsRead());\n\t}",
"static Object getLCState(StateManagerInternal sm)\r\n\t{\r\n\t\t// unfortunately the LifeCycleState classes are package private.\r\n\t\t// so we have to do some dirty reflection hack to access them\r\n\t\ttry\r\n\t\t{\r\n\t\t\tField myLC = sm.getClass().getDeclaredField(\"myLC\");\r\n\t\t\tmyLC.setAccessible(true);\r\n\t\t\treturn myLC.get(sm);\r\n\t\t}\r\n\t\tcatch (NoSuchFieldException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\r\n\t\tcatch (IllegalAccessException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\t\r\n\t}"
] |
Populate a resource assignment.
@param record MPX record
@param assignment resource assignment
@throws MPXJException | [
"private void populateResourceAssignment(Record record, ResourceAssignment assignment) throws MPXJException\n {\n //\n // Handle malformed MPX files - ensure that we can locate the resource\n // using either the Unique ID attribute or the ID attribute.\n //\n Resource resource = m_projectFile.getResourceByUniqueID(record.getInteger(12));\n if (resource == null)\n {\n resource = m_projectFile.getResourceByID(record.getInteger(0));\n }\n\n assignment.setUnits(record.getUnits(1));\n assignment.setWork(record.getDuration(2));\n assignment.setBaselineWork(record.getDuration(3));\n assignment.setActualWork(record.getDuration(4));\n assignment.setOvertimeWork(record.getDuration(5));\n assignment.setCost(record.getCurrency(6));\n assignment.setBaselineCost(record.getCurrency(7));\n assignment.setActualCost(record.getCurrency(8));\n assignment.setStart(record.getDateTime(9));\n assignment.setFinish(record.getDateTime(10));\n assignment.setDelay(record.getDuration(11));\n\n //\n // Calculate the remaining work\n //\n Duration work = assignment.getWork();\n Duration actualWork = assignment.getActualWork();\n if (work != null && actualWork != null)\n {\n if (work.getUnits() != actualWork.getUnits())\n {\n actualWork = actualWork.convertUnits(work.getUnits(), m_projectFile.getProjectProperties());\n }\n\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }"
] | [
"public Collection<FieldNode> removeAndGetCandidatesWithoutInitialisingMethod() {\n final List<FieldNode> result = new ArrayList<FieldNode>();\n for (final Map.Entry<FieldNode, Initialisers> entry : candidatesAndInitialisers.entrySet()) {\n final Initialisers setters = entry.getValue();\n final List<MethodNode> initialisingMethods = setters.getMethods();\n if (initialisingMethods.isEmpty()) {\n result.add(entry.getKey());\n }\n }\n for (final FieldNode unassociatedVariable : result) {\n candidatesAndInitialisers.remove(unassociatedVariable);\n }\n return result;\n }",
"public synchronized boolean tryDelegateSlop(Node node) {\n if(asyncCallbackShouldSendhint) {\n return false;\n } else {\n slopDestinations.put(node, true);\n return true;\n }\n }",
"private boolean checkTagAndParam(XDoc doc, String tagName, String paramName, String paramValue)\r\n {\r\n if (tagName == null) {\r\n return true;\r\n }\r\n if (!doc.hasTag(tagName)) {\r\n return false;\r\n }\r\n if (paramName == null) {\r\n return true;\r\n }\r\n if (!doc.getTag(tagName).getAttributeNames().contains(paramName)) {\r\n return false;\r\n }\r\n return (paramValue == null) || paramValue.equals(doc.getTagAttributeValue(tagName, paramName));\r\n }",
"private ServerSetup[] createServerSetup() {\n List<ServerSetup> setups = new ArrayList<>();\n if (smtpProtocol) {\n smtpServerSetup = createTestServerSetup(ServerSetup.SMTP);\n setups.add(smtpServerSetup);\n }\n if (smtpsProtocol) {\n smtpsServerSetup = createTestServerSetup(ServerSetup.SMTPS);\n setups.add(smtpsServerSetup);\n }\n if (pop3Protocol) {\n setups.add(createTestServerSetup(ServerSetup.POP3));\n }\n if (pop3sProtocol) {\n setups.add(createTestServerSetup(ServerSetup.POP3S));\n }\n if (imapProtocol) {\n setups.add(createTestServerSetup(ServerSetup.IMAP));\n }\n if (imapsProtocol) {\n setups.add(createTestServerSetup(ServerSetup.IMAPS));\n }\n return setups.toArray(new ServerSetup[setups.size()]);\n }",
"public LogSegment getLastView() {\n List<LogSegment> views = getView();\n return views.get(views.size() - 1);\n }",
"public static int compactDistance(String s1, String s2) {\n if (s1.length() == 0)\n return s2.length();\n if (s2.length() == 0)\n return s1.length();\n\n // the maximum edit distance there is any point in reporting.\n int maxdist = Math.min(s1.length(), s2.length()) / 2;\n \n // we allocate just one column instead of the entire matrix, in\n // order to save space. this also enables us to implement the\n // algorithm somewhat faster. the first cell is always the\n // virtual first row.\n int s1len = s1.length();\n int[] column = new int[s1len + 1];\n\n // first we need to fill in the initial column. we use a separate\n // loop for this, because in this case our basis for comparison is\n // not the previous column, but a virtual first column.\n int ix2 = 0;\n char ch2 = s2.charAt(ix2);\n column[0] = 1; // virtual first row\n for (int ix1 = 1; ix1 <= s1len; ix1++) {\n int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1;\n\n // Lowest of three: above (column[ix1 - 1]), aboveleft: ix1 - 1,\n // left: ix1. Latter cannot possibly be lowest, so is\n // ignored.\n column[ix1] = Math.min(column[ix1 - 1], ix1 - 1) + cost;\n }\n\n // okay, now we have an initialized first column, and we can\n // compute the rest of the matrix.\n int above = 0;\n for (ix2 = 1; ix2 < s2.length(); ix2++) {\n ch2 = s2.charAt(ix2);\n above = ix2 + 1; // virtual first row\n\n int smallest = s1len * 2; // used to implement cutoff\n for (int ix1 = 1; ix1 <= s1len; ix1++) {\n int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1;\n\n // above: above\n // aboveleft: column[ix1 - 1]\n // left: column[ix1]\n int value = Math.min(Math.min(above, column[ix1 - 1]), column[ix1]) +\n cost;\n column[ix1 - 1] = above; // write previous\n above = value; // keep current\n smallest = Math.min(smallest, value);\n }\n column[s1len] = above;\n\n // check if we can stop because we'll be going over the max distance\n if (smallest > maxdist)\n return smallest;\n }\n\n // ok, we're done\n return above;\n }",
"@Override\n public boolean visit(VariableDeclarationStatement node)\n {\n for (int i = 0; i < node.fragments().size(); ++i)\n {\n String nodeType = node.getType().toString();\n VariableDeclarationFragment frag = (VariableDeclarationFragment) node.fragments().get(i);\n state.getNames().add(frag.getName().getIdentifier());\n state.getNameInstance().put(frag.getName().toString(), nodeType.toString());\n }\n\n processType(node.getType(), TypeReferenceLocation.VARIABLE_DECLARATION,\n compilationUnit.getLineNumber(node.getStartPosition()),\n compilationUnit.getColumnNumber(node.getStartPosition()), node.getLength(), node.toString());\n return super.visit(node);\n }",
"public PeriodicEvent runEvery(Runnable task, float delay, float period,\n int repetitions) {\n if (repetitions < 1) {\n return null;\n } else if (repetitions == 1) {\n // Better to burn a handful of CPU cycles than to churn memory by\n // creating a new callback\n return runAfter(task, delay);\n } else {\n return runEvery(task, delay, period, new RunFor(repetitions));\n }\n }",
"public synchronized void stop() {\n if (isRunning()) {\n try {\n setSendingStatus(false);\n } catch (Throwable t) {\n logger.error(\"Problem stopping sending status during shutdown\", t);\n }\n DeviceFinder.getInstance().removeIgnoredAddress(socket.get().getLocalAddress());\n socket.get().close();\n socket.set(null);\n broadcastAddress.set(null);\n updates.clear();\n setTempoMaster(null);\n setDeviceNumber((byte)0); // Set up for self-assignment if restarted.\n deliverLifecycleAnnouncement(logger, false);\n }\n }"
] |
Get the possible beans for the given element
@param resolvable The resolving criteria
@return An unmodifiable set of matching beans | [
"public F resolve(R resolvable, boolean cache) {\n R wrappedResolvable = wrap(resolvable);\n if (cache) {\n return resolved.getValue(wrappedResolvable);\n } else {\n return resolverFunction.apply(wrappedResolvable);\n }\n }"
] | [
"public void setDates(SortedSet<Date> dates, boolean checked) {\n\n m_checkBoxes.clear();\n for (Date date : dates) {\n CmsCheckBox cb = generateCheckBox(date, checked);\n m_checkBoxes.add(cb);\n }\n reInitLayoutElements();\n setDatesInternal(dates);\n }",
"public ItemRequest<Task> dependents(String task) {\n \n String path = String.format(\"/tasks/%s/dependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }",
"private int tryAcquireExclusiveTransaction(@NotNull final Thread thread, final int timeout) {\n long nanos = TimeUnit.MILLISECONDS.toNanos(timeout);\n try (CriticalSection ignored = criticalSection.enter()) {\n if (getThreadPermits(thread) > 0) {\n throw new ExodusException(\"Exclusive transaction can't be nested\");\n }\n final Condition condition = criticalSection.newCondition();\n final long currentOrder = acquireOrder++;\n regularQueue.put(currentOrder, condition);\n while (acquiredPermits > 0 || regularQueue.firstKey() != currentOrder) {\n try {\n nanos = condition.awaitNanos(nanos);\n if (nanos < 0) {\n break;\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n break;\n }\n }\n if (acquiredPermits == 0 && regularQueue.firstKey() == currentOrder) {\n regularQueue.pollFirstEntry();\n acquiredPermits = availablePermits;\n threadPermits.put(thread, availablePermits);\n return availablePermits;\n }\n regularQueue.remove(currentOrder);\n notifyNextWaiters();\n }\n return 0;\n }",
"public synchronized void stop() throws DatastoreEmulatorException {\n // We intentionally don't check the internal state. If people want to try and stop the server\n // multiple times that's fine.\n stopEmulatorInternal();\n if (state != State.STOPPED) {\n state = State.STOPPED;\n if (projectDirectory != null) {\n try {\n Process process =\n new ProcessBuilder(\"rm\", \"-r\", projectDirectory.getAbsolutePath()).start();\n if (process.waitFor() != 0) {\n throw new IOException(\n \"Temporary project directory deletion exited with \" + process.exitValue());\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n }\n }\n }\n }",
"public static base_response save(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup saveresource = new cachecontentgroup();\n\t\tsaveresource.name = resource.name;\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}",
"public Date getFinishDate()\n {\n Date result = (Date) getCachedValue(ProjectField.FINISH_DATE);\n if (result == null)\n {\n result = getParentFile().getFinishDate();\n }\n return (result);\n }",
"public static CombinedInterceptorAndDecoratorStackMethodHandler peekIfNotEmpty() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n return null;\n }\n return stack.peek();\n }",
"private ResourceReport getResourceReport(TwillController controller, int maxWaitMs) {\n ResourceReport report = controller.getResourceReport();\n int elapsed = 0;\n while (report == null) {\n report = controller.getResourceReport();\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n throw new IllegalStateException(e);\n }\n elapsed += 500;\n if ((maxWaitMs != -1) && (elapsed > maxWaitMs)) {\n String msg = String.format(\"Exceeded max wait time to retrieve ResourceReport from Twill.\"\n + \" Elapsed time = %s ms\", elapsed);\n log.error(msg);\n throw new IllegalStateException(msg);\n }\n if ((elapsed % 10000) == 0) {\n log.info(\"Waiting for ResourceReport from Twill. Elapsed time = {} ms\", elapsed);\n }\n }\n return report;\n }",
"public static String getImageIdFromTag(String imageTag, String host) throws IOException {\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n return dockerClient.inspectImageCmd(imageTag).exec().getId();\n } finally {\n closeQuietly(dockerClient);\n }\n }"
] |
Unzip a file or a folder
@param zipFile
@param unzippedFolder optional, if null the file/folder will be extracted in the same folder as zipFile
@return | [
"public static boolean unzipFileOrFolder(File zipFile, String unzippedFolder){\n\t\tInputStream is;\n\t\tArchiveInputStream in = null;\n\t\tOutputStream out = null;\n\t\t\n\t\tif(!zipFile.isFile()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(unzippedFolder == null){\n\t\t\tunzippedFolder = FilenameUtils.removeExtension(zipFile.getAbsolutePath());\n\t\t}\n\t\ttry {\n\t\t\tis = new FileInputStream(zipFile);\n\t\t\tnew File(unzippedFolder).mkdir();\n\t\t\t\n\t\t\tin = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is);\n\t\t\t\n\t\t\tZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry();\n\t\t\twhile(entry != null){\n\t\t\t\tif(entry.isDirectory()){\n\t\t\t\t\tnew File(unzippedFolder,entry.getName()).mkdir();\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tout = new FileOutputStream(new File(unzippedFolder, entry.getName()));\n\t\t\t\t\tIOUtils.copy(in, out);\n\t\t\t\t\tout.close();\n\t\t\t\t\tout = null;\n\t\t\t\t}\n\t\t\t\tentry = (ZipArchiveEntry)in.getNextEntry();\n\t\t\t}\t\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t} catch (ArchiveException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\tfinally{\n\t\t\tif(out != null){\n\t\t\t\ttry {\n\t\t\t\t\tout.close();\n\t\t\t\t} catch (IOException e) {}\n\t\t\t}\n\t\t\tif(in != null){\n\t\t\t\ttry {\n\t\t\t\t\tin.close();\n\t\t\t\t} catch (IOException e) {}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}"
] | [
"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 Set<String> rangeByRankReverse(final long start, final long end) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n return jedis.zrevrange(getKey(), start, end);\n }\n });\n }",
"public String toIPTC(SubjectReferenceSystem srs) {\r\n\t\tStringBuffer b = new StringBuffer();\r\n\t\tb.append(\"IPTC:\");\r\n\t\tb.append(getNumber());\r\n\t\tb.append(\":\");\r\n\t\tif (getNumber().endsWith(\"000000\")) {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t\tb.append(\"::\");\r\n\t\t} else if (getNumber().endsWith(\"000\")) {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + \"000000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t\tb.append(\":\");\r\n\t\t} else {\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + \"000000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 5) + \"000\"))));\r\n\t\t\tb.append(\":\");\r\n\t\t\tb.append(toIPTCHelper(srs.getName(this)));\r\n\t\t}\r\n\t\treturn b.toString();\r\n\t}",
"public String getCanonicalTypeName(Object object) {\n ensureNotNull(\"object\", object);\n\n for (TypeDetector typeDetector : typeDetectors) {\n if (typeDetector.canHandle(object)) {\n return typeDetector.detectType(object);\n }\n }\n\n throw LOG.unableToDetectCanonicalType(object);\n }",
"protected void parseIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) ) {\n start = t;\n state = 1;\n }\n } else if( state == 1 ) {\n // var ?\n if( isVariableInteger(t)) { // see if its explicit number sequence\n state = 2;\n } else { // just scalar integer, skip\n state = 0;\n }\n } else if ( state == 2 ) {\n // var var ....\n if( !isVariableInteger(t) ) {\n // create explicit list sequence\n IntegerSequence sequence = new IntegerSequence.Explicit(start,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }",
"public static File createDir(String dir) {\n // create outdir\n File directory = null;\n if(dir != null) {\n directory = new File(dir);\n if(!(directory.exists() || directory.mkdir())) {\n Utils.croak(\"Can't find or create directory \" + dir);\n }\n }\n return directory;\n }",
"public void setPerms(String photoId, Permissions permissions) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", permissions.isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", permissions.isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", permissions.isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"perm_comment\", Integer.toString(permissions.getComment()));\r\n parameters.put(\"perm_addmeta\", Integer.toString(permissions.getAddmeta()));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public String getPrototypeName() {\n\t\tString name = getClass().getName();\n\t\tif (name.startsWith(ORG_GEOMAJAS)) {\n\t\t\tname = name.substring(ORG_GEOMAJAS.length());\n\t\t}\n\t\tname = name.replace(\".dto.\", \".impl.\");\n\t\treturn name.substring(0, name.length() - 4) + \"Impl\";\n\t}",
"public static Trajectory combineTrajectory(Trajectory a, Trajectory b){\n\t\tif(a.getDimension()!=b.getDimension()){\n\t\t\tthrow new IllegalArgumentException(\"Combination not possible: The trajectorys does not have the same dimension\");\n\t\t}\n\t\tif(a.size()!=b.size()){\n\t\t\tthrow new IllegalArgumentException(\"Combination not possible: The trajectorys does not \"\n\t\t\t\t\t+ \"have the same number of steps a=\"+a.size() + \" b=\"+b.size());\n\t\t}\n\t\tTrajectory c = new Trajectory(a.getDimension());\n\t\t\n\t\tfor(int i = 0 ; i < a.size(); i++){\n\t\t\tPoint3d pos = new Point3d(a.get(i).x+b.get(i).x, \n\t\t\t\t\ta.get(i).y+b.get(i).y, \n\t\t\t\t\ta.get(i).z+b.get(i).z);\n\t\t\tc.add(pos);\n\t\t}\n\t\t\n\t\treturn c;\n\t}"
] |
Check if the the nodeId is present in the cluster managed by the metadata store
or throw an exception.
@param nodeId The nodeId to check existence of | [
"public static void assertValidNode(MetadataStore metadataStore, Integer nodeId) {\n if(!metadataStore.getCluster().hasNodeWithId(nodeId)) {\n throw new InvalidMetadataException(\"NodeId \" + nodeId + \" is not or no longer in this cluster\");\n }\n }"
] | [
"private void readBitFields(MppBitFlag[] flags, FieldContainer container, byte[] data)\n {\n for (MppBitFlag flag : flags)\n {\n flag.setValue(container, data);\n }\n }",
"public void retrieveCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, false);\r\n }",
"public static String strip(String text)\n {\n String result = text;\n if (text != null && !text.isEmpty())\n {\n try\n {\n boolean formalRTF = isFormalRTF(text);\n StringTextConverter stc = new StringTextConverter();\n stc.convert(new RtfStringSource(text));\n result = stripExtraLineEnd(stc.getText(), formalRTF);\n }\n catch (IOException ex)\n {\n result = \"\";\n }\n }\n\n return result;\n }",
"public Changes parameter(String name, String value) {\n this.databaseHelper.query(name, value);\n return this;\n }",
"private Integer mapTaskID(Integer id)\n {\n Integer mappedID = m_clashMap.get(id);\n if (mappedID == null)\n {\n mappedID = id;\n }\n return (mappedID);\n }",
"public static ipset get(nitro_service service, String name) throws Exception{\n\t\tipset obj = new ipset();\n\t\tobj.set_name(name);\n\t\tipset response = (ipset) obj.get_resource(service);\n\t\treturn response;\n\t}",
"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 void addBeanToBeanMapping(BeanToBeanMapping beanToBeanMapping) {\r\n\t\tbeanToBeanMappings.put(ClassPair.get(beanToBeanMapping\r\n\t\t\t\t.getSourceClass(), beanToBeanMapping.getDestinationClass()),\r\n\t\t\t\tbeanToBeanMapping);\r\n\t}",
"private static int getTrimmedWidth(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int trimmedWidth = 0;\n\n for (int i = 0; i < height; i++) {\n for (int j = width - 1; j >= 0; j--) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j > trimmedWidth) {\n trimmedWidth = j;\n break;\n }\n }\n }\n\n return trimmedWidth;\n }"
] |
The conditional expectation is calculated using a Monte-Carlo regression technique.
@param exerciseTime The exercise time
@param model The valuation model
@return The condition expectation estimator
@throws CalculationException Thrown if underlying model failed to calculate stochastic process. | [
"public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\r\n\t\tRandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model);\r\n\t\treturn conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions);\r\n\t}"
] | [
"public void makePickable(GVRSceneObject sceneObject) {\n try {\n GVRMeshCollider collider = new GVRMeshCollider(sceneObject.getGVRContext(), false);\n sceneObject.attachComponent(collider);\n } catch (Exception e) {\n // Possible that some objects (X3D panel nodes) are without mesh\n Log.e(Log.SUBSYSTEM.INPUT, TAG, \"makePickable(): possible that some objects (X3D panel nodes) are without mesh!\");\n }\n }",
"public static void main(String[] args) {\n if(args.length != 2) {\n System.out.println(\"Usage: SchemaEvolutionValidator pathToOldSchema pathToNewSchema\");\n return;\n }\n\n Schema oldSchema;\n Schema newSchema;\n\n try {\n oldSchema = Schema.parse(new File(args[0]));\n } catch(Exception ex) {\n oldSchema = null;\n System.out.println(\"Could not open or parse the old schema (\" + args[0] + \") due to \"\n + ex);\n }\n\n try {\n newSchema = Schema.parse(new File(args[1]));\n } catch(Exception ex) {\n newSchema = null;\n System.out.println(\"Could not open or parse the new schema (\" + args[1] + \") due to \"\n + ex);\n }\n\n if(oldSchema == null || newSchema == null) {\n return;\n }\n\n System.out.println(\"Comparing: \");\n System.out.println(\"\\t\" + args[0]);\n System.out.println(\"\\t\" + args[1]);\n\n List<Message> messages = SchemaEvolutionValidator.checkBackwardCompatibility(oldSchema,\n newSchema,\n oldSchema.getName());\n Level maxLevel = Level.ALL;\n for(Message message: messages) {\n System.out.println(message.getLevel() + \": \" + message.getMessage());\n if(message.getLevel().isGreaterOrEqual(maxLevel)) {\n maxLevel = message.getLevel();\n }\n }\n\n if(maxLevel.isGreaterOrEqual(Level.ERROR)) {\n System.out.println(Level.ERROR\n + \": The schema is not backward compatible. New clients will not be able to read existing data.\");\n } else if(maxLevel.isGreaterOrEqual(Level.WARN)) {\n System.out.println(Level.WARN\n + \": The schema is partially backward compatible, but old clients will not be able to read data serialized in the new format.\");\n } else {\n System.out.println(Level.INFO\n + \": The schema is backward compatible. Old and new clients will be able to read records serialized by one another.\");\n }\n }",
"private void configureConfigurationSelector() {\n\n if (m_checkinBean.getConfigurations().size() < 2) {\n // Do not show the configuration selection at all.\n removeComponent(m_configurationSelectionPanel);\n } else {\n for (CmsGitConfiguration configuration : m_checkinBean.getConfigurations()) {\n m_configurationSelector.addItem(configuration);\n m_configurationSelector.setItemCaption(configuration, configuration.getName());\n }\n m_configurationSelector.setNullSelectionAllowed(false);\n m_configurationSelector.setNewItemsAllowed(false);\n m_configurationSelector.setWidth(\"350px\");\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n\n // There is really a choice between configurations\n m_configurationSelector.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"synthetic-access\")\n public void valueChange(ValueChangeEvent event) {\n\n updateForNewConfiguration((CmsGitConfiguration)event.getProperty().getValue());\n restoreFieldsFromUserInfo();\n\n }\n });\n }\n }",
"public ArrayList getFields(String fieldNames) throws NoSuchFieldException\r\n {\r\n ArrayList result = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n String name;\r\n\r\n for (CommaListIterator it = new CommaListIterator(fieldNames); it.hasNext();)\r\n {\r\n name = it.getNext();\r\n fieldDef = getField(name);\r\n if (fieldDef == null)\r\n {\r\n throw new NoSuchFieldException(name);\r\n }\r\n result.add(fieldDef);\r\n }\r\n return result;\r\n }",
"static VaultConfig readVaultElement_3_0(XMLExtendedStreamReader reader, Namespace expectedNs) throws XMLStreamException {\n final VaultConfig config = new VaultConfig();\n\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n String name = reader.getAttributeLocalName(i);\n if (name.equals(CODE)){\n config.code = value;\n } else if (name.equals(MODULE)){\n config.module = value;\n } else {\n unexpectedVaultAttribute(reader.getAttributeLocalName(i), reader);\n }\n }\n if (config.code == null && config.module != null){\n throw new XMLStreamException(\"Attribute 'module' was specified without an attribute\"\n + \" 'code' for element '\" + VAULT + \"' at \" + reader.getLocation());\n }\n readVaultOptions(reader, config);\n return config;\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 void processStencilSet() throws IOException {\n StringBuilder stencilSetFileContents = new StringBuilder();\n\n Scanner scanner = null;\n try {\n scanner = new Scanner(new File(ssInFile),\n \"UTF-8\");\n String currentLine = \"\";\n String prevLine = \"\";\n while (scanner.hasNextLine()) {\n prevLine = currentLine;\n currentLine = scanner.nextLine();\n\n String trimmedPrevLine = prevLine.trim();\n String trimmedCurrentLine = currentLine.trim();\n\n // First time processing - replace view=\"<file>.svg\" with _view_file=\"<file>.svg\" + view=\"<svg_xml>\"\n if (trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN) && trimmedCurrentLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)) {\n String newLines = processViewPropertySvgReference(currentLine);\n stencilSetFileContents.append(newLines);\n }\n // Second time processing - replace view=\"<svg_xml>\" with refreshed contents of file referenced by previous line\n else if (trimmedPrevLine.matches(VIEW_FILE_PROPERTY_NAME_PATTERN) && trimmedPrevLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)\n && trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN)) {\n String newLines = processViewFilePropertySvgReference(prevLine,\n currentLine);\n stencilSetFileContents.append(newLines);\n } else {\n stencilSetFileContents.append(currentLine + LINE_SEPARATOR);\n }\n }\n } finally {\n if (scanner != null) {\n scanner.close();\n }\n }\n\n Writer out = null;\n try {\n out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ssOutFile),\n \"UTF-8\"));\n out.write(stencilSetFileContents.toString());\n } catch (FileNotFoundException e) {\n\n } catch (UnsupportedEncodingException e) {\n } catch (IOException e) {\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n }\n }\n }\n\n System.out.println(\"SVG files referenced more than once:\");\n for (Map.Entry<String, Integer> stringIntegerEntry : mapSVGCounts.entrySet()) {\n if (stringIntegerEntry.getValue() > 1) {\n System.out.println(\"\\t\" + stringIntegerEntry.getKey() + \"\\t = \" + stringIntegerEntry.getValue());\n }\n }\n }",
"static String from(Class<?> entryClass) {\n List<String> tokens = tokenOf(entryClass);\n return fromTokens(tokens);\n }",
"protected static BoxCollaboration.Info create(BoxAPIConnection api, JsonObject accessibleBy, JsonObject item,\n BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) {\n\n\n String queryString = \"\";\n if (notify != null) {\n queryString = new QueryStringBuilder().appendParam(\"notify\", notify.toString()).toString();\n }\n URL url;\n if (queryString.length() > 0) {\n url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString);\n } else {\n url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL());\n }\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", item);\n requestJSON.add(\"accessible_by\", accessibleBy);\n requestJSON.add(\"role\", role.toJSONString());\n if (canViewPath != null) {\n requestJSON.add(\"can_view_path\", canViewPath.booleanValue());\n }\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxCollaboration newCollaboration = new BoxCollaboration(api, responseJSON.get(\"id\").asString());\n return newCollaboration.new Info(responseJSON);\n }"
] |
Marks the start of a query identified by the provided correlationId
@param query - Query data
@param correlationId - Identifier
@return Start event to pass to the Events systems EventBus | [
"public static <T> AddQuery<T> start(T query, long correlationId) {\n return start(query, correlationId, \"default\", null);\n }"
] | [
"public static int getNumberOfDependentLayers(String imageContent) throws IOException {\n JsonNode history = Utils.mapper().readTree(imageContent).get(\"history\");\n if (history == null) {\n throw new IllegalStateException(\"Could not find 'history' tag\");\n }\n\n int layersNum = history.size();\n boolean newImageLayers = true;\n for (int i = history.size() - 1; i >= 0; i--) {\n\n if (newImageLayers) {\n layersNum--;\n }\n\n JsonNode layer = history.get(i);\n JsonNode emptyLayer = layer.get(\"empty_layer\");\n if (!newImageLayers && emptyLayer != null) {\n layersNum--;\n }\n\n if (layer.get(\"created_by\") == null) {\n continue;\n }\n String createdBy = layer.get(\"created_by\").textValue();\n if (createdBy.contains(\"ENTRYPOINT\") || createdBy.contains(\"MAINTAINER\")) {\n newImageLayers = false;\n }\n }\n return layersNum;\n }",
"public AT_Row setPadding(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().setPadding(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public BoxFile.Info restoreFile(String fileID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFile restoredFile = new BoxFile(this.api, responseJSON.get(\"id\").asString());\n return restoredFile.new Info(responseJSON);\n }",
"protected void parseCombineIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int numFound = 0;\n\n TokenList.Token start = null;\n TokenList.Token end = null;\n\n while( t != null ) {\n if( t.getType() == Type.VARIABLE && (isVariableInteger(t) ||\n t.getVariable().getType() == VariableType.INTEGER_SEQUENCE )) {\n if( numFound == 0 ) {\n numFound = 1;\n start = end = t;\n } else {\n numFound++;\n end = t;\n }\n } else if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n numFound = 0;\n } else {\n numFound = 0;\n }\n t = t.next;\n }\n\n if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n }\n }",
"public void setTimewarpInt(String timewarp) {\n\n try {\n m_userSettings.setTimeWarp(Long.valueOf(timewarp).longValue());\n } catch (Exception e) {\n m_userSettings.setTimeWarp(-1);\n }\n }",
"private final void replyErrors(final String errorMessage,\n final String stackTrace, final String statusCode,\n final int statusCodeInt) {\n reply(true, errorMessage, stackTrace, statusCode, statusCodeInt,\n PcConstants.NA, null);\n\n }",
"private void checkProcedures(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ProcedureDef procDef;\r\n String type;\r\n String name;\r\n String fieldName;\r\n String argName;\r\n \r\n for (Iterator it = classDef.getProcedures(); it.hasNext();)\r\n {\r\n procDef = (ProcedureDef)it.next();\r\n type = procDef.getName();\r\n name = procDef.getProperty(PropertyHelper.OJB_PROPERTY_NAME);\r\n if ((name == null) || (name.length() == 0))\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure in class \"+classDef.getName()+\" doesn't have a name\");\r\n }\r\n fieldName = procDef.getProperty(PropertyHelper.OJB_PROPERTY_RETURN_FIELD_REF);\r\n if ((fieldName != null) && (fieldName.length() > 0))\r\n {\r\n if (classDef.getField(fieldName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure \"+name+\" in class \"+classDef.getName()+\" references an unknown or non-persistent return field \"+fieldName);\r\n }\r\n }\r\n for (CommaListIterator argIt = new CommaListIterator(procDef.getProperty(PropertyHelper.OJB_PROPERTY_ARGUMENTS)); argIt.hasNext();)\r\n {\r\n argName = argIt.getNext();\r\n if (classDef.getProcedureArgument(argName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure \"+name+\" in class \"+classDef.getName()+\" references an unknown argument \"+argName);\r\n }\r\n }\r\n }\r\n\r\n ProcedureArgumentDef argDef;\r\n\r\n for (Iterator it = classDef.getProcedureArguments(); it.hasNext();)\r\n {\r\n argDef = (ProcedureArgumentDef)it.next();\r\n type = argDef.getProperty(PropertyHelper.OJB_PROPERTY_TYPE);\r\n if (\"runtime\".equals(type))\r\n {\r\n fieldName = argDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELD_REF);\r\n if ((fieldName != null) && (fieldName.length() > 0))\r\n {\r\n if (classDef.getField(fieldName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-argument \"+argDef.getName()+\" in class \"+classDef.getName()+\" references an unknown or non-persistent return field \"+fieldName);\r\n }\r\n }\r\n }\r\n }\r\n }",
"public RgbaColor adjustHue(float degrees) {\n float[] HSL = convertToHsl();\n HSL[0] = hueCheck(HSL[0] + degrees); // ensure [0-360)\n return RgbaColor.fromHsl(HSL);\n }",
"public\tRandomVariableInterface[]\tgetFactorLoading(double time, double component, RandomVariableInterface[] realizationAtTimeIndex) {\n\t\tint componentIndex = liborPeriodDiscretization.getTimeIndex(component);\n\t\tif(componentIndex < 0) {\n\t\t\tcomponentIndex = -componentIndex - 2;\n\t\t}\n\t\treturn getFactorLoading(time, componentIndex, realizationAtTimeIndex);\n\t}"
] |
Extracts location result from intent object
@param intent valid intent object
@return location result.
@since 1.1.0 | [
"@Nullable\n public static LocationEngineResult extractResult(Intent intent) {\n LocationEngineResult result = null;\n if (isOnClasspath(GOOGLE_PLAY_LOCATION_RESULT)) {\n result = extractGooglePlayResult(intent);\n }\n return result == null ? extractAndroidResult(intent) : result;\n }"
] | [
"public static sslcipher get(nitro_service service, String ciphergroupname) throws Exception{\n\t\tsslcipher obj = new sslcipher();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\tsslcipher response = (sslcipher) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void init(boolean upgrade)\n {\n initAdapter();\n initQueries();\n if (upgrade)\n {\n dbUpgrade();\n }\n\n // First contact with the DB is version checking (if no connection opened by pool).\n // If DB is in wrong version or not available, just wait for it to be ready.\n boolean versionValid = false;\n while (!versionValid)\n {\n try\n {\n checkSchemaVersion();\n versionValid = true;\n }\n catch (Exception e)\n {\n String msg = e.getLocalizedMessage();\n if (e.getCause() != null)\n {\n msg += \" - \" + e.getCause().getLocalizedMessage();\n }\n jqmlogger.error(\"Database not ready: \" + msg + \". Waiting for database...\");\n try\n {\n Thread.sleep(10000);\n }\n catch (Exception e2)\n {\n }\n }\n }\n }",
"public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tAssert.notNull(methodName, \"Method name must not be null\");\n\t\ttry {\n\t\t\tMethod method = clazz.getMethod(methodName, args);\n\t\t\treturn Modifier.isStatic(method.getModifiers()) ? method : null;\n\t\t}\n\t\tcatch (NoSuchMethodException ex) {\n\t\t\treturn null;\n\t\t}\n\t}",
"public static base_responses update(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice updateresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbservice();\n\t\t\t\tupdateresources[i].servicename = resources[i].servicename;\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].publicip = resources[i].publicip;\n\t\t\t\tupdateresources[i].publicport = resources[i].publicport;\n\t\t\t\tupdateresources[i].cip = resources[i].cip;\n\t\t\t\tupdateresources[i].cipheader = resources[i].cipheader;\n\t\t\t\tupdateresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\tupdateresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\tupdateresources[i].maxclient = resources[i].maxclient;\n\t\t\t\tupdateresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\tupdateresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\tupdateresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\tupdateresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\tupdateresources[i].viewname = resources[i].viewname;\n\t\t\t\tupdateresources[i].viewip = resources[i].viewip;\n\t\t\t\tupdateresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].monitor_name_svc = resources[i].monitor_name_svc;\n\t\t\t\tupdateresources[i].hashid = resources[i].hashid;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public UpdateDescription merge(@Nullable final UpdateDescription otherDescription) {\n if (otherDescription != null) {\n for (final Map.Entry<String, BsonValue> entry : this.updatedFields.entrySet()) {\n if (otherDescription.removedFields.contains(entry.getKey())) {\n this.updatedFields.remove(entry.getKey());\n }\n }\n for (final String removedField : this.removedFields) {\n if (otherDescription.updatedFields.containsKey(removedField)) {\n this.removedFields.remove(removedField);\n }\n }\n\n this.removedFields.addAll(otherDescription.removedFields);\n this.updatedFields.putAll(otherDescription.updatedFields);\n }\n\n return this;\n }",
"public Module getModule(final String name, final String version) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));\n final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module details\", name, version);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(Module.class);\n }",
"public List<PPVItemsType.PPVItem> getPPVItem()\n {\n if (ppvItem == null)\n {\n ppvItem = new ArrayList<PPVItemsType.PPVItem>();\n }\n return this.ppvItem;\n }",
"public final void warn(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.WARN, pObject, null);\r\n\t}",
"public static boolean isInteger(CharSequence self) {\n try {\n Integer.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }"
] |
Check if a module can be promoted in the Grapes server
@param name
@param version
@return a boolean which is true only if the module can be promoted
@throws GrapesCommunicationException | [
"public PromotionEvaluationReport getModulePromotionReport(final String name, final String version) throws GrapesCommunicationException {\n return getModulePromotionReportRaw(name, version, false, PromotionEvaluationReport.class);\n }"
] | [
"public static int getLineNumber(Member member) {\n\n if (!(member instanceof Method || member instanceof Constructor)) {\n // We are not able to get this info for fields\n return 0;\n }\n\n // BCEL is an optional dependency, if we cannot load it, simply return 0\n if (!Reflections.isClassLoadable(BCEL_CLASS, WeldClassLoaderResourceLoader.INSTANCE)) {\n return 0;\n }\n\n String classFile = member.getDeclaringClass().getName().replace('.', '/');\n ClassLoaderResourceLoader classFileResourceLoader = new ClassLoaderResourceLoader(member.getDeclaringClass().getClassLoader());\n InputStream in = null;\n\n try {\n URL classFileUrl = classFileResourceLoader.getResource(classFile + \".class\");\n\n if (classFileUrl == null) {\n // The class file is not available\n return 0;\n }\n in = classFileUrl.openStream();\n\n ClassParser cp = new ClassParser(in, classFile);\n JavaClass javaClass = cp.parse();\n\n // First get all declared methods and constructors\n // Note that in bytecode constructor is translated into a method\n org.apache.bcel.classfile.Method[] methods = javaClass.getMethods();\n org.apache.bcel.classfile.Method match = null;\n\n String signature;\n String name;\n if (member instanceof Method) {\n signature = DescriptorUtils.methodDescriptor((Method) member);\n name = member.getName();\n } else if (member instanceof Constructor) {\n signature = DescriptorUtils.makeDescriptor((Constructor<?>) member);\n name = INIT_METHOD_NAME;\n } else {\n return 0;\n }\n\n for (org.apache.bcel.classfile.Method method : methods) {\n // Matching method must have the same name, modifiers and signature\n if (method.getName().equals(name)\n && member.getModifiers() == method.getModifiers()\n && method.getSignature().equals(signature)) {\n match = method;\n }\n }\n if (match != null) {\n // If a method is found, try to obtain the optional LineNumberTable attribute\n LineNumberTable lineNumberTable = match.getLineNumberTable();\n if (lineNumberTable != null) {\n int line = lineNumberTable.getSourceLine(0);\n return line == -1 ? 0 : line;\n }\n }\n // No suitable method found\n return 0;\n\n } catch (Throwable t) {\n return 0;\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (Exception e) {\n return 0;\n }\n }\n }\n }",
"public String expand(String macro) {\n if (!isMacro(macro)) {\n return macro;\n }\n String definition = macros.get(Config.canonical(macro));\n if (null == definition) {\n warn(\"possible missing definition of macro[%s]\", macro);\n }\n return null == definition ? macro : definition;\n }",
"public static List<String> getNodeListFromStringLineSeperateOrSpaceSeperate(\n String listStr, boolean removeDuplicate) {\n\n List<String> nodes = new ArrayList<String>();\n\n for (String token : listStr.split(\"[\\\\r?\\\\n| +]+\")) {\n\n // 20131025: fix if fqdn has space in the end.\n if (token != null && !token.trim().isEmpty()) {\n nodes.add(token.trim());\n\n }\n }\n\n if (removeDuplicate) {\n removeDuplicateNodeList(nodes);\n }\n logger.info(\"Target hosts size : \" + nodes.size());\n\n return nodes;\n\n }",
"@Override public View getView(int position, View convertView, ViewGroup parent) {\n T content = getItem(position);\n rendererBuilder.withContent(content);\n rendererBuilder.withConvertView(convertView);\n rendererBuilder.withParent(parent);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext()));\n Renderer<T> renderer = rendererBuilder.build();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null Renderer\");\n }\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n return renderer.getRootView();\n }",
"private SiteRecord getSiteRecord(String siteKey) {\n\t\tSiteRecord siteRecord = this.siteRecords.get(siteKey);\n\t\tif (siteRecord == null) {\n\t\t\tsiteRecord = new SiteRecord(siteKey);\n\t\t\tthis.siteRecords.put(siteKey, siteRecord);\n\t\t}\n\t\treturn siteRecord;\n\t}",
"private void renderAsLI(Writer writer, ProjectModel project, Iterator<Link> links, boolean wrap) throws IOException\n {\n if (!links.hasNext())\n return;\n\n if (wrap)\n writer.append(\"<ul>\");\n while (links.hasNext())\n {\n Link link = links.next();\n writer.append(\"<li>\");\n renderLink(writer, project, link);\n writer.append(\"</li>\");\n }\n if (wrap)\n writer.append(\"</ul>\");\n }",
"public void explore() {\n if (isLeaf) return;\n if (isGeneric) return;\n removeAllChildren();\n\n try {\n String addressPath = addressPath();\n ModelNode resourceDesc = executor.doCommand(addressPath + \":read-resource-description\");\n resourceDesc = resourceDesc.get(\"result\");\n ModelNode response = executor.doCommand(addressPath + \":read-resource(include-runtime=true,include-defaults=true)\");\n ModelNode result = response.get(\"result\");\n if (!result.isDefined()) return;\n\n List<String> childrenTypes = getChildrenTypes(addressPath);\n for (ModelNode node : result.asList()) {\n Property prop = node.asProperty();\n if (childrenTypes.contains(prop.getName())) { // resource node\n if (hasGenericOperations(addressPath, prop.getName())) {\n add(new ManagementModelNode(cliGuiCtx, new UserObject(node, prop.getName())));\n }\n if (prop.getValue().isDefined()) {\n for (ModelNode innerNode : prop.getValue().asList()) {\n UserObject usrObj = new UserObject(innerNode, prop.getName(), innerNode.asProperty().getName());\n add(new ManagementModelNode(cliGuiCtx, usrObj));\n }\n }\n } else { // attribute node\n UserObject usrObj = new UserObject(node, resourceDesc, prop.getName(), prop.getValue().asString());\n add(new ManagementModelNode(cliGuiCtx, usrObj));\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"private static Data loadLeapSeconds() {\n Data bestData = null;\n URL url = null;\n try {\n // this is the new location of the file, working on Java 8, Java 9 class path and Java 9 module path\n Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(\"META-INF/\" + LEAP_SECONDS_TXT);\n while (en.hasMoreElements()) {\n url = en.nextElement();\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n // this location does not work on Java 9 module path because the resource is encapsulated\n en = Thread.currentThread().getContextClassLoader().getResources(LEAP_SECONDS_TXT);\n while (en.hasMoreElements()) {\n url = en.nextElement();\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n // this location is the canonical one, and class-based loading works on Java 9 module path\n url = SystemUtcRules.class.getResource(\"/\" + LEAP_SECONDS_TXT);\n if (url != null) {\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n } catch (Exception ex) {\n throw new RuntimeException(\"Unable to load time-zone rule data: \" + url, ex);\n }\n if (bestData == null) {\n // no data on classpath, but we allow manual registration of leap seconds\n // setup basic known data - MJD 1972-01-01 is 41317L, where offset was 10\n bestData = new Data(new long[] {41317L}, new int[] {10}, new long[] {tai(41317L, 10)});\n }\n return bestData;\n }",
"public String stripUnnecessaryComments(String javaContent, AntlrOptions options) {\n\t\tif (!options.isOptimizeCodeQuality()) {\n\t\t\treturn javaContent;\n\t\t}\n\t\tjavaContent = stripMachineDependentPaths(javaContent);\n\t\tif (options.isStripAllComments()) {\n\t\t\tjavaContent = stripAllComments(javaContent);\n\t\t}\n\t\treturn javaContent;\n\t}"
] |
Used for unit tests only.
FIXME: Refactor test code with dependency injection or scope restrictions so this function is not public.
@deprecated Do not use for production code, use {@link #fetch(String, String, voldemort.server.protocol.admin.AsyncOperationStatus, String, long, voldemort.store.metadata.MetadataStore, Long diskQuotaSizeInKB)} instead. | [
"@Deprecated\n @Override\n public File fetch(String source, String dest, long diskQuotaSizeInKB) throws Exception {\n return fetchFromSource(source, dest, null, null, -1, diskQuotaSizeInKB, null);\n }"
] | [
"public void load(InputStream in) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(in);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public static ExtensibleConfigurationPersister createHostXmlConfigurationPersister(final ConfigurationFile file, final HostControllerEnvironment environment,\n final ExecutorService executorService, final ExtensionRegistry hostExtensionRegistry,\n final LocalHostControllerInfo localHostControllerInfo) {\n String defaultHostname = localHostControllerInfo.getLocalHostName();\n if (environment.getRunningModeControl().isReloaded()) {\n if (environment.getRunningModeControl().getReloadHostName() != null) {\n defaultHostname = environment.getRunningModeControl().getReloadHostName();\n }\n }\n HostXml hostXml = new HostXml(defaultHostname, environment.getRunningModeControl().getRunningMode(),\n environment.isUseCachedDc(), Module.getBootModuleLoader(), executorService, hostExtensionRegistry);\n BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), \"host\"), hostXml, hostXml, false);\n for (Namespace namespace : Namespace.domainValues()) {\n if (!namespace.equals(Namespace.CURRENT)) {\n persister.registerAdditionalRootElement(new QName(namespace.getUriString(), \"host\"), hostXml);\n }\n }\n hostExtensionRegistry.setWriterRegistry(persister);\n return persister;\n }",
"public static List<String> asListLines(String content) {\n List<String> retorno = new ArrayList<String>();\n content = content.replace(CARRIAGE_RETURN, RETURN);\n content = content.replace(RETURN, CARRIAGE_RETURN);\n for (String str : content.split(CARRIAGE_RETURN)) {\n retorno.add(str);\n }\n return retorno;\n }",
"@NonNull\n public static File[] listAllFiles(File directory) {\n if (directory == null) {\n return new File[0];\n }\n File[] files = directory.listFiles();\n return files != null ? files : new File[0];\n }",
"public List getFeedback()\n\t {\n\t List<?> messages = new ArrayList();\n\t for ( ValueSource vs : valueSources )\n\t {\n\t List feedback = vs.getFeedback();\n\t if ( feedback != null && !feedback.isEmpty() )\n\t {\n\t messages.addAll( feedback );\n\t }\n\t }\n\n\t return messages;\n\t }",
"private void setUserFieldValue(UDFAssignmentType udf, DataType dataType, Object value)\n {\n switch (dataType)\n {\n case DURATION:\n {\n udf.setTextValue(((Duration) value).toString());\n break;\n }\n\n case CURRENCY:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setCostValue((Double) value);\n break;\n }\n\n case BINARY:\n {\n udf.setTextValue(\"\");\n break;\n }\n\n case STRING:\n {\n udf.setTextValue((String) value);\n break;\n }\n\n case DATE:\n {\n udf.setStartDateValue((Date) value);\n break;\n }\n\n case NUMERIC:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setDoubleValue((Double) value);\n break;\n }\n\n case BOOLEAN:\n {\n udf.setIntegerValue(BooleanHelper.getBoolean((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0));\n break;\n }\n\n case INTEGER:\n case SHORT:\n {\n udf.setIntegerValue(NumberHelper.getInteger((Number) value));\n break;\n }\n\n default:\n {\n throw new RuntimeException(\"Unconvertible data type: \" + dataType);\n }\n }\n }",
"public List<ProjectFile> readAll() throws MPXJException\n {\n Map<Integer, String> projects = listProjects();\n List<ProjectFile> result = new ArrayList<ProjectFile>(projects.keySet().size());\n for (Integer id : projects.keySet())\n {\n setProjectID(id.intValue());\n result.add(read());\n }\n return result;\n }",
"public static lbvserver_stats[] get(nitro_service service) throws Exception{\n\t\tlbvserver_stats obj = new lbvserver_stats();\n\t\tlbvserver_stats[] response = (lbvserver_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) {\n if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) {\n for (int i = 0; i <= a.numCols; i++) {\n if( a.col_idx[i] != b.col_idx[i] )\n return false;\n }\n for (int i = 0; i < a.nz_length; i++) {\n if( a.nz_rows[i] != b.nz_rows[i] )\n return false;\n }\n return true;\n }\n return false;\n }"
] |
Set the month.
@param monthStr the month to set. | [
"public void setMonth(String monthStr) {\n\n final Month month = Month.valueOf(monthStr);\n if ((m_model.getMonth() == null) || !m_model.getMonth().equals(monthStr)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setMonth(month);\n onValueChange();\n\n }\n });\n }\n }"
] | [
"private List<TimephasedCost> getTimephasedCostMultipleRates(List<TimephasedWork> standardWorkList, List<TimephasedWork> overtimeWorkList)\n {\n List<TimephasedWork> standardWorkResult = new LinkedList<TimephasedWork>();\n List<TimephasedWork> overtimeWorkResult = new LinkedList<TimephasedWork>();\n CostRateTable table = getCostRateTable();\n ProjectCalendar calendar = getCalendar();\n\n Iterator<TimephasedWork> iter = overtimeWorkList.iterator();\n for (TimephasedWork standardWork : standardWorkList)\n {\n TimephasedWork overtimeWork = iter.hasNext() ? iter.next() : null;\n\n int startIndex = getCostRateTableEntryIndex(standardWork.getStart());\n int finishIndex = getCostRateTableEntryIndex(standardWork.getFinish());\n\n if (startIndex == finishIndex)\n {\n standardWorkResult.add(standardWork);\n if (overtimeWork != null)\n {\n overtimeWorkResult.add(overtimeWork);\n }\n }\n else\n {\n standardWorkResult.addAll(splitWork(table, calendar, standardWork, startIndex));\n if (overtimeWork != null)\n {\n overtimeWorkResult.addAll(splitWork(table, calendar, overtimeWork, startIndex));\n }\n }\n }\n\n return getTimephasedCostSingleRate(standardWorkResult, overtimeWorkResult);\n }",
"public static ActorSystem createAndGetActorSystem() {\n if (actorSystem == null || actorSystem.isTerminated()) {\n actorSystem = ActorSystem.create(PcConstants.ACTOR_SYSTEM, conf);\n }\n return actorSystem;\n }",
"public Character getCharacter(int field)\n {\n Character result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Character.valueOf(m_fields[field].charAt(0));\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"protected void processAliases(List<MonolingualTextValue> addAliases, List<MonolingualTextValue> deleteAliases) {\n for(MonolingualTextValue val : addAliases) {\n addAlias(val);\n }\n for(MonolingualTextValue val : deleteAliases) {\n deleteAlias(val);\n }\n }",
"private Entry getEntry(Object key)\r\n {\r\n if (key == null) return null;\r\n int hash = hashCode(key);\r\n int index = indexFor(hash);\r\n for (Entry entry = table[index]; entry != null; entry = entry.next)\r\n {\r\n if ((entry.hash == hash) && equals(key, entry.getKey()))\r\n {\r\n return entry;\r\n }\r\n }\r\n return null;\r\n }",
"public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource,\n\t\t\tint resultFlags, ObjectCache objectCache) throws SQLException {\n\t\tprepareQueryForAll();\n\t\treturn buildIterator(classDao, connectionSource, preparedQueryForAll, objectCache, resultFlags);\n\t}",
"private void logRequestHistory(HttpMethod httpMethodProxyRequest, PluginResponse httpServletResponse,\n History history) {\n try {\n if (requestInformation.get().handle && requestInformation.get().client.getIsActive()) {\n logger.info(\"Storing history\");\n String createdDate;\n SimpleDateFormat sdf = new SimpleDateFormat();\n sdf.setTimeZone(new SimpleTimeZone(0, \"GMT\"));\n sdf.applyPattern(\"dd MMM yyyy HH:mm:ss\");\n createdDate = sdf.format(new Date()) + \" GMT\";\n\n history.setCreatedAt(createdDate);\n history.setRequestURL(HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));\n history.setRequestParams(httpMethodProxyRequest.getQueryString() == null ? \"\"\n : httpMethodProxyRequest.getQueryString());\n history.setRequestHeaders(HttpUtilities.getHeaders(httpMethodProxyRequest));\n history.setResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));\n history.setResponseCode(Integer.toString(httpServletResponse.getStatus()));\n history.setResponseContentType(httpServletResponse.getContentType());\n history.setResponseData(httpServletResponse.getContentString());\n history.setResponseBodyDecoded(httpServletResponse.isContentDecoded());\n HistoryService.getInstance().addHistory(history);\n logger.info(\"Done storing\");\n }\n } catch (URIException e) {\n e.printStackTrace();\n }\n }",
"private Expression correctClassClassChain(PropertyExpression pe) {\n LinkedList<Expression> stack = new LinkedList<Expression>();\n ClassExpression found = null;\n for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) {\n if (it instanceof ClassExpression) {\n found = (ClassExpression) it;\n break;\n } else if (!(it.getClass() == PropertyExpression.class)) {\n return pe;\n }\n stack.addFirst(it);\n }\n if (found == null) return pe;\n\n if (stack.isEmpty()) return pe;\n Object stackElement = stack.removeFirst();\n if (!(stackElement.getClass() == PropertyExpression.class)) return pe;\n PropertyExpression classPropertyExpression = (PropertyExpression) stackElement;\n String propertyNamePart = classPropertyExpression.getPropertyAsString();\n if (propertyNamePart == null || !propertyNamePart.equals(\"class\")) return pe;\n\n found.setSourcePosition(classPropertyExpression);\n if (stack.isEmpty()) return found;\n stackElement = stack.removeFirst();\n if (!(stackElement.getClass() == PropertyExpression.class)) return pe;\n PropertyExpression classPropertyExpressionContainer = (PropertyExpression) stackElement;\n\n classPropertyExpressionContainer.setObjectExpression(found);\n return pe;\n }",
"public void addRequiredBundles(Set<String> bundles) {\n\t\t// TODO manage transitive dependencies\n\t\t// don't require self\n\t\tSet<String> bundlesToMerge;\n\t\tString bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME);\n\t\tif (bundleName != null) {\n\t\t\tint idx = bundleName.indexOf(';');\n\t\t\tif (idx >= 0) {\n\t\t\t\tbundleName = bundleName.substring(0, idx);\n\t\t\t}\n\t\t}\n\t\tif (bundleName != null && bundles.contains(bundleName)\n\t\t\t\t|| projectName != null && bundles.contains(projectName)) {\n\t\t\tbundlesToMerge = new LinkedHashSet<String>(bundles);\n\t\t\tbundlesToMerge.remove(bundleName);\n\t\t\tbundlesToMerge.remove(projectName);\n\t\t} else {\n\t\t\tbundlesToMerge = bundles;\n\t\t}\n\t\tString s = (String) getMainAttributes().get(REQUIRE_BUNDLE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(REQUIRE_BUNDLE, result);\n\t}"
] |
Sets all padding for all cells in the row to the same value.
@param padding new padding for top, bottom, left, and right, ignored if smaller than 0
@return this to allow chaining | [
"public AT_Row setPadding(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().setPadding(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] | [
"private void updateBeatGrid(TrackMetadataUpdate update, BeatGrid beatGrid) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), beatGrid); // 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 hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), beatGrid);\n }\n }\n }\n deliverBeatGridUpdate(update.player, beatGrid);\n }",
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n public void blacklistNode(int nodeId) {\n Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes();\n\n if(blackListedNodes == null) {\n blackListedNodes = new ArrayList();\n }\n blackListedNodes.add(nodeId);\n\n for(Node node: nodesInCluster) {\n\n if(node.getId() == nodeId) {\n nodesToStream.remove(node);\n break;\n }\n\n }\n\n for(String store: storeNames) {\n try {\n SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId));\n close(sands.getSocket());\n SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,\n nodeId));\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n }\n }",
"public final void addRule(TableRowStyle style){\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN, \"cannot add a rule of unknown style\");\r\n\t\tthis.rows.add(AT_Row.createRule(TableRowType.RULE, style));\r\n\t}",
"public static base_responses delete(nitro_service client, String jsoncontenttypevalue[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (jsoncontenttypevalue != null && jsoncontenttypevalue.length > 0) {\n\t\t\tappfwjsoncontenttype deleteresources[] = new appfwjsoncontenttype[jsoncontenttypevalue.length];\n\t\t\tfor (int i=0;i<jsoncontenttypevalue.length;i++){\n\t\t\t\tdeleteresources[i] = new appfwjsoncontenttype();\n\t\t\t\tdeleteresources[i].jsoncontenttypevalue = jsoncontenttypevalue[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Nonnull\n public final Style getDefaultStyle(@Nonnull final String geometryType) {\n String normalizedGeomName = GEOMETRY_NAME_ALIASES.get(geometryType.toLowerCase());\n if (normalizedGeomName == null) {\n normalizedGeomName = geometryType.toLowerCase();\n }\n Style style = this.defaultStyle.get(normalizedGeomName.toLowerCase());\n if (style == null) {\n style = this.namedStyles.get(normalizedGeomName.toLowerCase());\n }\n\n if (style == null) {\n StyleBuilder builder = new StyleBuilder();\n final Symbolizer symbolizer;\n if (isPointType(normalizedGeomName)) {\n symbolizer = builder.createPointSymbolizer();\n } else if (isLineType(normalizedGeomName)) {\n symbolizer = builder.createLineSymbolizer(Color.black, 2);\n } else if (isPolygonType(normalizedGeomName)) {\n symbolizer = builder.createPolygonSymbolizer(Color.lightGray, Color.black, 2);\n } else if (normalizedGeomName.equalsIgnoreCase(Constants.Style.Raster.NAME)) {\n symbolizer = builder.createRasterSymbolizer();\n } else if (normalizedGeomName.startsWith(Constants.Style.OverviewMap.NAME)) {\n symbolizer = createMapOverviewStyle(normalizedGeomName, builder);\n } else {\n final Style geomStyle = this.defaultStyle.get(Geometry.class.getSimpleName().toLowerCase());\n if (geomStyle != null) {\n return geomStyle;\n } else {\n symbolizer = builder.createPointSymbolizer();\n }\n }\n style = builder.createStyle(symbolizer);\n }\n return style;\n }",
"@Override public void render() {\n Video video = getContent();\n renderThumbnail(video);\n renderTitle(video);\n renderMarker(video);\n renderLabel();\n }",
"@SuppressWarnings({\"WeakerAccess\"})\n protected void initDeviceID() {\n getDeviceCachedInfo(); // put this here to avoid running on main thread\n\n // generate a provisional while we do the rest async\n generateProvisionalGUID();\n // grab and cache the googleAdID in any event if available\n // if we already have a deviceID we won't user ad id as the guid\n cacheGoogleAdID();\n\n // if we already have a device ID use it and just notify\n // otherwise generate one, either from ad id if available or the provisional\n String deviceID = getDeviceID();\n if (deviceID == null || deviceID.trim().length() <= 2) {\n generateDeviceID();\n }\n\n }",
"PollingState<T> withResponse(Response<ResponseBody> response) {\n this.response = response;\n withPollingUrlFromResponse(response);\n withPollingRetryTimeoutFromResponse(response);\n return this;\n }",
"private boolean operations(Options opt, MethodDoc m[]) {\n\tboolean printed = false;\n\tfor (MethodDoc md : m) {\n\t if (hidden(md))\n\t\tcontinue;\n\t // Filter-out static initializer method\n\t if (md.name().equals(\"<clinit>\") && md.isStatic() && md.isPackagePrivate())\n\t\tcontinue;\n\t stereotype(opt, md, Align.LEFT);\n\t String op = visibility(opt, md) + md.name() + //\n\t\t (opt.showType ? \"(\" + parameter(opt, md.parameters()) + \")\" + typeAnnotation(opt, md.returnType())\n\t\t\t : \"()\");\n\t tableLine(Align.LEFT, (md.isAbstract() ? Font.ABSTRACT : Font.NORMAL).wrap(opt, op));\n\t printed = true;\n\n\t tagvalue(opt, md);\n\t}\n\treturn printed;\n }"
] |
Returns a new color with a new value of the specified HSL
component. | [
"private RgbaColor withHsl(int index, float value) {\n float[] HSL = convertToHsl();\n HSL[index] = value;\n return RgbaColor.fromHsl(HSL);\n }"
] | [
"public void load(List<E> result) {\n ++pageCount;\n if (this.result == null || this.result.isEmpty()) {\n this.result = result;\n } else {\n this.result.addAll(result);\n }\n }",
"protected Integer getCorrectIndex(Integer index) {\n Integer size = jsonNode.size();\n Integer newIndex = index;\n\n // reverse walking through the array\n if(index < 0) {\n newIndex = size + index;\n }\n\n // the negative index would be greater than the size a second time!\n if(newIndex < 0) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n // the index is greater as the actual size\n if(index > size) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n return newIndex;\n }",
"protected CmsProject createAndSetModuleImportProject(CmsObject cms, CmsModule module) throws CmsException {\n\n CmsProject importProject = cms.createProject(\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_NAME_1,\n new Object[] {module.getName()}),\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_DESC_1,\n new Object[] {module.getName()}),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n cms.getRequestContext().setCurrentProject(importProject);\n cms.copyResourceToProject(\"/\");\n return importProject;\n }",
"public static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) {\n return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(List<InnerT> inners) {\n return Observable.from(inners);\n }\n });\n }",
"void markReferenceElements(PersistenceBroker broker)\r\n {\r\n // these cases will be handled by ObjectEnvelopeTable#cascadingDependents()\r\n // if(getModificationState().needsInsert() || getModificationState().needsDelete()) return;\r\n\r\n Map oldImage = getBeforeImage();\r\n Map newImage = getCurrentImage();\r\n\r\n Iterator iter = newImage.entrySet().iterator();\r\n while (iter.hasNext())\r\n {\r\n Map.Entry entry = (Map.Entry) iter.next();\r\n Object key = entry.getKey();\r\n // we only interested in references\r\n if(key instanceof ObjectReferenceDescriptor)\r\n {\r\n Image oldRefImage = (Image) oldImage.get(key);\r\n Image newRefImage = (Image) entry.getValue();\r\n newRefImage.performReferenceDetection(oldRefImage);\r\n }\r\n }\r\n }",
"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 static double fastNormP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return fastNormF(A);\n } else {\n return inducedP2(A);\n }\n }",
"protected void appendWhereClause(StringBuffer stmt, Object[] columns)\r\n {\r\n stmt.append(\" WHERE \");\r\n\r\n for (int i = 0; i < columns.length; i++)\r\n {\r\n if (i > 0)\r\n {\r\n stmt.append(\" AND \");\r\n }\r\n stmt.append(columns[i]);\r\n stmt.append(\"=?\");\r\n }\r\n }",
"public static String getAt(GString text, int index) {\n return (String) getAt(text.toString(), index);\n }"
] |
Orders first by word, then by tag.
@param wordTag object to compare to
@return result (positive if <code>this</code> is greater than
<code>obj</code>, 0 if equal, negative otherwise) | [
"public int compareTo(WordTag wordTag) { \r\n int first = (word != null ? word().compareTo(wordTag.word()) : 0);\r\n if(first != 0)\r\n return first;\r\n else {\r\n if (tag() == null) {\r\n if (wordTag.tag() == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return tag().compareTo(wordTag.tag());\r\n }\r\n }"
] | [
"private String formatDateTimeNull(Date value)\n {\n return (value == null ? m_formats.getNullText() : m_formats.getDateTimeFormat().format(value));\n }",
"public static cacheselector get(nitro_service service, String selectorname) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tobj.set_selectorname(selectorname);\n\t\tcacheselector response = (cacheselector) obj.get_resource(service);\n\t\treturn response;\n\t}",
"static boolean shouldShowRequestPermissionRationale(Activity activity, String... permissions) {\n for (String permission : permissions) {\n if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {\n return true;\n }\n }\n return false;\n }",
"private void setPlaybackPosition(long milliseconds) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.position != milliseconds) {\n setPlaybackState(oldState.player, milliseconds, oldState.playing);\n }\n }",
"protected final void _onConnect(WebSocketContext context) {\n if (null != connectionListener) {\n connectionListener.onConnect(context);\n }\n connectionListenerManager.notifyFreeListeners(context, false);\n Act.eventBus().emit(new WebSocketConnectEvent(context));\n }",
"public int sum() {\n int total = 0;\n int N = getNumElements();\n for (int i = 0; i < N; i++) {\n if( data[i] )\n total += 1;\n }\n return total;\n }",
"public void setAttribute(String strKey, Object value)\r\n {\r\n this.propertyChangeDelegate.firePropertyChange(strKey,\r\n hmAttributes.put(strKey, value), value);\r\n }",
"private void internalCleanup()\r\n {\r\n if(hasBroker())\r\n {\r\n PersistenceBroker broker = getBroker();\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Do internal cleanup and close the internal used connection without\" +\r\n \" closing the used broker\");\r\n }\r\n ConnectionManagerIF cm = broker.serviceConnectionManager();\r\n if(cm.isInLocalTransaction())\r\n {\r\n /*\r\n arminw:\r\n in managed environment this call will be ignored because, the JTA transaction\r\n manager control the connection status. But to make connectionManager happy we\r\n have to complete the \"local tx\" of the connectionManager before release the\r\n connection\r\n */\r\n cm.localCommit();\r\n }\r\n cm.releaseConnection();\r\n }\r\n }",
"public static void scanClassPathForFormattingAnnotations() {\n\n\t\tExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);\n\n\t\t// scan classpath and filter out classes that don't begin with \"com.nds\"\n\t\tReflections reflections = new Reflections(\"com.nds\",\"com.cisco\");\n\n\t\tSet<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class);\n\n// Reflections ciscoReflections = new Reflections(\"com.cisco\");\n//\n// annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class));\n\n\t\tfor (Class<?> markerClass : annotated) {\n\n\t\t\t// if the marker class is indeed implementing FoundationLoggingMarker\n\t\t\t// interface\n\t\t\tif (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) {\n\n\t\t\t\tfinal Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass;\n\n\t\t\t\texecutorService.execute(new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\tif (markersMap.get(clazz) == null) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// generate formatter class for this marker\n\t\t\t\t\t\t\t\t// class\n\t\t\t\t\t\t\t\tgenerateAndUpdateFormatterInMap(clazz);\n\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\tLOGGER.trace(\"problem generating formatter class from static scan method. error is: \" + e.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t} else {// if marker class does not implement FoundationLoggingMarker\n\t\t\t\t\t// interface, log ERROR\n\n\t\t\t\t// verify the LOGGER was initialized. It might not be as this\n\t\t\t\t// Method is called in a static block\n\t\t\t\tif (LOGGER == null) {\n\t\t\t\t\tLOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class);\n\t\t\t\t}\n\t\t\t\tLOGGER.error(\"Formatter annotations should only appear on foundationLoggingMarker implementations\");\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tTimeUnit.SECONDS.sleep(30);\n\t\t} catch (InterruptedException e) {\n\t\t\tLOGGER.trace(e.toString(), e);\n\t\t}\n\t\texecutorService.shutdown();\n\t\t// try {\n\t\t// executorService.awaitTermination(15, TimeUnit.SECONDS);\n\t\t// } catch (InterruptedException e) {\n\t\t// LOGGER.error(\"creation of formatters has been interrupted\");\n\t\t// }\n\t}"
] |
Retrieves state and metrics information for individual node.
@param name node name
@return node information | [
"public NodeInfo getNode(String name) {\n final URI uri = uriWithPath(\"./nodes/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, NodeInfo.class);\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 }",
"public WaveformPreview requestWaveformPreviewFrom(final DataReference dataReference) {\n ensureRunning();\n for (WaveformPreview cached : previewHotCache.values()) {\n if (cached.dataReference.equals(dataReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n return requestPreviewInternal(dataReference, false);\n }",
"public void addUIEventHandler(JavascriptObject obj, UIEventType type, UIEventHandler h) {\n String key = registerEventHandler(h);\n String mcall = \"google.maps.event.addListener(\" + obj.getVariableName() + \", '\" + type.name() + \"', \"\n + \"function(event) {document.jsHandlers.handleUIEvent('\" + key + \"', event);});\";//.latLng\n //System.out.println(\"addUIEventHandler mcall: \" + mcall);\n runtime.execute(mcall);\n }",
"public Date getTime(String fieldName) {\n\t\ttry {\n\t\t\tif (hasValue(fieldName)) {\n\t\t\t\treturn new Date(Long.valueOf(String.valueOf(resultMap.get(fieldName))) * 1000);\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a time.\", e);\n\t\t}\n\t}",
"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 transformXPath(String originalXPath)\n {\n // use a list to maintain the multiple joined xqueries (if there are multiple queries joined with the \"|\" operator)\n List<StringBuilder> compiledXPaths = new ArrayList<>(1);\n\n int frameIdx = -1;\n boolean inQuote = false;\n int conditionLevel = 0;\n char startQuoteChar = 0;\n StringBuilder currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n for (int i = 0; i < originalXPath.length(); i++)\n {\n char curChar = originalXPath.charAt(i);\n if (!inQuote && curChar == '[')\n {\n frameIdx++;\n conditionLevel++;\n currentXPath.append(\"[windup:startFrame(\").append(frameIdx).append(\") and windup:evaluate(\").append(frameIdx).append(\", \");\n }\n else if (!inQuote && curChar == ']')\n {\n conditionLevel--;\n currentXPath.append(\")]\");\n }\n else if (!inQuote && conditionLevel == 0 && curChar == '|')\n {\n // joining multiple xqueries\n currentXPath = new StringBuilder();\n compiledXPaths.add(currentXPath);\n }\n else\n {\n if (inQuote && curChar == startQuoteChar)\n {\n inQuote = false;\n startQuoteChar = 0;\n }\n else if (curChar == '\"' || curChar == '\\'')\n {\n inQuote = true;\n startQuoteChar = curChar;\n }\n\n if (!inQuote && originalXPath.startsWith(WINDUP_MATCHES_FUNCTION_PREFIX, i))\n {\n i += (WINDUP_MATCHES_FUNCTION_PREFIX.length() - 1);\n currentXPath.append(\"windup:matches(\").append(frameIdx).append(\", \");\n }\n else\n {\n currentXPath.append(curChar);\n }\n }\n }\n\n Pattern leadingAndTrailingWhitespace = Pattern.compile(\"(\\\\s*)(.*?)(\\\\s*)\");\n StringBuilder finalResult = new StringBuilder();\n for (StringBuilder compiledXPath : compiledXPaths)\n {\n if (StringUtils.isNotBlank(compiledXPath))\n {\n Matcher whitespaceMatcher = leadingAndTrailingWhitespace.matcher(compiledXPath);\n if (!whitespaceMatcher.matches())\n continue;\n\n compiledXPath = new StringBuilder();\n compiledXPath.append(whitespaceMatcher.group(1));\n compiledXPath.append(whitespaceMatcher.group(2));\n compiledXPath.append(\"/self::node()[windup:persist(\").append(frameIdx).append(\", \").append(\".)]\");\n compiledXPath.append(whitespaceMatcher.group(3));\n\n if (StringUtils.isNotBlank(finalResult))\n finalResult.append(\"|\");\n finalResult.append(compiledXPath);\n }\n }\n return finalResult.toString();\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public TrackMetadata requestMetadataFrom(final CdjStatus status) {\n if (status.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK || status.getRekordboxId() == 0) {\n return null;\n }\n final DataReference track = new DataReference(status.getTrackSourcePlayer(), status.getTrackSourceSlot(),\n status.getRekordboxId());\n return requestMetadataFrom(track, status.getTrackType());\n }",
"public boolean setVisibility(final Visibility visibility) {\n if (visibility != mVisibility) {\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"setVisibility(%s) for %s\", visibility, getName());\n updateVisibility(visibility);\n mVisibility = visibility;\n return true;\n }\n return false;\n }",
"private static JsonObject getFieldJsonObject(Field field) {\n JsonObject fieldObj = new JsonObject();\n fieldObj.add(\"type\", field.getType());\n fieldObj.add(\"key\", field.getKey());\n fieldObj.add(\"displayName\", field.getDisplayName());\n\n String fieldDesc = field.getDescription();\n if (fieldDesc != null) {\n fieldObj.add(\"description\", field.getDescription());\n }\n\n Boolean fieldIsHidden = field.getIsHidden();\n if (fieldIsHidden != null) {\n fieldObj.add(\"hidden\", field.getIsHidden());\n }\n\n JsonArray array = new JsonArray();\n List<String> options = field.getOptions();\n if (options != null && !options.isEmpty()) {\n for (String option : options) {\n JsonObject optionObj = new JsonObject();\n optionObj.add(\"key\", option);\n\n array.add(optionObj);\n }\n fieldObj.add(\"options\", array);\n }\n\n return fieldObj;\n }"
] |
Return input mapper from processor. | [
"@Nonnull\n public BiMap<String, String> getInputMapper() {\n final BiMap<String, String> inputMapper = this.processor.getInputMapperBiMap();\n if (inputMapper == null) {\n return HashBiMap.create();\n }\n return inputMapper;\n }"
] | [
"public void fill(long offset, long length, byte value) {\n unsafe.setMemory(address() + offset, length, value);\n }",
"public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForStandalone(null, client, startupTimeout);\n }",
"public void addBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final boolean statementBatchingSupported = m_batchStatementsInProgress.containsKey(stmt);\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n stmt.executeUpdate();\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n super.addBatch(stmt);\r\n }\r\n }",
"public Where<T, ID> le(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LESS_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}",
"public void setValueSelected(T value, boolean selected) {\n int idx = getIndex(value);\n if (idx >= 0) {\n setItemSelectedInternal(idx, selected);\n }\n }",
"public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength);\n recordResourceRequestQueueLength(null, queueLength);\n } else {\n this.resourceRequestQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }",
"public DynamicReportBuilder setProperty(String name, String value) {\n this.report.setProperty(name, value);\n return this;\n }",
"private void readAssignment(Resource resource, Assignment assignment)\n {\n Task task = m_activityMap.get(assignment.getActivity());\n if (task != null)\n {\n task.addResourceAssignment(resource);\n }\n }",
"public void setSlideDrawable(Drawable drawable) {\n mSlideDrawable = new SlideDrawable(drawable);\n mSlideDrawable.setIsRtl(ViewHelper.getLayoutDirection(this) == LAYOUT_DIRECTION_RTL);\n\n if (mActionBarHelper != null) {\n mActionBarHelper.setDisplayShowHomeAsUpEnabled(true);\n\n if (mDrawerIndicatorEnabled) {\n mActionBarHelper.setActionBarUpIndicator(mSlideDrawable,\n isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc);\n }\n }\n }"
] |
Get a list of tags for the specified photo.
<p>
This method does not require authentication.
</p>
@param photoId
The photo ID
@return The collection of Tag objects | [
"public Photo getListPhoto(String photoId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_PHOTO);\n\n parameters.put(\"photo_id\", photoId);\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 photoElement = response.getPayload();\n Photo photo = new Photo();\n photo.setId(photoElement.getAttribute(\"id\"));\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) photoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setId(tagElement.getAttribute(\"id\"));\n tag.setAuthor(tagElement.getAttribute(\"author\"));\n tag.setAuthorName(tagElement.getAttribute(\"authorname\"));\n tag.setRaw(tagElement.getAttribute(\"raw\"));\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n photo.setTags(tags);\n return photo;\n }"
] | [
"public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\n }",
"public static base_response update(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig updateresource = new nsconfig();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.nsvlan = resource.nsvlan;\n\t\tupdateresource.ifnum = resource.ifnum;\n\t\tupdateresource.tagged = resource.tagged;\n\t\tupdateresource.httpport = resource.httpport;\n\t\tupdateresource.maxconn = resource.maxconn;\n\t\tupdateresource.maxreq = resource.maxreq;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.cookieversion = resource.cookieversion;\n\t\tupdateresource.securecookie = resource.securecookie;\n\t\tupdateresource.pmtumin = resource.pmtumin;\n\t\tupdateresource.pmtutimeout = resource.pmtutimeout;\n\t\tupdateresource.ftpportrange = resource.ftpportrange;\n\t\tupdateresource.crportrange = resource.crportrange;\n\t\tupdateresource.timezone = resource.timezone;\n\t\tupdateresource.grantquotamaxclient = resource.grantquotamaxclient;\n\t\tupdateresource.exclusivequotamaxclient = resource.exclusivequotamaxclient;\n\t\tupdateresource.grantquotaspillover = resource.grantquotaspillover;\n\t\tupdateresource.exclusivequotaspillover = resource.exclusivequotaspillover;\n\t\tupdateresource.nwfwmode = resource.nwfwmode;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void processTask(ChildTaskContainer parent, MapRow row) throws IOException\n {\n Task task = parent.addTask();\n task.setName(row.getString(\"NAME\"));\n task.setGUID(row.getUUID(\"UUID\"));\n task.setText(1, row.getString(\"ID\"));\n task.setDuration(row.getDuration(\"PLANNED_DURATION\"));\n task.setRemainingDuration(row.getDuration(\"REMAINING_DURATION\"));\n task.setHyperlink(row.getString(\"URL\"));\n task.setPercentageComplete(row.getDouble(\"PERCENT_COMPLETE\"));\n task.setNotes(getNotes(row.getRows(\"COMMENTARY\")));\n task.setMilestone(task.getDuration().getDuration() == 0);\n\n ProjectCalendar calendar = m_calendarMap.get(row.getUUID(\"CALENDAR_UUID\"));\n if (calendar != m_project.getDefaultCalendar())\n {\n task.setCalendar(calendar);\n }\n\n switch (row.getInteger(\"STATUS\").intValue())\n {\n case 1: // Planned\n {\n task.setStart(row.getDate(\"PLANNED_START\"));\n task.setFinish(task.getEffectiveCalendar().getDate(task.getStart(), task.getDuration(), false));\n break;\n }\n\n case 2: // Started\n {\n task.setActualStart(row.getDate(\"ACTUAL_START\"));\n task.setStart(task.getActualStart());\n task.setFinish(row.getDate(\"ESTIMATED_FINISH\"));\n if (task.getFinish() == null)\n {\n task.setFinish(row.getDate(\"PLANNED_FINISH\"));\n }\n break;\n }\n\n case 3: // Finished\n {\n task.setActualStart(row.getDate(\"ACTUAL_START\"));\n task.setActualFinish(row.getDate(\"ACTUAL_FINISH\"));\n task.setPercentageComplete(Double.valueOf(100.0));\n task.setStart(task.getActualStart());\n task.setFinish(task.getActualFinish());\n break;\n }\n }\n\n setConstraints(task, row);\n\n processChildTasks(task, row);\n\n m_taskMap.put(task.getGUID(), task);\n\n List<MapRow> predecessors = row.getRows(\"PREDECESSORS\");\n if (predecessors != null && !predecessors.isEmpty())\n {\n m_predecessorMap.put(task, predecessors);\n }\n\n List<MapRow> resourceAssignmnets = row.getRows(\"RESOURCE_ASSIGNMENTS\");\n if (resourceAssignmnets != null && !resourceAssignmnets.isEmpty())\n {\n processResourceAssignments(task, resourceAssignmnets);\n }\n }",
"public void write(Configuration config)\n throws IOException {\n\n pp.startDocument();\n pp.startElement(\"duke\", null);\n\n // FIXME: here we should write the objects, but that's not\n // possible with the current API. we don't need that for the\n // genetic algorithm at the moment, but it would be useful.\n\n pp.startElement(\"schema\", null);\n\n writeElement(\"threshold\", \"\" + config.getThreshold());\n if (config.getMaybeThreshold() != 0.0)\n writeElement(\"maybe-threshold\", \"\" + config.getMaybeThreshold());\n\n for (Property p : config.getProperties())\n writeProperty(p);\n\n pp.endElement(\"schema\");\n\n String dbclass = config.getDatabase(false).getClass().getName();\n AttributeListImpl atts = new AttributeListImpl();\n atts.addAttribute(\"class\", \"CDATA\", dbclass);\n pp.startElement(\"database\", atts);\n pp.endElement(\"database\");\n\n if (config.isDeduplicationMode())\n for (DataSource src : config.getDataSources())\n writeDataSource(src);\n else {\n pp.startElement(\"group\", null);\n for (DataSource src : config.getDataSources(1))\n writeDataSource(src);\n pp.endElement(\"group\");\n\n pp.startElement(\"group\", null);\n for (DataSource src : config.getDataSources(2))\n writeDataSource(src);\n pp.endElement(\"group\");\n }\n\n pp.endElement(\"duke\");\n pp.endDocument();\n }",
"private boolean processQueue(K key) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key);\n if(requestQueue.isEmpty()) {\n return false;\n }\n\n // Attempt to get a resource.\n Pool<V> resourcePool = getResourcePoolForKey(key);\n V resource = null;\n Exception ex = null;\n try {\n // Must attempt non-blocking checkout to ensure resources are\n // created for the pool.\n resource = attemptNonBlockingCheckout(key, resourcePool);\n } catch(Exception e) {\n destroyResource(key, resourcePool, resource);\n ex = e;\n resource = null;\n }\n // Neither we got a resource, nor an exception. So no requests can be\n // processed return\n if(resource == null && ex == null) {\n return false;\n }\n\n // With resource in hand, process the resource requests\n AsyncResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue);\n if(resourceRequest == null) {\n if(resource != null) {\n // Did not use the resource! Directly check in via super to\n // avoid\n // circular call to processQueue().\n try {\n super.checkin(key, resource);\n } catch(Exception e) {\n logger.error(\"Exception checking in resource: \", e);\n }\n } else {\n // Poor exception, no request to tag this exception onto\n // drop it on the floor and continue as usual.\n }\n return false;\n } else {\n // We have a request here.\n if(resource != null) {\n resourceRequest.useResource(resource);\n } else {\n resourceRequest.handleException(ex);\n }\n return true;\n }\n }",
"@SuppressWarnings(\"boxing\")\r\n public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) {\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n\r\n // Flickr seems to return invalid token sometimes so retry a few times.\r\n // See http://www.flickr.com/groups/api/discuss/72157628028927244/\r\n OAuth1Token accessToken = null;\r\n boolean success = false;\r\n for (int i = 0; i < maxGetTokenRetries && !success; i++) {\r\n try {\r\n accessToken = service.getAccessToken(oAuthRequestToken, verifier);\r\n success = true;\r\n } catch (OAuthException | IOException | InterruptedException | ExecutionException e) {\r\n if (i == maxGetTokenRetries - 1) {\r\n logger.error(String.format(\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\", i), e);\r\n throw new FlickrRuntimeException(e);\r\n } else {\r\n logger.warn(String.format(\"OAuthService.getAccessToken failed, try number %d: %s\", i, e.getMessage()));\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n }\r\n\r\n return accessToken;\r\n }",
"public void awaitPodReadinessOrFail(Predicate<Pod> filter) {\n await().atMost(5, TimeUnit.MINUTES).until(() -> {\n List<Pod> list = client.pods().inNamespace(namespace).list().getItems();\n return list.stream()\n .filter(filter)\n .filter(Readiness::isPodReady)\n .collect(Collectors.toList()).size() >= 1;\n }\n );\n }",
"@SuppressWarnings(\"unused\")\n public void setError(CharSequence error, Drawable icon) {\n mPhoneEdit.setError(error, icon);\n }",
"private void updateScheduleSource(ProjectProperties properties)\n {\n // Rudimentary identification of schedule source\n if (properties.getCompany() != null && properties.getCompany().equals(\"Synchro Software Ltd\"))\n {\n properties.setFileApplication(\"Synchro\");\n }\n else\n {\n if (properties.getAuthor() != null && properties.getAuthor().equals(\"SG Project\"))\n {\n properties.setFileApplication(\"Simple Genius\");\n }\n else\n {\n properties.setFileApplication(\"Microsoft\");\n }\n }\n properties.setFileType(\"MSPDI\");\n }"
] |
Merge two maps of configuration properties. If the original contains a mapping for the same key, the new mapping is ignored.
@param original
@param toMerge | [
"static void merge(Map<ConfigurationKey, Object> original, Map<ConfigurationKey, Object> toMerge, String mergedSourceDescription) {\n for (Entry<ConfigurationKey, Object> entry : toMerge.entrySet()) {\n Object existing = original.get(entry.getKey());\n if (existing != null) {\n ConfigurationLogger.LOG.configurationKeyAlreadySet(entry.getKey().get(), existing, entry.getValue(), mergedSourceDescription);\n } else {\n original.put(entry.getKey(), entry.getValue());\n }\n }\n }"
] | [
"protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }",
"public static Boolean assertTrue(Boolean value, String message) {\n if (!Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }",
"public void printInferredDependencies(ClassDoc c) {\n\tif (hidden(c))\n\t return;\n\n\tOptions opt = optionProvider.getOptionsFor(c);\n\tSet<Type> types = new HashSet<Type>();\n\t// harvest method return and parameter types\n\tfor (MethodDoc method : filterByVisibility(c.methods(false), opt.inferDependencyVisibility)) {\n\t types.add(method.returnType());\n\t for (Parameter parameter : method.parameters()) {\n\t\ttypes.add(parameter.type());\n\t }\n\t}\n\t// and the field types\n\tif (!opt.inferRelationships) {\n\t for (FieldDoc field : filterByVisibility(c.fields(false), opt.inferDependencyVisibility)) {\n\t\ttypes.add(field.type());\n\t }\n\t}\n\t// see if there are some type parameters\n\tif (c.asParameterizedType() != null) {\n\t ParameterizedType pt = c.asParameterizedType();\n\t types.addAll(Arrays.asList(pt.typeArguments()));\n\t}\n\t// see if type parameters extend something\n\tfor(TypeVariable tv: c.typeParameters()) {\n\t if(tv.bounds().length > 0 )\n\t\ttypes.addAll(Arrays.asList(tv.bounds()));\n\t}\n\n\t// and finally check for explicitly imported classes (this\n\t// assumes there are no unused imports...)\n\tif (opt.useImports)\n\t types.addAll(Arrays.asList(importedClasses(c)));\n\n\t// compute dependencies\n\tfor (Type type : types) {\n\t // skip primitives and type variables, as well as dependencies\n\t // on the source class\n\t if (type.isPrimitive() || type instanceof WildcardType || type instanceof TypeVariable\n\t\t || c.toString().equals(type.asClassDoc().toString()))\n\t\tcontinue;\n\n\t // check if the destination is excluded from inference\n\t ClassDoc fc = type.asClassDoc();\n\t if (hidden(fc))\n\t\tcontinue;\n\t \n\t // check if source and destination are in the same package and if we are allowed\n\t // to infer dependencies between classes in the same package\n\t if(!opt.inferDepInPackage && c.containingPackage().equals(fc.containingPackage()))\n\t\tcontinue;\n\n\t // if source and dest are not already linked, add a dependency\n\t RelationPattern rp = getClassInfo(c, true).getRelation(fc.toString());\n\t if (rp == null || rp.matchesOne(new RelationPattern(RelationDirection.OUT))) {\n\t\trelation(opt, RelationType.DEPEND, c, fc, \"\", \"\", \"\");\n\t }\n\t \n\t}\n }",
"public final double getMedian()\n {\n assertNotEmpty();\n // Sort the data (take a copy to do this).\n double[] dataCopy = new double[getSize()];\n System.arraycopy(dataSet, 0, dataCopy, 0, dataCopy.length);\n Arrays.sort(dataCopy);\n int midPoint = dataCopy.length / 2;\n if (dataCopy.length % 2 != 0)\n {\n return dataCopy[midPoint];\n }\n else\n {\n return dataCopy[midPoint - 1] + (dataCopy[midPoint] - dataCopy[midPoint - 1]) / 2;\n }\n }",
"public void setWorkDir(String dir) throws IOException\r\n {\r\n File workDir = new File(dir);\r\n\r\n if (!workDir.exists() || !workDir.canWrite() || !workDir.canRead())\r\n {\r\n throw new IOException(\"Cannot access directory \"+dir);\r\n }\r\n _workDir = workDir;\r\n }",
"public boolean getBoolean(FastTrackField type)\n {\n boolean result = false;\n Object value = getObject(type);\n if (value != null)\n {\n result = BooleanHelper.getBoolean((Boolean) value);\n }\n return result;\n }",
"public static <T> List<T> load(ClassLoader classLoader, Class<T> serviceType) {\n List<T> foundServices = new ArrayList<>();\n Iterator<T> iterator = ServiceLoader.load(serviceType, classLoader).iterator();\n\n while (checkHasNextSafely(iterator)) {\n try {\n T item = iterator.next();\n foundServices.add(item);\n LOGGER.debug(String.format(\"Found %s [%s]\", serviceType.getSimpleName(), item.toString()));\n } catch (ServiceConfigurationError e) {\n LOGGER.trace(\"Can't find services using Java SPI\", e);\n LOGGER.error(e.getMessage());\n }\n }\n return foundServices;\n }",
"private static EventEnumType convertEventType(org.talend.esb.sam.common.event.EventTypeEnum eventType) {\n if (eventType == null) {\n return null;\n }\n return EventEnumType.valueOf(eventType.name());\n }",
"private void addHours(ProjectCalendarDateRanges ranges, Record hoursRecord)\n {\n if (hoursRecord.getValue() != null)\n {\n String[] wh = hoursRecord.getValue().split(\"\\\\|\");\n try\n {\n String startText;\n String endText;\n\n if (wh[0].equals(\"s\"))\n {\n startText = wh[1];\n endText = wh[3];\n }\n else\n {\n startText = wh[3];\n endText = wh[1];\n }\n\n // for end time treat midnight as midnight next day\n if (endText.equals(\"00:00\"))\n {\n endText = \"24:00\";\n }\n Date start = m_calendarTimeFormat.parse(startText);\n Date end = m_calendarTimeFormat.parse(endText);\n\n ranges.addRange(new DateRange(start, end));\n }\n catch (ParseException e)\n {\n // silently ignore date parse exceptions\n }\n }\n }"
] |
Sets the path of the edited file in the corresponding display.
@param editedFilePath path of the edited file to set. | [
"public void setEditedFilePath(final String editedFilePath) {\n\n m_filePathField.setReadOnly(false);\n m_filePathField.setValue(editedFilePath);\n m_filePathField.setReadOnly(true);\n\n }"
] | [
"public base_response enable_features(String[] features) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsfeature resource = new nsfeature();\n\t\tresource.set_feature(features);\n\t\toptions option = new options();\n\t\toption.set_action(\"enable\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}",
"@Override\n public void run()\n {\n try {\n startBarrier.await();\n\n int idleCount = 0;\n while (!isRunning.compareAndSet(idleCount > lingerIterations && pidToProcessMap.isEmpty(), false)) {\n idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);\n }\n }\n catch (Exception e) {\n // TODO: how to handle this error?\n isRunning.set(false);\n }\n }",
"private LocatorSelectionStrategy getLocatorSelectionStrategy(String locatorSelectionStrategy) {\n if (null == locatorSelectionStrategy) {\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Strategy \" + locatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n\n if (locatorSelectionStrategyMap.containsKey(locatorSelectionStrategy)) {\n return locatorSelectionStrategyMap.get(locatorSelectionStrategy).getInstance();\n } else {\n if (LOG.isLoggable(Level.WARNING)) {\n LOG.log(Level.WARNING, \"LocatorSelectionStrategy \" + locatorSelectionStrategy\n + \" not registered at LocatorClientEnabler.\");\n }\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\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 }",
"public PhotoList<Photo> getPublicPhotos(String userId, Set<String> extras, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_PHOTOS);\r\n\r\n parameters.put(\"user_id\", userId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n if (extras != null) {\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 Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\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 EventBus emit(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }",
"public <T> T getState(HttpConnectionInterceptor interceptor, String stateName, Class<T>\n stateType) {\n Map<String, Object> state = interceptorStates.get(interceptor);\n if (state != null) {\n return stateType.cast(state.get(stateName));\n } else {\n return null;\n }\n }",
"public HashMap<String, IndexInput> getIndexInputList() {\n HashMap<String, IndexInput> clonedIndexInputList = new HashMap<String, IndexInput>();\n for (Entry<String, IndexInput> entry : indexInputList.entrySet()) {\n clonedIndexInputList.put(entry.getKey(), entry.getValue().clone());\n }\n return clonedIndexInputList;\n }"
] |
Set the group name
@param name new name of server group
@param id ID of group | [
"public void setGroupName(String name, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" SET \" + Constants.GENERIC_NAME + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\n statement.close();\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 }"
] | [
"private static long hexdump(InputStream is, PrintWriter pw) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n long byteCount = 0;\n\n char c;\n int loop;\n int count;\n StringBuilder sb = new StringBuilder();\n\n while (true)\n {\n count = is.read(buffer);\n if (count == -1)\n {\n break;\n }\n\n byteCount += count;\n\n sb.setLength(0);\n\n for (loop = 0; loop < count; loop++)\n {\n sb.append(\" \");\n sb.append(HEX_DIGITS[(buffer[loop] & 0xF0) >> 4]);\n sb.append(HEX_DIGITS[buffer[loop] & 0x0F]);\n }\n\n while (loop < BUFFER_SIZE)\n {\n sb.append(\" \");\n ++loop;\n }\n\n sb.append(\" \");\n\n for (loop = 0; loop < count; loop++)\n {\n c = (char) buffer[loop];\n if (c > 200 || c < 27)\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n\n pw.println(sb.toString());\n }\n\n return (byteCount);\n }",
"public void addHeader(String key, String value) {\n if (key.equals(\"As-User\")) {\n for (int i = 0; i < this.headers.size(); i++) {\n if (this.headers.get(i).getKey().equals(\"As-User\")) {\n this.headers.remove(i);\n }\n }\n }\n if (key.equals(\"X-Box-UA\")) {\n throw new IllegalArgumentException(\"Altering the X-Box-UA header is not permitted\");\n }\n this.headers.add(new RequestHeader(key, value));\n }",
"public Info getInfo(String ... fields) {\r\n QueryStringBuilder builder = new QueryStringBuilder();\r\n if (fields.length > 0) {\r\n builder.appendParam(\"fields\", fields);\r\n }\r\n URL url = DEVICE_PIN_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n return new Info(responseJSON);\r\n }",
"private void populateDefaultSettings(Record record, ProjectProperties properties) throws MPXJException\n {\n properties.setDefaultDurationUnits(record.getTimeUnit(0));\n properties.setDefaultDurationIsFixed(record.getNumericBoolean(1));\n properties.setDefaultWorkUnits(record.getTimeUnit(2));\n properties.setMinutesPerDay(Double.valueOf(NumberHelper.getDouble(record.getFloat(3)) * 60));\n properties.setMinutesPerWeek(Double.valueOf(NumberHelper.getDouble(record.getFloat(4)) * 60));\n properties.setDefaultStandardRate(record.getRate(5));\n properties.setDefaultOvertimeRate(record.getRate(6));\n properties.setUpdatingTaskStatusUpdatesResourceStatus(record.getNumericBoolean(7));\n properties.setSplitInProgressTasks(record.getNumericBoolean(8));\n }",
"public void addWord(MtasCQLParserWordFullCondition w) throws ParseException {\n assert w.getCondition()\n .not() == false : \"condition word should be positive in sentence definition\";\n if (!simplified) {\n partList.add(w);\n } else {\n throw new ParseException(\"already simplified\");\n }\n }",
"protected Object getFieldData(Integer id, FieldType type, byte[][] fixedData, Var2Data varData)\n {\n Object result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.read(id, fixedData, varData);\n }\n\n return result;\n }",
"public String calculateCacheKey(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability){\r\n\t\tStringBuilder tmp = calculateCacheKeyInternal(sql, resultSetType,\r\n\t\t\t\tresultSetConcurrency);\r\n\r\n\t\ttmp.append(\", H:\");\r\n\t\ttmp.append(resultSetHoldability);\r\n\r\n\t\treturn tmp.toString();\r\n\t}",
"public static DMatrixRBlock initializeQ(DMatrixRBlock Q,\n int numRows , int numCols , int blockLength ,\n boolean compact) {\n int minLength = Math.min(numRows,numCols);\n if( compact ) {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,minLength,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != minLength ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n } else {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,numRows,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != numRows ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n }\n return Q;\n }",
"private static boolean isConjWithNoPrep(TreeGraphNode node, Collection<TypedDependency> list) {\r\n for (TypedDependency td : list) {\r\n if (td.gov() == node && td.reln() == CONJUNCT) {\r\n // we have a conjunct\r\n // check the POS of the dependent\r\n String tdDepPOS = td.dep().parent().value();\r\n if (!(tdDepPOS.equals(\"IN\") || tdDepPOS.equals(\"TO\"))) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }"
] |
SetLoop will either set the GVRNodeAnimation's Repeat Mode to REPEATED if loop is true.
or it will set the GVRNodeAnimation's Repeat Mode to ONCE if loop is false
if loop is set to TRUE, when it was previously FALSE, then start the Animation.
@param doLoop
@param gvrContext | [
"public void setLoop(boolean doLoop, GVRContext gvrContext) {\n if (this.loop != doLoop ) {\n // a change in the loop\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n if (doLoop) gvrKeyFrameAnimation.setRepeatMode(GVRRepeatMode.REPEATED);\n else gvrKeyFrameAnimation.setRepeatMode(GVRRepeatMode.ONCE);\n }\n // be sure to start the animations if loop is true\n if ( doLoop ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n gvrKeyFrameAnimation.start(gvrContext.getAnimationEngine() );\n }\n }\n this.loop = doLoop;\n }\n }"
] | [
"public static boolean isKeyUsed(final Jedis jedis, final String key) {\n return !NONE.equalsIgnoreCase(jedis.type(key));\n }",
"protected void eciProcess() {\n\n EciMode eci = EciMode.of(content, \"ISO8859_1\", 3)\n .or(content, \"ISO8859_2\", 4)\n .or(content, \"ISO8859_3\", 5)\n .or(content, \"ISO8859_4\", 6)\n .or(content, \"ISO8859_5\", 7)\n .or(content, \"ISO8859_6\", 8)\n .or(content, \"ISO8859_7\", 9)\n .or(content, \"ISO8859_8\", 10)\n .or(content, \"ISO8859_9\", 11)\n .or(content, \"ISO8859_10\", 12)\n .or(content, \"ISO8859_11\", 13)\n .or(content, \"ISO8859_13\", 15)\n .or(content, \"ISO8859_14\", 16)\n .or(content, \"ISO8859_15\", 17)\n .or(content, \"ISO8859_16\", 18)\n .or(content, \"Windows_1250\", 21)\n .or(content, \"Windows_1251\", 22)\n .or(content, \"Windows_1252\", 23)\n .or(content, \"Windows_1256\", 24)\n .or(content, \"SJIS\", 20)\n .or(content, \"UTF8\", 26);\n\n if (EciMode.NONE.equals(eci)) {\n throw new OkapiException(\"Unable to determine ECI mode.\");\n }\n\n eciMode = eci.mode;\n inputData = toBytes(content, eci.charset);\n\n encodeInfo += \"ECI Mode: \" + eci.mode + \"\\n\";\n encodeInfo += \"ECI Charset: \" + eci.charset.name() + \"\\n\";\n }",
"private void addMembers(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n if (!type.isInterface() && (type.getFields() != null)) {\r\n XField field;\r\n\r\n for (Iterator it = type.getFields().iterator(); it.hasNext(); ) {\r\n field = (XField)it.next();\r\n if (!field.isFinal() && !field.isStatic() && !field.isTransient()) {\r\n if (checkTagAndParam(field.getDoc(), tagName, paramName, paramValue)) {\r\n // already processed ?\r\n if (!members.containsKey(field.getName())) {\r\n memberNames.add(field.getName());\r\n members.put(field.getName(), field);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (type.getMethods() != null) {\r\n XMethod method;\r\n String propertyName;\r\n\r\n for (Iterator it = type.getMethods().iterator(); it.hasNext(); ) {\r\n method = (XMethod)it.next();\r\n if (!method.isConstructor() && !method.isNative() && !method.isStatic()) {\r\n if (checkTagAndParam(method.getDoc(), tagName, paramName, paramValue)) {\r\n if (MethodTagsHandler.isGetterMethod(method) || MethodTagsHandler.isSetterMethod(method)) {\r\n propertyName = MethodTagsHandler.getPropertyNameFor(method);\r\n if (!members.containsKey(propertyName)) {\r\n memberNames.add(propertyName);\r\n members.put(propertyName, method);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }",
"private void readWorkWeeks(Project.Calendars.Calendar xmlCalendar, ProjectCalendar mpxjCalendar)\n {\n WorkWeeks ww = xmlCalendar.getWorkWeeks();\n if (ww != null)\n {\n for (WorkWeek xmlWeek : ww.getWorkWeek())\n {\n ProjectCalendarWeek week = mpxjCalendar.addWorkWeek();\n week.setName(xmlWeek.getName());\n Date startTime = xmlWeek.getTimePeriod().getFromDate();\n Date endTime = xmlWeek.getTimePeriod().getToDate();\n week.setDateRange(new DateRange(startTime, endTime));\n\n WeekDays xmlWeekDays = xmlWeek.getWeekDays();\n if (xmlWeekDays != null)\n {\n for (WeekDay xmlWeekDay : xmlWeekDays.getWeekDay())\n {\n int dayNumber = xmlWeekDay.getDayType().intValue();\n Day day = Day.getInstance(dayNumber);\n week.setWorkingDay(day, BooleanHelper.getBoolean(xmlWeekDay.isDayWorking()));\n ProjectCalendarHours hours = week.addCalendarHours(day);\n\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes times = xmlWeekDay.getWorkingTimes();\n if (times != null)\n {\n for (Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime())\n {\n startTime = period.getFromTime();\n endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }\n }\n }\n }\n }",
"private void readLSD() {\n // Logical screen size.\n header.width = readShort();\n header.height = readShort();\n // Packed fields\n int packed = read();\n // 1 : global color table flag.\n header.gctFlag = (packed & 0x80) != 0;\n // 2-4 : color resolution.\n // 5 : gct sort flag.\n // 6-8 : gct size.\n header.gctSize = 2 << (packed & 7);\n // Background color index.\n header.bgIndex = read();\n // Pixel aspect ratio\n header.pixelAspect = read();\n }",
"public boolean hasNullPKField(ClassDescriptor cld, Object obj)\r\n {\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n boolean hasNull = false;\r\n // an unmaterialized proxy object can never have nullified PK's\r\n IndirectionHandler handler = ProxyHelper.getIndirectionHandler(obj);\r\n if(handler == null || handler.alreadyMaterialized())\r\n {\r\n if(handler != null) obj = handler.getRealSubject();\r\n FieldDescriptor fld;\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n fld = fields[i];\r\n hasNull = representsNull(fld, fld.getPersistentField().get(obj));\r\n if(hasNull) break;\r\n }\r\n }\r\n return hasNull;\r\n }",
"private boolean hasBidirectionalAssociation(Class clazz)\r\n {\r\n ClassDescriptor cdesc;\r\n Collection refs;\r\n boolean hasBidirAssc;\r\n\r\n if (_withoutBidirAssc.contains(clazz))\r\n {\r\n return false;\r\n }\r\n\r\n if (_withBidirAssc.contains(clazz))\r\n {\r\n return true;\r\n }\r\n\r\n // first time we meet this class, let's look at metadata\r\n cdesc = _pb.getClassDescriptor(clazz);\r\n refs = cdesc.getObjectReferenceDescriptors();\r\n hasBidirAssc = false;\r\n REFS_CYCLE:\r\n for (Iterator it = refs.iterator(); it.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor ord;\r\n ClassDescriptor relCDesc;\r\n Collection relRefs;\r\n\r\n ord = (ObjectReferenceDescriptor) it.next();\r\n relCDesc = _pb.getClassDescriptor(ord.getItemClass());\r\n relRefs = relCDesc.getObjectReferenceDescriptors();\r\n for (Iterator relIt = relRefs.iterator(); relIt.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor relOrd;\r\n\r\n relOrd = (ObjectReferenceDescriptor) relIt.next();\r\n if (relOrd.getItemClass().equals(clazz))\r\n {\r\n hasBidirAssc = true;\r\n break REFS_CYCLE;\r\n }\r\n }\r\n }\r\n if (hasBidirAssc)\r\n {\r\n _withBidirAssc.add(clazz);\r\n }\r\n else\r\n {\r\n _withoutBidirAssc.add(clazz);\r\n }\r\n\r\n return hasBidirAssc;\r\n }",
"private void destroySession() {\n currentSessionId = 0;\n setAppLaunchPushed(false);\n getConfigLogger().verbose(getAccountId(),\"Session destroyed; Session ID is now 0\");\n clearSource();\n clearMedium();\n clearCampaign();\n clearWzrkParams();\n }",
"protected static void appendHandler(LogRecordHandler parent, LogRecordHandler child){\r\n RecordHandlerTree p = handlers.find(parent);\r\n if(p != null){\r\n p.addChild(child);\r\n } else {\r\n throw new IllegalArgumentException(\"No such parent handler: \" + parent);\r\n }\r\n }"
] |
Processes a row of the sites table and stores the site information found
therein.
@param siteRow
string serialisation of a sites table row as found in the SQL
dump | [
"void processSiteRow(String siteRow) {\n\t\tString[] row = getSiteRowFields(siteRow);\n\n\t\tString filePath = \"\";\n\t\tString pagePath = \"\";\n\n\t\tString dataArray = row[8].substring(row[8].indexOf('{'),\n\t\t\t\trow[8].length() - 2);\n\n\t\t// Explanation for the regular expression below:\n\t\t// \"'{' or ';'\" followed by either\n\t\t// \"NOT: ';', '{', or '}'\" repeated one or more times; or\n\t\t// \"a single '}'\"\n\t\t// The first case matches \";s:5:\\\"paths\\\"\"\n\t\t// but also \";a:2:\" in \"{s:5:\\\"paths\\\";a:2:{s:9:\\ ...\".\n\t\t// The second case matches \";}\" which terminates (sub)arrays.\n\t\tMatcher matcher = Pattern.compile(\"[{;](([^;}{][^;}{]*)|[}])\").matcher(\n\t\t\t\tdataArray);\n\t\tString prevString = \"\";\n\t\tString curString = \"\";\n\t\tString path = \"\";\n\t\tboolean valuePosition = false;\n\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group().substring(1);\n\t\t\tif (match.length() == 0) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (match.charAt(0) == 's') {\n\t\t\t\tvaluePosition = !valuePosition && !\"\".equals(prevString);\n\t\t\t\tcurString = match.substring(match.indexOf('\"') + 1,\n\t\t\t\t\t\tmatch.length() - 2);\n\t\t\t} else if (match.charAt(0) == 'a') {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path + \"/\" + prevString;\n\t\t\t} else if (\"}\".equals(match)) {\n\t\t\t\tvaluePosition = false;\n\t\t\t\tpath = path.substring(0, path.lastIndexOf('/'));\n\t\t\t}\n\n\t\t\tif (valuePosition && \"file_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tfilePath = curString;\n\t\t\t} else if (valuePosition && \"page_path\".equals(prevString)\n\t\t\t\t\t&& \"/paths\".equals(path)) {\n\t\t\t\tpagePath = curString;\n\t\t\t}\n\n\t\t\tprevString = curString;\n\t\t\tcurString = \"\";\n\t\t}\n\n\t\tMwSitesDumpFileProcessor.logger.debug(\"Found site data \\\"\" + row[1]\n\t\t\t\t+ \"\\\" (group \\\"\" + row[3] + \"\\\", language \\\"\" + row[5]\n\t\t\t\t+ \"\\\", type \\\"\" + row[2] + \"\\\")\");\n\t\tthis.sites.setSiteInformation(row[1], row[3], row[5], row[2], filePath,\n\t\t\t\tpagePath);\n\t}"
] | [
"private void recordMount(SlotReference slot) {\n if (mediaMounts.add(slot)) {\n deliverMountUpdate(slot, true);\n }\n if (!mediaDetails.containsKey(slot)) {\n try {\n VirtualCdj.getInstance().sendMediaQuery(slot);\n } catch (Exception e) {\n logger.warn(\"Problem trying to request media details for \" + slot, e);\n }\n }\n }",
"public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException {\n\t\tlog.debug(\"clipTile before {}\", tile);\n\t\tList<InternalFeature> orgFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tGeometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping.\n\t\tfor (InternalFeature feature : orgFeatures) {\n\t\t\t// clip feature if necessary\n\t\t\tif (exceedsScreenDimensions(feature, scale)) {\n\t\t\t\tlog.debug(\"feature {} exceeds screen dimensions\", feature);\n\t\t\t\tInternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone();\n\t\t\t\ttile.setClipped(true);\n\t\t\t\tvectorFeature.setClipped(true);\n\t\t\t\tif (null == maxScreenBbox) {\n\t\t\t\t\tmaxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin));\n\t\t\t\t}\n\t\t\t\tGeometry clipped = maxScreenBbox.intersection(feature.getGeometry());\n\t\t\t\tvectorFeature.setClippedGeometry(clipped);\n\t\t\t\ttile.addFeature(vectorFeature);\n\t\t\t} else {\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t\tlog.debug(\"clipTile after {}\", tile);\n\t}",
"private static EventEnumType convertEventType(org.talend.esb.sam.common.event.EventTypeEnum eventType) {\n if (eventType == null) {\n return null;\n }\n return EventEnumType.valueOf(eventType.name());\n }",
"public void connect(final String serialPortName)\n\t\t\tthrows SerialInterfaceException {\n\t\tlogger.info(\"Connecting to serial port {}\", serialPortName);\n\t\ttry {\n\t\t\tCommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);\n\t\t\tCommPort commPort = portIdentifier.open(\"org.openhab.binding.zwave\",2000);\n\t\t\tthis.serialPort = (SerialPort) commPort;\n\t\t\tthis.serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);\n\t\t\tthis.serialPort.enableReceiveThreshold(1);\n\t\t\tthis.serialPort.enableReceiveTimeout(ZWAVE_RECEIVE_TIMEOUT);\n\t\t\tthis.receiveThread = new ZWaveReceiveThread();\n\t\t\tthis.receiveThread.start();\n\t\t\tthis.sendThread = new ZWaveSendThread();\n\t\t\tthis.sendThread.start();\n\n\t\t\tlogger.info(\"Serial port is initialized\");\n\t\t} catch (NoSuchPortException e) {\n\t\t\tlogger.error(e.getLocalizedMessage());\n\t\t\tthrow new SerialInterfaceException(e.getLocalizedMessage(), e);\n\t\t} catch (PortInUseException e) {\n\t\t\tlogger.error(e.getLocalizedMessage());\n\t\t\tthrow new SerialInterfaceException(e.getLocalizedMessage(), e);\n\t\t} catch (UnsupportedCommOperationException e) {\n\t\t\tlogger.error(e.getLocalizedMessage());\n\t\t\tthrow new SerialInterfaceException(e.getLocalizedMessage(), e);\n\t\t}\n\t}",
"public static base_response add(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile addresource = new autoscaleprofile();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.url = resource.url;\n\t\taddresource.apikey = resource.apikey;\n\t\taddresource.sharedsecret = resource.sharedsecret;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static String readFlowId(Message message) {\n String flowId = null;\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n List<String> flowIds = headers.get(FLOWID_HTTP_HEADER_NAME);\n if (flowIds != null && flowIds.size() > 0) {\n flowId = flowIds.get(0);\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' found: \" + flowId);\n }\n } else {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' found\");\n }\n }\n\n return flowId;\n }",
"public Method getMethod(Method method) {\n return getMethod(method.getReturnType(), method.getName(), method.getParameterTypes());\n }",
"public String[] getString() {\n String[] valueDestination = new String[ string.size() ];\n this.string.getValue(valueDestination);\n return valueDestination;\n }",
"public static void clearallLocalDBs() {\n for (final Map.Entry<MongoClient, Boolean> entry : localInstances.entrySet()) {\n for (final String dbName : entry.getKey().listDatabaseNames()) {\n entry.getKey().getDatabase(dbName).drop();\n }\n }\n }"
] |
Delete a path recursively, not throwing Exception if it fails or if the path is null.
@param path a Path pointing to a file or a directory that may not exists anymore. | [
"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 }"
] | [
"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 }",
"private static Constructor retrieveCollectionProxyConstructor(Class proxyClass, Class baseType, String typeDesc)\r\n {\r\n if(proxyClass == null)\r\n {\r\n throw new MetadataException(\"No \" + typeDesc + \" specified.\");\r\n }\r\n if(proxyClass.isInterface() || Modifier.isAbstract(proxyClass.getModifiers()) || !baseType.isAssignableFrom(proxyClass))\r\n {\r\n throw new MetadataException(\"Illegal class \"\r\n + proxyClass.getName()\r\n + \" specified for \"\r\n + typeDesc\r\n + \". Must be a concrete subclass of \"\r\n + baseType.getName());\r\n }\r\n\r\n Class[] paramType = {PBKey.class, Class.class, Query.class};\r\n\r\n try\r\n {\r\n return proxyClass.getConstructor(paramType);\r\n }\r\n catch(NoSuchMethodException ex)\r\n {\r\n throw new MetadataException(\"The class \"\r\n + proxyClass.getName()\r\n + \" specified for \"\r\n + typeDesc\r\n + \" is required to have a public constructor with signature (\"\r\n + PBKey.class.getName()\r\n + \", \"\r\n + Class.class.getName()\r\n + \", \"\r\n + Query.class.getName()\r\n + \").\");\r\n }\r\n }",
"public double getProgressFromResponse(ResponseOnSingeRequest myResponse) {\n\n double progress = 0.0;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return progress;\n }\n\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(progressRegex);\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n String progressStr = matcher.group(1);\n progress = Double.parseDouble(progressStr);\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n\n return progress;\n }",
"public String printHelp(String commandName) {\n int maxLength = 0;\n int width = 80;\n List<ProcessedOption> opts = getOptions();\n for (ProcessedOption o : opts) {\n if(o.getFormattedLength() > maxLength)\n maxLength = o.getFormattedLength();\n }\n\n StringBuilder sb = new StringBuilder();\n //first line\n sb.append(\"Usage: \");\n if(commandName == null || commandName.length() == 0)\n sb.append(name());\n else\n sb.append(commandName);\n if(opts.size() > 0)\n sb.append(\" [<options>]\");\n\n if(argument != null) {\n if(argument.isTypeAssignableByResourcesOrFile())\n sb.append(\" <file>\");\n else\n sb.append(\" <\").append(argument.getFieldName()).append(\">\");\n }\n\n if(arguments != null) {\n if(arguments.isTypeAssignableByResourcesOrFile())\n sb.append(\" [<files>]\");\n else\n sb.append(\" [<\").append(arguments.getFieldName()).append(\">]\");\n }\n sb.append(Config.getLineSeparator());\n //second line\n sb.append(description()).append(Config.getLineSeparator());\n\n //options and arguments\n if (opts.size() > 0)\n sb.append(Config.getLineSeparator()).append(\"Options:\").append(Config.getLineSeparator());\n for (ProcessedOption o : opts)\n sb.append(o.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator());\n if(arguments != null) {\n sb.append(Config.getLineSeparator()).append(\"Arguments:\").append(Config.getLineSeparator());\n sb.append(arguments.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator());\n }\n if(argument != null) {\n sb.append(Config.getLineSeparator()).append(\"Argument:\").append(Config.getLineSeparator());\n sb.append(argument.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator());\n }\n return sb.toString();\n }",
"public static ipseccounters_stats get(nitro_service service) throws Exception{\n\t\tipseccounters_stats obj = new ipseccounters_stats();\n\t\tipseccounters_stats[] response = (ipseccounters_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public PhotoList<Photo> search(SearchParameters params, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SEARCH);\r\n\r\n parameters.putAll(params.getAsParameters());\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }",
"public void setBean(String name, Object object) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\tbean = new Bean();\n\t\t\tbeans.put(name, bean);\n\t\t}\n\t\tbean.object = object;\n\t}",
"public String getKeyValue(String key){\n String keyName = keysMap.get(key);\n if (keyName != null){\n return keyName;\n }\n return \"\"; //key wasn't defined in keys properties file\n }"
] |
Attempts to clear the global log context used for embedded servers. | [
"static synchronized void clearLogContext() {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n // Remove the configurator and clear the log context\n final Configurator configurator = embeddedLogContext.getLogger(\"\").detach(Configurator.ATTACHMENT_KEY);\n // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext\n if (configurator instanceof PropertyConfigurator) {\n final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();\n clearLogContext(logContextConfiguration);\n } else if (configurator instanceof LogContextConfiguration) {\n clearLogContext((LogContextConfiguration) configurator);\n } else {\n // Remove all the handlers and close them as well as reset the loggers\n final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());\n for (String name : loggerNames) {\n final Logger logger = embeddedLogContext.getLoggerIfExists(name);\n if (logger != null) {\n final Handler[] handlers = logger.clearHandlers();\n if (handlers != null) {\n for (Handler handler : handlers) {\n handler.close();\n }\n }\n logger.setFilter(null);\n logger.setUseParentFilters(false);\n logger.setUseParentHandlers(true);\n logger.setLevel(Level.INFO);\n }\n }\n }\n }"
] | [
"public void updateAnimation()\n {\n Date time = new Date();\n long currentTime = time.getTime() - this.beginAnimation;\n if (currentTime > animationTime)\n {\n this.currentQuaternion.set(endQuaternion);\n for (int i = 0; i < 3; i++)\n {\n\n this.currentPos[i] = this.endPos[i];\n }\n this.animate = false;\n }\n\n else\n {\n float t = (float) currentTime / animationTime;\n this.currentQuaternion = this.beginQuaternion.slerp(this.endQuaternion,\n t);\n for (int i = 0; i < 3; i++)\n {\n this.currentPos[i] = this.beginPos[i] + totalTranslation[i] * t;\n }\n\n }\n }",
"public List<BoxComment.Info> getComments() {\n URL url = GET_COMMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxComment.Info> comments = new ArrayList<BoxComment.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject commentJSON = value.asObject();\n BoxComment comment = new BoxComment(this.getAPI(), commentJSON.get(\"id\").asString());\n BoxComment.Info info = comment.new Info(commentJSON);\n comments.add(info);\n }\n\n return comments;\n }",
"public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) {\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size());\n for(Integer serverId: serverIds) {\n clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue));\n }\n return new VectorClock(clockEntries, timestamp);\n }",
"public void setCanvasWidthHeight(int width, int height) {\n hudWidth = width;\n hudHeight = height;\n HUD = Bitmap.createBitmap(width, height, Config.ARGB_8888);\n canvas = new Canvas(HUD);\n texture = null;\n }",
"protected FluentModelTImpl prepareForFutureCommitOrPostRun(FluentModelTImpl childResource) {\n if (this.isPostRunMode) {\n if (!childResource.taskGroup().dependsOn(this.parentTaskGroup)) {\n this.parentTaskGroup.addPostRunDependentTaskGroup(childResource.taskGroup());\n }\n return childResource;\n } else {\n return childResource;\n }\n }",
"private boolean isWorkingDate(Date date, Day day)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, day);\n return ranges.getRangeCount() != 0;\n }",
"public List<TerminalString> getOptionLongNamesWithDash() {\n List<ProcessedOption> opts = getOptions();\n List<TerminalString> names = new ArrayList<>(opts.size());\n for (ProcessedOption o : opts) {\n if(o.getValues().size() == 0 &&\n o.activator().isActivated(new ParsedCommand(this)))\n names.add(o.getRenderedNameWithDashes());\n }\n\n return names;\n }",
"private boolean isSecuredByPolicy(Server server) {\n boolean isSecured = false;\n\n EndpointInfo ei = server.getEndpoint().getEndpointInfo();\n\n PolicyEngine pe = bus.getExtension(PolicyEngine.class);\n if (null == pe) {\n LOG.finest(\"No Policy engine found\");\n return isSecured;\n }\n\n Destination destination = server.getDestination();\n EndpointPolicy ep = pe.getServerEndpointPolicy(ei, destination, null);\n Collection<Assertion> assertions = ep.getChosenAlternative();\n for (Assertion a : assertions) {\n if (a instanceof TransportBinding) {\n TransportBinding tb = (TransportBinding) a;\n TransportToken tt = tb.getTransportToken();\n AbstractToken t = tt.getToken();\n if (t instanceof HttpsToken) {\n isSecured = true;\n break;\n }\n }\n }\n\n Policy policy = ep.getPolicy();\n List<PolicyComponent> pcList = policy.getPolicyComponents();\n for (PolicyComponent a : pcList) {\n if (a instanceof TransportBinding) {\n TransportBinding tb = (TransportBinding) a;\n TransportToken tt = tb.getTransportToken();\n AbstractToken t = tt.getToken();\n if (t instanceof HttpsToken) {\n isSecured = true;\n break;\n }\n }\n }\n\n return isSecured;\n }",
"public static TagModel getSingleParent(TagModel tag)\n {\n final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator();\n if (!parents.hasNext())\n throw new WindupException(\"Tag is not designated by any tags: \" + tag);\n\n final TagModel maybeOnlyParent = parents.next();\n\n if (parents.hasNext()) {\n StringBuilder sb = new StringBuilder();\n tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(\", \"));\n throw new WindupException(String.format(\"Tag %s is designated by multiple tags: %s\", tag, sb.toString()));\n }\n\n return maybeOnlyParent;\n }"
] |
Returns true if the given document should be included in the
serialization.
@param itemDocument
the document to check
@return true if the document should be serialized | [
"private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}"
] | [
"public void setTextureBufferSize(final int size) {\n mRootViewGroup.post(new Runnable() {\n @Override\n public void run() {\n mRootViewGroup.setTextureBufferSize(size);\n }\n });\n }",
"public BoxStoragePolicy.Info getInfo(String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = STORAGE_POLICY_WITH_ID_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(),\n this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Info(response.getJSON());\n }",
"public static ComplexNumber Multiply(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real * scalar, z1.imaginary * scalar);\r\n }",
"public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static ProctorLoadResult verifyWithoutSpecification(@Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n for (final Entry<String, ConsumableTestDefinition> entry : testMatrix.getTests().entrySet()) {\n final String testName = entry.getKey();\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition);\n } catch (IncompatibleTestMatrixException e) {\n LOGGER.info(String.format(\"Unable to load test matrix for %s\", testName), e);\n resultBuilder.recordError(testName, e);\n }\n }\n return resultBuilder.build();\n }",
"public void ifMemberTagValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n if (isTagValueEqual(attributes, FOR_FIELD)) {\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (isTagValueEqual(attributes, FOR_METHOD)) {\r\n generate(template);\r\n }\r\n }\r\n }",
"public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) {\n\n if (clazz.isPrimitive()) {\n throw new IllegalArgumentException(\"Primitive types not supported.\");\n }\n\n List<Field> result = new ArrayList<Field>();\n\n while (true) {\n\n if (clazz == Object.class) {\n break;\n }\n\n result.addAll(Arrays.asList(clazz.getDeclaredFields()));\n clazz = clazz.getSuperclass();\n }\n\n return result.toArray(new Field[result.size()]);\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 }",
"@Override\n public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deploymentConfig = entities.stream()\n .filter(hm -> hm instanceof DeploymentConfig)\n .map(hm -> (DeploymentConfig) hm)\n .map(dc -> dc.getMetadata().getName()).findFirst();\n\n deploymentConfig.ifPresent(name -> this.applicationName = name);\n }\n }"
] |
Transforms a single configuration file using the given transformation source.
@param file the configuration file
@param transformSource the transform soruce
@throws TransformerConfigurationException -
@throws IOException -
@throws SAXException -
@throws TransformerException -
@throws ParserConfigurationException - | [
"private void transform(File file, Source transformSource)\n throws TransformerConfigurationException, IOException, SAXException, TransformerException,\n ParserConfigurationException {\n\n Transformer transformer = m_transformerFactory.newTransformer(transformSource);\n transformer.setOutputProperty(OutputKeys.ENCODING, \"us-ascii\");\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"4\");\n String configDirPath = m_configDir.getAbsolutePath();\n configDirPath = configDirPath.replaceFirst(\"[/\\\\\\\\]$\", \"\");\n transformer.setParameter(\"configDir\", configDirPath);\n XMLReader reader = m_parserFactory.newSAXParser().getXMLReader();\n reader.setEntityResolver(NO_ENTITY_RESOLVER);\n\n Source source;\n\n if (file.exists()) {\n source = new SAXSource(reader, new InputSource(file.getCanonicalPath()));\n } else {\n source = new SAXSource(reader, new InputSource(new ByteArrayInputStream(DEFAULT_XML.getBytes(\"UTF-8\"))));\n }\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n Result target = new StreamResult(baos);\n transformer.transform(source, target);\n byte[] transformedConfig = baos.toByteArray();\n try (FileOutputStream output = new FileOutputStream(file)) {\n output.write(transformedConfig);\n }\n }"
] | [
"@JavaScriptMethod\n @SuppressWarnings({\"UnusedDeclaration\"})\n public LoadBuildsResponse loadBuild(String buildId) {\n LoadBuildsResponse response = new LoadBuildsResponse();\n // When we load a new build we need also to reset the promotion plugin.\n // The null plugin is related to 'None' plugin.\n setPromotionPlugin(null);\n try {\n this.currentPromotionCandidate = promotionCandidates.get(buildId);\n if (this.currentPromotionCandidate == null) {\n throw new IllegalArgumentException(\"Can't find build by ID: \" + buildId);\n }\n List<String> repositoryKeys = getRepositoryKeys();\n List<UserPluginInfo> plugins = getPromotionsUserPluginInfo();\n PromotionConfig promotionConfig = getPromotionConfig();\n String defaultTargetRepository = getDefaultPromotionTargetRepository();\n if (StringUtils.isNotBlank(defaultTargetRepository) && repositoryKeys.contains(defaultTargetRepository)) {\n promotionConfig.setTargetRepo(defaultTargetRepository);\n }\n response.addRepositories(repositoryKeys);\n response.setPlugins(plugins);\n response.setPromotionConfig(promotionConfig);\n response.setSuccess(true);\n } catch (Exception e) {\n response.setResponseMessage(e.getMessage());\n }\n return response;\n }",
"public void processClass(String template, Properties attributes) throws XDocletException\r\n {\r\n if (!_model.hasClass(getCurrentClass().getQualifiedName()))\r\n {\r\n // we only want to output the log message once\r\n LogHelper.debug(true, OjbTagsHandler.class, \"processClass\", \"Type \"+getCurrentClass().getQualifiedName());\r\n }\r\n\r\n ClassDescriptorDef classDef = ensureClassDef(getCurrentClass());\r\n String attrName;\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n classDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n _curClassDef = classDef;\r\n generate(template);\r\n _curClassDef = null;\r\n }",
"public void setFrustum(float fovy, float aspect, float znear, float zfar)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.perspective((float) Math.toRadians(fovy), aspect, znear, zfar);\n setFrustum(projMatrix);\n }",
"protected void load()\r\n {\r\n // properties file may be set as a System property.\r\n // if no property is set take default name.\r\n String fn = System.getProperty(OJB_PROPERTIES_FILE, OJB_PROPERTIES_FILE);\r\n setFilename(fn);\r\n super.load();\r\n\r\n // default repository & connection descriptor file\r\n repositoryFilename = getString(\"repositoryFile\", OJB_METADATA_FILE);\r\n\r\n // object cache class\r\n objectCacheClass = getClass(\"ObjectCacheClass\", ObjectCacheDefaultImpl.class, ObjectCache.class);\r\n\r\n // load PersistentField Class\r\n persistentFieldClass =\r\n getClass(\"PersistentFieldClass\", PersistentFieldDirectImpl.class, PersistentField.class);\r\n\r\n // load PersistenceBroker Class\r\n persistenceBrokerClass =\r\n getClass(\"PersistenceBrokerClass\", PersistenceBrokerImpl.class, PersistenceBroker.class);\r\n\r\n // load ListProxy Class\r\n listProxyClass = getClass(\"ListProxyClass\", ListProxyDefaultImpl.class);\r\n\r\n // load SetProxy Class\r\n setProxyClass = getClass(\"SetProxyClass\", SetProxyDefaultImpl.class);\r\n\r\n // load CollectionProxy Class\r\n collectionProxyClass = getClass(\"CollectionProxyClass\", CollectionProxyDefaultImpl.class);\r\n\r\n // load IndirectionHandler Class\r\n indirectionHandlerClass =\r\n getClass(\"IndirectionHandlerClass\", IndirectionHandlerJDKImpl.class, IndirectionHandler.class);\r\n \r\n // load ProxyFactory Class\r\n proxyFactoryClass =\r\n getClass(\"ProxyFactoryClass\", ProxyFactoryJDKImpl.class, ProxyFactory.class);\r\n\r\n // load configuration for ImplicitLocking parameter:\r\n useImplicitLocking = getBoolean(\"ImplicitLocking\", false);\r\n\r\n // load configuration for LockAssociations parameter:\r\n lockAssociationAsWrites = (getString(\"LockAssociations\", \"WRITE\").equalsIgnoreCase(\"WRITE\"));\r\n\r\n // load OQL Collection Class\r\n oqlCollectionClass = getClass(\"OqlCollectionClass\", DListImpl.class, ManageableCollection.class);\r\n\r\n // set the limit for IN-sql , -1 for no limits\r\n sqlInLimit = getInteger(\"SqlInLimit\", -1);\r\n\r\n //load configuration for PB pool\r\n maxActive = getInteger(PoolConfiguration.MAX_ACTIVE,\r\n PoolConfiguration.DEFAULT_MAX_ACTIVE);\r\n maxIdle = getInteger(PoolConfiguration.MAX_IDLE,\r\n PoolConfiguration.DEFAULT_MAX_IDLE);\r\n maxWait = getLong(PoolConfiguration.MAX_WAIT,\r\n PoolConfiguration.DEFAULT_MAX_WAIT);\r\n timeBetweenEvictionRunsMillis = getLong(PoolConfiguration.TIME_BETWEEN_EVICTION_RUNS_MILLIS,\r\n PoolConfiguration.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);\r\n minEvictableIdleTimeMillis = getLong(PoolConfiguration.MIN_EVICTABLE_IDLE_TIME_MILLIS,\r\n PoolConfiguration.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);\r\n whenExhaustedAction = getByte(PoolConfiguration.WHEN_EXHAUSTED_ACTION,\r\n PoolConfiguration.DEFAULT_WHEN_EXHAUSTED_ACTION);\r\n\r\n useSerializedRepository = getBoolean(\"useSerializedRepository\", false);\r\n }",
"private Field getFieldRecursive(Class c, String name) throws NoSuchFieldException\r\n {\r\n try\r\n {\r\n return c.getDeclaredField(name);\r\n }\r\n catch (NoSuchFieldException e)\r\n {\r\n // if field could not be found in the inheritance hierarchy, signal error\r\n if ((c == Object.class) || (c.getSuperclass() == null) || c.isInterface())\r\n {\r\n throw e;\r\n }\r\n // if field could not be found in class c try in superclass\r\n else\r\n {\r\n return getFieldRecursive(c.getSuperclass(), name);\r\n }\r\n }\r\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 final static String process(final File file, final Configuration configuration) throws IOException\n {\n final FileInputStream input = new FileInputStream(file);\n final String ret = process(input, configuration);\n input.close();\n return ret;\n }",
"public static base_response delete(nitro_service client, appfwlearningdata resource) throws Exception {\n\t\tappfwlearningdata deleteresource = new appfwlearningdata();\n\t\tdeleteresource.profilename = resource.profilename;\n\t\tdeleteresource.starturl = resource.starturl;\n\t\tdeleteresource.cookieconsistency = resource.cookieconsistency;\n\t\tdeleteresource.fieldconsistency = resource.fieldconsistency;\n\t\tdeleteresource.formactionurl_ffc = resource.formactionurl_ffc;\n\t\tdeleteresource.crosssitescripting = resource.crosssitescripting;\n\t\tdeleteresource.formactionurl_xss = resource.formactionurl_xss;\n\t\tdeleteresource.sqlinjection = resource.sqlinjection;\n\t\tdeleteresource.formactionurl_sql = resource.formactionurl_sql;\n\t\tdeleteresource.fieldformat = resource.fieldformat;\n\t\tdeleteresource.formactionurl_ff = resource.formactionurl_ff;\n\t\tdeleteresource.csrftag = resource.csrftag;\n\t\tdeleteresource.csrfformoriginurl = resource.csrfformoriginurl;\n\t\tdeleteresource.xmldoscheck = resource.xmldoscheck;\n\t\tdeleteresource.xmlwsicheck = resource.xmlwsicheck;\n\t\tdeleteresource.xmlattachmentcheck = resource.xmlattachmentcheck;\n\t\tdeleteresource.totalxmlrequests = resource.totalxmlrequests;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static Set<String> getStoreNamesSet(List<StoreDefinition> storeDefList) {\n HashSet<String> storeSet = new HashSet<String>();\n for(StoreDefinition def: storeDefList) {\n storeSet.add(def.getName());\n }\n return storeSet;\n }"
] |
Updates the position and direction of this light from the transform of
scene object that owns it. | [
"public void onDrawFrame(float frameTime)\n {\n if (!isEnabled() || (owner == null) || (getFloat(\"enabled\") <= 0.0f))\n {\n return;\n }\n float[] odir = getVec3(\"world_direction\");\n float[] opos = getVec3(\"world_position\");\n GVRSceneObject parent = owner;\n Matrix4f worldmtx = parent.getTransform().getModelMatrix4f();\n\n mOldDir.x = odir[0];\n mOldDir.y = odir[1];\n mOldDir.z = odir[2];\n mOldPos.x = opos[0];\n mOldPos.y = opos[1];\n mOldPos.z = opos[2];\n mNewDir.x = 0.0f;\n mNewDir.y = 0.0f;\n mNewDir.z = -1.0f;\n worldmtx.getTranslation(mNewPos);\n worldmtx.mul(mLightRot);\n worldmtx.transformDirection(mNewDir);\n if ((mOldDir.x != mNewDir.x) || (mOldDir.y != mNewDir.y) || (mOldDir.z != mNewDir.z))\n {\n setVec4(\"world_direction\", mNewDir.x, mNewDir.y, mNewDir.z, 0);\n }\n if ((mOldPos.x != mNewPos.x) || (mOldPos.y != mNewPos.y) || (mOldPos.z != mNewPos.z))\n {\n setPosition(mNewPos.x, mNewPos.y, mNewPos.z);\n }\n }"
] | [
"private static String decode(String s) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (ch == '%') {\n baos.write(hexToInt(s.charAt(i + 1)) * 16 + hexToInt(s.charAt(i + 2)));\n i += 2;\n continue;\n }\n baos.write(ch);\n }\n try {\n return new String(baos.toByteArray(), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n }\n }",
"public StringBuilder getSQLCondition(StringBuilder builder, String columnName) {\n\t\tString string = networkString.getString();\n\t\tif(isEntireAddress) {\n\t\t\tmatchString(builder, columnName, string);\n\t\t} else {\n\t\t\tmatchSubString(\n\t\t\t\t\tbuilder,\n\t\t\t\t\tcolumnName,\n\t\t\t\t\tnetworkString.getTrailingSegmentSeparator(),\n\t\t\t\t\tnetworkString.getTrailingSeparatorCount() + 1,\n\t\t\t\t\tstring);\n\t\t}\n\t\treturn builder;\n\t}",
"public boolean isPublisherWrapped(AbstractProject<?, ?> project, Class<T> type) {\n return find(project, type) != null;\n }",
"@Override\n public final boolean has(final String key) {\n String result = this.obj.optString(key, null);\n return result != null;\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> updateClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID,\n @RequestParam(required = false) Boolean active,\n @RequestParam(required = false) String friendlyName,\n @RequestParam(required = false) Boolean reset) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n if (active != null) {\n logger.info(\"Active: {}\", active);\n clientService.updateActive(profileId, clientUUID, active);\n }\n\n if (friendlyName != null) {\n clientService.setFriendlyName(profileId, clientUUID, friendlyName);\n }\n\n if (reset != null && reset) {\n clientService.reset(profileId, clientUUID);\n }\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", clientService.findClient(clientUUID, profileId));\n return valueHash;\n }",
"public static <T> JacksonParser<T> json(Class<T> contentType) {\n return new JacksonParser<>(null, contentType);\n }",
"public Object remove(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null != bean) {\n\t\t\tbeans.remove(name);\n\t\t\tbean.destructionCallback.run();\n\t\t\treturn bean.object;\n\t\t}\n\t\treturn null;\n\t}",
"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 void addNode(NodeT node) {\n node.setOwner(this);\n nodeTable.put(node.key(), node);\n }"
] |
Use this API to reset appfwlearningdata. | [
"public static base_response reset(nitro_service client) throws Exception {\n\t\tappfwlearningdata resetresource = new appfwlearningdata();\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}"
] | [
"@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}",
"public static ipset[] get(nitro_service service) throws Exception{\n\t\tipset obj = new ipset();\n\t\tipset[] response = (ipset[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"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}",
"private String[] getHeaders() {\n final List<String> headers = new ArrayList<>();\n\n if(decorator.getShowSources()){\n headers.add(SOURCE_FIELD);\n }\n\n if(decorator.getShowSourcesVersion()){\n headers.add(SOURCE_VERSION_FIELD);\n }\n\n if(decorator.getShowTargets()){\n headers.add(TARGET_FIELD);\n }\n\n if(decorator.getShowTargetsDownloadUrl()){\n headers.add(DOWNLOAD_URL_FIELD);\n }\n\n if(decorator.getShowTargetsSize()){\n headers.add(SIZE_FIELD);\n }\n\n if(decorator.getShowScopes()){\n headers.add(SCOPE_FIELD);\n }\n\n if(decorator.getShowLicenses()){\n headers.add(LICENSE_FIELD);\n }\n\n if(decorator.getShowLicensesLongName()){\n headers.add(LICENSE_LONG_NAME_FIELD);\n }\n\n if(decorator.getShowLicensesUrl()){\n headers.add(LICENSE_URL_FIELD);\n }\n\n if(decorator.getShowLicensesComment()){\n headers.add(LICENSE_COMMENT_FIELD);\n }\n\n return headers.toArray(new String[headers.size()]);\n }",
"@OnClick(R.id.navigateToModule1Service)\n public void onNavigationServiceCTAClick() {\n Intent intentService = HensonNavigator.gotoModule1Service(this)\n .stringExtra(\"foo\")\n .build();\n\n startService(intentService);\n }",
"public void close() {\n Iterator<SocketDestination> it = getStatsMap().keySet().iterator();\n while(it.hasNext()) {\n try {\n SocketDestination destination = it.next();\n JmxUtils.unregisterMbean(JmxUtils.createObjectName(JmxUtils.getPackageName(ClientRequestExecutor.class),\n \"stats_\"\n + destination.toString()\n .replace(':',\n '_')\n + identifierString));\n } catch(Exception e) {}\n }\n }",
"public ConfigurableMessages getConfigurableMessages(CmsMessages defaultMessages, Locale locale) {\n\n return new ConfigurableMessages(defaultMessages, locale, m_configuredBundle);\n\n }",
"public void search(String query) {\n final Query newQuery = searcher.getQuery().setQuery(query);\n searcher.setQuery(newQuery).search();\n }",
"public int[] sampleBatchWithReplacement() {\n // Sample the indices with replacement.\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n batch[i] = Prng.nextInt(numExamples);\n }\n return batch;\n }"
] |
Read data for a single column.
@param startIndex block start
@param length block length | [
"private void readColumn(int startIndex, int length) throws Exception\n {\n if (m_currentTable != null)\n {\n int value = FastTrackUtility.getByte(m_buffer, startIndex);\n Class<?> klass = COLUMN_MAP[value];\n if (klass == null)\n {\n klass = UnknownColumn.class;\n }\n\n FastTrackColumn column = (FastTrackColumn) klass.newInstance();\n m_currentColumn = column;\n\n logColumnData(startIndex, length);\n\n column.read(m_currentTable.getType(), m_buffer, startIndex, length);\n FastTrackField type = column.getType();\n\n //\n // Don't try to add this data if:\n // 1. We don't know what type it is\n // 2. We have seen the type already\n //\n if (type != null && !m_currentFields.contains(type))\n {\n m_currentFields.add(type);\n m_currentTable.addColumn(column);\n updateDurationTimeUnit(column);\n updateWorkTimeUnit(column);\n\n logColumn(column);\n }\n }\n }"
] | [
"private void checkDuplicateStdOutOutput(DumpProcessingAction newAction) {\n\t\tif (newAction.useStdOut()) {\n\t\t\tif (this.quiet) {\n\t\t\t\tlogger.warn(\"Multiple actions are using stdout as output destination.\");\n\t\t\t}\n\t\t\tthis.quiet = true;\n\t\t}\n\t}",
"public static byte[] copy(byte[] array, int from, int to) {\n if(to - from < 0) {\n return new byte[0];\n } else {\n byte[] a = new byte[to - from];\n System.arraycopy(array, from, a, 0, to - from);\n return a;\n }\n }",
"public Map<String, CmsCategory> getReadCategory() {\n\n if (null == m_categories) {\n m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object categoryPath) {\n\n try {\n CmsCategoryService catService = CmsCategoryService.getInstance();\n return catService.localizeCategory(\n m_cms,\n catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()),\n m_cms.getRequestContext().getLocale());\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n\n });\n }\n return m_categories;\n }",
"public GeoPolygon addHoles(List<List<GeoPoint>> holes) {\n\t\tContracts.assertNotNull( holes, \"holes\" );\n\t\tthis.rings.addAll( holes );\n\t\treturn this;\n\t}",
"protected void processLabels(List<MonolingualTextValue> labels) {\n for(MonolingualTextValue label : labels) {\n \tString lang = label.getLanguageCode();\n \tNameWithUpdate currentValue = newLabels.get(lang);\n \tif (currentValue == null || !currentValue.value.equals(label)) {\n\t newLabels.put(lang,\n\t new NameWithUpdate(label, true));\n\t \n\t // Delete any alias that matches the new label\n\t AliasesWithUpdate currentAliases = newAliases.get(lang);\n\t if (currentAliases != null && currentAliases.aliases.contains(label)) {\n\t \tdeleteAlias(label);\n\t }\n \t}\n }\n \n }",
"public static <T> void injectEEFields(Iterable<Set<ResourceInjection<?>>> resourceInjectionsHierarchy,\n T beanInstance, CreationalContext<T> ctx) {\n for (Set<ResourceInjection<?>> resourceInjections : resourceInjectionsHierarchy) {\n for (ResourceInjection<?> resourceInjection : resourceInjections) {\n resourceInjection.injectResourceReference(beanInstance, ctx);\n }\n }\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 boolean hasValue(String fieldName) {\n\t\treturn resultMap.containsKey(fieldName) && resultMap.get(fieldName) != null;\n\t}",
"public static base_response unset(nitro_service client, sslcertkey resource, String[] args) throws Exception{\n\t\tsslcertkey unsetresource = new sslcertkey();\n\t\tunsetresource.certkey = resource.certkey;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] |
Serializes the given object in JSON and returns the resulting string. In
case of errors, null is returned. In particular, this happens if the
object is not based on a Jackson-annotated class. An error is logged in
this case.
@param object
object to serialize
@return JSON serialization or null | [
"protected static String jacksonObjectToString(Object object) {\n\t\ttry {\n\t\t\treturn mapper.writeValueAsString(object);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tlogger.error(\"Failed to serialize JSON data: \" + e.toString());\n\t\t\treturn null;\n\t\t}\n\t}"
] | [
"public static appfwpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_stats response = (appfwpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"private String escapeQuotes(String value)\n {\n StringBuilder sb = new StringBuilder();\n int length = value.length();\n char c;\n\n sb.append('\"');\n for (int index = 0; index < length; index++)\n {\n c = value.charAt(index);\n sb.append(c);\n\n if (c == '\"')\n {\n sb.append('\"');\n }\n }\n sb.append('\"');\n\n return (sb.toString());\n }",
"public static appflowpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_binding obj = new appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_binding response = (appflowpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private Integer getFrequency(Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n Integer period = NumberHelper.getInteger(exception.getPeriod());\n if (period == null)\n {\n period = Integer.valueOf(1);\n }\n return period;\n }",
"protected void sendEvent(final T event) {\n if (isStatic) {\n sendEvent(event, null, null);\n } else {\n CreationalContext<X> creationalContext = null;\n try {\n Object receiver = getReceiverIfExists(null);\n if (receiver == null && reception != Reception.IF_EXISTS) {\n // creational context is created only if we need it for obtaining receiver\n // ObserverInvocationStrategy takes care of creating CC for parameters, if needed\n creationalContext = beanManager.createCreationalContext(declaringBean);\n receiver = getReceiverIfExists(creationalContext);\n }\n if (receiver != null) {\n sendEvent(event, receiver, creationalContext);\n }\n } finally {\n if (creationalContext != null) {\n creationalContext.release();\n }\n }\n }\n }",
"public void sendMessageToAgents(String[] agent_name, String msgtype,\n Object message_content, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }",
"public static lbvserver_scpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_scpolicy_binding obj = new lbvserver_scpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_scpolicy_binding response[] = (lbvserver_scpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public boolean removeAll(Collection<?> collection) {\n boolean result = false;\n synchronized (mLock) {\n Iterator<?> it;\n if (mOriginalValues != null) {\n it = mOriginalValues.iterator();\n\n } else {\n it = mObjects.iterator();\n }\n while (it.hasNext()) {\n if (collection.contains(it.next())) {\n it.remove();\n result = true;\n }\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n return result;\n }",
"public Request option(String key, Object value) {\n this.options.put(key, value);\n return this;\n }"
] |
Update the plane based on arcore best knowledge of the world
@param scale | [
"protected void update(float scale) {\n GVRSceneObject owner = getOwnerObject();\n if (isEnabled() && (owner != null) && owner.isEnabled())\n {\n float w = getWidth();\n float h = getHeight();\n mPose.update(mARPlane.getCenterPose(), scale);\n Matrix4f m = new Matrix4f();\n m.set(mPose.getPoseMatrix());\n m.scaleLocal(w * 0.95f, h * 0.95f, 1.0f);\n owner.getTransform().setModelMatrix(m);\n }\n }"
] | [
"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 }",
"public static BatchASTFuture analyze(final BatchASTListener listener, final WildcardImportResolver importResolver,\n final Set<String> libraryPaths,\n final Set<String> sourcePaths, Set<Path> sourceFiles)\n {\n\n final String[] encodings = null;\n final String[] bindingKeys = new String[0];\n final ExecutorService executor = WindupExecutors.newFixedThreadPool(WindupExecutors.getDefaultThreadCount());\n final FileASTRequestor requestor = new FileASTRequestor()\n {\n @Override\n public void acceptAST(String sourcePath, CompilationUnit ast)\n {\n try\n {\n /*\n * This super() call doesn't do anything, but we call it just to be nice, in case that ever changes.\n */\n super.acceptAST(sourcePath, ast);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, ast, sourcePath);\n ast.accept(visitor);\n listener.processed(Paths.get(sourcePath), visitor.getJavaClassReferences());\n }\n catch (WindupStopException ex)\n {\n throw ex;\n }\n catch (Throwable t)\n {\n listener.failed(Paths.get(sourcePath), t);\n }\n }\n };\n\n List<List<String>> batches = createBatches(sourceFiles);\n\n for (final List<String> batch : batches)\n {\n executor.submit(new Callable<Void>()\n {\n @Override\n public Void call() throws Exception\n {\n ASTParser parser = ASTParser.newParser(AST.JLS8);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map<String, String> options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n // these options seem to slightly reduce the number of times that JDT aborts on compilation errors\n options.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, \"warning\");\n options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, \"ignore\");\n options.put(JavaCore.COMPILER_PB_NULL_ANNOTATION_INFERENCE_CONFLICT, \"warning\");\n options.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, \"warning\");\n\n parser.setCompilerOptions(options);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]),\n sourcePaths.toArray(new String[sourcePaths.size()]),\n null,\n true);\n\n parser.createASTs(batch.toArray(new String[batch.size()]), encodings, bindingKeys, requestor, null);\n return null;\n }\n });\n }\n\n executor.shutdown();\n\n return new BatchASTFuture()\n {\n @Override\n public boolean isDone()\n {\n return executor.isTerminated();\n }\n };\n }",
"public static int getMpxField(int value)\n {\n int result = 0;\n\n if (value >= 0 && value < MPXJ_MPX_ARRAY.length)\n {\n result = MPXJ_MPX_ARRAY[value];\n }\n return (result);\n }",
"public static Key toKey(RowColumn rc) {\n if ((rc == null) || (rc.getRow().equals(Bytes.EMPTY))) {\n return null;\n }\n Text row = ByteUtil.toText(rc.getRow());\n if ((rc.getColumn().equals(Column.EMPTY)) || !rc.getColumn().isFamilySet()) {\n return new Key(row);\n }\n Text cf = ByteUtil.toText(rc.getColumn().getFamily());\n if (!rc.getColumn().isQualifierSet()) {\n return new Key(row, cf);\n }\n Text cq = ByteUtil.toText(rc.getColumn().getQualifier());\n if (!rc.getColumn().isVisibilitySet()) {\n return new Key(row, cf, cq);\n }\n Text cv = ByteUtil.toText(rc.getColumn().getVisibility());\n return new Key(row, cf, cq, cv);\n }",
"public static String printUUID(UUID guid)\n {\n return guid == null ? null : \"{\" + guid.toString().toUpperCase() + \"}\";\n }",
"public List<String> deviceTypes() {\n Integer count = json().size(DEVICE_FAMILIES);\n List<String> deviceTypes = new ArrayList<String>(count);\n for(int i = 0 ; i < count ; i++) {\n String familyNumber = json().stringValue(DEVICE_FAMILIES, i);\n if(familyNumber.equals(\"1\")) deviceTypes.add(\"iPhone\");\n if(familyNumber.equals(\"2\")) deviceTypes.add(\"iPad\");\n }\n return deviceTypes;\n }",
"public MACAddress toEUI64(boolean asMAC) {\r\n\t\tif(!isExtended()) {//getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT\r\n\t\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\t\tMACAddressSegment segs[] = creator.createSegmentArray(EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT);\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tsection.getSegments(0, 3, segs, 0);\r\n\t\t\tMACAddressSegment ffSegment = creator.createSegment(0xff);\r\n\t\t\tsegs[3] = ffSegment;\r\n\t\t\tsegs[4] = asMAC ? ffSegment : creator.createSegment(0xfe);\r\n\t\t\tsection.getSegments(3, 6, segs, 5);\r\n\t\t\tInteger prefLength = getPrefixLength();\r\n\t\t\tif(prefLength != null) {\r\n\t\t\t\tMACAddressSection resultSection = creator.createSectionInternal(segs, true);\r\n\t\t\t\tif(prefLength >= 24) {\r\n\t\t\t\t\tprefLength += MACAddress.BITS_PER_SEGMENT << 1; //two segments\r\n\t\t\t\t}\r\n\t\t\t\tresultSection.assignPrefixLength(prefLength);\r\n\t\t\t}\r\n\t\t\treturn creator.createAddressInternal(segs);\r\n\t\t} else {\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tMACAddressSegment seg3 = section.getSegment(3);\r\n\t\t\tMACAddressSegment seg4 = section.getSegment(4);\r\n\t\t\tif(seg3.matches(0xff) && seg4.matches(asMAC ? 0xff : 0xfe)) {\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new IncompatibleAddressException(this, \"ipaddress.mac.error.not.eui.convertible\");\r\n\t}",
"private void showSettingsMenu(final Cursor cursor) {\n Log.d(TAG, \"showSettingsMenu\");\n enableSettingsCursor(cursor);\n context.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n new SettingsView(context, scene, CursorManager.this,\n settingsCursor.getIoDevice().getCursorControllerId(), cursor, new\n SettingsChangeListener() {\n @Override\n public void onBack(boolean cascading) {\n disableSettingsCursor();\n }\n\n @Override\n public int onDeviceChanged(IoDevice device) {\n // we are changing the io device on the settings cursor\n removeCursorFromScene(settingsCursor);\n IoDevice clickedDevice = getAvailableIoDevice(device);\n settingsCursor.setIoDevice(clickedDevice);\n addCursorToScene(settingsCursor);\n return device.getCursorControllerId();\n }\n });\n }\n });\n }",
"public List<Integer> getConnectionRetries() {\n List<Integer> items = new ArrayList<Integer>();\n for (int i = 0; i < 10; i++) {\n items.add(i);\n }\n return items;\n }"
] |
Adds the given value to the list of values that should still be
serialized. The given RDF resource will be used as a subject.
@param value
the value to be serialized
@param resource
the RDF resource that is used as a subject for serialization | [
"void addValue(V value, Resource resource) {\n\t\tthis.valueQueue.add(value);\n\t\tthis.valueSubjectQueue.add(resource);\n\t}"
] | [
"private void flushOutput() throws IOException {\n outStream.flush();\n outWriter.completeLine();\n errStream.flush();\n errWriter.completeLine();\n }",
"public synchronized void removeControlPoint(ControlPoint controlPoint) {\n if (controlPoint.decreaseReferenceCount() == 0) {\n ControlPointIdentifier id = new ControlPointIdentifier(controlPoint.getDeployment(), controlPoint.getEntryPoint());\n entryPoints.remove(id);\n }\n }",
"public ArrayList<Duration> segmentBaselineWork(ProjectFile file, List<TimephasedWork> work, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n return segmentWork(file.getBaselineCalendar(), work, rangeUnits, dateList);\n }",
"public void updateIteratorPosition(int length) {\n if(length > 0) {\n //make sure we dont go OB\n if((length + character) > parsedLine.line().length())\n length = parsedLine.line().length() - character;\n\n //move word counter to the correct word\n while(hasNextWord() &&\n (length + character) >= parsedLine.words().get(word).lineIndex() +\n parsedLine.words().get(word).word().length())\n word++;\n\n character = length + character;\n }\n else\n throw new IllegalArgumentException(\"The length given must be > 0 and not exceed the boundary of the line (including the current position)\");\n }",
"private PersistentResourceXMLDescription getSimpleMapperParser() {\n if (version.equals(Version.VERSION_1_0)) {\n return simpleMapperParser_1_0;\n } else if (version.equals(Version.VERSION_1_1)) {\n return simpleMapperParser_1_1;\n }\n return simpleMapperParser;\n }",
"int query(int downloadId) {\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tfor (DownloadRequest request : mCurrentRequests) {\n\t\t\t\tif (request.getDownloadId() == downloadId) {\n\t\t\t\t\treturn request.getDownloadState();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn DownloadManager.STATUS_NOT_FOUND;\n\t}",
"public static void fire(I_CmsHasDateBoxEventHandlers source, Date date, boolean isTyping) {\n\n if (TYPE != null) {\n CmsDateBoxEvent event = new CmsDateBoxEvent(date, isTyping);\n source.fireEvent(event);\n }\n }",
"public static base_response update(nitro_service client, ipv6 resource) throws Exception {\n\t\tipv6 updateresource = new ipv6();\n\t\tupdateresource.ralearning = resource.ralearning;\n\t\tupdateresource.routerredirection = resource.routerredirection;\n\t\tupdateresource.ndbasereachtime = resource.ndbasereachtime;\n\t\tupdateresource.ndretransmissiontime = resource.ndretransmissiontime;\n\t\tupdateresource.natprefix = resource.natprefix;\n\t\tupdateresource.dodad = resource.dodad;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private ProjectFile readProjectFile(ProjectReader reader, InputStream stream) throws MPXJException\n {\n addListeners(reader);\n return reader.read(stream);\n }"
] |
Utility method used to convert an integer time representation into a
Duration instance.
@param totalTime integer time representation
@param format required time format
@return new Duration instance | [
"private Duration convertFormat(long totalTime, TimeUnit format)\n {\n double duration = totalTime;\n\n switch (format)\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n duration /= (60 * 1000);\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n duration /= (60 * 60 * 1000);\n break;\n }\n\n case DAYS:\n {\n double minutesPerDay = getMinutesPerDay();\n if (minutesPerDay != 0)\n {\n duration /= (minutesPerDay * 60 * 1000);\n }\n else\n {\n duration = 0;\n }\n break;\n }\n\n case WEEKS:\n {\n double minutesPerWeek = getMinutesPerWeek();\n if (minutesPerWeek != 0)\n {\n duration /= (minutesPerWeek * 60 * 1000);\n }\n else\n {\n duration = 0;\n }\n break;\n }\n\n case MONTHS:\n {\n double daysPerMonth = getParentFile().getProjectProperties().getDaysPerMonth().doubleValue();\n double minutesPerDay = getMinutesPerDay();\n if (daysPerMonth != 0 && minutesPerDay != 0)\n {\n duration /= (daysPerMonth * minutesPerDay * 60 * 1000);\n }\n else\n {\n duration = 0;\n }\n break;\n }\n\n case ELAPSED_DAYS:\n {\n duration /= (24 * 60 * 60 * 1000);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n duration /= (7 * 24 * 60 * 60 * 1000);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n duration /= (30 * 24 * 60 * 60 * 1000);\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"TimeUnit \" + format + \" not supported\");\n }\n }\n\n return (Duration.getInstance(duration, format));\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 static Method getSetterPropertyMethod(Class<?> type,\r\n\t\t\tString propertyName) {\r\n\t\tString sourceMethodName = \"set\"\r\n\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\r\n\t\tMethod sourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\r\n\t\treturn sourceMethod;\r\n\t}",
"protected void runStatements(Reader reader, PrintStream out)\n throws IOException {\n log.debug(\"runStatements()\");\n StringBuilder txt = new StringBuilder();\n String line = \"\";\n BufferedReader in = new BufferedReader(reader);\n\n while ((line = in.readLine()) != null) {\n line = getProject().replaceProperties(line);\n if (line.indexOf(\"--\") >= 0) {\n txt.append(\"\\n\");\n }\n }\n // Catch any statements not followed by ;\n if (!txt.toString().equals(\"\")) {\n execGroovy(txt.toString(), out);\n }\n }",
"public static final char getChar(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return (bundle.getString(key).charAt(0));\n }",
"private String[] getColumnNames(ResultSetMetaData rsmd) throws Exception {\n ArrayList<String> names = new ArrayList<String>();\n\n // Get result set meta data\n int numColumns = rsmd.getColumnCount();\n\n // Get the column names; column indices start from 1\n for (int i = 1; i < numColumns + 1; i++) {\n String columnName = rsmd.getColumnName(i);\n\n names.add(columnName);\n }\n\n return names.toArray(new String[0]);\n }",
"public byte[] getPacketBytes() {\n byte[] result = new byte[packetBytes.length];\n System.arraycopy(packetBytes, 0, result, 0, packetBytes.length);\n return result;\n }",
"public static String fileNameClean(String s) {\r\n char[] chars = s.toCharArray();\r\n StringBuilder sb = new StringBuilder();\r\n for (char c : chars) {\r\n if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_')) {\r\n sb.append(c);\r\n } else {\r\n if (c == ' ' || c == '-') {\r\n sb.append('_');\r\n } else {\r\n sb.append('x').append((int) c).append('x');\r\n }\r\n }\r\n }\r\n return sb.toString();\r\n }",
"public ArrayList<IntPoint> process(ImageSource fastBitmap) {\r\n //FastBitmap l = new FastBitmap(fastBitmap);\r\n if (points == null) {\r\n apply(fastBitmap);\r\n }\r\n\r\n int width = fastBitmap.getWidth();\r\n int height = fastBitmap.getHeight();\r\n points = new ArrayList<IntPoint>();\r\n\r\n if (fastBitmap.isGrayscale()) {\r\n for (int x = 0; x < height; x++) {\r\n for (int y = 0; y < width; y++) {\r\n if (fastBitmap.getRGB(y, x) == 255) points.add(new IntPoint(y, x));\r\n }\r\n }\r\n } else {\r\n for (int x = 0; x < height; x++) {\r\n for (int y = 0; y < width; y++) {\r\n // TODO Check for green and blue?\r\n if (fastBitmap.getR(y, x) == 255) points.add(new IntPoint(y, x));\r\n }\r\n }\r\n }\r\n\r\n return points;\r\n }",
"public static ActorSystem createAndGetActorSystem() {\n if (actorSystem == null || actorSystem.isTerminated()) {\n actorSystem = ActorSystem.create(PcConstants.ACTOR_SYSTEM, conf);\n }\n return actorSystem;\n }"
] |
Bessel function of the first kind, of order n.
@param n Order.
@param x Value.
@return I value. | [
"public static double I(int n, double x) {\r\n if (n < 0)\r\n throw new IllegalArgumentException(\"the variable n out of range.\");\r\n else if (n == 0)\r\n return I0(x);\r\n else if (n == 1)\r\n return I(x);\r\n\r\n if (x == 0.0)\r\n return 0.0;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n double tox = 2.0 / Math.abs(x);\r\n double bip = 0, ans = 0.0;\r\n double bi = 1.0;\r\n\r\n for (int j = 2 * (n + (int) Math.sqrt(ACC * n)); j > 0; j--) {\r\n double bim = bip + j * tox * bi;\r\n bip = bi;\r\n bi = bim;\r\n\r\n if (Math.abs(bi) > BIGNO) {\r\n ans *= BIGNI;\r\n bi *= BIGNI;\r\n bip *= BIGNI;\r\n }\r\n\r\n if (j == n)\r\n ans = bip;\r\n }\r\n\r\n ans *= I0(x) / bi;\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }"
] | [
"private 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 }",
"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 final boolean getBool(final String key) {\n Boolean result = optBool(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"protected Map<String, String> getGalleryOpenParams(\n CmsObject cms,\n CmsMessages messages,\n I_CmsWidgetParameter param,\n String resource,\n long hashId) {\n\n Map<String, String> result = new HashMap<String, String>();\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_MODE, A_CmsAjaxGallery.MODE_WIDGET);\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_STORAGE_PREFIX, getGalleryStoragePrefix());\n result.put(I_CmsGalleryProviderConstants.CONFIG_RESOURCE_TYPES, getGalleryTypes());\n if (param.getId() != null) {\n result.put(I_CmsGalleryProviderConstants.KEY_FIELD_ID, param.getId());\n // use javascript to read the current field value\n result.put(\n I_CmsGalleryProviderConstants.CONFIG_CURRENT_ELEMENT,\n \"'+document.getElementById('\" + param.getId() + \"').getAttribute('value')+'\");\n }\n result.put(I_CmsGalleryProviderConstants.KEY_HASH_ID, \"\" + hashId);\n // the edited resource\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(resource)) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_REFERENCE_PATH, resource);\n }\n // the start up gallery path\n CmsGalleryWidgetConfiguration configuration = getWidgetConfiguration(cms, messages, param);\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getStartup())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_PATH, configuration.getStartup());\n }\n // set gallery types if available\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getGalleryTypes())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_TYPES, configuration.getGalleryTypes());\n }\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_NAME, getGalleryName());\n return result;\n }",
"private void initEditorStates() {\n\n m_editorState = new HashMap<CmsMessageBundleEditorTypes.EditMode, EditorState>();\n List<TableProperty> cols = null;\n switch (m_bundleType) {\n case PROPERTY:\n case XML:\n if (hasDescriptor()) { // bundle descriptor is present, keys are not editable in default mode, maybe master mode is available\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, getDefaultState());\n if (hasMasterMode()) { // the bundle descriptor is editable\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.MASTER, getMasterState());\n }\n } else { // no bundle descriptor given - implies no master mode\n cols = new ArrayList<TableProperty>(1);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.TRANSLATION);\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, new EditorState(cols, true));\n }\n break;\n case DESCRIPTOR:\n cols = new ArrayList<TableProperty>(3);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.DESCRIPTION);\n cols.add(TableProperty.DEFAULT);\n m_editorState.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, new EditorState(cols, true));\n break;\n default:\n throw new IllegalArgumentException();\n }\n\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n BeatFinder.getInstance().removeBeatListener(beatListener);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n running.set(false);\n positions.clear();\n updates.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }",
"@RequestMapping(value = \"api/edit/server\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getjqRedirects(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"clientUUID\", required = true) String clientUUID,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int clientId = ClientService.getInstance().findClient(clientUUID, profileId).getId();\n\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(ServerRedirectService.getInstance().tableServers(clientId), \"servers\");\n returnJson.put(\"hostEditor\", Client.isAvailable());\n return returnJson;\n }",
"public <T> T with( Closure<T> closure ) {\n return DefaultGroovyMethods.with( null, closure ) ;\n }",
"public void waitAndRetry() {\n ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(\n processedWorkerCount);\n\n logger.debug(\"NOW WAIT Another \" + asstManagerRetryIntervalMillis\n + \" MS. at \" + PcDateUtils.getNowDateTimeStrStandard());\n getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(asstManagerRetryIntervalMillis,\n TimeUnit.MILLISECONDS), getSelf(),\n continueToSendToBatchSenderAsstManager,\n getContext().system().dispatcher(), getSelf());\n return;\n }"
] |
Use this API to fetch all the spilloverpolicy resources that are configured on netscaler. | [
"public static spilloverpolicy[] get(nitro_service service, options option) throws Exception{\n\t\tspilloverpolicy obj = new spilloverpolicy();\n\t\tspilloverpolicy[] response = (spilloverpolicy[])obj.get_resources(service,option);\n\t\treturn response;\n\t}"
] | [
"public void validate(final List<Throwable> validationErrors) {\n if (this.matchers == null) {\n validationErrors.add(new IllegalArgumentException(\n \"Matchers cannot be null. There should be at least a !acceptAll matcher\"));\n }\n if (this.matchers != null && this.matchers.isEmpty()) {\n validationErrors.add(new IllegalArgumentException(\n \"There are no url matchers defined. There should be at least a \" +\n \"!acceptAll matcher\"));\n }\n }",
"public static responderhtmlpage get(nitro_service service) throws Exception{\n\t\tresponderhtmlpage obj = new responderhtmlpage();\n\t\tresponderhtmlpage[] response = (responderhtmlpage[])obj.get_resources(service);\n\t\treturn response[0];\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 }",
"private Long fetchServiceId(ServiceReference serviceReference) {\n return (Long) serviceReference.getProperty(org.osgi.framework.Constants.SERVICE_ID);\n }",
"public void removeCollaborator(String appName, String collaborator) {\n connection.execute(new SharingRemove(appName, collaborator), apiKey);\n }",
"public boolean isDeleted(Identity id)\r\n {\r\n ObjectEnvelope envelope = buffer.getByIdentity(id);\r\n\r\n return (envelope != null && envelope.needsDelete());\r\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<InternationalFixedDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<InternationalFixedDate>) super.zonedDateTime(temporal);\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 void close() throws IOException {\n\t\tSystem.out.println(\"Serialized \"\n\t\t\t\t+ this.jsonSerializer.getEntityDocumentCount()\n\t\t\t\t+ \" item documents to JSON file \" + OUTPUT_FILE_NAME + \".\");\n\t\tthis.jsonSerializer.close();\n\t}"
] |
Get the VCS revision from the Jenkins build environment. The search will one of "SVN_REVISION", "GIT_COMMIT",
"P4_CHANGELIST" in the environment.
@param env Th Jenkins build environment.
@return The vcs revision for supported VCS | [
"public static String getVcsRevision(Map<String, String> env) {\n String revision = env.get(\"SVN_REVISION\");\n if (StringUtils.isBlank(revision)) {\n revision = env.get(GIT_COMMIT);\n }\n if (StringUtils.isBlank(revision)) {\n revision = env.get(\"P4_CHANGELIST\");\n }\n return revision;\n }"
] | [
"public static csvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_spilloverpolicy_binding obj = new csvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_spilloverpolicy_binding response[] = (csvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String wordShape(String inStr, int wordShaper, Collection<String> knownLCWords) {\r\n // this first bit is for backwards compatibility with how things were first\r\n // implemented, where the word shaper name encodes whether to useLC.\r\n // If the shaper is in the old compatibility list, then a specified\r\n // list of knownLCwords is ignored\r\n if (knownLCWords != null && dontUseLC(wordShaper)) {\r\n knownLCWords = null;\r\n }\r\n switch (wordShaper) {\r\n case NOWORDSHAPE:\r\n return inStr;\r\n case WORDSHAPEDAN1:\r\n return wordShapeDan1(inStr);\r\n case WORDSHAPECHRIS1:\r\n return wordShapeChris1(inStr);\r\n case WORDSHAPEDAN2:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2USELC:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIO:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIOUSELC:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1USELC:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPECHRIS2:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS2USELC:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS3:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS3USELC:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS4:\r\n return wordShapeChris4(inStr, false, knownLCWords);\r\n case WORDSHAPEDIGITS:\r\n return wordShapeDigits(inStr);\r\n default:\r\n throw new IllegalStateException(\"Bad WordShapeClassifier\");\r\n }\r\n }",
"private boolean hidden(ProgramElementDoc c) {\n\tif (c.tags(\"hidden\").length > 0 || c.tags(\"view\").length > 0)\n\t return true;\n\tOptions opt = optionProvider.getOptionsFor(c instanceof ClassDoc ? (ClassDoc) c : c.containingClass());\n\treturn opt.matchesHideExpression(c.toString()) //\n\t\t|| (opt.hidePrivateInner && c instanceof ClassDoc && c.isPrivate() && ((ClassDoc) c).containingClass() != null);\n }",
"public synchronized void shutdownTaskScheduler(){\n if (scheduler != null && !scheduler.isShutdown()) {\n scheduler.shutdown();\n logger.info(\"shutdowned the task scheduler. No longer accepting new tasks\");\n scheduler = null;\n }\n }",
"@Override\n public boolean postBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener)\n throws InterruptedException, IOException {\n build.executeAsync(new BuildCallable<Void, IOException>() {\n // record is transient, so needs to make a copy first\n private final Set<MavenDependency> d = dependencies;\n\n public Void call(MavenBuild build) throws IOException, InterruptedException {\n // add the action\n //TODO: [by yl] These actions are persisted into the build.xml of each build run - we need another\n //context to store these actions\n build.getActions().add(new MavenDependenciesRecord(build, d));\n return null;\n }\n });\n return true;\n }",
"private void removeFromInverseAssociations(\n\t\t\tTuple resultset,\n\t\t\tint tableIndex,\n\t\t\tSerializable id,\n\t\t\tSharedSessionContractImplementor session) {\n\t\tnew EntityAssociationUpdater( this )\n\t\t\t\t.id( id )\n\t\t\t\t.resultset( resultset )\n\t\t\t\t.session( session )\n\t\t\t\t.tableIndex( tableIndex )\n\t\t\t\t.propertyMightRequireInverseAssociationManagement( propertyMightBeMainSideOfBidirectionalAssociation )\n\t\t\t\t.removeNavigationalInformationFromInverseSide();\n\t}",
"private int getMaxHeight() {\n int result = 0;\n for (int i = 0; i < segmentCount; i++) {\n result = Math.max(result, segmentHeight(i, false));\n }\n return result;\n }",
"public static void createEphemeralPath(ZkClient zkClient, String path, String data) {\n try {\n zkClient.createEphemeral(path, Utils.getBytes(data));\n } catch (ZkNoNodeException e) {\n createParentPath(zkClient, path);\n zkClient.createEphemeral(path, Utils.getBytes(data));\n }\n }",
"public static tmtrafficpolicy_tmglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficpolicy_tmglobal_binding obj = new tmtrafficpolicy_tmglobal_binding();\n\t\tobj.set_name(name);\n\t\ttmtrafficpolicy_tmglobal_binding response[] = (tmtrafficpolicy_tmglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Performs an implicit double step given the set of two imaginary eigenvalues provided.
Since one eigenvalue is the complex conjugate of the other only one set of real and imaginary
numbers is needed.
@param x1 upper index of submatrix.
@param x2 lower index of submatrix.
@param real Real component of each of the eigenvalues.
@param img Imaginary component of one of the eigenvalues. | [
"public void performImplicitDoubleStep(int x1, int x2 , double real , double img ) {\n double a11 = A.get(x1,x1);\n double a21 = A.get(x1+1,x1);\n double a12 = A.get(x1,x1+1);\n double a22 = A.get(x1+1,x1+1);\n double a32 = A.get(x1+2,x1+1);\n\n double p_plus_t = 2.0*real;\n double p_times_t = real*real + img*img;\n\n double b11,b21,b31;\n if( useStandardEq ) {\n b11 = (a11*a11 - p_plus_t*a11+p_times_t)/a21 + a12;\n b21 = a11+a22-p_plus_t;\n b31 = a32;\n } else {\n // this is different from the version in the book and seems in my testing to be more resilient to\n // over flow issues\n b11 = (a11*a11 - p_plus_t*a11+p_times_t) + a12*a21;\n b21 = (a11+a22-p_plus_t)*a21;\n b31 = a32*a21;\n }\n\n performImplicitDoubleStep(x1, x2, b11, b21, b31);\n }"
] | [
"private void bubbleUpNodeTable(DAGraph<DataT, NodeT> from, LinkedList<String> path) {\n if (path.contains(from.rootNode.key())) {\n path.push(from.rootNode.key()); // For better error message\n throw new IllegalStateException(\"Detected circular dependency: \" + StringUtils.join(path, \" -> \"));\n }\n path.push(from.rootNode.key());\n for (DAGraph<DataT, NodeT> to : from.parentDAGs) {\n this.merge(from.nodeTable, to.nodeTable);\n this.bubbleUpNodeTable(to, path);\n }\n path.pop();\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 }",
"protected void deliverLifecycleAnnouncement(final Logger logger, final boolean starting) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n for (final LifecycleListener listener : getLifecycleListeners()) {\n try {\n if (starting) {\n listener.started(LifecycleParticipant.this);\n } else {\n listener.stopped(LifecycleParticipant.this);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering lifecycle announcement to listener\", t);\n }\n }\n }\n }, \"Lifecycle announcement delivery\").start();\n }",
"private String getProperty(String name) {\n return System.getSecurityManager() == null ? System.getProperty(name) : doPrivileged(new ReadPropertyAction(name));\n }",
"private DBHandling createDBHandling() throws BuildException\r\n {\r\n if ((_handling == null) || (_handling.length() == 0))\r\n {\r\n throw new BuildException(\"No handling specified\");\r\n }\r\n try\r\n {\r\n String className = \"org.apache.ojb.broker.platforms.\"+\r\n \t\t\t\t\t Character.toTitleCase(_handling.charAt(0))+_handling.substring(1)+\r\n \t\t\t\t\t \"DBHandling\";\r\n Class handlingClass = ClassHelper.getClass(className);\r\n\r\n return (DBHandling)handlingClass.newInstance();\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new BuildException(\"Invalid handling '\"+_handling+\"' specified\");\r\n }\r\n }",
"public GVRAnimationChannel findChannel(String boneName)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n return mBoneChannels[boneId];\n }\n return null;\n }",
"public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\n }",
"public T removeBundle(final String moduleName, final String slot, final byte[] existingHash) {\n final ContentItem item = createBundleItem(moduleName, slot, NO_CONTENT);\n addContentModification(createContentModification(item, ModificationType.REMOVE, existingHash));\n return returnThis();\n }",
"public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\n }"
] |
Function to filter files based on defined rules. | [
"@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 }"
] | [
"private void reInitLayoutElements() {\n\n m_panel.clear();\n for (CmsCheckBox cb : m_checkBoxes) {\n m_panel.add(setStyle(m_onlyLabels ? new Label(cb.getText()) : cb));\n }\n }",
"private void generateCopyingPart(WrappingHint.Builder builder) {\n ImmutableCollection<CopyMethod> copyMethods = ImmutableMultimap.<String, CopyMethod>builder()\n .putAll(configuration.FIELD_TYPE_TO_COPY_METHODS)\n .putAll(userDefinedCopyMethods)\n .build()\n .get(typeAssignedToField);\n \n if (copyMethods.isEmpty()) {\n throw new WrappingHintGenerationException();\n }\n \n CopyMethod firstSuitable = copyMethods.iterator().next();\n builder.setCopyMethodOwnerName(firstSuitable.owner.toString())\n .setCopyMethodName(firstSuitable.name);\n \n if (firstSuitable.isGeneric && typeSignature != null) {\n CollectionField withRemovedWildcards = CollectionField.from(typeAssignedToField, typeSignature)\n .transformGenericTree(GenericType::withoutWildcard);\n builder.setCopyTypeParameterName(formatTypeParameter(withRemovedWildcards.asSimpleString()));\n }\n }",
"public void alias( double value , String name ) {\n if( isReserved(name))\n throw new RuntimeException(\"Reserved word or contains a reserved character. '\"+name+\"'\");\n\n VariableDouble old = (VariableDouble)variables.get(name);\n if( old == null ) {\n variables.put(name, new VariableDouble(value));\n }else {\n old.value = value;\n }\n }",
"private static void deleteOldAndEmptyFiles() {\n File dir = LOG_FILE_DIR;\n if (dir.exists()) {\n File[] files = dir.listFiles();\n\n for (File f : files) {\n if (f.length() == 0 ||\n f.lastModified() + MAXFILEAGE < System.currentTimeMillis()) {\n f.delete();\n }\n }\n }\n }",
"public Client getClient(int clientId) throws Exception {\n Client client = null;\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\";\n\n statement = sqlConnection.prepareStatement(queryString);\n statement.setInt(1, clientId);\n\n results = statement.executeQuery();\n if (results.next()) {\n client = this.getClientFromResultSet(results);\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return client;\n }",
"public static base_responses clear(nitro_service client, gslbldnsentries resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbldnsentries clearresources[] = new gslbldnsentries[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new gslbldnsentries();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}",
"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 int getOpacity() {\n\t\tint opacity = Math\n\t\t\t\t.round((mPosToOpacFactor * (mBarPointerPosition - mBarPointerHaloRadius)));\n\t\tif (opacity < 5) {\n\t\t\treturn 0x00;\n\t\t} else if (opacity > 250) {\n\t\t\treturn 0xFF;\n\t\t} else {\n\t\t\treturn opacity;\n\t\t}\n\t}",
"private void performDownload(HttpResponse response, File destFile)\n throws IOException {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n return;\n }\n \n //get content length\n long contentLength = entity.getContentLength();\n if (contentLength >= 0) {\n size = toLengthText(contentLength);\n }\n \n processedBytes = 0;\n loggedKb = 0;\n \n //open stream and start downloading\n InputStream is = entity.getContent();\n streamAndMove(is, destFile);\n }"
] |
In Gerrit < 2.12 the XSRF token was included in the start page HTML. | [
"private Optional<String> getXsrfFromHtmlBody(HttpResponse loginResponse) throws IOException {\n Optional<Cookie> gerritAccountCookie = findGerritAccountCookie();\n if (gerritAccountCookie.isPresent()) {\n Matcher matcher = GERRIT_AUTH_PATTERN.matcher(EntityUtils.toString(loginResponse.getEntity(), Consts.UTF_8));\n if (matcher.find()) {\n return Optional.of(matcher.group(1));\n }\n }\n return Optional.absent();\n }"
] | [
"public static base_response add(nitro_service client, sslocspresponder resource) throws Exception {\n\t\tsslocspresponder addresource = new sslocspresponder();\n\t\taddresource.name = resource.name;\n\t\taddresource.url = resource.url;\n\t\taddresource.cache = resource.cache;\n\t\taddresource.cachetimeout = resource.cachetimeout;\n\t\taddresource.batchingdepth = resource.batchingdepth;\n\t\taddresource.batchingdelay = resource.batchingdelay;\n\t\taddresource.resptimeout = resource.resptimeout;\n\t\taddresource.respondercert = resource.respondercert;\n\t\taddresource.trustresponder = resource.trustresponder;\n\t\taddresource.producedattimeskew = resource.producedattimeskew;\n\t\taddresource.signingcert = resource.signingcert;\n\t\taddresource.usenonce = resource.usenonce;\n\t\taddresource.insertclientcert = resource.insertclientcert;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static void downloadUrl(String stringUrl, Map<String, String> parameters, File fileToSave)\n throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setFollowRedirects(true);\n \n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n\n boolean redirect = false;\n\n // normally, 3xx is redirect\n int status = conn.getResponseCode();\n if (status != HttpURLConnection.HTTP_OK) {\n if (status == HttpURLConnection.HTTP_MOVED_TEMP\n || status == HttpURLConnection.HTTP_MOVED_PERM\n || status == HttpURLConnection.HTTP_SEE_OTHER)\n redirect = true;\n }\n\n if (redirect) {\n\n // get redirect url from \"location\" header field\n String newUrl = conn.getHeaderField(\"Location\");\n\n // get the cookie if need, for login\n String cookies = conn.getHeaderField(\"Set-Cookie\");\n\n // open the new connnection again\n conn = (HttpURLConnection) new URL(newUrl).openConnection();\n conn.setRequestProperty(\"Cookie\", cookies);\n\n }\n \n byte[] data = MyStreamUtils.readContentBytes(conn.getInputStream());\n FileOutputStream fos = new FileOutputStream(fileToSave);\n fos.write(data);\n fos.close();\n }",
"public void abort() {\n URL abortURL = this.sessionInfo.getSessionEndpoints().getAbortEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), abortURL, HttpMethod.DELETE);\n request.send();\n }",
"private void parseJSON(JsonObject jsonObject) {\n for (JsonObject.Member member : jsonObject) {\n JsonValue value = member.getValue();\n if (value.isNull()) {\n continue;\n }\n\n try {\n String memberName = member.getName();\n if (memberName.equals(\"id\")) {\n this.versionID = value.asString();\n } else if (memberName.equals(\"sha1\")) {\n this.sha1 = value.asString();\n } else if (memberName.equals(\"name\")) {\n this.name = value.asString();\n } else if (memberName.equals(\"size\")) {\n this.size = Double.valueOf(value.toString()).longValue();\n } else if (memberName.equals(\"created_at\")) {\n this.createdAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"modified_at\")) {\n this.modifiedAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"trashed_at\")) {\n this.trashedAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"modified_by\")) {\n JsonObject userJSON = value.asObject();\n String userID = userJSON.get(\"id\").asString();\n BoxUser user = new BoxUser(getAPI(), userID);\n this.modifiedBy = user.new Info(userJSON);\n }\n } catch (ParseException e) {\n assert false : \"A ParseException indicates a bug in the SDK.\";\n }\n }\n }",
"private long getTotalTime(ProjectCalendarDateRanges hours, Date startDate, Date endDate)\n {\n long total = 0;\n if (startDate.getTime() != endDate.getTime())\n {\n Date start = DateHelper.getCanonicalTime(startDate);\n Date end = DateHelper.getCanonicalTime(endDate);\n\n for (DateRange range : hours)\n {\n Date rangeStart = range.getStart();\n Date rangeEnd = range.getEnd();\n if (rangeStart != null && rangeEnd != null)\n {\n Date canoncialRangeStart = DateHelper.getCanonicalTime(rangeStart);\n Date canonicalRangeEnd = DateHelper.getCanonicalTime(rangeEnd);\n\n Date startDay = DateHelper.getDayStartDate(rangeStart);\n Date finishDay = DateHelper.getDayStartDate(rangeEnd);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n canonicalRangeEnd = DateHelper.addDays(canonicalRangeEnd, 1);\n }\n\n if (canoncialRangeStart.getTime() == canonicalRangeEnd.getTime() && rangeEnd.getTime() > rangeStart.getTime())\n {\n total += (24 * 60 * 60 * 1000);\n }\n else\n {\n total += getTime(start, end, canoncialRangeStart, canonicalRangeEnd);\n }\n }\n }\n }\n\n return (total);\n }",
"public void process(Connection connection, String directory) throws Exception\n {\n connection.setAutoCommit(true);\n\n //\n // Retrieve meta data about the connection\n //\n DatabaseMetaData dmd = connection.getMetaData();\n\n String[] types =\n {\n \"TABLE\"\n };\n\n FileWriter fw = new FileWriter(directory);\n PrintWriter pw = new PrintWriter(fw);\n\n pw.println(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n pw.println();\n pw.println(\"<database>\");\n\n ResultSet tables = dmd.getTables(null, null, null, types);\n while (tables.next() == true)\n {\n processTable(pw, connection, tables.getString(\"TABLE_NAME\"));\n }\n\n pw.println(\"</database>\");\n\n pw.close();\n\n tables.close();\n }",
"void insertMacros(TokenList tokens ) {\n TokenList.Token t = tokens.getFirst();\n while( t != null ) {\n if( t.getType() == Type.WORD ) {\n Macro v = lookupMacro(t.word);\n if (v != null) {\n TokenList.Token before = t.previous;\n List<TokenList.Token> inputs = new ArrayList<TokenList.Token>();\n t = parseMacroInput(inputs,t.next);\n\n TokenList sniplet = v.execute(inputs);\n tokens.extractSubList(before.next,t);\n tokens.insertAfter(before,sniplet);\n t = sniplet.last;\n }\n }\n t = t.next;\n }\n }",
"public static <T extends Annotation> List<T> searchForAnnotation(Method method, Class<T> annotation) {\n if (method == null) {\n return Lists.newArrayList();\n }\n return searchClasses(method, annotation, method.getDeclaringClass());\n }",
"public static sslocspresponder get(nitro_service service, String name) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tobj.set_name(name);\n\t\tsslocspresponder response = (sslocspresponder) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.