query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Add the extra parameters which are passed as report parameters. The type of the parameter is "guessed" from the
first letter of the parameter name.
@param model view model
@param request servlet request | [
"@SuppressWarnings(\"unchecked\")\n\tprivate void addParameters(Model model, HttpServletRequest request) {\n\t\tfor (Object objectEntry : request.getParameterMap().entrySet()) {\n\t\t\tMap.Entry<String, String[]> entry = (Map.Entry<String, String[]>) objectEntry;\n\t\t\tString key = entry.getKey();\n\t\t\tString[] values = entry.getValue();\n\t\t\tif (null != values && values.length > 0) {\n\t\t\t\tString value = values[0];\n\t\t\t\ttry {\n\t\t\t\t\tmodel.addAttribute(key, getParameter(key, value));\n\t\t\t\t} catch (ParseException pe) {\n\t\t\t\t\tlog.error(\"Could not parse parameter value {} for {}, ignoring parameter.\", key, value);\n\t\t\t\t} catch (NumberFormatException nfe) {\n\t\t\t\t\tlog.error(\"Could not parse parameter value {} for {}, ignoring parameter.\", key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] | [
"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 }",
"private String decodeStr(String str) {\r\n try {\r\n return MimeUtility.decodeText(str);\r\n } catch (UnsupportedEncodingException e) {\r\n return str;\r\n }\r\n }",
"public static base_response link(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey linkresource = new sslcertkey();\n\t\tlinkresource.certkey = resource.certkey;\n\t\tlinkresource.linkcertkeyname = resource.linkcertkeyname;\n\t\treturn linkresource.perform_operation(client,\"link\");\n\t}",
"public CollectionRequest<Project> tasks(String project) {\n \n String path = String.format(\"/projects/%s/tasks\", project);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }",
"private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {\n if (eventType != null) {\n return EventTypeEnum.valueOf(eventType.name());\n }\n return EventTypeEnum.UNKNOWN;\n }",
"public static final double round(double value, double precision)\n {\n precision = Math.pow(10, precision);\n return Math.round(value * precision) / precision;\n }",
"public void finished(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n this.runningProcessors.remove(processorGraphNode.getProcessor());\n this.executedProcessors.put(processorGraphNode.getProcessor(), null);\n } finally {\n this.processorLock.unlock();\n }\n }",
"protected boolean isStoreValid() {\n boolean result = false;\n String requestURI = this.request.getUri();\n this.storeName = parseStoreName(requestURI);\n if(storeName != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. Missing store name.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing store name. Critical error.\");\n }\n return result;\n }",
"private String getRequestBody(ServletRequest request) throws IOException {\n\n final StringBuilder sb = new StringBuilder();\n\n String line = request.getReader().readLine();\n while (null != line) {\n sb.append(line);\n line = request.getReader().readLine();\n }\n\n return sb.toString();\n }"
] |
Returns the supplied string with any trailing '\n' removed. | [
"public static String chomp(String s) {\r\n if(s.length() == 0)\r\n return s;\r\n int l_1 = s.length() - 1;\r\n if (s.charAt(l_1) == '\\n') {\r\n return s.substring(0, l_1);\r\n }\r\n return s;\r\n }"
] | [
"private int getCostRateTableEntryIndex(Date date)\n {\n int result = -1;\n\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n if (table.size() == 1)\n {\n result = 0;\n }\n else\n {\n result = table.getIndexByDate(date);\n }\n }\n\n return result;\n }",
"void unbind(String key)\r\n {\r\n NamedEntry entry = new NamedEntry(key, null, false);\r\n localUnbind(key);\r\n addForDeletion(entry);\r\n }",
"public void transform(DataPipe cr) {\n Map<String, String> map = cr.getDataMap();\n\n for (String key : map.keySet()) {\n String value = map.get(key);\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n map.put(key, String.valueOf(ran));\n } else if (value.equals(\"#{divideBy2}\")) {\n String i = map.get(\"var_out_V3\");\n String result = String.valueOf(Integer.valueOf(i) / 2);\n map.put(key, result);\n }\n }\n }",
"protected void addPoint(double time, RandomVariable value, boolean isParameter) {\n\t\tsynchronized (rationalFunctionInterpolationLazyInitLock) {\n\t\t\tif(interpolationEntity == InterpolationEntity.LOG_OF_VALUE_PER_TIME && time == 0) {\n\t\t\t\tboolean containsOne = false; int index=0;\n\t\t\t\tfor(int i = 0; i< value.size(); i++){if(value.get(i)==1.0) {containsOne = true; index=i; break;}}\n\t\t\t\tif(containsOne && isParameter == false) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new IllegalArgumentException(\"The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index\" + index + \").\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tRandomVariable interpolationEntityValue = interpolationEntityFromValue(value, time);\n\n\t\t\tint index = getTimeIndex(time);\n\t\t\tif(index >= 0) {\n\t\t\t\tif(points.get(index).value == interpolationEntityValue) {\n\t\t\t\t\treturn;\t\t\t// Already in list\n\t\t\t\t} else if(isParameter) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new RuntimeException(\"Trying to add a value for a time for which another value already exists.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Insert the new point, retain ordering.\n\t\t\t\tPoint point = new Point(time, interpolationEntityValue, isParameter);\n\t\t\t\tpoints.add(-index-1, point);\n\n\t\t\t\tif(isParameter) {\n\t\t\t\t\t// Add this point also to the list of parameters\n\t\t\t\t\tint parameterIndex = getParameterIndex(time);\n\t\t\t\t\tif(parameterIndex >= 0) {\n\t\t\t\t\t\tnew RuntimeException(\"CurveFromInterpolationPoints inconsistent.\");\n\t\t\t\t\t}\n\t\t\t\t\tpointsBeingParameters.add(-parameterIndex-1, point);\n\t\t\t\t}\n\t\t\t}\n\t\t\trationalFunctionInterpolation = null;\n\t\t\tcurveCacheReference = null;\n\t\t}\n\t}",
"public double Function2D(double x, double y) {\n double frequency = initFrequency;\n double amplitude = initAmplitude;\n double sum = 0;\n\n // octaves\n for (int i = 0; i < octaves; i++) {\n sum += SmoothedNoise(x * frequency, y * frequency) * amplitude;\n\n frequency *= 2;\n amplitude *= persistence;\n }\n return sum;\n }",
"private boolean isAllNumeric(TokenStream stream) {\n List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens();\n for(Token token:tokens) {\n try {\n Integer.parseInt(token.getText());\n } catch(NumberFormatException e) {\n return false;\n }\n }\n return true;\n }",
"public static base_response convert(nitro_service client, sslpkcs12 resource) throws Exception {\n\t\tsslpkcs12 convertresource = new sslpkcs12();\n\t\tconvertresource.outfile = resource.outfile;\n\t\tconvertresource.Import = resource.Import;\n\t\tconvertresource.pkcs12file = resource.pkcs12file;\n\t\tconvertresource.des = resource.des;\n\t\tconvertresource.des3 = resource.des3;\n\t\tconvertresource.export = resource.export;\n\t\tconvertresource.certfile = resource.certfile;\n\t\tconvertresource.keyfile = resource.keyfile;\n\t\tconvertresource.password = resource.password;\n\t\tconvertresource.pempassphrase = resource.pempassphrase;\n\t\treturn convertresource.perform_operation(client,\"convert\");\n\t}",
"public static base_responses expire(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject expireresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texpireresources[i] = new cacheobject();\n\t\t\t\texpireresources[i].locator = resources[i].locator;\n\t\t\t\texpireresources[i].url = resources[i].url;\n\t\t\t\texpireresources[i].host = resources[i].host;\n\t\t\t\texpireresources[i].port = resources[i].port;\n\t\t\t\texpireresources[i].groupname = resources[i].groupname;\n\t\t\t\texpireresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, expireresources,\"expire\");\n\t\t}\n\t\treturn result;\n\t}",
"private ModelNode createCPUNode() throws OperationFailedException {\n ModelNode cpu = new ModelNode().setEmptyObject();\n cpu.get(ARCH).set(getProperty(\"os.arch\"));\n cpu.get(AVAILABLE_PROCESSORS).set(ProcessorInfo.availableProcessors());\n return cpu;\n }"
] |
Creates a new Box Developer Edition connection with enterprise token leveraging BoxConfig.
@param boxConfig box configuration settings object
@return a new instance of BoxAPIConnection. | [
"public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(BoxConfig boxConfig) {\n\n BoxDeveloperEditionAPIConnection connection = getAppEnterpriseConnection(boxConfig.getEnterpriseId(),\n boxConfig.getClientId(), boxConfig.getClientSecret(), boxConfig.getJWTEncryptionPreferences());\n\n return connection;\n }"
] | [
"public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }",
"public StatementGroup findStatementGroup(String propertyIdValue) {\n\t\tif (this.claims.containsKey(propertyIdValue)) {\n\t\t\treturn new StatementGroupImpl(this.claims.get(propertyIdValue));\n\t\t}\n\t\treturn null;\n\t}",
"protected void postLayoutChild(final int dataIndex) {\n if (!mContainer.isDynamic()) {\n boolean visibleInLayout = !mViewPort.isClippingEnabled() || inViewPort(dataIndex);\n ViewPortVisibility visibility = visibleInLayout ?\n ViewPortVisibility.FULLY_VISIBLE : ViewPortVisibility.INVISIBLE;\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"onLayout: child with dataId [%d] viewportVisibility = %s\",\n dataIndex, visibility);\n\n Widget childWidget = mContainer.get(dataIndex);\n if (childWidget != null) {\n childWidget.setViewPortVisibility(visibility);\n }\n }\n }",
"public static boolean isVariable(ASTNode expression, String pattern) {\r\n return (expression instanceof VariableExpression && ((VariableExpression) expression).getName().matches(pattern));\r\n }",
"public int create(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedInsert == null) {\n\t\t\tmappedInsert = MappedCreate.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedInsert.insert(databaseType, databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}",
"public static bridgegroup_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_nsip_binding obj = new bridgegroup_nsip_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_nsip_binding response[] = (bridgegroup_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String tail(String moduleName) {\n if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) {\n return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1);\n } else {\n return \"\";\n }\n }",
"protected void checkProducerMethod(EnhancedAnnotatedMethod<T, ? super X> method) {\n if (method.getEnhancedParameters(Observes.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@Observes\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (method.getEnhancedParameters(ObservesAsync.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@ObservesAsync\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (method.getEnhancedParameters(Disposes.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@Disposes\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (getDeclaringBean() instanceof SessionBean<?> && !Modifier.isStatic(method.slim().getJavaMember().getModifiers())) {\n boolean methodDeclaredOnTypes = false;\n for (Type type : getDeclaringBean().getTypes()) {\n Class<?> clazz = Reflections.getRawType(type);\n try {\n AccessController.doPrivileged(new GetMethodAction(clazz, method.getName(), method.getParameterTypesAsArray()));\n methodDeclaredOnTypes = true;\n break;\n } catch (PrivilegedActionException ignored) {\n }\n }\n if (!methodDeclaredOnTypes) {\n throw BeanLogger.LOG.methodNotBusinessMethod(\"Producer\", this, getDeclaringBean(), Formats.formatAsStackTraceElement(method.getJavaMember()));\n }\n }\n }",
"public ListenableFuture<Connection> getAsyncConnection(){\r\n\r\n\t\treturn this.asyncExecutor.submit(new Callable<Connection>() {\r\n\r\n\t\t\tpublic Connection call() throws Exception {\r\n\t\t\t\treturn getConnection();\r\n\t\t\t}});\r\n\t}"
] |
Sets the background color of the scene rendered by this camera.
If you don't set the background color, the default is an opaque black.
Meaningful parameter values are from 0 to 1, inclusive: values
{@literal < 0} are clamped to 0; values {@literal > 1} are clamped to 1. | [
"public void setBackgroundColor(float r, float g, float b, float a) {\n setBackgroundColorR(r);\n setBackgroundColorG(g);\n setBackgroundColorB(b);\n setBackgroundColorA(a);\n }"
] | [
"@Override\n public Iterator<BoxItem.Info> iterator() {\n URL url = GET_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxFolder.this.getID());\n return new BoxItemIterator(BoxFolder.this.getAPI(), url);\n }",
"public void createAssignmentFieldMap(Props props)\n {\n //System.out.println(\"ASSIGN\");\n byte[] fieldMapData = null;\n for (Integer key : ASSIGNMENT_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultAssignmentData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }",
"public static base_responses disable(nitro_service client, String trapname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm disableresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tdisableresources[i] = new snmpalarm();\n\t\t\t\tdisableresources[i].trapname = trapname[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}",
"public static void main(String[] args) {\n\t\ttry {\n\t\t\tJarRunner runner = new JarRunner(args);\n\t\t\trunner.runIfConfigured();\n\t\t} catch (NumberFormatException e) {\n\t\t\tSystem.err.println(\"Could not parse number \" + e.getMessage());\n\t\t\tSystem.exit(1);\n\t\t} catch (RuntimeException e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\tSystem.exit(1);\n\t\t}\n\t}",
"public Pair<int[][][], int[]> documentToDataAndLabels(List<IN> document) {\r\n\r\n int docSize = document.size();\r\n // first index is position in the document also the index of the\r\n // clique/factor table\r\n // second index is the number of elements in the clique/window these\r\n // features are for (starting with last element)\r\n // third index is position of the feature in the array that holds them\r\n // element in data[j][k][m] is the index of the mth feature occurring in\r\n // position k of the jth clique\r\n int[][][] data = new int[docSize][windowSize][];\r\n // index is the position in the document\r\n // element in labels[j] is the index of the correct label (if it exists) at\r\n // position j of document\r\n int[] labels = new int[docSize];\r\n\r\n if (flags.useReverse) {\r\n Collections.reverse(document);\r\n }\r\n\r\n // System.err.println(\"docSize:\"+docSize);\r\n for (int j = 0; j < docSize; j++) {\r\n CRFDatum<List<String>, CRFLabel> d = makeDatum(document, j, featureFactory);\r\n\r\n List<List<String>> features = d.asFeatures();\r\n for (int k = 0, fSize = features.size(); k < fSize; k++) {\r\n Collection<String> cliqueFeatures = features.get(k);\r\n data[j][k] = new int[cliqueFeatures.size()];\r\n int m = 0;\r\n for (String feature : cliqueFeatures) {\r\n int index = featureIndex.indexOf(feature);\r\n if (index >= 0) {\r\n data[j][k][m] = index;\r\n m++;\r\n } else {\r\n // this is where we end up when we do feature threshold cutoffs\r\n }\r\n }\r\n // Reduce memory use when some features were cut out by threshold\r\n if (m < data[j][k].length) {\r\n int[] f = new int[m];\r\n System.arraycopy(data[j][k], 0, f, 0, m);\r\n data[j][k] = f;\r\n }\r\n }\r\n\r\n IN wi = document.get(j);\r\n labels[j] = classIndex.indexOf(wi.get(AnswerAnnotation.class));\r\n }\r\n\r\n if (flags.useReverse) {\r\n Collections.reverse(document);\r\n }\r\n\r\n // System.err.println(\"numClasses: \"+classIndex.size()+\" \"+classIndex);\r\n // System.err.println(\"numDocuments: 1\");\r\n // System.err.println(\"numDatums: \"+data.length);\r\n // System.err.println(\"numFeatures: \"+featureIndex.size());\r\n\r\n return new Pair<int[][][], int[]>(data, labels);\r\n }",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl) throws IOException {\n return getResponseHeaders(stringUrl, true);\n }",
"public static CmsJspResourceWrapper convertResource(CmsObject cms, Object input) throws CmsException {\n\n CmsJspResourceWrapper result;\n if (input instanceof CmsResource) {\n result = CmsJspResourceWrapper.wrap(cms, (CmsResource)input);\n } else {\n result = CmsJspResourceWrapper.wrap(cms, convertRawResource(cms, input));\n }\n return result;\n }",
"@Override\n public Future<RawGcsCreationToken> continueObjectCreationAsync(final RawGcsCreationToken token,\n final ByteBuffer chunk, long timeoutMillis) {\n try {\n ensureInitialized();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n final Environment environment = ApiProxy.getCurrentEnvironment();\n return writePool.schedule(new Callable<RawGcsCreationToken>() {\n @Override\n public RawGcsCreationToken call() throws Exception {\n ApiProxy.setEnvironmentForCurrentThread(environment);\n return append(token, chunk);\n }\n }, 50, TimeUnit.MILLISECONDS);\n }",
"public void addProcedureArgument(ProcedureArgumentDef argDef)\r\n {\r\n argDef.setOwner(this);\r\n _procedureArguments.put(argDef.getName(), argDef);\r\n }"
] |
Use this API to fetch all the bridgetable resources that are configured on netscaler. | [
"public static bridgetable[] get(nitro_service service) throws Exception{\n\t\tbridgetable obj = new bridgetable();\n\t\tbridgetable[] response = (bridgetable[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"protected <T> Request doInvoke(ResponseReader responseReader,\n String methodName, RpcStatsContext statsContext, String requestData,\n AsyncCallback<T> callback) {\n\n RequestBuilder rb = doPrepareRequestBuilderImpl(responseReader, methodName,\n statsContext, requestData, callback);\n\n try {\n return rb.send();\n } catch (RequestException ex) {\n InvocationException iex = new InvocationException(\n \"Unable to initiate the asynchronous service invocation (\" +\n methodName + \") -- check the network connection\",\n ex);\n callback.onFailure(iex);\n } finally {\n if (statsContext.isStatsAvailable()) {\n statsContext.stats(statsContext.bytesStat(methodName,\n requestData.length(), \"requestSent\"));\n }\n }\n return null;\n }",
"public CollectionRequest<Task> findByProject(String projectId) {\n \n String path = String.format(\"/projects/%s/tasks\", projectId);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"private MetadataManager initOJB()\r\n {\r\n try\r\n {\r\n if (_ojbPropertiesFile == null)\r\n {\r\n _ojbPropertiesFile = new File(\"OJB.properties\");\r\n if (!_ojbPropertiesFile.exists())\r\n {\r\n throw new BuildException(\"Could not find OJB.properties, please specify it via the ojbpropertiesfile attribute\");\r\n }\r\n }\r\n else\r\n {\r\n if (!_ojbPropertiesFile.exists())\r\n {\r\n throw new BuildException(\"Could not load the specified OJB properties file \"+_ojbPropertiesFile);\r\n }\r\n log(\"Using properties file \"+_ojbPropertiesFile.getAbsolutePath(), Project.MSG_INFO);\r\n System.setProperty(\"OJB.properties\", _ojbPropertiesFile.getAbsolutePath());\r\n }\r\n\r\n MetadataManager metadataManager = MetadataManager.getInstance();\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n\r\n if (_repositoryFile != null)\r\n {\r\n if (!_repositoryFile.exists())\r\n {\r\n throw new BuildException(\"Could not load the specified repository file \"+_repositoryFile);\r\n }\r\n log(\"Loading repository file \"+_repositoryFile.getAbsolutePath(), Project.MSG_INFO);\r\n\r\n // this will load the info from the specified repository file\r\n // and merge it with the existing info (if it has been loaded)\r\n metadataManager.mergeConnectionRepository(persistor.readConnectionRepository(_repositoryFile.getAbsolutePath()));\r\n metadataManager.mergeDescriptorRepository(persistor.readDescriptorRepository(_repositoryFile.getAbsolutePath()));\r\n }\r\n else if (metadataManager.connectionRepository().getAllDescriptor().isEmpty() &&\r\n metadataManager.getGlobalRepository().getDescriptorTable().isEmpty())\r\n {\r\n // Seems nothing was loaded, probably because we're not starting in the directory\r\n // that the properties file is in, and the repository file path is relative\r\n // So lets try to resolve this path and load the repository info manually\r\n Properties props = new Properties();\r\n\r\n props.load(new FileInputStream(_ojbPropertiesFile));\r\n \r\n String repositoryPath = props.getProperty(\"repositoryFile\", \"repository.xml\");\r\n File repositoryFile = new File(repositoryPath);\r\n \r\n if (!repositoryFile.exists())\r\n {\r\n repositoryFile = new File(_ojbPropertiesFile.getParentFile(), repositoryPath);\r\n }\r\n metadataManager.mergeConnectionRepository(persistor.readConnectionRepository(repositoryFile.getAbsolutePath()));\r\n metadataManager.mergeDescriptorRepository(persistor.readDescriptorRepository(repositoryFile.getAbsolutePath()));\r\n }\r\n // we might have to determine the default pb key ourselves\r\n if (metadataManager.getDefaultPBKey() == null)\r\n {\r\n for (Iterator it = metadataManager.connectionRepository().getAllDescriptor().iterator(); it.hasNext();)\r\n {\r\n JdbcConnectionDescriptor descriptor = (JdbcConnectionDescriptor)it.next();\r\n\r\n if (descriptor.isDefaultConnection())\r\n {\r\n metadataManager.setDefaultPBKey(new PBKey(descriptor.getJcdAlias(), descriptor.getUserName(), descriptor.getPassWord()));\r\n break;\r\n }\r\n }\r\n }\r\n return metadataManager;\r\n }\r\n catch (Exception ex)\r\n {\r\n if (ex instanceof BuildException)\r\n {\r\n throw (BuildException)ex;\r\n }\r\n else\r\n {\r\n throw new BuildException(ex);\r\n }\r\n }\r\n }",
"public Collection<Group> getGroups() throws FlickrException {\r\n GroupList<Group> groups = new GroupList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GROUPS);\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 groupsElement = response.getPayload();\r\n groups.setPage(groupsElement.getAttribute(\"page\"));\r\n groups.setPages(groupsElement.getAttribute(\"pages\"));\r\n groups.setPerPage(groupsElement.getAttribute(\"perpage\"));\r\n groups.setTotal(groupsElement.getAttribute(\"total\"));\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(\"id\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n group.setAdmin(\"1\".equals(groupElement.getAttribute(\"admin\")));\r\n group.setPrivacy(groupElement.getAttribute(\"privacy\"));\r\n group.setIconServer(groupElement.getAttribute(\"iconserver\"));\r\n group.setIconFarm(groupElement.getAttribute(\"iconfarm\"));\r\n group.setPhotoCount(groupElement.getAttribute(\"photos\"));\r\n groups.add(group);\r\n }\r\n return groups;\r\n }",
"public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)\r\n throws SQLException\r\n {\r\n return getObjectFromColumn(rs, null, jdbcType, null, columnId);\r\n }",
"public void adjustGlassSize() {\n if (isGlassEnabled()) {\n ResizeHandler handler = getGlassResizer();\n if (handler != null) handler.onResize(null);\n }\n }",
"public boolean mapsCell(String cell) {\n return mappedCells.stream().anyMatch(x -> x.equals(cell));\n }",
"private static void generateContextDiagrams(RootDoc root, Options opt, String outputFolder)\n\t throws IOException {\n Set<ClassDoc> classDocs = new TreeSet<ClassDoc>(new Comparator<ClassDoc>() {\n public int compare(ClassDoc cd1, ClassDoc cd2) {\n return cd1.name().compareTo(cd2.name());\n }\n });\n for (ClassDoc classDoc : root.classes())\n classDocs.add(classDoc);\n\n\tContextView view = null;\n\tfor (ClassDoc classDoc : classDocs) {\n\t try {\n\t\tif(view == null)\n\t\t view = new ContextView(outputFolder, classDoc, root, opt);\n\t\telse\n\t\t view.setContextCenter(classDoc);\n\t\tUmlGraph.buildGraph(root, view, classDoc);\n\t\trunGraphviz(opt.dotExecutable, outputFolder, classDoc.containingPackage().name(), classDoc.name(), root);\n\t\talterHtmlDocs(opt, outputFolder, classDoc.containingPackage().name(), classDoc.name(),\n\t\t\tclassDoc.name() + \".html\", Pattern.compile(\".*(Class|Interface|Enum) \" + classDoc.name() + \".*\") , root);\n\t } catch (Exception e) {\n\t\tthrow new RuntimeException(\"Error generating \" + classDoc.name(), e);\n\t }\n\t}\n }",
"public void addFile(InputStream inputStream) {\n String name = \"file\";\n fileStreams.put(normalizeDuplicateName(name), inputStream);\n }"
] |
Read assignment data. | [
"private void processAssignments() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zscheduleitem where zproject=? and z_ent=? order by zorderinactivity\", m_projectID, m_entityMap.get(\"Assignment\"));\n for (Row row : rows)\n {\n Task task = m_project.getTaskByUniqueID(row.getInteger(\"ZACTIVITY_\"));\n Resource resource = m_project.getResourceByUniqueID(row.getInteger(\"ZRESOURCE\"));\n if (task != null && resource != null)\n {\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setGUID(row.getUUID(\"ZUNIQUEID\"));\n assignment.setActualFinish(row.getTimestamp(\"ZGIVENACTUALENDDATE_\"));\n assignment.setActualStart(row.getTimestamp(\"ZGIVENACTUALSTARTDATE_\"));\n\n assignment.setWork(assignmentDuration(task, row.getWork(\"ZGIVENWORK_\")));\n assignment.setOvertimeWork(assignmentDuration(task, row.getWork(\"ZGIVENWORKOVERTIME_\")));\n assignment.setActualWork(assignmentDuration(task, row.getWork(\"ZGIVENACTUALWORK_\")));\n assignment.setActualOvertimeWork(assignmentDuration(task, row.getWork(\"ZGIVENACTUALWORKOVERTIME_\")));\n assignment.setRemainingWork(assignmentDuration(task, row.getWork(\"ZGIVENREMAININGWORK_\")));\n\n assignment.setLevelingDelay(row.getDuration(\"ZLEVELINGDELAY_\"));\n\n if (assignment.getRemainingWork() == null)\n {\n assignment.setRemainingWork(assignment.getWork());\n }\n\n if (resource.getType() == ResourceType.WORK)\n {\n assignment.setUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble(\"ZRESOURCEUNITS_\")) * 100.0));\n }\n }\n }\n }"
] | [
"private long interpolateTimeSinceUpdate(TrackPositionUpdate update, long currentTimestamp) {\n if (!update.playing) {\n return update.milliseconds;\n }\n long elapsedMillis = (currentTimestamp - update.timestamp) / 1000000;\n long moved = Math.round(update.pitch * elapsedMillis);\n if (update.reverse) {\n return update.milliseconds - moved;\n }\n return update.milliseconds + moved;\n }",
"private static boolean getSystemConnectivity(Context context) {\n try {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if (cm == null) {\n return false;\n }\n\n NetworkInfo activeNetwork = cm.getActiveNetworkInfo();\n return activeNetwork.isConnectedOrConnecting();\n } catch (Exception exception) {\n return false;\n }\n }",
"void portForward(final Patch patch, IdentityPatchContext context) throws PatchingException, IOException, XMLStreamException {\n assert patch.getIdentity().getPatchType() == Patch.PatchType.CUMULATIVE;\n\n final PatchingHistory history = context.getHistory();\n for (final PatchElement element : patch.getElements()) {\n\n final PatchElementProvider provider = element.getProvider();\n final String name = provider.getName();\n final boolean addOn = provider.isAddOn();\n\n final IdentityPatchContext.PatchEntry target = context.resolveForElement(element);\n final String cumulativePatchID = target.getCumulativePatchID();\n if (Constants.BASE.equals(cumulativePatchID)) {\n reenableRolledBackInBase(target);\n continue;\n }\n\n boolean found = false;\n final PatchingHistory.Iterator iterator = history.iterator();\n while (iterator.hasNextCP()) {\n final PatchingHistory.Entry entry = iterator.nextCP();\n final String patchId = addOn ? entry.getAddOnPatches().get(name) : entry.getLayerPatches().get(name);\n\n if (patchId != null && patchId.equals(cumulativePatchID)) {\n final Patch original = loadPatchInformation(entry.getPatchId(), installedImage);\n for (final PatchElement originalElement : original.getElements()) {\n if (name.equals(originalElement.getProvider().getName())\n && addOn == originalElement.getProvider().isAddOn()) {\n PatchingTasks.addMissingModifications(target, originalElement.getModifications(), ContentItemFilter.ALL_BUT_MISC);\n }\n }\n // Record a loader to have access to the current modules\n final DirectoryStructure structure = target.getDirectoryStructure();\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(null, bundlesRoot, modulesRoot);\n context.recordContentLoader(patchId, loader);\n found = true;\n break;\n }\n }\n if (!found) {\n throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(cumulativePatchID);\n }\n\n reenableRolledBackInBase(target);\n }\n }",
"private void getMonthlyRelativeDates(Calendar calendar, int frequency, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int dayNumber = NumberHelper.getInt(m_dayNumber);\n\n while (moreDates(calendar, dates))\n {\n if (dayNumber > 4)\n {\n setCalendarToLastRelativeDay(calendar);\n }\n else\n {\n setCalendarToOrdinalRelativeDay(calendar, dayNumber);\n }\n\n if (calendar.getTimeInMillis() > startDate)\n {\n dates.add(calendar.getTime());\n if (!moreDates(calendar, dates))\n {\n break;\n }\n }\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }",
"public static boolean checkAddProperty(\r\n CmsCmisTypeManager typeManager,\r\n Properties properties,\r\n String typeId,\r\n Set<String> filter,\r\n String id) {\r\n\r\n if ((properties == null) || (properties.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Properties must not be null!\");\r\n }\r\n\r\n if (id == null) {\r\n throw new IllegalArgumentException(\"Id must not be null!\");\r\n }\r\n\r\n TypeDefinition type = typeManager.getType(typeId);\r\n if (type == null) {\r\n throw new IllegalArgumentException(\"Unknown type: \" + typeId);\r\n }\r\n if (!type.getPropertyDefinitions().containsKey(id)) {\r\n throw new IllegalArgumentException(\"Unknown property: \" + id);\r\n }\r\n\r\n String queryName = type.getPropertyDefinitions().get(id).getQueryName();\r\n\r\n if ((queryName != null) && (filter != null)) {\r\n if (!filter.contains(queryName)) {\r\n return false;\r\n } else {\r\n filter.remove(queryName);\r\n }\r\n }\r\n\r\n return true;\r\n }",
"void countNonZeroInR( int[] parent ) {\n TriangularSolver_DSCC.postorder(parent,n,post,gwork);\n columnCounts.process(A,parent,post,countsR);\n nz_in_R = 0;\n for (int k = 0; k < n; k++) {\n nz_in_R += countsR[k];\n }\n if( nz_in_R < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in R counts\");\n }",
"public 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 saveLocalization() {\n\n SortedProperties localization = new SortedProperties();\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n String value = item.getItemProperty(TableProperty.TRANSLATION).getValue().toString();\n if (!(key.isEmpty() || value.isEmpty())) {\n localization.put(key, value);\n }\n }\n m_keyset.updateKeySet(m_localizations.get(m_locale).keySet(), localization.keySet());\n m_localizations.put(m_locale, localization);\n\n }",
"public static base_response unset(nitro_service client, csparameter resource, String[] args) throws Exception{\n\t\tcsparameter unsetresource = new csparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] |
Gets all checked widget indexes in the group. The indexes are counted from 0 to size -1,
where size is the number of Checkable widgets in the group. It does not take into account
any non-Checkable widgets added to the group widget.
@return list of checked widget indexes | [
"public <T extends Widget & Checkable> List<Integer> getCheckedWidgetIndexes() {\n List<Integer> checked = new ArrayList<>();\n List<Widget> children = getChildren();\n\n final int size = children.size();\n for (int i = 0, j = -1; i < size; ++i) {\n Widget c = children.get(i);\n if (c instanceof Checkable) {\n ++j;\n if (((Checkable) c).isChecked()) {\n checked.add(j);\n }\n }\n }\n\n return checked;\n }"
] | [
"private void initKeySetForXmlBundle() {\n\n // consider only available locales\n for (Locale l : m_locales) {\n if (m_xmlBundle.hasLocale(l)) {\n Set<Object> keys = new HashSet<Object>();\n for (I_CmsXmlContentValue msg : m_xmlBundle.getValueSequence(\"Message\", l).getValues()) {\n String msgpath = msg.getPath();\n keys.add(m_xmlBundle.getStringValue(m_cms, msgpath + \"/Key\", l));\n }\n m_keyset.updateKeySet(null, keys);\n }\n }\n\n }",
"public static CuratorFramework newFluoCurator(FluoConfiguration config) {\n return newCurator(config.getInstanceZookeepers(), config.getZookeeperTimeout(),\n config.getZookeeperSecret());\n }",
"public static dnstxtrec[] get(nitro_service service, String domain[]) throws Exception{\n\t\tif (domain !=null && domain.length>0) {\n\t\t\tdnstxtrec response[] = new dnstxtrec[domain.length];\n\t\t\tdnstxtrec obj[] = new dnstxtrec[domain.length];\n\t\t\tfor (int i=0;i<domain.length;i++) {\n\t\t\t\tobj[i] = new dnstxtrec();\n\t\t\t\tobj[i].set_domain(domain[i]);\n\t\t\t\tresponse[i] = (dnstxtrec) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public static Map<String, List<String>> getPartitionsForTopics(ZkClient zkClient, Collection<String> topics) {\n Map<String, List<String>> ret = new HashMap<String, List<String>>();\n for (String topic : topics) {\n List<String> partList = new ArrayList<String>();\n List<String> brokers = getChildrenParentMayNotExist(zkClient, BrokerTopicsPath + \"/\" + topic);\n if (brokers != null) {\n for (String broker : brokers) {\n final String parts = readData(zkClient, BrokerTopicsPath + \"/\" + topic + \"/\" + broker);\n int nParts = Integer.parseInt(parts);\n for (int i = 0; i < nParts; i++) {\n partList.add(broker + \"-\" + i);\n }\n }\n }\n Collections.sort(partList);\n ret.put(topic, partList);\n }\n return ret;\n }",
"public static double Cosh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return 1 + (x * x) / 2D;\r\n } else {\r\n\r\n double mult = x * x;\r\n double fact = 2;\r\n int factS = 4;\r\n double result = 1 + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }",
"public static boolean zipFolder(File folder, String fileName){\n\t\tboolean success = false;\n\t\tif(!folder.isDirectory()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(fileName == null){\n\t\t\tfileName = folder.getAbsolutePath()+ZIP_EXT;\n\t\t}\n\t\t\n\t\tZipArchiveOutputStream zipOutput = null;\n\t\ttry {\n\t\t\tzipOutput = new ZipArchiveOutputStream(new File(fileName));\n\t\t\t\n\t\t\tsuccess = addFolderContentToZip(folder,zipOutput,\"\");\n\n\t\t\tzipOutput.close();\n\t\t\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\tfinally{\n\t\t\ttry {\n\t\t\t\tif(zipOutput != null){\n\t\t\t\t\tzipOutput.close();\n\t\t\t\t}\n\t\t\t} catch (IOException e) {}\n\t\t}\n\t\treturn success;\n\t}",
"public void validateOperations(final List<ModelNode> operations) {\n if (operations == null) {\n return;\n }\n\n for (ModelNode operation : operations) {\n try {\n validateOperation(operation);\n } catch (RuntimeException e) {\n if (exitOnError) {\n throw e;\n } else {\n System.out.println(\"---- Operation validation error:\");\n System.out.println(e.getMessage());\n }\n\n }\n }\n }",
"@Override\n\tpublic int compareTo(IPAddressString other) {\n\t\tif(this == other) {\n\t\t\treturn 0;\n\t\t}\n\t\tboolean isValid = isValid();\n\t\tboolean otherIsValid = other.isValid();\n\t\tif(!isValid && !otherIsValid) {\n\t\t\treturn toString().compareTo(other.toString());\n\t\t}\n\t\treturn addressProvider.providerCompare(other.addressProvider);\n\t}",
"private boolean shouldWrapMethodCall(String methodName) {\n if (methodList == null) {\n return true; // Wrap all by default\n }\n\n if (methodList.contains(methodName)) {\n return true; //Wrap a specific method\n }\n\n // If I get to this point, I should not wrap the call.\n return false;\n }"
] |
return a prepared Select Statement for the given ClassDescriptor | [
"public PreparedStatement getSelectByPKStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getSelectByPKStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }"
] | [
"public static String getDefaultJdbcTypeFor(String javaType)\r\n {\r\n return _jdbcMappings.containsKey(javaType) ? (String)_jdbcMappings.get(javaType) : JDBC_DEFAULT_TYPE;\r\n }",
"public static Span exact(Bytes row) {\n Objects.requireNonNull(row);\n return new Span(row, true, row, true);\n }",
"public void addProfile(Object key, DescriptorRepository repository)\r\n {\r\n if (metadataProfiles.contains(key))\r\n {\r\n throw new MetadataException(\"Duplicate profile key. Key '\" + key + \"' already exists.\");\r\n }\r\n metadataProfiles.put(key, repository);\r\n }",
"public static base_response unset(nitro_service client, callhome resource, String[] args) throws Exception{\n\t\tcallhome unsetresource = new callhome();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"private String getOrdinal(Integer value)\n {\n String result;\n int index = value.intValue();\n if (index >= ORDINAL.length)\n {\n result = \"every \" + index + \"th\";\n }\n else\n {\n result = ORDINAL[index];\n }\n return result;\n }",
"public double[][] getU() {\n double[][] X = new double[n][n];\n double[][] U = X;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (i <= j) {\n U[i][j] = LU[i][j];\n } else {\n U[i][j] = 0.0;\n }\n }\n }\n return X;\n }",
"private static boolean equalAsInts(Vec2d a, Vec2d b) {\n return ((int) a.x) == ((int) b.x) && ((int) a.y) == ((int) b.y);\n }",
"public static void removeZeros( DMatrixSparseCSC input , DMatrixSparseCSC output , double tol ) {\n ImplCommonOps_DSCC.removeZeros(input,output,tol);\n }",
"private String getLogRequestIdentifier() {\n if (logIdentifier == null) {\n logIdentifier = String.format(\"%s-%s %s %s\", Integer.toHexString(hashCode()),\n numberOfRetries, connection.getRequestMethod(), connection.getURL());\n }\n return logIdentifier;\n }"
] |
File URLs whose protocol are in these list will be processed as jars
containing classes
@param fileProtocols
Comma separated list of file protocols that will be considered
as jar files and scanned | [
"@Inject(\"struts.json.action.fileProtocols\")\n\tpublic void setFileProtocols(String fileProtocols) {\n\t\tif (StringUtils.isNotBlank(fileProtocols)) {\n\t\t\tthis.fileProtocols = TextParseUtil.commaDelimitedStringToSet(fileProtocols);\n\t\t}\n\t}"
] | [
"public static base_responses link(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey linkresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tlinkresources[i] = new sslcertkey();\n\t\t\t\tlinkresources[i].certkey = resources[i].certkey;\n\t\t\t\tlinkresources[i].linkcertkeyname = resources[i].linkcertkeyname;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, linkresources,\"link\");\n\t\t}\n\t\treturn result;\n\t}",
"public void register(Delta delta) {\n\t\tfinal IResourceDescription newDesc = delta.getNew();\n\t\tif (newDesc == null) {\n\t\t\tremoveDescription(delta.getUri());\n\t\t} else {\n\t\t\taddDescription(delta.getUri(), newDesc);\n\t\t}\n\t}",
"private List<ParameterConverter> methodReturningConverters(final Class<?> type) {\n final List<ParameterConverter> converters = new ArrayList<>();\n for (final Method method : type.getMethods()) {\n if (method.isAnnotationPresent(AsParameterConverter.class)) {\n converters.add(new MethodReturningConverter(method, type, this));\n }\n }\n return converters;\n }",
"public SimplifySpanBuild append(String text) {\n if (TextUtils.isEmpty(text)) return this;\n\n mNormalSizeText.append(text);\n mStringBuilder.append(text);\n return this;\n }",
"public static cachecontentgroup[] get(nitro_service service) throws Exception{\n\t\tcachecontentgroup obj = new cachecontentgroup();\n\t\tcachecontentgroup[] response = (cachecontentgroup[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public ItemRequest<Workspace> findById(String workspace) {\n \n String path = String.format(\"/workspaces/%s\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"GET\");\n }",
"public RedwoodConfiguration loggingClass(final Class<?> classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces.getName()); } });\r\n return this;\r\n }",
"public CollectionRequest<Task> subtasks(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (CallableStatement) Proxy.newProxyInstance(\n\t\t\t\tCallableStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {CallableStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}"
] |
Use this API to fetch all the lbsipparameters resources that are configured on netscaler. | [
"public static lbsipparameters get(nitro_service service) throws Exception{\n\t\tlbsipparameters obj = new lbsipparameters();\n\t\tlbsipparameters[] response = (lbsipparameters[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] | [
"private void validateAttributesToCreateANewRendererViewHolder() {\n if (viewType == null) {\n throw new NullContentException(\n \"RendererBuilder needs a view type to create a RendererViewHolder\");\n }\n if (layoutInflater == null) {\n throw new NullLayoutInflaterException(\n \"RendererBuilder needs a LayoutInflater to create a RendererViewHolder\");\n }\n if (parent == null) {\n throw new NullParentException(\n \"RendererBuilder needs a parent to create a RendererViewHolder\");\n }\n }",
"public static void writeProcessorOutputToValues(\n final Object output,\n final Processor<?, ?> processor,\n final Values values) {\n Map<String, String> mapper = processor.getOutputMapperBiMap();\n if (mapper == null) {\n mapper = Collections.emptyMap();\n }\n\n final Collection<Field> fields = getAllAttributes(output.getClass());\n for (Field field: fields) {\n String name = getOutputValueName(processor.getOutputPrefix(), mapper, field);\n try {\n final Object value = field.get(output);\n if (value != null) {\n values.put(name, value);\n } else {\n values.remove(name);\n }\n } catch (IllegalAccessException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n }",
"public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createBundleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }",
"public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n if (creationalContext != null) {\n T instance = contextual.create(creationalContext);\n if (creationalContext instanceof WeldCreationalContext<?>) {\n addDependentInstance(instance, contextual, (WeldCreationalContext<T>) creationalContext);\n }\n return instance;\n } else {\n return null;\n }\n }",
"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 }",
"private void calculateSCL(double[] x) {\r\n //System.out.println(\"Checking at: \"+x[0]+\" \"+x[1]+\" \"+x[2]);\r\n value = 0.0;\r\n Arrays.fill(derivative, 0.0);\r\n double[] sums = new double[numClasses];\r\n double[] probs = new double[numClasses];\r\n double[] counts = new double[numClasses];\r\n Arrays.fill(counts, 0.0);\r\n for (int d = 0; d < data.length; d++) {\r\n // if (d == testMin) {\r\n // d = testMax - 1;\r\n // continue;\r\n // }\r\n int[] features = data[d];\r\n // activation\r\n Arrays.fill(sums, 0.0);\r\n for (int c = 0; c < numClasses; c++) {\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n sums[c] += x[i];\r\n }\r\n }\r\n // expectation (slower routine replaced by fast way)\r\n // double total = Double.NEGATIVE_INFINITY;\r\n // for (int c=0; c<numClasses; c++) {\r\n // total = SloppyMath.logAdd(total, sums[c]);\r\n // }\r\n double total = ArrayMath.logSum(sums);\r\n int ld = labels[d];\r\n for (int c = 0; c < numClasses; c++) {\r\n probs[c] = Math.exp(sums[c] - total);\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n derivative[i] += probs[ld] * probs[c];\r\n }\r\n }\r\n // observed\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], labels[d]);\r\n derivative[i] -= probs[ld];\r\n }\r\n value -= probs[ld];\r\n }\r\n // priors\r\n if (true) {\r\n for (int i = 0; i < x.length; i++) {\r\n double k = 1.0;\r\n double w = x[i];\r\n value += k * w * w / 2.0;\r\n derivative[i] += k * w;\r\n }\r\n }\r\n }",
"public static boolean isPostJDK5(String bytecodeVersion) {\n return JDK5.equals(bytecodeVersion)\n || JDK6.equals(bytecodeVersion)\n || JDK7.equals(bytecodeVersion)\n || JDK8.equals(bytecodeVersion);\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 Object getRealSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tif (_realSubject == null)\r\n\t\t{\r\n\t\t\tbeforeMaterialization();\r\n\t\t\t_realSubject = materializeSubject();\r\n\t\t\tafterMaterialization();\r\n\t\t}\r\n\t\treturn _realSubject;\r\n\t}"
] |
Extracts the words from a string. Words are seperated by a space character.
@param line The line that is being parsed.
@return A list of words contained on the line. | [
"protected List<String> parseWords(String line) {\n List<String> words = new ArrayList<String>();\n boolean insideWord = !isSpace(line.charAt(0));\n int last = 0;\n for( int i = 0; i < line.length(); i++) {\n char c = line.charAt(i);\n\n if( insideWord ) {\n // see if its at the end of a word\n if( isSpace(c)) {\n words.add( line.substring(last,i) );\n insideWord = false;\n }\n } else {\n if( !isSpace(c)) {\n last = i;\n insideWord = true;\n }\n }\n }\n\n // if the line ended add the final word\n if( insideWord ) {\n words.add( line.substring(last));\n }\n return words;\n }"
] | [
"public static boolean isPropertyAllowed(Class defClass, String propertyName)\r\n {\r\n HashMap props = (HashMap)_properties.get(defClass);\r\n\r\n return (props == null ? true : props.containsKey(propertyName));\r\n }",
"public static <T> T splitEachLine(File self, String regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure<T> closure) throws IOException {\n return IOGroovyMethods.splitEachLine(newReader(self), regex, closure);\n }",
"public static Object formatL(final String template, final Object... args) {\n return new Object() {\n @Override\n public String toString() {\n return format(template, args);\n }\n };\n }",
"private static int[] getMode2PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n for (int i = 0; i < postcode.length(); i++) {\r\n if (postcode.charAt(i) < '0' || postcode.charAt(i) > '9') {\r\n postcode = postcode.substring(0, i);\r\n break;\r\n }\r\n }\r\n\r\n int postcodeNum = Integer.parseInt(postcode);\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNum & 0x03) << 4) | 2;\r\n primary[1] = ((postcodeNum & 0xfc) >> 2);\r\n primary[2] = ((postcodeNum & 0x3f00) >> 8);\r\n primary[3] = ((postcodeNum & 0xfc000) >> 14);\r\n primary[4] = ((postcodeNum & 0x3f00000) >> 20);\r\n primary[5] = ((postcodeNum & 0x3c000000) >> 26) | ((postcode.length() & 0x3) << 4);\r\n primary[6] = ((postcode.length() & 0x3c) >> 2) | ((country & 0x3) << 4);\r\n primary[7] = (country & 0xfc) >> 2;\r\n primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);\r\n primary[9] = ((service & 0x3f0) >> 4);\r\n\r\n return primary;\r\n }",
"void saveAction() {\n\n Map<Object, Object> filters = getFilters();\n m_table.clearFilters();\n\n try {\n\n m_model.save();\n disableSaveButtons();\n\n } catch (CmsException e) {\n LOG.error(m_messages.key(Messages.ERR_SAVING_CHANGES_0), e);\n CmsErrorDialog.showErrorDialog(m_messages.key(Messages.ERR_SAVING_CHANGES_0), e);\n }\n\n setFilters(filters);\n\n }",
"protected AbstractColumn buildSimpleColumn() {\n\t\tSimpleColumn column = new SimpleColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumnProperty.getFieldProperties().putAll(fieldProperties);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setFieldDescription(fieldDescription);\n\t\treturn column;\n\t}",
"private boolean isSplit(ProjectCalendar calendar, List<TimephasedWork> list)\n {\n boolean result = false;\n for (TimephasedWork assignment : list)\n {\n if (calendar != null && assignment.getTotalAmount().getDuration() == 0)\n {\n Duration calendarWork = calendar.getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.MINUTES);\n if (calendarWork.getDuration() != 0)\n {\n result = true;\n break;\n }\n }\n }\n return result;\n }",
"@Override\n public boolean applyLayout(Layout itemLayout) {\n boolean applied = false;\n if (itemLayout != null && mItemLayouts.add(itemLayout)) {\n\n // apply the layout to all visible pages\n List<Widget> views = getAllViews();\n for (Widget view: views) {\n view.applyLayout(itemLayout.clone());\n }\n applied = true;\n }\n return applied;\n }",
"private double getExpectedProbability(double x)\n {\n double y = 1 / (standardDeviation * Math.sqrt(Math.PI * 2));\n double z = -(Math.pow(x - mean, 2) / (2 * Math.pow(standardDeviation, 2)));\n return y * Math.exp(z);\n }"
] |
Returns all found resolvers
@return | [
"public static List<ObjectModelResolver> getResolvers() {\n if (resolvers == null) {\n synchronized (serviceLoader) {\n if (resolvers == null) {\n List<ObjectModelResolver> foundResolvers = new ArrayList<ObjectModelResolver>();\n for (ObjectModelResolver resolver : serviceLoader) {\n foundResolvers.add(resolver);\n }\n resolvers = foundResolvers;\n }\n }\n }\n\n return resolvers;\n }"
] | [
"private String getResourceField(int key)\n {\n String result = null;\n\n if (key > 0 && key < m_resourceNames.length)\n {\n result = m_resourceNames[key];\n }\n\n return (result);\n }",
"public boolean isConnectionHandleAlive(ConnectionHandle connection) {\r\n\t\tStatement stmt = null;\r\n\t\tboolean result = false;\r\n\t\tboolean logicallyClosed = connection.logicallyClosed.get();\r\n\t\ttry {\r\n\t\t\tconnection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed.\r\n\t\t\tString testStatement = this.config.getConnectionTestStatement();\r\n\t\t\tResultSet rs = null;\r\n\r\n\t\t\tif (testStatement == null) {\r\n\t\t\t\t// Make a call to fetch the metadata instead of a dummy query.\r\n\t\t\t\trs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE );\r\n\t\t\t} else {\r\n\t\t\t\tstmt = connection.createStatement();\r\n\t\t\t\tstmt.execute(testStatement);\r\n\t\t\t}\r\n\r\n\r\n\t\t\tif (rs != null) {\r\n\t\t\t\trs.close();\r\n\t\t\t}\r\n\r\n\t\t\tresult = true;\r\n\t\t} catch (SQLException e) {\r\n\t\t\t// connection must be broken!\r\n\t\t\tresult = false;\r\n\t\t} finally {\r\n\t\t\tconnection.logicallyClosed.set(logicallyClosed);\r\n\t\t\tconnection.setConnectionLastResetInMs(System.currentTimeMillis());\r\n\t\t\tresult = closeStatement(stmt, result);\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases)\n {\n int uniqueID = MPPUtility.getInt(data, offset);\n FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4));\n Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8));\n int style = MPPUtility.getByte(data, offset + 9);\n ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10));\n int change = MPPUtility.getByte(data, offset + 12);\n\n FontBase fontBase = fontBases.get(index);\n\n boolean bold = ((style & 0x01) != 0);\n boolean italic = ((style & 0x02) != 0);\n boolean underline = ((style & 0x04) != 0);\n\n boolean boldChanged = ((change & 0x01) != 0);\n boolean underlineChanged = ((change & 0x02) != 0);\n boolean italicChanged = ((change & 0x04) != 0);\n boolean colorChanged = ((change & 0x08) != 0);\n boolean fontChanged = ((change & 0x10) != 0);\n boolean backgroundColorChanged = (uniqueID == -1);\n boolean backgroundPatternChanged = (uniqueID == -1);\n\n return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged));\n }",
"private Database readSingleSchemaFile(DatabaseIO reader, File schemaFile)\r\n {\r\n Database model = null;\r\n\r\n if (!schemaFile.isFile())\r\n {\r\n log(\"Path \"+schemaFile.getAbsolutePath()+\" does not denote a schema file\", Project.MSG_ERR);\r\n }\r\n else if (!schemaFile.canRead())\r\n {\r\n log(\"Could not read schema file \"+schemaFile.getAbsolutePath(), Project.MSG_ERR);\r\n }\r\n else\r\n {\r\n try\r\n {\r\n model = reader.read(schemaFile);\r\n log(\"Read schema file \"+schemaFile.getAbsolutePath(), Project.MSG_INFO);\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new BuildException(\"Could not read schema file \"+schemaFile.getAbsolutePath()+\": \"+ex.getLocalizedMessage(), ex);\r\n }\r\n }\r\n return model;\r\n }",
"private ArrayList handleDependentCollections(Identity oid, Object obj,\r\n Object[] origCollections, Object[] newCollections,\r\n Object[] newCollectionsOfObjects)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(obj.getClass());\r\n Collection colDescs = mif.getCollectionDescriptors();\r\n ArrayList newObjects = new ArrayList();\r\n int count = 0;\r\n\r\n for (Iterator it = colDescs.iterator(); it.hasNext(); count++)\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) it.next();\r\n\r\n if (cds.getOtmDependent())\r\n {\r\n ArrayList origList = (origCollections == null ? null\r\n : (ArrayList) origCollections[count]);\r\n ArrayList newList = (ArrayList) newCollections[count];\r\n\r\n if (origList != null)\r\n {\r\n for (Iterator it2 = origList.iterator(); it2.hasNext(); )\r\n {\r\n Identity origOid = (Identity) it2.next();\r\n\r\n if ((newList == null) || !newList.contains(origOid))\r\n {\r\n markDelete(origOid, oid, true);\r\n }\r\n }\r\n }\r\n\r\n if (newList != null)\r\n {\r\n int countElem = 0;\r\n for (Iterator it2 = newList.iterator(); it2.hasNext(); countElem++)\r\n {\r\n Identity newOid = (Identity) it2.next();\r\n\r\n if ((origList == null) || !origList.contains(newOid))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n ArrayList relCol = (ArrayList)\r\n newCollectionsOfObjects[count];\r\n Object relObj = relCol.get(countElem);\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, null, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\n }",
"public static <T extends EObject> IScope scopeFor(Iterable<? extends T> elements,\n\t\t\tfinal Function<T, QualifiedName> nameComputation, IScope outer) {\n\t\treturn new SimpleScope(outer,scopedElementsFor(elements, nameComputation));\n\t}",
"public static Properties loadProperties(String[] filesToLoad)\n {\n Properties p = new Properties();\n InputStream fis = null;\n for (String path : filesToLoad)\n {\n try\n {\n fis = Db.class.getClassLoader().getResourceAsStream(path);\n if (fis != null)\n {\n p.load(fis);\n jqmlogger.info(\"A jqm.properties file was found at {}\", path);\n }\n }\n catch (IOException e)\n {\n // We allow no configuration files, but not an unreadable configuration file.\n throw new DatabaseException(\"META-INF/jqm.properties file is invalid\", e);\n }\n finally\n {\n closeQuietly(fis);\n }\n }\n\n // Overload the datasource name from environment variable if any (tests only).\n String dbName = System.getenv(\"DB\");\n if (dbName != null)\n {\n p.put(\"com.enioka.jqm.jdbc.datasource\", \"jdbc/\" + dbName);\n }\n\n // Done\n return p;\n }",
"public Where<T, ID> in(String columnName, Iterable<?> objects) throws SQLException {\n\t\taddClause(new In(columnName, findColumnFieldType(columnName), objects, true));\n\t\treturn this;\n\t}",
"public String getString(Integer id, Integer type)\n {\n return (getString(m_meta.getOffset(id, type)));\n }"
] |
prefetch defined relationships requires JDBC level 2.0, does not work
with Arrays | [
"private void prefetchRelationships(Query query)\r\n {\r\n List prefetchedRel;\r\n Collection owners;\r\n String relName;\r\n RelationshipPrefetcher[] prefetchers;\r\n\r\n if (query == null || query.getPrefetchedRelationships() == null || query.getPrefetchedRelationships().isEmpty())\r\n {\r\n return;\r\n }\r\n\r\n if (!supportsAdvancedJDBCCursorControl())\r\n {\r\n logger.info(\"prefetching relationships requires JDBC level 2.0\");\r\n return;\r\n }\r\n\r\n // prevent releasing of DBResources\r\n setInBatchedMode(true);\r\n\r\n prefetchedRel = query.getPrefetchedRelationships();\r\n prefetchers = new RelationshipPrefetcher[prefetchedRel.size()];\r\n\r\n // disable auto retrieve for all prefetched relationships\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n relName = (String) prefetchedRel.get(i);\r\n prefetchers[i] = getBroker().getRelationshipPrefetcherFactory()\r\n .createRelationshipPrefetcher(getQueryObject().getClassDescriptor(), relName);\r\n prefetchers[i].prepareRelationshipSettings();\r\n }\r\n\r\n // materialize ALL owners of this Iterator\r\n owners = getOwnerObjects();\r\n\r\n // prefetch relationships and associate with owners\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n prefetchers[i].prefetchRelationship(owners);\r\n }\r\n\r\n // reset auto retrieve for all prefetched relationships\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n prefetchers[i].restoreRelationshipSettings();\r\n }\r\n\r\n try\r\n {\r\n getRsAndStmt().m_rs.beforeFirst(); // reposition resultset jdbc 2.0\r\n }\r\n catch (SQLException e)\r\n {\r\n logger.error(\"beforeFirst failed !\", e);\r\n }\r\n\r\n setInBatchedMode(false);\r\n setHasCalledCheck(false);\r\n }"
] | [
"static Locale getLocale(PageContext pageContext, String name) {\r\n\r\n Locale loc = null;\r\n\r\n Object obj = javax.servlet.jsp.jstl.core.Config.find(pageContext, name);\r\n if (obj != null) {\r\n if (obj instanceof Locale) {\r\n loc = (Locale)obj;\r\n } else {\r\n loc = SetLocaleSupport.parseLocale((String)obj);\r\n }\r\n }\r\n\r\n return loc;\r\n }",
"public ReferrerList getCollectionReferrers(Date date, String domain, String collectionId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_COLLECTION_REFERRERS, domain, \"collection_id\", collectionId, date, perPage, page);\n }",
"public static dnssuffix get(nitro_service service, String Dnssuffix) throws Exception{\n\t\tdnssuffix obj = new dnssuffix();\n\t\tobj.set_Dnssuffix(Dnssuffix);\n\t\tdnssuffix response = (dnssuffix) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void writeTask(Task task) throws IOException\n {\n writeFields(null, task, TaskField.values());\n for (Task child : task.getChildTasks())\n {\n writeTask(child);\n }\n }",
"private void addPropertyCounters(UsageStatistics usageStatistics,\n\t\t\tPropertyIdValue property) {\n\t\tif (!usageStatistics.propertyCountsMain.containsKey(property)) {\n\t\t\tusageStatistics.propertyCountsMain.put(property, 0);\n\t\t\tusageStatistics.propertyCountsQualifier.put(property, 0);\n\t\t\tusageStatistics.propertyCountsReferences.put(property, 0);\n\t\t}\n\t}",
"private void merge(Integer cid1, Integer cid2) {\n Collection<String> klass1 = classix.get(cid1);\n Collection<String> klass2 = classix.get(cid2);\n\n // if klass1 is the smaller, swap the two\n if (klass1.size() < klass2.size()) {\n Collection<String> tmp = klass2;\n klass2 = klass1;\n klass1 = tmp;\n\n Integer itmp = cid2;\n cid2 = cid1;\n cid1 = itmp;\n }\n\n // now perform the actual merge\n for (String id : klass2) {\n klass1.add(id);\n recordix.put(id, cid1);\n }\n\n // delete the smaller class, and we're done\n classix.remove(cid2);\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 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 base_responses unset(nitro_service client, String certkey[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (certkey != null && certkey.length > 0) {\n\t\t\tsslcertkey unsetresources[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++){\n\t\t\t\tunsetresources[i] = new sslcertkey();\n\t\t\t\tunsetresources[i].certkey = certkey[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] |
Get a list of referrers from a given domain to a collection.
@param date
(Required) Stats will be returned for this date. A day according to Flickr Stats starts at midnight GMT for all users, and timestamps will
automatically be rounded down to the start of the day.
@param domain
(Required) The domain to return referrers for. This should be a hostname (eg: "flickr.com") with no protocol or pathname.
@param collectionId
(Optional) The id of the collection to get stats for. If not provided, stats for all collections will be returned.
@param perPage
(Optional) Number of domains to return per page. If this argument is omitted, it defaults to 25. The maximum allowed value is 100.
@param page
(Optional) The page of results to return. If this argument is omitted, it defaults to 1.
@see "http://www.flickr.com/services/api/flickr.stats.getCollectionReferrers.html" | [
"public ReferrerList getCollectionReferrers(Date date, String domain, String collectionId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_COLLECTION_REFERRERS, domain, \"collection_id\", collectionId, date, perPage, page);\n }"
] | [
"@Override\n public boolean invokeFunction(String funcName, Object[] params) {\n // Run script if it is dirty. This makes sure the script is run\n // on the same thread as the caller (suppose the caller is always\n // calling from the same thread).\n checkDirty();\n\n // Skip bad functions\n if (isBadFunction(funcName)) {\n return false;\n }\n\n String statement = getInvokeStatementCached(funcName, params);\n\n synchronized (mEngineLock) {\n localBindings = mLocalEngine.getBindings(ScriptContext.ENGINE_SCOPE);\n if (localBindings == null) {\n localBindings = mLocalEngine.createBindings();\n mLocalEngine.setBindings(localBindings, ScriptContext.ENGINE_SCOPE);\n }\n }\n\n fillBindings(localBindings, params);\n\n try {\n mLocalEngine.eval(statement);\n } catch (ScriptException e) {\n // The function is either undefined or throws, avoid invoking it later\n addBadFunction(funcName);\n mLastError = e.getMessage();\n return false;\n } finally {\n removeBindings(localBindings, params);\n }\n\n return true;\n }",
"public static MethodNode findSAM(ClassNode type) {\n if (!Modifier.isAbstract(type.getModifiers())) return null;\n if (type.isInterface()) {\n List<MethodNode> methods = type.getMethods();\n MethodNode found=null;\n for (MethodNode mi : methods) {\n // ignore methods, that are not abstract and from Object\n if (!Modifier.isAbstract(mi.getModifiers())) continue;\n // ignore trait methods which have a default implementation\n if (Traits.hasDefaultImplementation(mi)) continue;\n if (mi.getDeclaringClass().equals(OBJECT_TYPE)) continue;\n if (OBJECT_TYPE.getDeclaredMethod(mi.getName(), mi.getParameters())!=null) continue;\n\n // we have two methods, so no SAM\n if (found!=null) return null;\n found = mi;\n }\n return found;\n\n } else {\n\n List<MethodNode> methods = type.getAbstractMethods();\n MethodNode found = null;\n if (methods!=null) {\n for (MethodNode mi : methods) {\n if (!hasUsableImplementation(type, mi)) {\n if (found!=null) return null;\n found = mi;\n }\n }\n }\n return found;\n }\n }",
"public static Type boxedType(Type type) {\n if (type instanceof Class<?>) {\n return boxedClass((Class<?>) type);\n } else {\n return type;\n }\n }",
"public int getXForBeat(int beat) {\n BeatGrid grid = beatGrid.get();\n if (grid != null) {\n return millisecondsToX(grid.getTimeWithinTrack(beat));\n }\n return 0;\n }",
"public Double getAvgEventValue() {\n resetIfNeeded();\n synchronized(this) {\n long eventsLastInterval = numEventsLastInterval - numEventsLastLastInterval;\n if(eventsLastInterval > 0)\n return ((totalEventValueLastInterval - totalEventValueLastLastInterval) * 1.0)\n / eventsLastInterval;\n else\n return 0.0;\n }\n }",
"public WebSocketContext sendToUser(String message, String username) {\n return sendToConnections(message, username, manager.usernameRegistry(), true);\n }",
"public static base_responses reset(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 resetresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tresetresources[i] = new appfwlearningdata();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, resetresources,\"reset\");\n\t\t}\n\t\treturn result;\n\t}",
"protected static int calculateShift(int minimumValue, int maximumValue) {\n\t\tint shift = 0;\n\t\tint value = 1;\n\t\twhile (value < minimumValue && value < maximumValue) {\n\t\t\tvalue <<= 1;\n\t\t\tshift++;\n\t\t}\n\t\treturn shift;\n\t}",
"public static rnatparam get(nitro_service service) throws Exception{\n\t\trnatparam obj = new rnatparam();\n\t\trnatparam[] response = (rnatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] |
Registers all custom Externalizer implementations that Hibernate OGM needs into a running
Infinispan CacheManager configuration.
This is only safe to do when Caches from this CacheManager haven't been started yet,
or the ones already started do not contain any data needing these.
@see ExternalizerIds
@param globalCfg the Serialization section of a GlobalConfiguration builder | [
"public static void registerOgmExternalizers(GlobalConfiguration globalCfg) {\n\t\tMap<Integer, AdvancedExternalizer<?>> externalizerMap = globalCfg.serialization().advancedExternalizers();\n\t\texternalizerMap.putAll( ogmExternalizers );\n\t}"
] | [
"public static String readCorrelationId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String correlationId = null;\n Header hdCorrelationId = ((SoapMessage) message).getHeader(CORRELATION_ID_QNAME);\n if (hdCorrelationId != null) {\n if (hdCorrelationId.getObject() instanceof String) {\n correlationId = (String) hdCorrelationId.getObject();\n } else if (hdCorrelationId.getObject() instanceof Node) {\n Node headerNode = (Node) hdCorrelationId.getObject();\n correlationId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found CorrelationId soap header but value is not a String or a Node! Value: \"\n + hdCorrelationId.getObject().toString());\n }\n }\n return correlationId;\n }",
"public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\n }",
"@RequestMapping(value = \"api/edit/enable/custom\", method = RequestMethod.POST)\n public\n @ResponseBody\n String enableCustomResponse(Model model, String custom, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n if (custom.equals(\"undefined\"))\n return null;\n editService.enableCustomResponse(custom, path_id, clientUUID);\n return null;\n }",
"private void writePredecessors(Task mpxjTask, net.sf.mpxj.planner.schema.Task plannerTask)\n {\n Predecessors plannerPredecessors = m_factory.createPredecessors();\n plannerTask.setPredecessors(plannerPredecessors);\n List<Predecessor> predecessorList = plannerPredecessors.getPredecessor();\n int id = 0;\n\n List<Relation> predecessors = mpxjTask.getPredecessors();\n for (Relation rel : predecessors)\n {\n Integer taskUniqueID = rel.getTargetTask().getUniqueID();\n Predecessor plannerPredecessor = m_factory.createPredecessor();\n plannerPredecessor.setId(getIntegerString(++id));\n plannerPredecessor.setPredecessorId(getIntegerString(taskUniqueID));\n plannerPredecessor.setLag(getDurationString(rel.getLag()));\n plannerPredecessor.setType(RELATIONSHIP_TYPES.get(rel.getType()));\n predecessorList.add(plannerPredecessor);\n m_eventManager.fireRelationWrittenEvent(rel);\n }\n }",
"@Deprecated\n public ModelNode navigate(ModelNode model, boolean create) throws NoSuchElementException {\n final Iterator<PathElement> i = pathAddressList.iterator();\n while (i.hasNext()) {\n final PathElement element = i.next();\n if (create && !i.hasNext()) {\n if (element.isMultiTarget()) {\n throw new IllegalStateException();\n }\n model = model.require(element.getKey()).get(element.getValue());\n } else {\n model = model.require(element.getKey()).require(element.getValue());\n }\n }\n return model;\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 static void listResourceNotes(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n String notes = resource.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + resource.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\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}",
"Response put(URI uri, InputStream instream, String contentType) {\n HttpConnection connection = Http.PUT(uri, contentType);\n\n connection.setRequestBody(instream);\n\n return executeToResponse(connection);\n }"
] |
Returns the adapter position of the Parent associated with this ChildViewHolder
@return The adapter position of the Parent if it still exists in the adapter.
RecyclerView.NO_POSITION if item has been removed from the adapter,
RecyclerView.Adapter.notifyDataSetChanged() has been called after the last
layout pass or the ViewHolder has already been recycled. | [
"@UiThread\n public int getParentAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) {\n return RecyclerView.NO_POSITION;\n }\n\n return mExpandableAdapter.getNearestParentPosition(flatPosition);\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 }",
"public boolean remove(long key) {\n int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;\n Entry previous = null;\n Entry entry = table[index];\n while (entry != null) {\n Entry next = entry.next;\n if (entry.key == key) {\n if (previous == null) {\n table[index] = next;\n } else {\n previous.next = next;\n }\n size--;\n return true;\n }\n previous = entry;\n entry = next;\n }\n return false;\n }",
"@Override\n public void detachScriptFile(IScriptable target) {\n IScriptFile scriptFile = mScriptMap.remove(target);\n if (scriptFile != null) {\n scriptFile.invokeFunction(\"onDetach\", new Object[] { target });\n }\n }",
"public void setColor(int n, int color) {\n\t\tint firstColor = map[0];\n\t\tint lastColor = map[256-1];\n\t\tif (n > 0)\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)i/n, firstColor, color);\n\t\tif (n < 256-1)\n\t\t\tfor (int i = n; i < 256; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)(i-n)/(256-n), color, lastColor);\n\t}",
"public void logAttributeWarning(PathAddress address, String message, String attribute) {\n logAttributeWarning(address, null, message, attribute);\n }",
"@Override\n public Response doRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doRequestUrl(stitchReq, getHostname());\n }",
"private void readSubProjects(byte[] data, int uniqueIDOffset, int filePathOffset, int fileNameOffset, int subprojectIndex)\n {\n while (uniqueIDOffset < filePathOffset)\n {\n readSubProject(data, uniqueIDOffset, filePathOffset, fileNameOffset, subprojectIndex++);\n uniqueIDOffset += 4;\n }\n }",
"private void throwOrWarnAboutDescriptorProblem(String message) {\n if (validateDescriptions) {\n throw new IllegalArgumentException(message);\n }\n ControllerLogger.ROOT_LOGGER.warn(message);\n }",
"public static int[] randomSubset(int k, int n) {\n assert(0 < k && k <= n);\n Random r = new Random();\n int t = 0, m = 0;\n int[] result = new int[k];\n\n while (m < k) {\n double u = r.nextDouble();\n if ( (n - t) * u < k - m ) {\n result[m] = t;\n m++;\n }\n t++;\n }\n return result;\n }"
] |
Makes an spatial shape representing the time range defined by the two specified dates.
@param from the start {@link Date}
@param to the end {@link Date}
@return a shape | [
"public NRShape makeShape(Date from, Date to) {\n UnitNRShape fromShape = tree.toUnitShape(from);\n UnitNRShape toShape = tree.toUnitShape(to);\n return tree.toRangeShape(fromShape, toShape);\n }"
] | [
"private void registerNonExists(\n\t\tfinal org.hibernate.engine.spi.EntityKey[] keys,\n\t\tfinal Loadable[] persisters,\n\t\tfinal SharedSessionContractImplementor session) {\n\n\t\tfinal int[] owners = getOwners();\n\t\tif ( owners != null ) {\n\n\t\t\tEntityType[] ownerAssociationTypes = getOwnerAssociationTypes();\n\t\t\tfor ( int i = 0; i < keys.length; i++ ) {\n\n\t\t\t\tint owner = owners[i];\n\t\t\t\tif ( owner > -1 ) {\n\t\t\t\t\torg.hibernate.engine.spi.EntityKey ownerKey = keys[owner];\n\t\t\t\t\tif ( keys[i] == null && ownerKey != null ) {\n\n\t\t\t\t\t\tfinal PersistenceContext persistenceContext = session.getPersistenceContext();\n\n\t\t\t\t\t\t/*final boolean isPrimaryKey;\n\t\t\t\t\t\tfinal boolean isSpecialOneToOne;\n\t\t\t\t\t\tif ( ownerAssociationTypes == null || ownerAssociationTypes[i] == null ) {\n\t\t\t\t\t\t\tisPrimaryKey = true;\n\t\t\t\t\t\t\tisSpecialOneToOne = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tisPrimaryKey = ownerAssociationTypes[i].getRHSUniqueKeyPropertyName()==null;\n\t\t\t\t\t\t\tisSpecialOneToOne = ownerAssociationTypes[i].getLHSPropertyName()!=null;\n\t\t\t\t\t\t}*/\n\n\t\t\t\t\t\t//TODO: can we *always* use the \"null property\" approach for everything?\n\t\t\t\t\t\t/*if ( isPrimaryKey && !isSpecialOneToOne ) {\n\t\t\t\t\t\t\tpersistenceContext.addNonExistantEntityKey(\n\t\t\t\t\t\t\t\t\tnew EntityKey( ownerKey.getIdentifier(), persisters[i], session.getEntityMode() )\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if ( isSpecialOneToOne ) {*/\n\t\t\t\t\t\tboolean isOneToOneAssociation = ownerAssociationTypes != null &&\n\t\t\t\t\t\t\t\townerAssociationTypes[i] != null &&\n\t\t\t\t\t\t\t\townerAssociationTypes[i].isOneToOne();\n\t\t\t\t\t\tif ( isOneToOneAssociation ) {\n\t\t\t\t\t\t\tpersistenceContext.addNullProperty( ownerKey,\n\t\t\t\t\t\t\t\t\townerAssociationTypes[i].getPropertyName() );\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/*}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tpersistenceContext.addNonExistantEntityUniqueKey( new EntityUniqueKey(\n\t\t\t\t\t\t\t\t\tpersisters[i].getEntityName(),\n\t\t\t\t\t\t\t\t\townerAssociationTypes[i].getRHSUniqueKeyPropertyName(),\n\t\t\t\t\t\t\t\t\townerKey.getIdentifier(),\n\t\t\t\t\t\t\t\t\tpersisters[owner].getIdentifierType(),\n\t\t\t\t\t\t\t\t\tsession.getEntityMode()\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\t\t}\n\t}",
"private void readCalendar(Gantt gantt)\n {\n Gantt.Calendar ganttCalendar = gantt.getCalendar();\n m_projectFile.getProjectProperties().setWeekStartDay(ganttCalendar.getWeekStart());\n\n ProjectCalendar calendar = m_projectFile.addCalendar();\n calendar.setName(\"Standard\");\n m_projectFile.setDefaultCalendar(calendar);\n\n String workingDays = ganttCalendar.getWorkDays();\n calendar.setWorkingDay(Day.SUNDAY, workingDays.charAt(0) == '1');\n calendar.setWorkingDay(Day.MONDAY, workingDays.charAt(1) == '1');\n calendar.setWorkingDay(Day.TUESDAY, workingDays.charAt(2) == '1');\n calendar.setWorkingDay(Day.WEDNESDAY, workingDays.charAt(3) == '1');\n calendar.setWorkingDay(Day.THURSDAY, workingDays.charAt(4) == '1');\n calendar.setWorkingDay(Day.FRIDAY, workingDays.charAt(5) == '1');\n calendar.setWorkingDay(Day.SATURDAY, workingDays.charAt(6) == '1');\n\n for (int i = 1; i <= 7; i++)\n {\n Day day = Day.getInstance(i);\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n if (calendar.isWorkingDay(day))\n {\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n\n for (Gantt.Holidays.Holiday holiday : gantt.getHolidays().getHoliday())\n {\n ProjectCalendarException exception = calendar.addCalendarException(holiday.getDate(), holiday.getDate());\n exception.setName(holiday.getContent());\n }\n }",
"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 ServiceFuture<Void> fromBody(final Completable completable, final ServiceCallback<Void> callback) {\n final ServiceFuture<Void> serviceFuture = new ServiceFuture<>();\n completable.subscribe(new Action0() {\n Void value = null;\n @Override\n public void call() {\n if (callback != null) {\n callback.success(value);\n }\n serviceFuture.set(value);\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n if (callback != null) {\n callback.failure(throwable);\n }\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\n }",
"static Property getProperty(String propName, ModelNode attrs) {\n String[] arr = propName.split(\"\\\\.\");\n ModelNode attrDescr = attrs;\n for (String item : arr) {\n // Remove list part.\n if (item.endsWith(\"]\")) {\n int i = item.indexOf(\"[\");\n if (i < 0) {\n return null;\n }\n item = item.substring(0, i);\n }\n ModelNode descr = attrDescr.get(item);\n if (!descr.isDefined()) {\n if (attrDescr.has(Util.VALUE_TYPE)) {\n ModelNode vt = attrDescr.get(Util.VALUE_TYPE);\n if (vt.has(item)) {\n attrDescr = vt.get(item);\n continue;\n }\n }\n return null;\n }\n attrDescr = descr;\n }\n return new Property(propName, attrDescr);\n }",
"public static base_response clear(nitro_service client, route6 resource) throws Exception {\n\t\troute6 clearresource = new route6();\n\t\tclearresource.routetype = resource.routetype;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"private String dumpZoneNAryDetails(StoreRoutingPlan storeRoutingPlan) {\n StringBuilder sb = new StringBuilder();\n\n sb.append(\"\\tDetailed Dump (Zone N-Aries):\").append(Utils.NEWLINE);\n for(Node node: storeRoutingPlan.getCluster().getNodes()) {\n int zoneId = node.getZoneId();\n int nodeId = node.getId();\n sb.append(\"\\tNode ID: \" + nodeId + \" in zone \" + zoneId).append(Utils.NEWLINE);\n List<Integer> naries = storeRoutingPlan.getZoneNAryPartitionIds(nodeId);\n Map<Integer, List<Integer>> zoneNaryTypeToPartitionIds = new HashMap<Integer, List<Integer>>();\n for(int nary: naries) {\n int zoneReplicaType = storeRoutingPlan.getZoneNaryForNodesPartition(zoneId,\n nodeId,\n nary);\n if(!zoneNaryTypeToPartitionIds.containsKey(zoneReplicaType)) {\n zoneNaryTypeToPartitionIds.put(zoneReplicaType, new ArrayList<Integer>());\n }\n zoneNaryTypeToPartitionIds.get(zoneReplicaType).add(nary);\n }\n\n for(int replicaType: new TreeSet<Integer>(zoneNaryTypeToPartitionIds.keySet())) {\n sb.append(\"\\t\\t\" + replicaType + \" : \");\n sb.append(zoneNaryTypeToPartitionIds.get(replicaType).toString());\n sb.append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }",
"public static String getTemplateAsString(String fileName) throws IOException {\n // in .jar file\n String fNameJar = getFileNameInPath(fileName);\n InputStream inStream = DomUtils.class.getResourceAsStream(\"/\"\n + fNameJar);\n if (inStream == null) {\n // try to find file normally\n File f = new File(fileName);\n if (f.exists()) {\n inStream = new FileInputStream(f);\n } else {\n throw new IOException(\"Cannot find \" + fileName + \" or \"\n + fNameJar);\n }\n }\n\n BufferedReader bufferedReader = new BufferedReader(\n new InputStreamReader(inStream));\n String line;\n StringBuilder stringBuilder = new StringBuilder();\n\n while ((line = bufferedReader.readLine()) != null) {\n stringBuilder.append(line).append(\"\\n\");\n }\n\n bufferedReader.close();\n return stringBuilder.toString();\n }",
"public void useSimpleProxy() {\n String webAppAddress = \"http://localhost:\" + port + \"/services/personservice\";\n PersonService proxy = JAXRSClientFactory.create(webAppAddress, PersonService.class);\n\n new PersonServiceProxyClient(proxy).useService();\n }"
] |
return null if the operation has no params to validate | [
"public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException {\n\n final Set<String> keys = request.keys();\n if (keys.size() == 2) { // no props\n return null;\n }\n ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPONSE);\n if (outcome == null) {\n outcome = retrieveDescription(ctx, request, true);\n if (outcome == null) {\n return null;\n } else {\n ctx.set(Scope.REQUEST, DESCRIPTION_RESPONSE, outcome);\n }\n }\n if(!outcome.has(Util.RESULT)) {\n throw new CommandFormatException(\"Failed to perform \" + Util.READ_OPERATION_DESCRIPTION + \" to validate the request: result is not available.\");\n }\n\n final String operationName = request.get(Util.OPERATION).asString();\n\n final ModelNode result = outcome.get(Util.RESULT);\n final Set<String> definedProps = result.hasDefined(Util.REQUEST_PROPERTIES) ? result.get(Util.REQUEST_PROPERTIES).keys() : Collections.emptySet();\n if(definedProps.isEmpty()) {\n if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) {\n throw new CommandFormatException(\"Operation '\" + operationName + \"' does not expect any property.\");\n }\n } else {\n int skipped = 0;\n for(String prop : keys) {\n if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) {\n ++skipped;\n continue;\n }\n if(!definedProps.contains(prop)) {\n if(!Util.OPERATION_HEADERS.equals(prop)) {\n throw new CommandFormatException(\"'\" + prop + \"' is not found among the supported properties: \" + definedProps);\n }\n }\n }\n }\n return outcome;\n }"
] | [
"private static final int getUnicodeStringLengthInBytes(byte[] data, int offset)\n {\n int result;\n if (data == null || offset >= data.length)\n {\n result = 0;\n }\n else\n {\n result = data.length - offset;\n\n for (int loop = offset; loop < (data.length - 1); loop += 2)\n {\n if (data[loop] == 0 && data[loop + 1] == 0)\n {\n result = loop - offset;\n break;\n }\n }\n }\n return result;\n }",
"protected void propagateOnNoPick(GVRPicker picker)\n {\n if (mEventOptions.contains(EventOptions.SEND_PICK_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n getGVRContext().getEventManager().sendEvent(this, IPickEvents.class, \"onNoPick\", picker);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n getGVRContext().getEventManager().sendEvent(mScene, IPickEvents.class, \"onNoPick\", picker);\n }\n }\n }",
"private void addBlock(List<GenericCriteria> list, byte[] block, TestOperator operator)\n {\n GenericCriteria result = new GenericCriteria(m_properties);\n result.setOperator(operator);\n list.add(result);\n processBlock(result.getCriteriaList(), getChildBlock(block));\n processBlock(list, getListNextBlock(block));\n }",
"public void setAssociation(String collectionRole, Association association) {\n\t\tif ( associations == null ) {\n\t\t\tassociations = new HashMap<>();\n\t\t}\n\t\tassociations.put( collectionRole, association );\n\t}",
"public void setOccurrences(String occurrences) {\r\n\r\n int o = CmsSerialDateUtil.toIntWithDefault(occurrences, -1);\r\n if (m_model.getOccurrences() != o) {\r\n m_model.setOccurrences(o);\r\n valueChanged();\r\n }\r\n }",
"private void populateExpandedExceptions()\n {\n if (!m_exceptions.isEmpty() && m_expandedExceptions.isEmpty())\n {\n for (ProjectCalendarException exception : m_exceptions)\n {\n RecurringData recurring = exception.getRecurring();\n if (recurring == null)\n {\n m_expandedExceptions.add(exception);\n }\n else\n {\n for (Date date : recurring.getDates())\n {\n Date startDate = DateHelper.getDayStartDate(date);\n Date endDate = DateHelper.getDayEndDate(date);\n ProjectCalendarException newException = new ProjectCalendarException(startDate, endDate);\n int rangeCount = exception.getRangeCount();\n for (int rangeIndex = 0; rangeIndex < rangeCount; rangeIndex++)\n {\n newException.addRange(exception.getRange(rangeIndex));\n }\n m_expandedExceptions.add(newException);\n }\n }\n }\n Collections.sort(m_expandedExceptions);\n }\n }",
"@Override\n public final long optLong(final String key, final long defaultValue) {\n Long result = optLong(key);\n return result == null ? defaultValue : result;\n }",
"private <T extends ProgramElementDoc> List<T> filterByVisibility(T[] docs, Visibility visibility) {\n\tif (visibility == Visibility.PRIVATE)\n\t return Arrays.asList(docs);\n\n\tList<T> filtered = new ArrayList<T>();\n\tfor (T doc : docs) {\n\t if (Visibility.get(doc).compareTo(visibility) > 0)\n\t\tfiltered.add(doc);\n\t}\n\treturn filtered;\n }",
"public void handleStateEvent(String callbackKey) {\n if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {\n ((StateEventHandler) handlers.get(callbackKey)).handle();\n } else {\n System.err.println(\"Error in handle: \" + callbackKey + \" for state handler \");\n }\n }"
] |
Returns a set of the distinct colours used in this image.
@return the set of distinct Colors | [
"public Set<RGBColor> colours() {\n return stream().map(Pixel::toColor).collect(Collectors.toSet());\n }"
] | [
"public Map<String, ImplT> convertToUnmodifiableMap(List<InnerT> innerList) {\n Map<String, ImplT> result = new HashMap<>();\n for (InnerT inner : innerList) {\n result.put(name(inner), impl(inner));\n }\n\n return Collections.unmodifiableMap(result);\n }",
"public void setCycleInterval(float newCycleInterval) {\n if ( (this.cycleInterval != newCycleInterval) && (newCycleInterval > 0) ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n //TODO Cannot easily change the GVRAnimation's GVRChannel once set.\n }\n this.cycleInterval = newCycleInterval;\n }\n }",
"public List<TimephasedWork> getTimephasedBaselineWork(int index)\n {\n return m_timephasedBaselineWork[index] == null ? null : m_timephasedBaselineWork[index].getData();\n }",
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static float checkFloat(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInFloatRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), FLOAT_MIN, FLOAT_MAX);\n\t\t}\n\n\t\treturn number.floatValue();\n\t}",
"private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException {\n final RandomAccessFile raf = new RandomAccessFile(file, \"rw\");\n try {\n final FileChannel channel = raf.getChannel();\n try {\n long pos = channel.size() - ENDLEN;\n final ScanContext context;\n if (newSig == CRIPPLED_ENDSIG) {\n context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN);\n } else if (newSig == GOOD_ENDSIG) {\n context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN);\n } else {\n context = null;\n }\n\n if (!validateEndRecord(file, channel, pos, endSig)) {\n pos = scanForEndSig(file, channel, context);\n }\n if (pos == -1) {\n if (context.state == State.NOT_FOUND) {\n // Don't fail patching if we cannot validate a valid zip\n PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath());\n }\n return;\n }\n // Update the central directory record\n channel.position(pos);\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(newSig);\n buffer.flip();\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\n } finally {\n safeClose(channel);\n }\n } finally {\n safeClose(raf);\n }\n }",
"private void toCorrectDateWithDay(Calendar date, WeekOfMonth week) {\n\n date.set(Calendar.DAY_OF_MONTH, 1);\n int daysToFirstWeekDayMatch = ((m_weekDay.toInt() + I_CmsSerialDateValue.NUM_OF_WEEKDAYS)\n - (date.get(Calendar.DAY_OF_WEEK))) % I_CmsSerialDateValue.NUM_OF_WEEKDAYS;\n date.add(Calendar.DAY_OF_MONTH, daysToFirstWeekDayMatch);\n int wouldBeDayOfMonth = date.get(Calendar.DAY_OF_MONTH)\n + ((week.ordinal()) * I_CmsSerialDateValue.NUM_OF_WEEKDAYS);\n if (wouldBeDayOfMonth > date.getActualMaximum(Calendar.DAY_OF_MONTH)) {\n date.set(Calendar.DAY_OF_MONTH, wouldBeDayOfMonth - I_CmsSerialDateValue.NUM_OF_WEEKDAYS);\n } else {\n date.set(Calendar.DAY_OF_MONTH, wouldBeDayOfMonth);\n }\n\n }",
"private Integer getIntegerTimeInMinutes(Date date)\n {\n Integer result = null;\n if (date != null)\n {\n Calendar cal = DateHelper.popCalendar(date);\n int time = cal.get(Calendar.HOUR_OF_DAY) * 60;\n time += cal.get(Calendar.MINUTE);\n DateHelper.pushCalendar(cal);\n result = Integer.valueOf(time); \n }\n return (result);\n }",
"public Stats getPhotoStats(String photoId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTO_STATS, \"photo_id\", photoId, date);\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}"
] |
Re-initializes the shader texture used to fill in
the Circle upon drawing. | [
"public void updateBitmapShader() {\n\t\tif (image == null)\n\t\t\treturn;\n\n\t\tshader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);\n\n\t\tif(canvasSize != image.getWidth() || canvasSize != image.getHeight()) {\n\t\t\tMatrix matrix = new Matrix();\n\t\t\tfloat scale = (float) canvasSize / (float) image.getWidth();\n\t\t\tmatrix.setScale(scale, scale);\n\t\t\tshader.setLocalMatrix(matrix);\n\t\t}\n\t}"
] | [
"private void processResource(MapRow row) throws IOException\n {\n Resource resource = m_project.addResource();\n resource.setName(row.getString(\"NAME\"));\n resource.setGUID(row.getUUID(\"UUID\"));\n resource.setEmailAddress(row.getString(\"EMAIL\"));\n resource.setHyperlink(row.getString(\"URL\"));\n resource.setNotes(getNotes(row.getRows(\"COMMENTARY\")));\n resource.setText(1, row.getString(\"DESCRIPTION\"));\n resource.setText(2, row.getString(\"SUPPLY_REFERENCE\"));\n resource.setActive(true);\n\n List<MapRow> resources = row.getRows(\"RESOURCES\");\n if (resources != null)\n {\n for (MapRow childResource : sort(resources, \"NAME\"))\n {\n processResource(childResource);\n }\n }\n\n m_resourceMap.put(resource.getGUID(), resource);\n }",
"private void setNsid() throws FlickrException {\n\n if (username != null && !username.equals(\"\")) {\n Auth auth = null;\n if (authStore != null) {\n auth = authStore.retrieve(username); // assuming FileAuthStore is enhanced else need to\n // keep in user-level files.\n\n if (auth != null) {\n nsid = auth.getUser().getId();\n }\n }\n if (auth != null)\n return;\n\n Auth[] allAuths = authStore.retrieveAll();\n for (int i = 0; i < allAuths.length; i++) {\n if (username.equals(allAuths[i].getUser().getUsername())) {\n nsid = allAuths[i].getUser().getId();\n return;\n }\n }\n\n // For this to work: REST.java or PeopleInterface needs to change to pass apiKey\n // as the parameter to the call which is not authenticated.\n\n // Get nsid using flickr.people.findByUsername\n PeopleInterface peopleInterf = flickr.getPeopleInterface();\n User u = peopleInterf.findByUsername(username);\n if (u != null) {\n nsid = u.getId();\n }\n }\n }",
"@Pure\n\tpublic static <P1, P2, P3> Procedure2<P2, P3> curry(final Procedure3<? super P1, ? super P2, ? super P3> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure2<P2, P3>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p2, P3 p3) {\n\t\t\t\tprocedure.apply(argument, p2, p3);\n\t\t\t}\n\t\t};\n\t}",
"public static base_response unset(nitro_service client, coparameter resource, String[] args) throws Exception{\n\t\tcoparameter unsetresource = new coparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {\n\n if( decomposition.inputModified() ) {\n a = a.copy();\n }\n return decomposition.decompose(a);\n }",
"private boolean setAvailable(NodeStatus nodeStatus, boolean isAvailable) {\n synchronized(nodeStatus) {\n boolean previous = nodeStatus.isAvailable();\n\n nodeStatus.setAvailable(isAvailable);\n nodeStatus.setLastChecked(getConfig().getTime().getMilliseconds());\n\n return previous;\n }\n }",
"public String createSessionForResource(String configPath, String fileName) throws CmsUgcException {\n\n CmsUgcSession formSession = CmsUgcSessionFactory.getInstance().createSessionForFile(\n getCmsObject(),\n getRequest(),\n configPath,\n fileName);\n return \"\" + formSession.getId();\n }",
"public static base_response unset(nitro_service client, aaaparameter resource, String[] args) throws Exception{\n\t\taaaparameter unsetresource = new aaaparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public void clear() {\n if (arrMask != null) {\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n arrMask[x][y] = false;\n }\n }\n }\n }"
] |
Determine the enum value corresponding to the track source slot found in the packet.
@return the proper value | [
"private TrackSourceSlot findTrackSourceSlot() {\n TrackSourceSlot result = TRACK_SOURCE_SLOT_MAP.get(packetBytes[41]);\n if (result == null) {\n return TrackSourceSlot.UNKNOWN;\n }\n return result;\n }"
] | [
"public static nsrollbackcmd get(nitro_service service) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"private String getResponseString(boolean async, UploaderResponse response) {\r\n return async ? response.getTicketId() : response.getPhotoId();\r\n }",
"public int getMinutesPerWeek()\n {\n return m_minutesPerWeek == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerWeek()) : m_minutesPerWeek.intValue();\n }",
"private static QName getServiceName(Server server) {\n QName serviceName;\n String bindingId = getBindingId(server);\n EndpointInfo eInfo = server.getEndpoint().getEndpointInfo();\n \n if (JAXRS_BINDING_ID.equals(bindingId)) {\n serviceName = eInfo.getName();\n } else {\n ServiceInfo serviceInfo = eInfo.getService();\n serviceName = serviceInfo.getName();\n }\n return serviceName;\n }",
"public static String[] allLowerCase(String... strings){\n\t\tString[] tmp = new String[strings.length];\n\t\tfor(int idx=0;idx<strings.length;idx++){\n\t\t\tif(strings[idx] != null){\n\t\t\t\ttmp[idx] = strings[idx].toLowerCase();\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}",
"public static String get(Properties props, String name, String defval) {\n String value = props.getProperty(name);\n if (value == null)\n value = defval;\n return value;\n }",
"public String convert(BufferedImage image, boolean favicon) {\n // Reset statistics before anything\n statsArray = new int[12];\n // Begin the timer\n dStart = System.nanoTime();\n // Scale the image\n image = scale(image, favicon);\n // The +1 is for the newline characters\n StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight());\n\n for (int y = 0; y < image.getHeight(); y++) {\n // At the end of each line, add a newline character\n if (sb.length() != 0) sb.append(\"\\n\");\n for (int x = 0; x < image.getWidth(); x++) {\n //\n Color pixelColor = new Color(image.getRGB(x, y), true);\n int alpha = pixelColor.getAlpha();\n boolean isTransient = alpha < 0.1;\n double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250);\n final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue);\n sb.append(s);\n }\n }\n imgArray = sb.toString().toCharArray();\n dEnd = System.nanoTime();\n return sb.toString();\n }",
"public static base_responses disable(nitro_service client, String id[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (id != null && id.length > 0) {\n\t\t\tInterface disableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tdisableresources[i] = new Interface();\n\t\t\t\tdisableresources[i].id = id[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}",
"public static float calcDet(Vector3 a ,Vector3 b, Vector3 c) {\n\t\treturn (a.x*(b.y-c.y)) - (a.y*(b.x-c.x)) + (b.x*c.y-b.y*c.x);\n\t}"
] |
Resolves an idl jar for the artifact.
@return Returns idl artifact
@throws MojoExecutionException is idl jar is not present for the artifact. | [
"public static Artifact getIdlArtifact(Artifact artifact, ArtifactFactory artifactFactory,\n ArtifactResolver artifactResolver,\n ArtifactRepository localRepository,\n List<ArtifactRepository> remoteRepos,\n String classifier)\n throws MojoExecutionException {\n Artifact idlArtifact = artifactFactory.createArtifactWithClassifier(\n artifact.getGroupId(),\n artifact.getArtifactId(),\n artifact.getVersion(),\n \"jar\",\n classifier);\n try {\n artifactResolver.resolve(idlArtifact, remoteRepos, localRepository);\n return idlArtifact;\n } catch (final ArtifactResolutionException e) {\n throw new MojoExecutionException(\n \"Failed to resolve one or more idl artifacts:\\n\\n\" + e.getMessage(), e);\n } catch (final ArtifactNotFoundException e) {\n throw new MojoExecutionException(\n \"Failed to resolve one or more idl artifacts:\\n\\n\" + e.getMessage(), e);\n }\n }"
] | [
"public QueryBuilder<T, ID> selectColumns(String... columns) {\n\t\tfor (String column : columns) {\n\t\t\taddSelectColumnToList(column);\n\t\t}\n\t\treturn this;\n\t}",
"public void write(WritableByteChannel channel) throws IOException {\n logger.debug(\"..writing> {}\", this);\n Util.writeFully(getBytes(), channel);\n }",
"public static int cudnnLRNCrossChannelForward(\n cudnnHandle handle, \n cudnnLRNDescriptor normDesc, \n int lrnMode, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnLRNCrossChannelForwardNative(handle, normDesc, lrnMode, alpha, xDesc, x, beta, yDesc, y));\n }",
"public void attachMetadataCache(SlotReference slot, File file)\n throws IOException {\n ensureRunning();\n if (slot.player < 1 || slot.player > 4 || DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player) == null) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for player \" + slot.player);\n }\n if ((slot.slot != CdjStatus.TrackSourceSlot.USB_SLOT) && (slot.slot != CdjStatus.TrackSourceSlot.SD_SLOT)) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for slot \" + slot.slot);\n }\n\n MetadataCache cache = new MetadataCache(file);\n final MediaDetails slotDetails = getMediaDetailsFor(slot);\n if (cache.sourceMedia != null && slotDetails != null) {\n if (!slotDetails.hashKey().equals(cache.sourceMedia.hashKey())) {\n throw new IllegalArgumentException(\"Cache was created for different media (\" + cache.sourceMedia.hashKey() +\n \") than is in the slot (\" + slotDetails.hashKey() + \").\");\n }\n if (slotDetails.hasChanged(cache.sourceMedia)) {\n logger.warn(\"Media has changed (\" + slotDetails + \") since cache was created (\" + cache.sourceMedia +\n \"). Attaching anyway as instructed.\");\n }\n }\n attachMetadataCacheInternal(slot, cache);\n }",
"protected final void error(final HttpServletResponse httpServletResponse, final Throwable e) {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n LOGGER.error(\"Error while processing request\", e);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }",
"private static Collection<String> addOtherClasses(Collection<String> feats, List<? extends CoreLabel> info,\r\n int loc, Clique c) {\r\n String addend = null;\r\n String pAnswer = info.get(loc - 1).get(AnswerAnnotation.class);\r\n String p2Answer = info.get(loc - 2).get(AnswerAnnotation.class);\r\n String p3Answer = info.get(loc - 3).get(AnswerAnnotation.class);\r\n String p4Answer = info.get(loc - 4).get(AnswerAnnotation.class);\r\n String p5Answer = info.get(loc - 5).get(AnswerAnnotation.class);\r\n String nAnswer = info.get(loc + 1).get(AnswerAnnotation.class);\r\n // cdm 2009: Is this really right? Do we not need to differentiate names that would collide???\r\n if (c == FeatureFactory.cliqueCpC) {\r\n addend = '|' + pAnswer;\r\n } else if (c == FeatureFactory.cliqueCp2C) {\r\n addend = '|' + p2Answer;\r\n } else if (c == FeatureFactory.cliqueCp3C) {\r\n addend = '|' + p3Answer;\r\n } else if (c == FeatureFactory.cliqueCp4C) {\r\n addend = '|' + p4Answer;\r\n } else if (c == FeatureFactory.cliqueCp5C) {\r\n addend = '|' + p5Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2C) {\r\n addend = '|' + pAnswer + '-' + p2Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3Cp4C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer + '-' + p4Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3Cp4Cp5C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer + '-' + p4Answer + '-' + p5Answer;\r\n } else if (c == FeatureFactory.cliqueCnC) {\r\n addend = '|' + nAnswer;\r\n } else if (c == FeatureFactory.cliqueCpCnC) {\r\n addend = '|' + pAnswer + '-' + nAnswer;\r\n }\r\n if (addend == null) {\r\n return feats;\r\n }\r\n Collection<String> newFeats = new HashSet<String>();\r\n for (String feat : feats) {\r\n String newFeat = feat + addend;\r\n newFeats.add(newFeat);\r\n }\r\n return newFeats;\r\n }",
"public static base_responses create(nitro_service client, sslfipskey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslfipskey createresources[] = new sslfipskey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tcreateresources[i] = new sslfipskey();\n\t\t\t\tcreateresources[i].fipskeyname = resources[i].fipskeyname;\n\t\t\t\tcreateresources[i].modulus = resources[i].modulus;\n\t\t\t\tcreateresources[i].exponent = resources[i].exponent;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, createresources,\"create\");\n\t\t}\n\t\treturn result;\n\t}",
"private void processDestructionQueue(HttpServletRequest request) {\n Object contextsAttribute = request.getAttribute(DESTRUCTION_QUEUE_ATTRIBUTE_NAME);\n if (contextsAttribute instanceof Map) {\n Map<String, List<ContextualInstance<?>>> contexts = cast(contextsAttribute);\n synchronized (contexts) {\n FastEvent<String> beforeDestroyedEvent = FastEvent.of(String.class, beanManager, BeforeDestroyed.Literal.CONVERSATION);\n FastEvent<String> destroyedEvent = FastEvent.of(String.class, beanManager, Destroyed.Literal.CONVERSATION);\n for (Iterator<Entry<String, List<ContextualInstance<?>>>> iterator = contexts.entrySet().iterator(); iterator.hasNext();) {\n Entry<String, List<ContextualInstance<?>>> entry = iterator.next();\n beforeDestroyedEvent.fire(entry.getKey());\n for (ContextualInstance<?> contextualInstance : entry.getValue()) {\n destroyContextualInstance(contextualInstance);\n }\n // Note that for the attached/current conversation we fire the destroyed event twice because we can't reliably identify such a conversation\n destroyedEvent.fire(entry.getKey());\n iterator.remove();\n }\n }\n }\n }",
"public static List<CompiledAutomaton> createAutomata(String prefix,\n String regexp, Map<String, Automaton> automatonMap) throws IOException {\n List<CompiledAutomaton> list = new ArrayList<>();\n Automaton automatonRegexp = null;\n if (regexp != null) {\n RegExp re = new RegExp(prefix + MtasToken.DELIMITER + regexp + \"\\u0000*\");\n automatonRegexp = re.toAutomaton();\n }\n int step = 500;\n List<String> keyList = new ArrayList<>(automatonMap.keySet());\n for (int i = 0; i < keyList.size(); i += step) {\n int localStep = step;\n boolean success = false;\n CompiledAutomaton compiledAutomaton = null;\n while (!success) {\n success = true;\n int next = Math.min(keyList.size(), i + localStep);\n List<Automaton> listAutomaton = new ArrayList<>();\n for (int j = i; j < next; j++) {\n listAutomaton.add(automatonMap.get(keyList.get(j)));\n }\n Automaton automatonList = Operations.union(listAutomaton);\n Automaton automaton;\n if (automatonRegexp != null) {\n automaton = Operations.intersection(automatonList, automatonRegexp);\n } else {\n automaton = automatonList;\n }\n try {\n compiledAutomaton = new CompiledAutomaton(automaton);\n } catch (TooComplexToDeterminizeException e) {\n log.debug(e);\n success = false;\n if (localStep > 1) {\n localStep /= 2;\n } else {\n throw new IOException(\"TooComplexToDeterminizeException\");\n }\n }\n }\n list.add(compiledAutomaton);\n }\n return list;\n }"
] |
Returns the raw class of the given type. | [
"private static Class<?> getRawClass(Type type) {\n if (type instanceof Class) {\n return (Class<?>) type;\n }\n if (type instanceof ParameterizedType) {\n return getRawClass(((ParameterizedType) type).getRawType());\n }\n // For TypeVariable and WildcardType, returns the first upper bound.\n if (type instanceof TypeVariable) {\n return getRawClass(((TypeVariable) type).getBounds()[0]);\n }\n if (type instanceof WildcardType) {\n return getRawClass(((WildcardType) type).getUpperBounds()[0]);\n }\n if (type instanceof GenericArrayType) {\n Class<?> componentClass = getRawClass(((GenericArrayType) type).getGenericComponentType());\n return Array.newInstance(componentClass, 0).getClass();\n }\n // This shouldn't happen as we captured all implementations of Type above (as or Java 8)\n throw new IllegalArgumentException(\"Unsupported type \" + type + \" of type class \" + type.getClass());\n }"
] | [
"public static vpnsessionaction get(nitro_service service, String name) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tobj.set_name(name);\n\t\tvpnsessionaction response = (vpnsessionaction) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static base_response unset(nitro_service client, protocolhttpband resource, String[] args) throws Exception{\n\t\tprotocolhttpband unsetresource = new protocolhttpband();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"protected void addConstructors(ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) {\n try {\n if (getBeanType().isInterface()) {\n ConstructorUtils.addDefaultConstructor(proxyClassType, initialValueBytecode, !useConstructedFlag());\n } else {\n boolean constructorFound = false;\n for (Constructor<?> constructor : AccessController.doPrivileged(new GetDeclaredConstructorsAction(getBeanType()))) {\n if ((constructor.getModifiers() & Modifier.PRIVATE) == 0) {\n constructorFound = true;\n String[] exceptions = new String[constructor.getExceptionTypes().length];\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = constructor.getExceptionTypes()[i].getName();\n }\n ConstructorUtils.addConstructor(BytecodeUtils.VOID_CLASS_DESCRIPTOR, DescriptorUtils.parameterDescriptors(constructor.getParameterTypes()), exceptions, proxyClassType, initialValueBytecode, !useConstructedFlag());\n }\n }\n if (!constructorFound) {\n // the bean only has private constructors, we need to generate\n // two fake constructors that call each other\n addConstructorsForBeanWithPrivateConstructors(proxyClassType);\n }\n }\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }",
"public PayloadBuilder resizeAlertBody(final int payloadLength, final String postfix) {\n int currLength = length();\n if (currLength <= payloadLength) {\n return this;\n }\n\n // now we are sure that truncation is required\n String body = (String)customAlert.get(\"body\");\n\n final int acceptableSize = Utilities.toUTF8Bytes(body).length\n - (currLength - payloadLength\n + Utilities.toUTF8Bytes(postfix).length);\n body = Utilities.truncateWhenUTF8(body, acceptableSize) + postfix;\n\n // set it back\n customAlert.put(\"body\", body);\n\n // calculate the length again\n currLength = length();\n\n if(currLength > payloadLength) {\n // string is still too long, just remove the body as the body is\n // anyway not the cause OR the postfix might be too long\n customAlert.remove(\"body\");\n }\n\n return this;\n }",
"public static authenticationnegotiatepolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tauthenticationnegotiatepolicy_binding obj = new authenticationnegotiatepolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationnegotiatepolicy_binding response = (authenticationnegotiatepolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void removeMetadataProvider(MetadataProvider provider) {\n for (Set<MetadataProvider> providers : metadataProviders.values()) {\n providers.remove(provider);\n }\n }",
"public DataSetInfo create(int dataSet) throws InvalidDataSetException {\r\n\t\tDataSetInfo info = dataSets.get(createKey(dataSet));\r\n\t\tif (info == null) {\r\n\t\t\tint recordNumber = (dataSet >> 8) & 0xFF;\r\n\t\t\tint dataSetNumber = dataSet & 0xFF;\r\n\t\t\tthrow new UnsupportedDataSetException(recordNumber + \":\" + dataSetNumber);\r\n\t\t\t// info = super.create(dataSet);\r\n\t\t}\r\n\t\treturn info;\r\n\t}",
"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 }",
"@Override\n public JavaClassBuilderAt at(TypeReferenceLocation... locations)\n {\n if (locations != null)\n this.locations = Arrays.asList(locations);\n return this;\n }"
] |
Decomposes the matrix using the QR algorithm. Care was taken to minimize unnecessary memory copying
and cache skipping.
@param orig The matrix which is being decomposed. Not modified.
@return true if it decomposed the matrix or false if an error was detected. This will not catch all errors. | [
"@Override\n public boolean decompose(DMatrixRMaj orig) {\n if( orig.numCols != orig.numRows )\n throw new IllegalArgumentException(\"Matrix must be square.\");\n if( orig.numCols <= 0 )\n return false;\n\n int N = orig.numRows;\n\n // compute a similar tridiagonal matrix\n if( !decomp.decompose(orig) )\n return false;\n\n if( diag == null || diag.length < N) {\n diag = new double[N];\n off = new double[N-1];\n }\n decomp.getDiagonal(diag,off);\n\n // Tell the helper to work with this matrix\n helper.init(diag,off,N);\n\n if( computeVectors ) {\n if( computeVectorsWithValues ) {\n return extractTogether();\n } else {\n return extractSeparate(N);\n }\n } else {\n return computeEigenValues();\n }\n }"
] | [
"@UiHandler(\"m_startTime\")\n void onStartTimeChange(CmsDateBoxEvent event) {\n\n if (handleChange() && !event.isUserTyping()) {\n m_controller.setStartTime(event.getDate());\n }\n }",
"protected void setRandom(double lower, double upper, Random generator) {\n double range = upper - lower;\n\n x = generator.nextDouble() * range + lower;\n y = generator.nextDouble() * range + lower;\n z = generator.nextDouble() * range + lower;\n }",
"public static AliasOperationTransformer replaceLastElement(final PathElement element) {\n return create(new AddressTransformer() {\n @Override\n public PathAddress transformAddress(final PathAddress original) {\n final PathAddress address = original.subAddress(0, original.size() -1);\n return address.append(element);\n }\n });\n }",
"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}",
"public void transform(DataPipe cr) {\n Map<String, String> map = cr.getDataMap();\n\n for (String key : map.keySet()) {\n String value = map.get(key);\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n map.put(key, String.valueOf(ran));\n } else if (value.equals(\"#{divideBy2}\")) {\n String i = map.get(\"var_out_V3\");\n String result = String.valueOf(Integer.valueOf(i) / 2);\n map.put(key, result);\n }\n }\n }",
"public static base_responses delete(nitro_service client, String certkey[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (certkey != null && certkey.length > 0) {\n\t\t\tsslcertkey deleteresources[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++){\n\t\t\t\tdeleteresources[i] = new sslcertkey();\n\t\t\t\tdeleteresources[i].certkey = certkey[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 processCollection(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n CollectionDescriptorDef collDef = _curClassDef.getCollection(name);\r\n String attrName;\r\n\r\n if (collDef == null)\r\n {\r\n collDef = new CollectionDescriptorDef(name);\r\n _curClassDef.addCollection(collDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processCollection\", \" Processing collection \"+collDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n collDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n if (OjbMemberTagsHandler.getMemberDimension() > 0)\r\n {\r\n // we store the array-element type for later use\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n else\r\n { \r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n }\r\n\r\n _curCollectionDef = collDef;\r\n generate(template);\r\n _curCollectionDef = null;\r\n }",
"public static CuratorFramework newFluoCurator(FluoConfiguration config) {\n return newCurator(config.getInstanceZookeepers(), config.getZookeeperTimeout(),\n config.getZookeeperSecret());\n }",
"public void login(Object userIdentifier) {\n session().put(config().sessionKeyUsername(), userIdentifier);\n app().eventBus().trigger(new LoginEvent(userIdentifier.toString()));\n }"
] |
Start a timer of the given string name for the current thread. If no such
timer exists yet, then it will be newly created.
@param timerName
the name of the timer
@param todoFlags
@param threadId
of the thread to track, or 0 if only system clock should be
tracked | [
"public static void startNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).start();\n\t}"
] | [
"public void setParent(ProjectCalendar calendar)\n {\n // I've seen a malformed MSPDI file which sets the parent calendar to itself.\n // Silently ignore this here.\n if (calendar != this)\n {\n if (getParent() != null)\n {\n getParent().removeDerivedCalendar(this);\n }\n\n super.setParent(calendar);\n\n if (calendar != null)\n {\n calendar.addDerivedCalendar(this);\n }\n clearWorkingDateCache();\n }\n }",
"protected void createNewFile(final File file) {\n try {\n file.createNewFile();\n setFileNotWorldReadablePermissions(file);\n } catch (IOException e){\n throw new RuntimeException(e);\n }\n }",
"private void ensureLength(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_LENGTH))\r\n {\r\n String defaultLength = JdbcTypeHelper.getDefaultLengthFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultLength != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no length setting though its jdbc type requires it (in most databases); using default length of \"+defaultLength);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_LENGTH, defaultLength);\r\n }\r\n }\r\n }",
"public Set<CoreDocumentSynchronizationConfig> getSynchronizedDocuments(\n final MongoNamespace namespace\n ) {\n this.waitUntilInitialized();\n try {\n ongoingOperationsGroup.enter();\n return this.syncConfig.getSynchronizedDocuments(namespace);\n } finally {\n ongoingOperationsGroup.exit();\n }\n }",
"public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\n }",
"private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize)\n\t\t\tthrows SQLException {\n\t\tFieldType idField = tableInfo.getIdField();\n\t\tif (idField == null) {\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Cannot delete \" + tableInfo.getDataClass() + \" because it doesn't have an id field defined\");\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(128);\n\t\tDatabaseType databaseType = dao.getConnectionSource().getDatabaseType();\n\t\tappendTableName(databaseType, sb, \"DELETE FROM \", tableInfo.getTableName());\n\t\tFieldType[] argFieldTypes = new FieldType[dataSize];\n\t\tappendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes);\n\t\treturn new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes);\n\t}",
"public static double huntKennedyCMSAdjustedRate(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tdouble a = 1.0/swapMaturity;\n\t\tdouble b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;\n\t\tdouble convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);\n\n\t\tdouble rateUnadjusted\t= forwardSwaprate;\n\t\tdouble rateAdjusted\t\t= forwardSwaprate * convexityAdjustment;\n\n\t\treturn (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit;\n\t}",
"public static boolean organizeAssociationMapByRowKey(\n\t\t\torg.hibernate.ogm.model.spi.Association association,\n\t\t\tAssociationKey key,\n\t\t\tAssociationContext associationContext) {\n\n\t\tif ( association.isEmpty() ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( key.getMetadata().getRowKeyIndexColumnNames().length != 1 ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tObject valueOfFirstRow = association.get( association.getKeys().iterator().next() )\n\t\t\t\t.get( key.getMetadata().getRowKeyIndexColumnNames()[0] );\n\n\t\tif ( !( valueOfFirstRow instanceof String ) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// The list style may be explicitly enforced for compatibility reasons\n\t\treturn getMapStorage( associationContext ) == MapStorageType.BY_KEY;\n\t}",
"public int clear()\n {\n int n = 0;\n for (GVRCursorController c : controllers)\n {\n c.stopDrag();\n removeCursorController(c);\n ++n;\n }\n return n;\n }"
] |
Initializes OJB for the purposes of this task.
@return The metadata manager used by OJB | [
"private MetadataManager initOJB()\r\n {\r\n try\r\n {\r\n if (_ojbPropertiesFile == null)\r\n {\r\n _ojbPropertiesFile = new File(\"OJB.properties\");\r\n if (!_ojbPropertiesFile.exists())\r\n {\r\n throw new BuildException(\"Could not find OJB.properties, please specify it via the ojbpropertiesfile attribute\");\r\n }\r\n }\r\n else\r\n {\r\n if (!_ojbPropertiesFile.exists())\r\n {\r\n throw new BuildException(\"Could not load the specified OJB properties file \"+_ojbPropertiesFile);\r\n }\r\n log(\"Using properties file \"+_ojbPropertiesFile.getAbsolutePath(), Project.MSG_INFO);\r\n System.setProperty(\"OJB.properties\", _ojbPropertiesFile.getAbsolutePath());\r\n }\r\n\r\n MetadataManager metadataManager = MetadataManager.getInstance();\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n\r\n if (_repositoryFile != null)\r\n {\r\n if (!_repositoryFile.exists())\r\n {\r\n throw new BuildException(\"Could not load the specified repository file \"+_repositoryFile);\r\n }\r\n log(\"Loading repository file \"+_repositoryFile.getAbsolutePath(), Project.MSG_INFO);\r\n\r\n // this will load the info from the specified repository file\r\n // and merge it with the existing info (if it has been loaded)\r\n metadataManager.mergeConnectionRepository(persistor.readConnectionRepository(_repositoryFile.getAbsolutePath()));\r\n metadataManager.mergeDescriptorRepository(persistor.readDescriptorRepository(_repositoryFile.getAbsolutePath()));\r\n }\r\n else if (metadataManager.connectionRepository().getAllDescriptor().isEmpty() &&\r\n metadataManager.getGlobalRepository().getDescriptorTable().isEmpty())\r\n {\r\n // Seems nothing was loaded, probably because we're not starting in the directory\r\n // that the properties file is in, and the repository file path is relative\r\n // So lets try to resolve this path and load the repository info manually\r\n Properties props = new Properties();\r\n\r\n props.load(new FileInputStream(_ojbPropertiesFile));\r\n \r\n String repositoryPath = props.getProperty(\"repositoryFile\", \"repository.xml\");\r\n File repositoryFile = new File(repositoryPath);\r\n \r\n if (!repositoryFile.exists())\r\n {\r\n repositoryFile = new File(_ojbPropertiesFile.getParentFile(), repositoryPath);\r\n }\r\n metadataManager.mergeConnectionRepository(persistor.readConnectionRepository(repositoryFile.getAbsolutePath()));\r\n metadataManager.mergeDescriptorRepository(persistor.readDescriptorRepository(repositoryFile.getAbsolutePath()));\r\n }\r\n // we might have to determine the default pb key ourselves\r\n if (metadataManager.getDefaultPBKey() == null)\r\n {\r\n for (Iterator it = metadataManager.connectionRepository().getAllDescriptor().iterator(); it.hasNext();)\r\n {\r\n JdbcConnectionDescriptor descriptor = (JdbcConnectionDescriptor)it.next();\r\n\r\n if (descriptor.isDefaultConnection())\r\n {\r\n metadataManager.setDefaultPBKey(new PBKey(descriptor.getJcdAlias(), descriptor.getUserName(), descriptor.getPassWord()));\r\n break;\r\n }\r\n }\r\n }\r\n return metadataManager;\r\n }\r\n catch (Exception ex)\r\n {\r\n if (ex instanceof BuildException)\r\n {\r\n throw (BuildException)ex;\r\n }\r\n else\r\n {\r\n throw new BuildException(ex);\r\n }\r\n }\r\n }"
] | [
"public static double SymmetricChiSquareDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n double den = p[i] * q[i];\n if (den != 0) {\n double p1 = p[i] - q[i];\n double p2 = p[i] + q[i];\n r += (p1 * p1 * p2) / den;\n }\n }\n\n return r;\n }",
"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 Backup getBackupData() throws Exception {\n Backup backupData = new Backup();\n\n backupData.setGroups(getGroups());\n backupData.setProfiles(getProfiles());\n ArrayList<Script> scripts = new ArrayList<Script>();\n Collections.addAll(scripts, ScriptService.getInstance().getScripts());\n backupData.setScripts(scripts);\n\n return backupData;\n }",
"public ValueContainer[] getCurrentLockingValues(Object o) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n ValueContainer[] result = new ValueContainer[fields.length];\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n result[i] = new ValueContainer(fields[i].getPersistentField().get(o), fields[i].getJdbcType());\r\n }\r\n return result;\r\n }",
"public void setBaselineDurationText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber), value);\n }",
"public void add(Vector3d v1, Vector3d v2) {\n x = v1.x + v2.x;\n y = v1.y + v2.y;\n z = v1.z + v2.z;\n }",
"public static base_response change(nitro_service client, responderhtmlpage resource) throws Exception {\n\t\tresponderhtmlpage updateresource = new responderhtmlpage();\n\t\tupdateresource.name = resource.name;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}",
"public void removeGroup(int groupId) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_GROUPS\n + \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, groupId);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.OVERRIDE_GROUP_ID + \" = ?\"\n );\n\n statement.setInt(1, groupId);\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 removeGroupIdFromTablePaths(groupId);\n }",
"public static transformpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\ttransformpolicylabel obj = new transformpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\ttransformpolicylabel response = (transformpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Handle http worker response.
@param respOnSingleReq
the my response
@throws Exception
the exception | [
"private final void handleHttpWorkerResponse(\n ResponseOnSingeRequest respOnSingleReq) throws Exception {\n // Successful response from GenericAsyncHttpWorker\n\n // Jeff 20310411: use generic response\n\n String responseContent = respOnSingleReq.getResponseBody();\n response.setResponseContent(respOnSingleReq.getResponseBody());\n\n /**\n * Poller logic if pollable: check if need to poll/ or already complete\n * 1. init poller data and HttpPollerProcessor 2. check if task\n * complete, if not, send the request again.\n */\n if (request.isPollable()) {\n boolean scheduleNextPoll = false;\n boolean errorFindingUuid = false;\n\n // set JobId of the poller\n if (!pollerData.isUuidHasBeenSet()) {\n String jobId = httpPollerProcessor\n .getUuidFromResponse(respOnSingleReq);\n\n if (jobId.equalsIgnoreCase(PcConstants.NA)) {\n errorFindingUuid = true;\n pollingErrorCount++;\n logger.error(\"!!POLLING_JOB_FAIL_FIND_JOBID_IN_RESPONSE!! FAIL FAST NOW. PLEASE CHECK getJobIdRegex or retry. \"\n\n + \"DEBUG: REGEX_JOBID: \"\n + httpPollerProcessor.getJobIdRegex()\n\n + \"RESPONSE: \"\n + respOnSingleReq.getResponseBody()\n + \" polling Error count\"\n + pollingErrorCount\n + \" at \" + PcDateUtils.getNowDateTimeStrStandard());\n // fail fast\n pollerData.setError(true);\n pollerData.setComplete(true);\n\n } else {\n pollerData.setJobIdAndMarkHasBeenSet(jobId);\n // if myResponse has other errors, mark poll data as error.\n pollerData.setError(httpPollerProcessor\n .ifThereIsErrorInResponse(respOnSingleReq));\n }\n\n }\n if (!pollerData.isError()) {\n\n pollerData\n .setComplete(httpPollerProcessor\n .ifTaskCompletedSuccessOrFailureFromResponse(respOnSingleReq));\n pollerData.setCurrentProgress(httpPollerProcessor\n .getProgressFromResponse(respOnSingleReq));\n }\n\n // poll again only if not complete AND no error; 2015: change to\n // over limit\n scheduleNextPoll = !pollerData.isComplete()\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError());\n\n // Schedule next poll and return. (not to answer back to manager yet\n // )\n if (scheduleNextPoll\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError())) {\n\n pollMessageCancellable = getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(httpPollerProcessor\n .getPollIntervalMillis(),\n TimeUnit.MILLISECONDS), getSelf(),\n OperationWorkerMsgType.POLL_PROGRESS,\n getContext().system().dispatcher(), getSelf());\n\n logger.info(\"\\nPOLLER_NOW_ANOTHER_POLL: POLL_RECV_SEND\"\n + String.format(\"PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent,\n PcDateUtils.getNowDateTimeStrStandard()));\n\n String responseContentNew = errorFindingUuid ? responseContent\n + \"_PollingErrorCount:\" + pollingErrorCount\n : responseContent;\n logger.info(responseContentNew);\n // log\n pollerData.getPollingHistoryMap().put(\n \"RECV_\" + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\"PROGRESS:%.3f, BODY:%s\",\n pollerData.getCurrentProgress(),\n responseContent));\n return;\n } else {\n pollerData\n .getPollingHistoryMap()\n .put(\"RECV_\"\n + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\n \"POLL_COMPLETED_OR_ERROR: PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent));\n }\n\n }// end if (request.isPollable())\n\n reply(respOnSingleReq.isFailObtainResponse(),\n respOnSingleReq.getErrorMessage(),\n respOnSingleReq.getStackTrace(),\n respOnSingleReq.getStatusCode(),\n respOnSingleReq.getStatusCodeInt(),\n respOnSingleReq.getReceiveTime(), respOnSingleReq.getResponseHeaders());\n\n }"
] | [
"private int collectCandidates(Map<Long, Score> candidates,\n List<Bucket> buckets,\n int threshold) {\n int ix;\n for (ix = 0; ix < threshold &&\n candidates.size() < (CUTOFF_FACTOR_1 * max_search_hits); ix++) {\n Bucket b = buckets.get(ix);\n long[] ids = b.records;\n double score = b.getScore();\n \n for (int ix2 = 0; ix2 < b.nextfree; ix2++) {\n Score s = candidates.get(ids[ix2]);\n if (s == null) {\n s = new Score(ids[ix2]);\n candidates.put(ids[ix2], s);\n }\n s.score += score;\n }\n if (DEBUG)\n System.out.println(\"Bucket \" + b.nextfree + \" -> \" + candidates.size());\n }\n return ix;\n }",
"public ParsedWord pollParsedWord() {\n if(hasNextWord()) {\n //set correct next char\n if(parsedLine.words().size() > (word+1))\n character = parsedLine.words().get(word+1).lineIndex();\n else\n character = -1;\n return parsedLine.words().get(word++);\n }\n else\n return new ParsedWord(null, -1);\n }",
"public static Date getDateFromLong(long date)\n {\n TimeZone tz = TimeZone.getDefault();\n return (new Date(date - tz.getRawOffset()));\n }",
"public Collection<BoxGroupMembership.Info> getMemberships() {\n final BoxAPIConnection api = this.getAPI();\n final String groupID = this.getID();\n\n Iterable<BoxGroupMembership.Info> iter = new Iterable<BoxGroupMembership.Info>() {\n public Iterator<BoxGroupMembership.Info> iterator() {\n URL url = MEMBERSHIPS_URL_TEMPLATE.build(api.getBaseURL(), groupID);\n return new BoxGroupMembershipIterator(api, url);\n }\n };\n\n // We need to iterate all results because this method must return a Collection. This logic should be removed in\n // the next major version, and instead return the Iterable directly.\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>();\n for (BoxGroupMembership.Info membership : iter) {\n memberships.add(membership);\n }\n return memberships;\n }",
"private void deliverWaveformDetailUpdate(final int player, final WaveformDetail detail) {\n if (!getWaveformListeners().isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformDetailUpdate update = new WaveformDetailUpdate(player, detail);\n for (final WaveformListener listener : getWaveformListeners()) {\n try {\n listener.detailChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform detail update to listener\", t);\n }\n }\n }\n });\n }\n }",
"static void writeCertificates(final ModelNode result, final Certificate[] certificates) throws CertificateEncodingException, NoSuchAlgorithmException {\n if (certificates != null) {\n for (Certificate current : certificates) {\n ModelNode certificate = new ModelNode();\n writeCertificate(certificate, current);\n result.add(certificate);\n }\n }\n }",
"private void readResource(Document.Resources.Resource resource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setName(resource.getName());\n mpxjResource.setResourceCalendar(m_calendarMap.get(resource.getCalendarID()));\n mpxjResource.setStandardRate(new Rate(resource.getCost(), resource.getCostTimeUnit()));\n mpxjResource.setEmailAddress(resource.getEMail());\n mpxjResource.setGroup(resource.getGroup());\n //resource.getHyperlinks()\n mpxjResource.setUniqueID(resource.getID());\n //resource.getMarkerID()\n mpxjResource.setNotes(resource.getNote());\n mpxjResource.setID(Integer.valueOf(resource.getOutlineNumber()));\n //resource.getStyleProject()\n mpxjResource.setType(resource.getSubType() == null ? resource.getType() : resource.getSubType());\n }",
"protected Object buildOrRefreshObject(Map row, ClassDescriptor targetClassDescriptor, Object targetObject)\r\n {\r\n Object result = targetObject;\r\n FieldDescriptor fmd;\r\n FieldDescriptor[] fields = targetClassDescriptor.getFieldDescriptor(true);\r\n\r\n if(targetObject == null)\r\n {\r\n // 1. create new object instance if needed\r\n result = ClassHelper.buildNewObjectInstance(targetClassDescriptor);\r\n }\r\n\r\n // 2. fill all scalar attributes of the new object\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n fmd = fields[i];\r\n fmd.getPersistentField().set(result, row.get(fmd.getColumnName()));\r\n }\r\n\r\n if(targetObject == null)\r\n {\r\n // 3. for new build objects, invoke the initialization method for the class if one is provided\r\n Method initializationMethod = targetClassDescriptor.getInitializationMethod();\r\n if (initializationMethod != null)\r\n {\r\n try\r\n {\r\n initializationMethod.invoke(result, NO_ARGS);\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(\"Unable to invoke initialization method:\" + initializationMethod.getName() + \" for class:\" + m_cld.getClassOfObject(), ex);\r\n }\r\n }\r\n }\r\n return result;\r\n }",
"public static long count(nitro_service service, String zonename) throws Exception{\n\t\tdnszone_domain_binding obj = new dnszone_domain_binding();\n\t\tobj.set_zonename(zonename);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tdnszone_domain_binding response[] = (dnszone_domain_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}"
] |
Reads the XER file table and row structure ready for processing.
@param is input stream
@throws MPXJException | [
"private void processFile(InputStream is) throws MPXJException\n {\n int line = 1;\n\n try\n {\n //\n // Test the header and extract the separator. If this is successful,\n // we reset the stream back as far as we can. The design of the\n // BufferedInputStream class means that we can't get back to character\n // zero, so the first record we will read will get \"RMHDR\" rather than\n // \"ERMHDR\" in the first field position.\n //\n BufferedInputStream bis = new BufferedInputStream(is);\n byte[] data = new byte[6];\n data[0] = (byte) bis.read();\n bis.mark(1024);\n bis.read(data, 1, 5);\n\n if (!new String(data).equals(\"ERMHDR\"))\n {\n throw new MPXJException(MPXJException.INVALID_FILE);\n }\n\n bis.reset();\n\n InputStreamReader reader = new InputStreamReader(bis, getCharset());\n Tokenizer tk = new ReaderTokenizer(reader);\n tk.setDelimiter('\\t');\n List<String> record = new ArrayList<String>();\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n readRecord(tk, record);\n if (!record.isEmpty())\n {\n if (processRecord(record))\n {\n break;\n }\n }\n ++line;\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR + \" (failed at line \" + line + \")\", ex);\n }\n }"
] | [
"@Override\n protected void reset() {\n super.reset();\n mapClassesToNamedBoundProviders.clear();\n mapClassesToUnNamedBoundProviders.clear();\n hasTestModules = false;\n installBindingForScope();\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 }",
"private static ResourceBundle tryBundle(String baseName, Locale locale, boolean wantBase) {\n\n I_CmsResourceBundle first = null; // The most specialized bundle.\n I_CmsResourceBundle last = null; // The least specialized bundle.\n\n List<String> bundleNames = CmsLocaleManager.getLocaleVariants(baseName, locale, true, true);\n for (String bundleName : bundleNames) {\n // break if we would try the base bundle, but we do not want it directly\n if (bundleName.equals(baseName) && !wantBase && (first == null)) {\n break;\n }\n I_CmsResourceBundle foundBundle = tryBundle(bundleName);\n if (foundBundle != null) {\n if (first == null) {\n first = foundBundle;\n }\n\n if (last != null) {\n last.setParent((ResourceBundle)foundBundle);\n }\n foundBundle.setLocale(locale);\n\n last = foundBundle;\n }\n }\n return (ResourceBundle)first;\n }",
"public String get() {\n\t\tsynchronized (LOCK) {\n\t\t\tif (!initialised) {\n\t\t\t\t// generate the random number\n\t\t\t\tRandom rnd = new Random();\t// @todo need a different seed, this is now time based and I\n\t\t\t\t// would prefer something different, like an object address\n\t\t\t\t// get the random number, instead of getting an integer and converting that to base64 later,\n\t\t\t\t// we get a string and narrow that down to base64, use the top 6 bits of the characters\n\t\t\t\t// as they are more random than the bottom ones...\n\t\t\t\trnd.nextBytes(value);\t\t// get some random characters\n\t\t\t\tvalue[3] = BASE64[((value[3] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[4] = BASE64[((value[4] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[5] = BASE64[((value[5] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[6] = BASE64[((value[6] >> 2) & BITS_6)]; // NOSONAR\n\t\t\t\tvalue[7] = BASE64[((value[7] >> 2) & BITS_6)]; // NOSONAR\n\n\t\t\t\t// complete the time part in the HIGH value of the token\n\t\t\t\t// this also sets the initial low value\n\t\t\t\tcompleteToken(rnd);\n\n\t\t\t\tinitialised = true;\n\t\t\t}\n\n\t\t\t// fill in LOW value in id\n\t\t\tint l = low;\n\t\t\tvalue[0] = BASE64[(l & BITS_6)];\n\t\t\tl >>= SHIFT_6;\n\t\t\tvalue[1] = BASE64[(l & BITS_6)];\n\t\t\tl >>= SHIFT_6;\n\t\t\tvalue[2] = BASE64[(l & BITS_6)];\n\n\t\t\tString res = new String(value);\n\n\t\t\t// increment LOW\n\t\t\tlow++;\n\t\t\tif (low == LOW_MAX) {\n\t\t\t\tlow = 0;\n\t\t\t}\n\t\t\tif (low == lowLast) {\n\t\t\t\ttime = System.currentTimeMillis();\n\t\t\t\tcompleteToken();\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\t}",
"public void installApp(Functions.Func callback) {\n if (isPwaSupported()) {\n appInstaller = new AppInstaller(callback);\n appInstaller.prompt();\n }\n }",
"private ServerDetails createInitialDeployDetailsFromOldDeployDetails(ServerDetails oldDeployerDetails) {\n RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails.getDeployReleaseRepository();\n RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails.getDeploySnapshotRepository();\n RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldDeployRepositoryConfig;\n RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig;\n return new ServerDetails(oldDeployerDetails.getArtifactoryName(), oldDeployerDetails.getArtifactoryUrl(),\n deployReleaseRepos, deploySnapshotRepos, null, null, null, null);\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}",
"private void writeProperties() throws IOException\n {\n writeAttributeTypes(\"property_types\", ProjectField.values());\n writeFields(\"property_values\", m_projectFile.getProjectProperties(), ProjectField.values());\n }",
"public void calculateSize(PdfContext context) {\n\t\tfloat width = 0;\n\t\tfloat height = 0;\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.calculateSize(context);\n\t\t\tfloat cw = child.getBounds().getWidth() + 2 * child.getConstraint().getMarginX();\n\t\t\tfloat ch = child.getBounds().getHeight() + 2 * child.getConstraint().getMarginY();\n\t\t\tswitch (getConstraint().getFlowDirection()) {\n\t\t\t\tcase LayoutConstraint.FLOW_NONE:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_X:\n\t\t\t\t\twidth += cw;\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_Y:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight += ch;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unknown flow direction \" + getConstraint().getFlowDirection());\n\t\t\t}\n\t\t}\n\t\tif (getConstraint().getWidth() != 0) {\n\t\t\twidth = getConstraint().getWidth();\n\t\t}\n\t\tif (getConstraint().getHeight() != 0) {\n\t\t\theight = getConstraint().getHeight();\n\t\t}\n\t\tsetBounds(new Rectangle(0, 0, width, height));\n\t}"
] |
Get all the attribute values for an MBean by name. The values are HTML escaped.
@return the {@link Map} of attribute names and values.
@throws javax.management.AttributeNotFoundException Unable to find the 'attribute'
@throws InstanceNotFoundException unable to find the specific bean
@throws ReflectionException unable to interrogate the bean | [
"public Map<String,Object> getAttributeValues()\n throws AttributeNotFoundException, InstanceNotFoundException, ReflectionException {\n\n HashSet<String> attributeSet = new HashSet<String>();\n\n for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {\n attributeSet.add(attributeInfo.getName());\n }\n\n AttributeList attributeList =\n mBeanServer.getAttributes(objectName, attributeSet.toArray(new String[attributeSet.size()]));\n\n Map<String, Object> attributeValueMap = new TreeMap<String, Object>();\n for (Attribute attribute : attributeList.asList()) {\n attributeValueMap.put(attribute.getName(), sanitizer.escapeValue(attribute.getValue()));\n }\n\n return attributeValueMap;\n }"
] | [
"@Deprecated public Duration getDuration(Date startDate, Date endDate) throws MPXJException\n {\n return (getDuration(\"Standard\", startDate, endDate));\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 }",
"private void executePlan(RebalancePlan rebalancePlan) {\n logger.info(\"Starting to execute rebalance Plan!\");\n\n int batchCount = 0;\n int partitionStoreCount = 0;\n long totalTimeMs = 0;\n\n List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan();\n int numBatches = entirePlan.size();\n int numPartitionStores = rebalancePlan.getPartitionStoresMoved();\n\n for(RebalanceBatchPlan batchPlan: entirePlan) {\n logger.info(\"======== REBALANCING BATCH \" + (batchCount + 1)\n + \" ========\");\n RebalanceUtils.printBatchLog(batchCount,\n logger,\n batchPlan.toString());\n\n long startTimeMs = System.currentTimeMillis();\n // ACTUALLY DO A BATCH OF REBALANCING!\n executeBatch(batchCount, batchPlan);\n totalTimeMs += (System.currentTimeMillis() - startTimeMs);\n\n // Bump up the statistics\n batchCount++;\n partitionStoreCount += batchPlan.getPartitionStoreMoves();\n batchStatusLog(batchCount,\n numBatches,\n partitionStoreCount,\n numPartitionStores,\n totalTimeMs);\n }\n }",
"private Statement createStatement(Connection con, boolean scrollable, int explicitFetchSizeHint)\r\n throws java.sql.SQLException\r\n {\r\n Statement result;\r\n try\r\n {\r\n // if necessary use JDBC1.0 methods\r\n if (!FORCEJDBC1_0)\r\n {\r\n result =\r\n con.createStatement(\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);\r\n }\r\n else\r\n {\r\n result = con.createStatement();\r\n }\r\n }\r\n catch (AbstractMethodError err)\r\n {\r\n // if a JDBC1.0 driver is used, the signature\r\n // createStatement(int, int) is not defined.\r\n // we then call the JDBC1.0 variant createStatement()\r\n log.warn(\"Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode\", err);\r\n result = con.createStatement();\r\n FORCEJDBC1_0 = true;\r\n }\r\n catch (SQLException eSql)\r\n {\r\n // there are JDBC Driver that nominally implement JDBC 2.0, but\r\n // throw DriverNotCapableExceptions. If we catch one of these\r\n // we force usage of JDBC 1.0\r\n if (eSql.getClass().getName()\r\n .equals(\"interbase.interclient.DriverNotCapableException\"))\r\n {\r\n log.warn(\"JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode\");\r\n FORCEJDBC1_0 = true;\r\n result = con.createStatement();\r\n }\r\n else\r\n {\r\n throw eSql;\r\n }\r\n }\r\n try\r\n {\r\n platform.afterStatementCreate(result);\r\n }\r\n catch (PlatformException e)\r\n {\r\n log.error(\"Platform dependend failure\", e);\r\n }\r\n return result;\r\n }",
"public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getInsertStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }",
"private int[] changeColor() {\n int[] changedPixels = new int[pixels.length];\n double frequenz = 2 * Math.PI / 1020;\n\n for (int i = 0; i < pixels.length; i++) {\n int argb = pixels[i];\n int a = (argb >> 24) & 0xff;\n int r = (argb >> 16) & 0xff;\n int g = (argb >> 8) & 0xff;\n int b = argb & 0xff;\n\n r = (int) (255 * Math.sin(frequenz * r));\n b = (int) (-255 * Math.cos(frequenz * b) + 255);\n\n changedPixels[i] = (a << 24) | (r << 16) | (g << 8) | b;\n }\n\n return changedPixels;\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 }",
"public static appflowpolicy_appflowglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_appflowglobal_binding obj = new appflowpolicy_appflowglobal_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_appflowglobal_binding response[] = (appflowpolicy_appflowglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static double blackScholesATMOptionValue(\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble forward,\n\t\t\tdouble payoffUnit)\n\t{\n\t\tif(optionMaturity < 0) {\n\t\t\treturn 0.0;\n\t\t}\n\n\t\t// Calculate analytic value\n\t\tdouble dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);\n\t\tdouble dMinus = -dPlus;\n\n\t\tdouble valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;\n\n\t\treturn valueAnalytic;\n\t}"
] |
Append Join for non SQL92 Syntax | [
"private void appendJoin(StringBuffer where, StringBuffer buf, Join join)\r\n {\r\n buf.append(\",\");\r\n appendTableWithJoins(join.right, where, buf);\r\n if (where.length() > 0)\r\n {\r\n where.append(\" AND \");\r\n }\r\n join.appendJoinEqualities(where);\r\n }"
] | [
"public Release getReleaseInfo(String appName, String releaseName) {\n return connection.execute(new ReleaseInfo(appName, releaseName), apiKey);\n }",
"public String getCmdLineArg() {\n StringBuilder builder = new StringBuilder(\" --server-groups=\");\n boolean foundSelected = false;\n for (JCheckBox serverGroup : serverGroups) {\n if (serverGroup.isSelected()) {\n foundSelected = true;\n builder.append(serverGroup.getText());\n builder.append(\",\");\n }\n }\n builder.deleteCharAt(builder.length() - 1); // remove trailing comma\n\n if (!foundSelected) return \"\";\n return builder.toString();\n }",
"public static String fixLanguageCodeIfDeprecated(String wikimediaLanguageCode) {\n\t\tif (DEPRECATED_LANGUAGE_CODES.containsKey(wikimediaLanguageCode)) {\n\t\t\treturn DEPRECATED_LANGUAGE_CODES.get(wikimediaLanguageCode);\n\t\t} else {\n\t\t\treturn wikimediaLanguageCode;\n\t\t}\n\t}",
"public static Module unserializeModule(final String module) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(module, Module.class);\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 }",
"public void deleteServerGroup(int id) {\n try {\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_ID + \" = \" + id + \";\");\n\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = \" + id);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"public static String makeHTMLTable(String[][] table, String[] rowLabels, String[] colLabels) {\r\n StringBuilder buff = new StringBuilder();\r\n buff.append(\"<table class=\\\"auto\\\" border=\\\"1\\\" cellspacing=\\\"0\\\">\\n\");\r\n // top row\r\n buff.append(\"<tr>\\n\");\r\n buff.append(\"<td></td>\\n\"); // the top left cell\r\n for (int j = 0; j < table[0].length; j++) { // assume table is a rectangular matrix\r\n buff.append(\"<td class=\\\"label\\\">\").append(colLabels[j]).append(\"</td>\\n\");\r\n }\r\n buff.append(\"</tr>\\n\");\r\n // all other rows\r\n for (int i = 0; i < table.length; i++) {\r\n // one row\r\n buff.append(\"<tr>\\n\");\r\n buff.append(\"<td class=\\\"label\\\">\").append(rowLabels[i]).append(\"</td>\\n\");\r\n for (int j = 0; j < table[i].length; j++) {\r\n buff.append(\"<td class=\\\"data\\\">\");\r\n buff.append(((table[i][j] != null) ? table[i][j] : \"\"));\r\n buff.append(\"</td>\\n\");\r\n }\r\n buff.append(\"</tr>\\n\");\r\n }\r\n buff.append(\"</table>\");\r\n return buff.toString();\r\n }",
"private void cascadeDeleteFor(ObjectEnvelope mod, List alreadyPrepared)\r\n {\r\n // avoid endless recursion\r\n if(alreadyPrepared.contains(mod.getIdentity())) return;\r\n\r\n alreadyPrepared.add(mod.getIdentity());\r\n\r\n ClassDescriptor cld = getTransaction().getBroker().getClassDescriptor(mod.getObject().getClass());\r\n\r\n List refs = cld.getObjectReferenceDescriptors(true);\r\n cascadeDeleteSingleReferences(mod, refs, alreadyPrepared);\r\n\r\n List colls = cld.getCollectionDescriptors(true);\r\n cascadeDeleteCollectionReferences(mod, colls, alreadyPrepared);\r\n }",
"public static Info eye( final Variable A , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableMatrix ) {\n ret.op = new Operation(\"eye-m\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)A).matrix;\n output.matrix.reshape(mA.numRows,mA.numCols);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else if( A instanceof VariableInteger ) {\n ret.op = new Operation(\"eye-i\") {\n @Override\n public void process() {\n int N = ((VariableInteger)A).value;\n output.matrix.reshape(N,N);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable type \"+A);\n }\n\n return ret;\n }"
] |
Encodes the given URI port with the given encoding.
@param port the port to be encoded
@param encoding the character encoding to encode to
@return the encoded port
@throws UnsupportedEncodingException when the given encoding parameter is not supported | [
"public static String encodePort(String port, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(port, encoding, HierarchicalUriComponents.Type.PORT);\n\t}"
] | [
"@Override\n public void process() {\n if (client.isDone() || executorService.isTerminated()) {\n throw new IllegalStateException(\"Client is already stopped\");\n }\n Runnable runner = new Runnable() {\n @Override\n public void run() {\n try {\n while (!client.isDone()) {\n String msg = messageQueue.take();\n try {\n parseMessage(msg);\n } catch (Exception e) {\n logger.warn(\"Exception thrown during parsing msg \" + msg, e);\n onException(e);\n }\n }\n } catch (Exception e) {\n onException(e);\n }\n }\n };\n\n executorService.execute(runner);\n }",
"public DbLicense resolve(final String licenseId) {\n\n for (final Entry<String, DbLicense> regexp : licensesRegexp.entrySet()) {\n try {\n if (licenseId.matches(regexp.getKey())) {\n return regexp.getValue();\n }\n } catch (PatternSyntaxException e) {\n LOG.error(\"Wrong pattern for the following license \" + regexp.getValue().getName(), e);\n continue;\n }\n }\n\n if(LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"No matching pattern for license %s\", licenseId));\n }\n return null;\n }",
"public final void notifyFooterItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newFooterItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (newFooterItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount + newContentItemCount, itemCount);\n }",
"public static String getStringFromJSONPath(JSONObject record, String path) {\n final Object object = getObjectFromJSONPath(record, path);\n return object == null ? null : object.toString();\n }",
"private void performScriptedStep() {\n double scale = computeBulgeScale();\n if( steps > giveUpOnKnown ) {\n // give up on the script\n followScript = false;\n } else {\n // use previous singular value to step\n double s = values[x2]/scale;\n performImplicitSingleStep(scale,s*s,false);\n }\n }",
"public AirMapViewBuilder builder(AirMapViewTypes mapType) {\n switch (mapType) {\n case NATIVE:\n if (isNativeMapSupported) {\n return new NativeAirMapViewBuilder();\n }\n break;\n case WEB:\n return getWebMapViewBuilder();\n }\n throw new UnsupportedOperationException(\"Requested map type is not supported\");\n }",
"public static UndeployDescription of(final DeploymentDescription deploymentDescription) {\n Assert.checkNotNullParam(\"deploymentDescription\", deploymentDescription);\n return of(deploymentDescription.getName()).addServerGroups(deploymentDescription.getServerGroups());\n }",
"public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }",
"private Auth constructAuth(String authToken, String tokenSecret, String username) throws IOException {\n\n Auth auth = new Auth();\n auth.setToken(authToken);\n auth.setTokenSecret(tokenSecret);\n\n // Prompt to ask what permission is needed: read, update or delete.\n auth.setPermission(Permission.fromString(\"delete\"));\n\n User user = new User();\n // Later change the following 3. Either ask user to pass on command line or read\n // from saved file.\n user.setId(nsid);\n user.setUsername((username));\n user.setRealName(\"\");\n auth.setUser(user);\n this.authStore.store(auth);\n return auth;\n }"
] |
LV morphology helper functions | [
"private String filterTag(String tag) {\r\n\t AttributeValues answerAV = TagSet.getTagSet().fromTag(tag);\r\n\t answerAV.removeNonlexicalAttributes();\r\n\t return TagSet.getTagSet().toTag(answerAV);\r\n }"
] | [
"public static String formatBigDecimal(BigDecimal number) {\n\t\tif (number.signum() != -1) {\n\t\t\treturn \"+\" + number.toString();\n\t\t} else {\n\t\t\treturn number.toString();\n\t\t}\n\t}",
"public static cmpparameter get(nitro_service service) throws Exception{\n\t\tcmpparameter obj = new cmpparameter();\n\t\tcmpparameter[] response = (cmpparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static String getTabularData(String[] labels, String[][] data, int padding) {\n int[] size = new int[labels.length];\n \n for (int i = 0; i < labels.length; i++) {\n size[i] = labels[i].length() + padding;\n }\n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n if (row[i].length() >= size[i]) {\n size[i] = row[i].length() + padding;\n }\n }\n }\n \n StringBuffer tabularData = new StringBuffer();\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(labels[i]);\n tabularData.append(fill(' ', size[i] - labels[i].length()));\n }\n \n tabularData.append(\"\\n\");\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(fill('=', size[i] - 1)).append(\" \");\n }\n \n tabularData.append(\"\\n\");\n \n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n tabularData.append(row[i]);\n tabularData.append(fill(' ', size[i] - row[i].length()));\n }\n \n tabularData.append(\"\\n\");\n }\n \n return tabularData.toString();\n }",
"public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter)\n throws Throwable {\n run(configuration, candidateSteps, story, filter, null);\n }",
"private File getWorkDir() throws IOException\r\n {\r\n if (_workDir == null)\r\n { \r\n File dummy = File.createTempFile(\"dummy\", \".log\");\r\n String workDir = dummy.getPath().substring(0, dummy.getPath().lastIndexOf(File.separatorChar));\r\n \r\n if ((workDir == null) || (workDir.length() == 0))\r\n {\r\n workDir = \".\";\r\n }\r\n dummy.delete();\r\n _workDir = new File(workDir);\r\n }\r\n return _workDir;\r\n }",
"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 }",
"public static <T> boolean addAll(Collection<T> target, Iterator<? extends T> iterator) {\n Preconditions.checkArgumentNotNull(target, \"target\");\n boolean modified = false;\n while (iterator.hasNext()) {\n modified |= target.add(iterator.next());\n }\n return modified;\n }",
"@SuppressWarnings(\"unchecked\")\n public static <E> String serialize(E object, ParameterizedType<E> parameterizedType) throws IOException {\n return mapperFor(parameterizedType).serialize(object);\n }",
"public static Configuration getDefaultFreemarkerConfiguration()\n {\n freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26);\n DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);\n objectWrapperBuilder.setUseAdaptersForContainers(true);\n objectWrapperBuilder.setIterableSupport(true);\n configuration.setObjectWrapper(objectWrapperBuilder.build());\n configuration.setAPIBuiltinEnabled(true);\n\n configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader());\n configuration.setTemplateUpdateDelayMilliseconds(3600);\n return configuration;\n }"
] |
Add a plugin path
@param model
@param add
@return
@throws Exception | [
"@RequestMapping(value = \"/api/plugins\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addPluginPath(Model model, Plugin add) throws Exception {\n PluginManager.getInstance().addPluginPath(add.getPath());\n\n return pluginInformation();\n }"
] | [
"private void flushHotCacheSlot(SlotReference slot) {\n // Iterate over a copy to avoid concurrent modification issues\n for (Map.Entry<DeckReference, TrackMetadata> entry : new HashMap<DeckReference,TrackMetadata>(hotCache).entrySet()) {\n if (slot == SlotReference.getSlotReference(entry.getValue().trackReference)) {\n logger.debug(\"Evicting cached metadata in response to unmount report {}\", entry.getValue());\n hotCache.remove(entry.getKey());\n }\n }\n }",
"protected ExpectState prepareClosure(int pairIndex, MatchResult result) {\n /* TODO: potentially remove this?\n {\n System.out.println( \"Begin: \" + result.beginOffset(0) );\n System.out.println( \"Length: \" + result.length() );\n System.out.println( \"Current: \" + input.getCurrentOffset() );\n System.out.println( \"Begin: \" + input.getMatchBeginOffset() );\n System.out.println( \"End: \" + input.getMatchEndOffset() );\n //System.out.println( \"Match: \" + input.match() );\n //System.out.println( \"Pre: >\" + input.preMatch() + \"<\");\n //System.out.println( \"Post: \" + input.postMatch() );\n }\n */\n\n // Prepare Closure environment\n ExpectState state;\n Map<String, Object> prevMap = null;\n if (g_state != null) {\n prevMap = g_state.getVars();\n }\n\n int matchedWhere = result.beginOffset(0);\n String matchedText = result.toString(); // expect_out(0,string)\n\n // Unmatched upto end of match\n // expect_out(buffer)\n char[] chBuffer = input.getBuffer();\n String copyBuffer = new String(chBuffer, 0, result.endOffset(0) );\n\n List<String> groups = new ArrayList<>();\n for (int j = 1; j <= result.groups(); j++) {\n String group = result.group(j);\n groups.add( group );\n }\n state = new ExpectState(copyBuffer.toString(), matchedWhere, matchedText, pairIndex, groups, prevMap);\n\n return state;\n }",
"public static Integer convertPathIdentifier(String identifier, Integer profileId) throws Exception {\n Integer pathId = -1;\n try {\n pathId = Integer.parseInt(identifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n if (profileId == null)\n throw new Exception(\"A profileId must be specified\");\n\n pathId = PathOverrideService.getInstance().getPathId(identifier, profileId);\n }\n\n return pathId;\n }",
"public List<List<IN>> classifyRaw(String str,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromString(str, readerAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n // TaggedWord word = new TaggedWord(wi.word(), wi.answer());\r\n // sentence.add(word);\r\n sentence.add(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }",
"public void setShortVec(char[] data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 2)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with char array\");\n }\n if (!NativeIndexBuffer.setShortArray(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }",
"public static CmsUUID readId(JSONObject obj, String key) {\n\n String strValue = obj.optString(key);\n if (!CmsUUID.isValidUUID(strValue)) {\n return null;\n }\n return new CmsUUID(strValue);\n }",
"private <T> List<Class<?>> filter(List<Class<?>> enabledClasses, List<Class<?>> globallyEnabledClasses, LogMessageCallback logMessageCallback,\n BeanDeployment deployment) {\n for (Iterator<Class<?>> iterator = enabledClasses.iterator(); iterator.hasNext(); ) {\n Class<?> enabledClass = iterator.next();\n if (globallyEnabledClasses.contains(enabledClass)) {\n logMessageCallback.log(enabledClass, deployment.getBeanDeploymentArchive().getId());\n iterator.remove();\n }\n }\n return enabledClasses;\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 static Map<String, String> getContentMap(File file, String separator) throws IOException {\n List<String> content = getContentLines(file);\n Map<String, String> map = new LinkedHashMap<String, String>();\n \n for (String line : content) {\n String[] spl = line.split(separator);\n if (line.trim().length() > 0) {\n map.put(spl[0], (spl.length > 1 ? spl[1] : \"\"));\n }\n }\n \n return map;\n }"
] |
Computes the QR decomposition of A and store the results in A.
@param A The A matrix in the linear equation. Modified. Reference saved.
@return true if the decomposition was successful. | [
"@Override\n public boolean setA(DMatrixRBlock A) {\n if( A.numRows < A.numCols )\n throw new IllegalArgumentException(\"Number of rows must be more than or equal to the number of columns. \" +\n \"Can't solve an underdetermined system.\");\n\n if( !decomposer.decompose(A))\n return false;\n\n this.QR = decomposer.getQR();\n\n return true;\n }"
] | [
"public static <GIVEN, WHEN, THEN> Scenario<GIVEN, WHEN, THEN> create( Class<GIVEN> givenClass, Class<WHEN> whenClass,\n Class<THEN> thenClass ) {\n return new Scenario<GIVEN, WHEN, THEN>( givenClass, whenClass, thenClass );\n }",
"public static ipset_nsip6_binding[] get(nitro_service service, String name) throws Exception{\n\t\tipset_nsip6_binding obj = new ipset_nsip6_binding();\n\t\tobj.set_name(name);\n\t\tipset_nsip6_binding response[] = (ipset_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void signIn(String key, Collection<WebSocketConnection> connections) {\n if (connections.isEmpty()) {\n return;\n }\n Map<WebSocketConnection, WebSocketConnection> newMap = new HashMap<>();\n for (WebSocketConnection conn : connections) {\n newMap.put(conn, conn);\n }\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.putAll(newMap);\n }",
"public void newLineIfNotEmpty() {\n\t\tfor (int i = segments.size() - 1; i >= 0; i--) {\n\t\t\tString segment = segments.get(i);\n\t\t\tif (lineDelimiter.equals(segment)) {\n\t\t\t\tsegments.subList(i + 1, segments.size()).clear();\n\t\t\t\tcachedToString = null;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (int j = 0; j < segment.length(); j++) {\n\t\t\t\tif (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) {\n\t\t\t\t\tnewLine();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsegments.clear();\n\t\tcachedToString = null;\n\t}",
"private ProjectFile handleOleCompoundDocument(InputStream stream) throws Exception\n {\n POIFSFileSystem fs = new POIFSFileSystem(POIFSFileSystem.createNonClosingInputStream(stream));\n String fileFormat = MPPReader.getFileFormat(fs);\n if (fileFormat != null && fileFormat.startsWith(\"MSProject\"))\n {\n MPPReader reader = new MPPReader();\n addListeners(reader);\n return reader.read(fs);\n }\n return null;\n }",
"public static responderpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tresponderpolicy_binding obj = new responderpolicy_binding();\n\t\tobj.set_name(name);\n\t\tresponderpolicy_binding response = (responderpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"@Override\n public void addVariable(String varName, Object value) {\n synchronized (mGlobalVariables) {\n mGlobalVariables.put(varName, value);\n }\n refreshGlobalBindings();\n }",
"public void terminateAllConnections(){\r\n\t\tthis.terminationLock.lock();\r\n\t\ttry{\r\n\t\t\t// close off all connections.\r\n\t\t\tfor (int i=0; i < this.pool.partitionCount; i++) {\r\n\t\t\t\tthis.pool.partitions[i].setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization\r\n\t\t\t\tList<ConnectionHandle> clist = new LinkedList<ConnectionHandle>(); \r\n\t\t\t\tthis.pool.partitions[i].getFreeConnections().drainTo(clist);\r\n\t\t\t\tfor (ConnectionHandle c: clist){\r\n\t\t\t\t\tthis.pool.destroyConnection(c);\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t} finally {\r\n\t\t\tthis.terminationLock.unlock();\r\n\t\t}\r\n\t}",
"public synchronized void addNodesToWorkerList(List<Integer> nodeIds) {\n // Bookkeeping for nodes that will be involved in the next task\n nodeIdsWithWork.addAll(nodeIds);\n logger.info(\"Node IDs with work: \" + nodeIdsWithWork + \" Newly added nodes \" + nodeIds);\n }"
] |
Retrieves a vertex attribute as an integer buffer.
The attribute name must be one of the
attributes named in the descriptor passed to the constructor.
@param attributeName name of the attribute to update
@throws IllegalArgumentException if attribute name not in descriptor vertex attribute is not <i>int</i>
@see #setIntArray(String, int[])
@see #getIntVec(String) | [
"public IntBuffer getIntVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n IntBuffer data = buffer.asIntBuffer();\n if (!NativeVertexBuffer.getIntVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }"
] | [
"private void readResource(net.sf.mpxj.planner.schema.Resource plannerResource) throws MPXJException\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n //mpxjResource.setResourceCalendar(m_projectFile.getBaseCalendarByUniqueID(getInteger(plannerResource.getCalendar())));\n mpxjResource.setEmailAddress(plannerResource.getEmail());\n mpxjResource.setUniqueID(getInteger(plannerResource.getId()));\n mpxjResource.setName(plannerResource.getName());\n mpxjResource.setNotes(plannerResource.getNote());\n mpxjResource.setInitials(plannerResource.getShortName());\n mpxjResource.setType(getInt(plannerResource.getType()) == 2 ? ResourceType.MATERIAL : ResourceType.WORK);\n //plannerResource.getStdRate();\n //plannerResource.getOvtRate();\n //plannerResource.getUnits();\n //plannerResource.getProperties();\n\n ProjectCalendar calendar = mpxjResource.addResourceCalendar();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n ProjectCalendar baseCalendar = m_projectFile.getCalendarByUniqueID(getInteger(plannerResource.getCalendar()));\n if (baseCalendar == null)\n {\n baseCalendar = m_defaultCalendar;\n }\n calendar.setParent(baseCalendar);\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }",
"static <T> StitchEvent<T> fromEvent(final Event event,\n final Decoder<T> decoder) {\n return new StitchEvent<>(event.getEventName(), event.getData(), decoder);\n }",
"public void setStringValue(String value) {\n\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) {\n try {\n m_editValue = CmsLocationValue.parse(value);\n m_currentValue = m_editValue.cloneValue();\n displayValue();\n if ((m_popup != null) && m_popup.isVisible()) {\n m_popupContent.displayValues(m_editValue);\n updateMarkerPosition();\n }\n } catch (Exception e) {\n CmsLog.log(e.getLocalizedMessage() + \"\\n\" + CmsClientStringUtil.getStackTrace(e, \"\\n\"));\n }\n } else {\n m_currentValue = null;\n displayValue();\n }\n }",
"private void sendMessage(Message message) throws IOException {\n logger.debug(\"Sending> {}\", message);\n int totalSize = 0;\n for (Field field : message.fields) {\n totalSize += field.getBytes().remaining();\n }\n ByteBuffer combined = ByteBuffer.allocate(totalSize);\n for (Field field : message.fields) {\n logger.debug(\"..sending> {}\", field);\n combined.put(field.getBytes());\n }\n combined.flip();\n Util.writeFully(combined, channel);\n }",
"public ProjectCalendarHours addCalendarHours(Day day)\n {\n ProjectCalendarHours bch = new ProjectCalendarHours(this);\n bch.setDay(day);\n m_hours[day.getValue() - 1] = bch;\n return (bch);\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 }",
"public ProviderContextBuilder setRateTypes(Collection<RateType> rateTypes) {\n Objects.requireNonNull(rateTypes);\n if (rateTypes.isEmpty()) {\n throw new IllegalArgumentException(\"At least one RateType is required.\");\n }\n Set<RateType> rtSet = new HashSet<>(rateTypes);\n set(ProviderContext.KEY_RATE_TYPES, rtSet);\n return this;\n }",
"private MapRow getRow(int index)\n {\n MapRow result;\n\n if (index == m_rows.size())\n {\n result = new MapRow(this, new HashMap<FastTrackField, Object>());\n m_rows.add(result);\n }\n else\n {\n result = m_rows.get(index);\n }\n\n return result;\n }",
"public final void printClientConfig(final JSONWriter json) throws JSONException {\n json.key(\"layouts\");\n json.array();\n final Map<String, Template> accessibleTemplates = getTemplates();\n accessibleTemplates.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))\n .forEach(entry -> {\n json.object();\n json.key(\"name\").value(entry.getKey());\n entry.getValue().printClientConfig(json);\n json.endObject();\n });\n json.endArray();\n json.key(\"smtp\").object();\n json.key(\"enabled\").value(smtp != null);\n if (smtp != null) {\n json.key(\"storage\").object();\n json.key(\"enabled\").value(smtp.getStorage() != null);\n json.endObject();\n }\n json.endObject();\n }"
] |
helper function to convert strings to bytes as needed.
@param key
@param value | [
"@SuppressWarnings(\"unchecked\")\n public void put(String key, Versioned<Object> value) {\n // acquire write lock\n writeLock.lock();\n\n try {\n if(this.storeNames.contains(key) || key.equals(STORES_KEY)) {\n\n // Check for backwards compatibility\n List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) value.getValue();\n StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions);\n\n // If the put is on the entire stores.xml key, delete the\n // additional stores which do not exist in the specified\n // stores.xml\n Set<String> storeNamesToDelete = new HashSet<String>();\n for(String storeName: this.storeNames) {\n storeNamesToDelete.add(storeName);\n }\n\n // Add / update the list of store definitions specified in the\n // value\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n\n // Update the STORES directory and the corresponding entry in\n // metadata cache\n Set<String> specifiedStoreNames = new HashSet<String>();\n for(StoreDefinition storeDef: storeDefinitions) {\n specifiedStoreNames.add(storeDef.getName());\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr,\n value.getVersion());\n this.storeDefinitionsStorageEngine.put(storeDef.getName(),\n versionedValueStr,\n \"\");\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(),\n new Versioned<Object>(storeDefStr, value.getVersion()));\n }\n\n if(key.equals(STORES_KEY)) {\n storeNamesToDelete.removeAll(specifiedStoreNames);\n resetStoreDefinitions(storeNamesToDelete);\n }\n\n // Re-initialize the store definitions\n initStoreDefinitions(value.getVersion());\n\n // Update routing strategies\n updateRoutingStrategies(getCluster(), getStoreDefList());\n\n } else if(METADATA_KEYS.contains(key)) {\n // try inserting into inner store first\n putInner(key, convertObjectToString(key, value));\n\n // cache all keys if innerStore put succeeded\n metadataCache.put(key, value);\n\n // do special stuff if needed\n if(CLUSTER_KEY.equals(key)) {\n updateRoutingStrategies((Cluster) value.getValue(), getStoreDefList());\n } else if(NODE_ID_KEY.equals(key)) {\n initNodeId(getNodeIdNoLock());\n } else if(SYSTEM_STORES_KEY.equals(key))\n throw new VoldemortException(\"Cannot overwrite system store definitions\");\n\n } else {\n throw new VoldemortException(\"Unhandled Key:\" + key + \" for MetadataStore put()\");\n }\n } finally {\n writeLock.unlock();\n }\n }"
] | [
"public Duration getWork(Date date, TimeUnit format)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n long time = getTotalTime(ranges);\n return convertFormat(time, format);\n }",
"public static String getFailureDescriptionAsString(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n return \"\";\n }\n final String msg;\n if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) {\n if (result.hasDefined(ClientConstants.OP)) {\n msg = String.format(\"Operation '%s' at address '%s' failed: %s\", result.get(ClientConstants.OP), result.get(ClientConstants.OP_ADDR), result\n .get(ClientConstants.FAILURE_DESCRIPTION));\n } else {\n msg = String.format(\"Operation failed: %s\", result.get(ClientConstants.FAILURE_DESCRIPTION));\n }\n } else {\n msg = String.format(\"An unexpected response was found checking the deployment. Result: %s\", result);\n }\n return msg;\n }",
"public List<FailedEventInvocation> getFailedInvocations() {\n synchronized (this.mutex) {\n if (this.failedEvents == null) {\n return Collections.emptyList();\n }\n return Collections.unmodifiableList(this.failedEvents);\n }\n }",
"public static void configureLogging() {\n\t\t// Create the appender that will write log messages to the console.\n\t\tConsoleAppender consoleAppender = new ConsoleAppender();\n\t\t// Define the pattern of log messages.\n\t\t// Insert the string \"%c{1}:%L\" to also show class name and line.\n\t\tString pattern = \"%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n\";\n\t\tconsoleAppender.setLayout(new PatternLayout(pattern));\n\t\t// Change to Level.ERROR for fewer messages:\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\n\t\tconsoleAppender.activateOptions();\n\t\tLogger.getRootLogger().addAppender(consoleAppender);\n\t}",
"private static void setFields(final Object from, final Object to,\r\n\t final Field[] fields, final boolean accessible,\r\n\t final Map objMap, final Map metadataMap)\r\n\t{\r\n\t\tfor (int f = 0, fieldsLength = fields.length; f < fieldsLength; ++f)\r\n\t\t{\r\n\t\t\tfinal Field field = fields[f];\r\n\t\t\tfinal int modifiers = field.getModifiers();\r\n\t\t\tif ((Modifier.STATIC & modifiers) != 0) continue;\r\n\t\t\tif ((Modifier.FINAL & modifiers) != 0)\r\n\t\t\t\tthrow new ObjectCopyException(\"cannot set final field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]\");\r\n\t\t\tif (!accessible && ((Modifier.PUBLIC & modifiers) == 0))\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tfield.setAccessible(true);\r\n\t\t\t\t}\r\n\t\t\t\tcatch (SecurityException e)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow new ObjectCopyException(\"cannot access field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]: \" + e.toString(), e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tcloneAndSetFieldValue(field, from, to, objMap, metadataMap);\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tthrow new ObjectCopyException(\"cannot set field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]: \" + e.toString(), e);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"private GenericCriteriaPrompt getPromptValue(FieldType field, byte[] block)\n {\n int textOffset = getPromptOffset(block);\n String value = MPPUtility.getUnicodeString(m_criteriaData, m_criteriaTextStart + textOffset);\n GenericCriteriaPrompt prompt = new GenericCriteriaPrompt(field.getDataType(), value);\n if (m_prompts != null)\n {\n m_prompts.add(prompt);\n }\n return prompt;\n }",
"public static Diagram parseJson(String json,\n Boolean keepGlossaryLink) throws JSONException {\n JSONObject modelJSON = new JSONObject(json);\n return parseJson(modelJSON,\n keepGlossaryLink);\n }",
"public static int validateGeohashMaxLevels(Integer userMaxLevels, int defaultMaxLevels) {\n int maxLevels = userMaxLevels == null ? defaultMaxLevels : userMaxLevels;\n if (maxLevels < 1 || maxLevels > GeohashPrefixTree.getMaxLevelsPossible()) {\n throw new IndexException(\"max_levels must be in range [1, {}], but found {}\",\n GeohashPrefixTree.getMaxLevelsPossible(),\n maxLevels);\n }\n return maxLevels;\n }",
"public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \"=?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"=?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }"
] |
Get a list of comments made for a particular entity
@param entityId - id of the commented entity
@param entityType - type of the entity
@return list of comments | [
"public List<DbComment> getComments(String entityId, String entityType) {\n return repositoryHandler.getComments(entityId, entityType);\n }"
] | [
"public static String pennPOSToWordnetPOS(String s) {\r\n if (s.matches(\"NN|NNP|NNS|NNPS\")) {\r\n return \"noun\";\r\n }\r\n if (s.matches(\"VB|VBD|VBG|VBN|VBZ|VBP|MD\")) {\r\n return \"verb\";\r\n }\r\n if (s.matches(\"JJ|JJR|JJS|CD\")) {\r\n return \"adjective\";\r\n }\r\n if (s.matches(\"RB|RBR|RBS|RP|WRB\")) {\r\n return \"adverb\";\r\n }\r\n return null;\r\n }",
"public Date getFinish()\n {\n Date result = (Date) getCachedValue(AssignmentField.FINISH);\n if (result == null)\n {\n result = getTask().getFinish();\n }\n return result;\n }",
"private void registerProxyCreator(Node source,\n BeanDefinitionHolder holder,\n ParserContext context) {\n\n String beanName = holder.getBeanName();\n String proxyName = beanName + \"Proxy\";\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(BeanNameAutoProxyCreator.class);\n\n initializer.addPropertyValue(\"beanNames\", beanName);\n initializer.addPropertyValue(\"interceptorNames\", interceptorName);\n\n BeanDefinitionRegistry registry = context.getRegistry();\n registry.registerBeanDefinition(proxyName, initializer.getBeanDefinition());\n }",
"public TransformersSubRegistration getHostRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST);\n return new TransformersSubRegistrationImpl(range, domain, address);\n }",
"public static sslservicegroup_sslcertkey_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tsslservicegroup_sslcertkey_binding obj = new sslservicegroup_sslcertkey_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tsslservicegroup_sslcertkey_binding response[] = (sslservicegroup_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@NonNull\n @Override\n public File getParent(@NonNull final File from) {\n if (from.getPath().equals(getRoot().getPath())) {\n // Already at root, we can't go higher\n return from;\n } else if (from.getParentFile() != null) {\n return from.getParentFile();\n } else {\n return from;\n }\n }",
"public static int optionLength(String option) {\n\tint result = Standard.optionLength(option);\n\tif (result != 0)\n\t return result;\n\telse\n\t return UmlGraph.optionLength(option);\n }",
"private boolean isPacketLongEnough(DatagramPacket packet, int expectedLength, String name) {\n final int length = packet.getLength();\n if (length < expectedLength) {\n logger.warn(\"Ignoring too-short \" + name + \" packet; expecting \" + expectedLength + \" bytes and got \" +\n length + \".\");\n return false;\n }\n\n if (length > expectedLength) {\n logger.warn(\"Processing too-long \" + name + \" packet; expecting \" + expectedLength +\n \" bytes and got \" + length + \".\");\n }\n\n return true;\n }",
"@SuppressWarnings(\"unchecked\")\n private void addPrivateFieldsAccessors(ClassNode node) {\n Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);\n if (accessedFields==null) return;\n Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS);\n if (privateConstantAccessors!=null) {\n // already added\n return;\n }\n int acc = -1;\n privateConstantAccessors = new HashMap<String, MethodNode>();\n final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC;\n for (FieldNode fieldNode : node.getFields()) {\n if (accessedFields.contains(fieldNode)) {\n\n acc++;\n Parameter param = new Parameter(node.getPlainNodeReference(), \"$that\");\n Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param);\n Statement stmt = new ExpressionStatement(new PropertyExpression(\n receiver,\n fieldNode.getName()\n ));\n MethodNode accessor = node.addMethod(\"pfaccess$\"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt);\n privateConstantAccessors.put(fieldNode.getName(), accessor);\n }\n }\n node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors);\n }"
] |
Method used to write the name of the scenarios
@param word
@return the same word starting with capital letter | [
"public static String changeFirstLetterToCapital(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toUpperCase(a);\n return new String(letras);\n }"
] | [
"public void setEnterpriseNumber(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_NUMBER, index), value);\n }",
"@Override\n protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n // Is the line an empty comment \"#\" ?\n if (line.startsWith(COMMENT_PREFIX) && line.length() == 1) {\n String nextLine = bufferedFileReader.readLine();\n if (nextLine != null) {\n // Is the next line the realm name \"#$REALM_NAME=\" ?\n if (nextLine.startsWith(COMMENT_PREFIX) && nextLine.contains(REALM_COMMENT_PREFIX)) {\n // Realm name block detected!\n // The next line must be and empty comment \"#\"\n bufferedFileReader.readLine();\n // Avoid adding the realm block\n } else {\n // It's a user comment...\n content.add(line);\n content.add(nextLine);\n }\n } else {\n super.addLineContent(bufferedFileReader, content, line);\n }\n } else {\n super.addLineContent(bufferedFileReader, content, line);\n }\n }",
"@SuppressWarnings(\"unchecked\")\n\tstatic void logToFile(String filename) {\n\t\tLogger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);\n\n\t\tFileAppender<ILoggingEvent> fileappender = new FileAppender<>();\n\t\tfileappender.setContext(rootLogger.getLoggerContext());\n\t\tfileappender.setFile(filename);\n\t\tfileappender.setName(\"FILE\");\n\n\t\tConsoleAppender<?> console = (ConsoleAppender<?>) rootLogger.getAppender(\"STDOUT\");\n\t\tfileappender.setEncoder((Encoder<ILoggingEvent>) console.getEncoder());\n\n\t\tfileappender.start();\n\n\t\trootLogger.addAppender(fileappender);\n\n\t\tconsole.stop();\n\t}",
"public void revertWorkingCopy() throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new RevertWorkingCopyCallable(getLocation(), getSvnAuthenticationProvider(build), buildListener));\n }",
"public Object copy(Object obj, PersistenceBroker broker)\r\n\t\t\tthrows ObjectCopyException\r\n\t{\r\n\t\tif (obj instanceof OjbCloneable)\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\treturn ((OjbCloneable) obj).ojbClone();\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tthrow new ObjectCopyException(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthrow new ObjectCopyException(\"Object must implement OjbCloneable in order to use the\"\r\n\t\t\t\t\t\t\t\t\t\t + \" CloneableObjectCopyStrategy\");\r\n\t\t}\r\n\t}",
"private void getWeeklyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n int currentDay = calendar.get(Calendar.DAY_OF_WEEK);\n\n while (moreDates(calendar, dates))\n {\n int offset = 0;\n for (int dayIndex = 0; dayIndex < 7; dayIndex++)\n {\n if (getWeeklyDay(Day.getInstance(currentDay)))\n {\n if (offset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, offset);\n offset = 0;\n }\n if (!moreDates(calendar, dates))\n {\n break;\n }\n dates.add(calendar.getTime());\n }\n\n ++offset;\n ++currentDay;\n\n if (currentDay > 7)\n {\n currentDay = 1;\n }\n }\n\n if (frequency > 1)\n {\n offset += (7 * (frequency - 1));\n }\n calendar.add(Calendar.DAY_OF_YEAR, offset);\n }\n }",
"public Class getSearchClass()\r\n\t{\r\n\t\tObject obj = getExampleObject();\r\n\r\n\t\tif (obj instanceof Identity)\r\n\t\t{\r\n\t\t\treturn ((Identity) obj).getObjectsTopLevelClass();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn obj.getClass();\r\n\t\t}\r\n\t}",
"public static base_response enable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature enableresource = new nsfeature();\n\t\tenableresource.feature = resource.feature;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}",
"public static systemglobal_authenticationldappolicy_binding[] get(nitro_service service) throws Exception{\n\t\tsystemglobal_authenticationldappolicy_binding obj = new systemglobal_authenticationldappolicy_binding();\n\t\tsystemglobal_authenticationldappolicy_binding response[] = (systemglobal_authenticationldappolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Reset autoCommit state. | [
"protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }"
] | [
"public synchronized void withTransaction(Closure closure) throws SQLException {\n boolean savedCacheConnection = cacheConnection;\n cacheConnection = true;\n Connection connection = null;\n boolean savedAutoCommit = true;\n try {\n connection = createConnection();\n savedAutoCommit = connection.getAutoCommit();\n connection.setAutoCommit(false);\n callClosurePossiblyWithConnection(closure, connection);\n connection.commit();\n } catch (SQLException e) {\n handleError(connection, e);\n throw e;\n } catch (RuntimeException e) {\n handleError(connection, e);\n throw e;\n } catch (Error e) {\n handleError(connection, e);\n throw e;\n } catch (Exception e) {\n handleError(connection, e);\n throw new SQLException(\"Unexpected exception during transaction\", e);\n } finally {\n if (connection != null) {\n try {\n connection.setAutoCommit(savedAutoCommit);\n }\n catch (SQLException e) {\n LOG.finest(\"Caught exception resetting auto commit: \" + e.getMessage() + \" - continuing\");\n }\n }\n cacheConnection = false;\n closeResources(connection, null);\n cacheConnection = savedCacheConnection;\n if (dataSource != null && !cacheConnection) {\n useConnection = null;\n }\n }\n }",
"private static LblTree createTree(TreeWalker walker) {\n\t\tNode parent = walker.getCurrentNode();\n\t\tLblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1\n\t\tfor (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {\n\t\t\tnode.add(createTree(walker));\n\t\t}\n\t\twalker.setCurrentNode(parent);\n\t\treturn node;\n\t}",
"public static boolean removeDefaultCustomResponse(String pathValue, String requestType) {\n try {\n JSONObject profile = getDefaultProfile();\n String profileName = profile.getString(\"name\");\n PathValueClient client = new PathValueClient(profileName, false);\n return client.removeCustomResponse(pathValue, requestType);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public static Map<String, List<String>> getPartitionsForTopics(ZkClient zkClient, Collection<String> topics) {\n Map<String, List<String>> ret = new HashMap<String, List<String>>();\n for (String topic : topics) {\n List<String> partList = new ArrayList<String>();\n List<String> brokers = getChildrenParentMayNotExist(zkClient, BrokerTopicsPath + \"/\" + topic);\n if (brokers != null) {\n for (String broker : brokers) {\n final String parts = readData(zkClient, BrokerTopicsPath + \"/\" + topic + \"/\" + broker);\n int nParts = Integer.parseInt(parts);\n for (int i = 0; i < nParts; i++) {\n partList.add(broker + \"-\" + i);\n }\n }\n }\n Collections.sort(partList);\n ret.put(topic, partList);\n }\n return ret;\n }",
"@Override\n protected void onDataChanged() {\n super.onDataChanged();\n\n int currentAngle = 0;\n int index = 0;\n int size = mPieData.size();\n\n for (PieModel model : mPieData) {\n int endAngle = (int) (currentAngle + model.getValue() * 360.f / mTotalValue);\n if(index == size-1) {\n endAngle = 360;\n }\n\n model.setStartAngle(currentAngle);\n model.setEndAngle(endAngle);\n currentAngle = model.getEndAngle();\n index++;\n }\n calcCurrentItem();\n onScrollFinished();\n }",
"public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public Set<ConstraintViolation> validate(int record) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int ds = 0; ds < 250; ++ds) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSetInfo dataSetInfo = dsiFactory.create(IIM.DS(record, ds));\r\n\t\t\t\terrors.addAll(validate(dataSetInfo));\r\n\t\t\t} catch (InvalidDataSetException ignored) {\r\n\t\t\t\t// DataSetFactory doesn't know about this ds, so will skip it\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn errors;\r\n\t}",
"public int[] argb(int x, int y) {\n Pixel p = pixel(x, y);\n return new int[]{p.alpha(), p.red(), p.green(), p.blue()};\n }",
"public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_WHITELIST_ENTRY_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE);\n BoxAPIResponse response = request.send();\n response.disconnect();\n }"
] |
Facade method for operating the Telnet Shell supporting line editing and command
history over a socket.
@param prompt Prompt to be displayed
@param appName The app name string
@param mainHandler Main command handler
@param input Input stream.
@param output Output stream.
@return Shell that can be either further customized or run directly by calling commandLoop(). | [
"static Shell createTelnetConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n // Set up nvt4j; ignore the initial clear & reposition\n final nvt4j.impl.Terminal nvt4jTerminal = new nvt4j.impl.Terminal(input, output) {\n private boolean cleared;\n private boolean moved;\n\n @Override\n public void clear() throws IOException {\n if (this.cleared)\n super.clear();\n this.cleared = true;\n }\n\n @Override\n public void move(int row, int col) throws IOException {\n if (this.moved)\n super.move(row, col);\n this.moved = true;\n }\n };\n nvt4jTerminal.put(nvt4j.impl.Terminal.AUTO_WRAP_ON);\n nvt4jTerminal.setCursor(true);\n\n // Have JLine do input & output through telnet terminal\n final InputStream jlineInput = new InputStream() {\n @Override\n public int read() throws IOException {\n return nvt4jTerminal.get();\n }\n };\n final OutputStream jlineOutput = new OutputStream() {\n @Override\n public void write(int value) throws IOException {\n nvt4jTerminal.put(value);\n }\n };\n\n return createTerminalConsoleShell(prompt, appName, mainHandler, jlineInput, jlineOutput);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }"
] | [
"@Override\n public void init(NamedList args) {\n\n Object regex = args.remove(PARAM_REGEX);\n if (null == regex) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REGEX);\n }\n try {\n m_regex = Pattern.compile(regex.toString());\n } catch (PatternSyntaxException e) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Invalid regex: \" + regex, e);\n }\n\n Object replacement = args.remove(PARAM_REPLACEMENT);\n if (null == replacement) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REPLACEMENT);\n }\n m_replacement = replacement.toString();\n\n Object source = args.remove(PARAM_SOURCE);\n if (null == source) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_SOURCE);\n }\n m_source = source.toString();\n\n Object target = args.remove(PARAM_TARGET);\n if (null == target) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_TARGET);\n }\n m_target = target.toString();\n\n }",
"public String objectToString(T object) {\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tsb.append(object.getClass().getSimpleName());\n\t\tfor (FieldType fieldType : fieldTypes) {\n\t\t\tsb.append(' ').append(fieldType.getColumnName()).append('=');\n\t\t\ttry {\n\t\t\t\tsb.append(fieldType.extractJavaFieldValue(object));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not generate toString of field \" + fieldType, e);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}",
"public void drawGeometry(Geometry geometry, SymbolInfo symbol, Color fillColor, Color strokeColor, float lineWidth,\n\t\t\tfloat[] dashArray, Rectangle clipRect) {\n\t\ttemplate.saveState();\n\t\t// clipping code\n\t\tif (clipRect != null) {\n\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(), clipRect\n\t\t\t\t\t.getHeight());\n\t\t\ttemplate.clip();\n\t\t\ttemplate.newPath();\n\t\t}\n\t\tsetStroke(strokeColor, lineWidth, dashArray);\n\t\tsetFill(fillColor);\n\t\tdrawGeometry(geometry, symbol);\n\t\ttemplate.restoreState();\n\t}",
"public static String getFailureDescriptionAsString(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n return \"\";\n }\n final String msg;\n if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) {\n if (result.hasDefined(ClientConstants.OP)) {\n msg = String.format(\"Operation '%s' at address '%s' failed: %s\", result.get(ClientConstants.OP), result.get(ClientConstants.OP_ADDR), result\n .get(ClientConstants.FAILURE_DESCRIPTION));\n } else {\n msg = String.format(\"Operation failed: %s\", result.get(ClientConstants.FAILURE_DESCRIPTION));\n }\n } else {\n msg = String.format(\"An unexpected response was found checking the deployment. Result: %s\", result);\n }\n return msg;\n }",
"@Override\n public boolean parseAndValidateRequest() {\n if(!super.parseAndValidateRequest()) {\n return false;\n }\n isGetVersionRequest = hasGetVersionRequestHeader();\n if(isGetVersionRequest && this.parsedKeys.size() > 1) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Get version request cannot have multiple keys\");\n return false;\n }\n return true;\n }",
"@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Creatable<? extends Indexable> creatable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatable;\n return this.addPostRunDependent(dependency);\n }",
"@PostConstruct\n public void initDatabase() {\n MongoDBInit.LOGGER.info(\"initializing MongoDB\");\n String dbName = System.getProperty(\"mongodb.name\");\n if (dbName == null) {\n throw new RuntimeException(\"Missing database name; Set system property 'mongodb.name'\");\n }\n MongoDatabase db = this.mongo.getDatabase(dbName);\n\n try {\n PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();\n Resource[] resources = resolver.getResources(\"classpath*:mongodb/*.ndjson\");\n MongoDBInit.LOGGER.info(\"Scanning for collection data\");\n for (Resource res : resources) {\n String filename = res.getFilename();\n String collection = filename.substring(0, filename.length() - 7);\n MongoDBInit.LOGGER.info(\"Found collection file: {}\", collection);\n MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);\n try (Scanner scan = new Scanner(res.getInputStream(), \"UTF-8\")) {\n int lines = 0;\n while (scan.hasNextLine()) {\n String json = scan.nextLine();\n Object parse = JSON.parse(json);\n if (parse instanceof DBObject) {\n DBObject dbObject = (DBObject) parse;\n dbCollection.insertOne(dbObject);\n } else {\n MongoDBInit.LOGGER.error(\"Invalid object found: {}\", parse);\n throw new RuntimeException(\"Invalid object\");\n }\n lines++;\n }\n MongoDBInit.LOGGER.info(\"Imported {} objects into collection {}\", lines, collection);\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(\"Error importing objects\", e);\n }\n }",
"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}",
"public FieldLocation getFieldLocation(FieldType type)\n {\n FieldLocation result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFieldLocation();\n }\n return result;\n }"
] |
Parse a string representation of an Integer value.
@param value string representation
@return Integer value | [
"public static Integer parseInteger(String value) throws ParseException\n {\n Integer result = null;\n\n if (value.length() > 0 && value.indexOf(' ') == -1)\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n Number n = DatatypeConverter.parseDouble(value);\n result = Integer.valueOf(n.intValue());\n }\n }\n\n return result;\n }"
] | [
"public static java.util.Date toDateTime(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.util.Date) {\n return (java.util.Date) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return IN_DATETIME_FORMAT.parse((String) value);\n }\n\n return IN_DATETIME_FORMAT.parse(value.toString());\n }",
"public ReplicationResult trigger() {\n assertNotEmpty(source, \"Source\");\n assertNotEmpty(target, \"Target\");\n InputStream response = null;\n try {\n JsonObject json = createJson();\n if (log.isLoggable(Level.FINE)) {\n log.fine(json.toString());\n }\n\n final URI uri = new DatabaseURIHelper(client.getBaseUri()).path(\"_replicate\").build();\n response = client.post(uri, json.toString());\n final InputStreamReader reader = new InputStreamReader(response, \"UTF-8\");\n return client.getGson().fromJson(reader, ReplicationResult.class);\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 } finally {\n close(response);\n }\n }",
"private Bpmn2Resource unmarshall(JsonParser parser,\n String preProcessingData) throws IOException {\n try {\n parser.nextToken(); // open the object\n ResourceSet rSet = new ResourceSetImpl();\n rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(\"bpmn2\",\n new JBPMBpmn2ResourceFactoryImpl());\n Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI(\"virtual.bpmn2\"));\n rSet.getResources().add(bpmn2);\n _currentResource = bpmn2;\n\n if (preProcessingData == null || preProcessingData.length() < 1) {\n preProcessingData = \"ReadOnlyService\";\n }\n\n // do the unmarshalling now:\n Definitions def = (Definitions) unmarshallItem(parser,\n preProcessingData);\n def.setExporter(exporterName);\n def.setExporterVersion(exporterVersion);\n revisitUserTasks(def);\n revisitServiceTasks(def);\n revisitMessages(def);\n revisitCatchEvents(def);\n revisitThrowEvents(def);\n revisitLanes(def);\n revisitSubProcessItemDefs(def);\n revisitArtifacts(def);\n revisitGroups(def);\n revisitTaskAssociations(def);\n revisitTaskIoSpecification(def);\n revisitSendReceiveTasks(def);\n reconnectFlows();\n revisitGateways(def);\n revisitCatchEventsConvertToBoundary(def);\n revisitBoundaryEventsPositions(def);\n createDiagram(def);\n updateIDs(def);\n revisitDataObjects(def);\n revisitAssociationsIoSpec(def);\n revisitWsdlImports(def);\n revisitMultiInstanceTasks(def);\n addSimulation(def);\n revisitItemDefinitions(def);\n revisitProcessDoc(def);\n revisitDI(def);\n revisitSignalRef(def);\n orderDiagramElements(def);\n\n // return def;\n _currentResource.getContents().add(def);\n return _currentResource;\n } catch (Exception e) {\n _logger.error(e.getMessage());\n return _currentResource;\n } finally {\n parser.close();\n _objMap.clear();\n _idMap.clear();\n _outgoingFlows.clear();\n _sequenceFlowTargets.clear();\n _bounds.clear();\n _currentResource = null;\n }\n }",
"public void notifyEventListeners(ZWaveEvent event) {\n\t\tlogger.debug(\"Notifying event listeners\");\n\t\tfor (ZWaveEventListener listener : this.zwaveEventListeners) {\n\t\t\tlogger.trace(\"Notifying {}\", listener.toString());\n\t\t\tlistener.ZWaveIncomingEvent(event);\n\t\t}\n\t}",
"public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {\n calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);\n calendar.set(Calendar.MINUTE, minute);\n calendar.set(Calendar.SECOND, second);\n calendar.set(Calendar.MILLISECOND, millisecond);\n }",
"public MapBounds getRotatedBoundsAdjustedForPreciseRotatedMapSize() {\n Rectangle2D.Double paintAreaPrecise = getRotatedMapSizePrecise();\n Rectangle paintArea = new Rectangle(MapfishMapContext.rectangleDoubleToDimension(paintAreaPrecise));\n return getRotatedBounds(paintAreaPrecise, paintArea);\n }",
"protected boolean isTransient(ClassDescriptor cld, Object obj, Identity oid)\r\n {\r\n // if the Identity is transient we assume a non-persistent object\r\n boolean isNew = oid != null && oid.isTransient();\r\n /*\r\n detection of new objects is costly (select of ID in DB to check if object\r\n already exists) we do:\r\n a. check if the object has nullified PK field\r\n b. check if the object is already registered\r\n c. lookup from cache and if not found, last option select on DB\r\n */\r\n if(!isNew)\r\n {\r\n final PersistenceBroker pb = getBroker();\r\n if(cld == null)\r\n {\r\n cld = pb.getClassDescriptor(obj.getClass());\r\n }\r\n isNew = pb.serviceBrokerHelper().hasNullPKField(cld, obj);\r\n if(!isNew)\r\n {\r\n if(oid == null)\r\n {\r\n oid = pb.serviceIdentity().buildIdentity(cld, obj);\r\n }\r\n final ObjectEnvelope mod = objectEnvelopeTable.getByIdentity(oid);\r\n if(mod != null)\r\n {\r\n // already registered object, use current state\r\n isNew = mod.needsInsert();\r\n }\r\n else\r\n {\r\n // if object was found cache, assume it's old\r\n // else make costly check against the DB\r\n isNew = pb.serviceObjectCache().lookup(oid) == null\r\n && !pb.serviceBrokerHelper().doesExist(cld, oid, obj);\r\n }\r\n }\r\n }\r\n return isNew;\r\n }",
"private void writeAssignments() throws IOException\n {\n writeAttributeTypes(\"assignment_types\", AssignmentField.values());\n\n m_writer.writeStartList(\"assignments\");\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n writeFields(null, assignment, AssignmentField.values());\n }\n m_writer.writeEndList();\n\n }",
"private void readColumnBlock(int startIndex, int blockLength) throws Exception\n {\n int endIndex = startIndex + blockLength;\n List<Integer> blocks = new ArrayList<Integer>();\n for (int index = startIndex; index < endIndex - 11; index++)\n {\n if (matchChildBlock(index))\n {\n int childBlockStart = index - 2;\n blocks.add(Integer.valueOf(childBlockStart));\n }\n }\n blocks.add(Integer.valueOf(endIndex));\n\n int childBlockStart = -1;\n for (int childBlockEnd : blocks)\n {\n if (childBlockStart != -1)\n {\n int childblockLength = childBlockEnd - childBlockStart;\n try\n {\n readColumn(childBlockStart, childblockLength);\n }\n catch (UnexpectedStructureException ex)\n {\n logUnexpectedStructure();\n }\n }\n childBlockStart = childBlockEnd;\n }\n }"
] |
Computes the householder vector used in QR decomposition.
u = x / max(x)
u(0) = u(0) + |u|
u = u / u(0)
@param x Input vector. Unmodified.
@return The found householder reflector vector | [
"public static ZMatrixRMaj householderVector(ZMatrixRMaj x ) {\n ZMatrixRMaj u = x.copy();\n\n double max = CommonOps_ZDRM.elementMaxAbs(u);\n\n CommonOps_ZDRM.elementDivide(u, max, 0, u);\n\n double nx = NormOps_ZDRM.normF(u);\n Complex_F64 c = new Complex_F64();\n u.get(0,0,c);\n\n double realTau,imagTau;\n\n if( c.getMagnitude() == 0 ) {\n realTau = nx;\n imagTau = 0;\n } else {\n realTau = c.real/c.getMagnitude()*nx;\n imagTau = c.imaginary/c.getMagnitude()*nx;\n }\n\n u.set(0,0,c.real + realTau,c.imaginary + imagTau);\n CommonOps_ZDRM.elementDivide(u,u.getReal(0,0),u.getImag(0,0),u);\n\n return u;\n }"
] | [
"public void pause(ServerActivityCallback requestCountListener) {\n if (paused) {\n throw ServerLogger.ROOT_LOGGER.serverAlreadyPaused();\n }\n this.paused = true;\n listenerUpdater.set(this, requestCountListener);\n if (activeRequestCountUpdater.get(this) == 0) {\n if (listenerUpdater.compareAndSet(this, requestCountListener, null)) {\n requestCountListener.done();\n }\n }\n }",
"@Override\r\n public ImageSource apply(ImageSource source) {\r\n if (radius != 0) {\r\n if (source.isGrayscale()) {\r\n return applyGrayscale(source, radius);\r\n } else {\r\n return applyRGB(source, radius);\r\n }\r\n } else {\r\n if (source.isGrayscale()) {\r\n return applyGrayscale(source, kernel);\r\n } else {\r\n return applyRGB(source, kernel);\r\n }\r\n }\r\n }",
"public static final PolygonOptions buildClosedArc(LatLong center, LatLong start, LatLong end, ArcType arcType) {\n MVCArray res = buildArcPoints(center, start, end);\n if (ArcType.ROUND.equals(arcType)) {\n res.push(center);\n }\n return new PolygonOptions().paths(res);\n }",
"private Map<ConfigurationKey, Object> getObsoleteSystemProperties() {\n Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);\n String concurrentDeployment = getSystemProperty(\"org.jboss.weld.bootstrap.properties.concurrentDeployment\");\n if (concurrentDeployment != null) {\n processKeyValue(found, ConfigurationKey.CONCURRENT_DEPLOYMENT, concurrentDeployment);\n found.put(ConfigurationKey.CONCURRENT_DEPLOYMENT, ConfigurationKey.CONCURRENT_DEPLOYMENT.convertValue(concurrentDeployment));\n }\n String preloaderThreadPoolSize = getSystemProperty(\"org.jboss.weld.bootstrap.properties.preloaderThreadPoolSize\");\n if (preloaderThreadPoolSize != null) {\n found.put(ConfigurationKey.PRELOADER_THREAD_POOL_SIZE, ConfigurationKey.PRELOADER_THREAD_POOL_SIZE.convertValue(preloaderThreadPoolSize));\n }\n return found;\n }",
"protected void sendPageBreakToBottom(JRDesignBand band) {\n\t\tJRElement[] elems = band.getElements();\n\t\tJRElement aux = null;\n\t\tfor (JRElement elem : elems) {\n\t\t\tif ((\"\" + elem.getKey()).startsWith(PAGE_BREAK_FOR_)) {\n\t\t\t\taux = elem;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aux != null)\n\t\t\t((JRDesignElement)aux).setY(band.getHeight());\n\t}",
"@SuppressWarnings({\"unchecked\", \"WeakerAccess\"})\n public static <T> List<T> readListAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n // todo: fix this when this method signature is corrected\n final List<T> value = (List<T>) reader.getListAttributeValue(0, type);\n requireNoContent(reader);\n return value;\n }",
"public synchronized boolean acquireRebalancingPermit(int nodeId) {\n boolean added = rebalancePermits.add(nodeId);\n logger.info(\"Acquiring rebalancing permit for node id \" + nodeId + \", returned: \" + added);\n\n return added;\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 void updateExceptions() {\n\n m_exceptionsList.setDates(m_model.getExceptions());\n if (m_model.getExceptions().size() > 0) {\n m_exceptionsPanel.setVisible(true);\n } else {\n m_exceptionsPanel.setVisible(false);\n }\n }"
] |
Gets the progress from response.
@param myResponse
the my response
@return the progress from response | [
"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 }"
] | [
"private void processPredecessor(Task task, MapRow row)\n {\n Task predecessor = m_taskMap.get(row.getUUID(\"PREDECESSOR_UUID\"));\n if (predecessor != null)\n {\n task.addPredecessor(predecessor, row.getRelationType(\"RELATION_TYPE\"), row.getDuration(\"LAG\"));\n }\n }",
"private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }",
"public static final String getUnicodeString(byte[] data, int offset)\n {\n int length = getUnicodeStringLengthInBytes(data, offset);\n return length == 0 ? \"\" : new String(data, offset, length, CharsetHelper.UTF16LE);\n }",
"public static Map<FieldType, String> getDefaultResourceFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(ResourceField.UNIQUE_ID, \"rsrc_id\");\n map.put(ResourceField.GUID, \"guid\");\n map.put(ResourceField.NAME, \"rsrc_name\");\n map.put(ResourceField.CODE, \"employee_code\");\n map.put(ResourceField.EMAIL_ADDRESS, \"email_addr\");\n map.put(ResourceField.NOTES, \"rsrc_notes\");\n map.put(ResourceField.CREATED, \"create_date\");\n map.put(ResourceField.TYPE, \"rsrc_type\");\n map.put(ResourceField.INITIALS, \"rsrc_short_name\");\n map.put(ResourceField.PARENT_ID, \"parent_rsrc_id\");\n\n return map;\n }",
"private void verifyOrAddStore(String clusterURL,\n String keySchema,\n String valueSchema) {\n String newStoreDefXml = VoldemortUtils.getStoreDefXml(\n storeName,\n props.getInt(BUILD_REPLICATION_FACTOR, 2),\n props.getInt(BUILD_REQUIRED_READS, 1),\n props.getInt(BUILD_REQUIRED_WRITES, 1),\n props.getNullableInt(BUILD_PREFERRED_READS),\n props.getNullableInt(BUILD_PREFERRED_WRITES),\n props.getString(PUSH_FORCE_SCHEMA_KEY, keySchema),\n props.getString(PUSH_FORCE_SCHEMA_VALUE, valueSchema),\n description,\n owners);\n\n log.info(\"Verifying store against cluster URL: \" + clusterURL + \"\\n\" + newStoreDefXml.toString());\n StoreDefinition newStoreDef = VoldemortUtils.getStoreDef(newStoreDefXml);\n\n try {\n adminClientPerCluster.get(clusterURL).storeMgmtOps.verifyOrAddStore(newStoreDef, \"BnP config/data\",\n enableStoreCreation, this.storeVerificationExecutorService);\n } catch (UnreachableStoreException e) {\n log.info(\"verifyOrAddStore() failed on some nodes for clusterURL: \" + clusterURL + \" (this is harmless).\", e);\n // When we can't reach some node, we just skip it and won't create the store on it.\n // Next time BnP is run while the node is up, it will get the store created.\n } // Other exceptions need to bubble up!\n\n storeDef = newStoreDef;\n }",
"public static boolean checkAddProperty(\r\n CmsCmisTypeManager typeManager,\r\n Properties properties,\r\n String typeId,\r\n Set<String> filter,\r\n String id) {\r\n\r\n if ((properties == null) || (properties.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Properties must not be null!\");\r\n }\r\n\r\n if (id == null) {\r\n throw new IllegalArgumentException(\"Id must not be null!\");\r\n }\r\n\r\n TypeDefinition type = typeManager.getType(typeId);\r\n if (type == null) {\r\n throw new IllegalArgumentException(\"Unknown type: \" + typeId);\r\n }\r\n if (!type.getPropertyDefinitions().containsKey(id)) {\r\n throw new IllegalArgumentException(\"Unknown property: \" + id);\r\n }\r\n\r\n String queryName = type.getPropertyDefinitions().get(id).getQueryName();\r\n\r\n if ((queryName != null) && (filter != null)) {\r\n if (!filter.contains(queryName)) {\r\n return false;\r\n } else {\r\n filter.remove(queryName);\r\n }\r\n }\r\n\r\n return true;\r\n }",
"static InjectionProvider<?>[] toArray(final Set<InjectionProvider<?>> injectionProviders) {\n return injectionProviders.toArray(new InjectionProvider<?>[injectionProviders.size()]);\n }",
"public long indexOf(final String element) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return doIndexOf(jedis, element);\n }\n });\n }",
"private static Predicate join(final String joinWord, final List<Predicate> preds) {\n return new Predicate() {\n public void init(AbstractSqlCreator creator) {\n for (Predicate p : preds) {\n p.init(creator);\n }\n }\n public String toSql() {\n StringBuilder sb = new StringBuilder()\n .append(\"(\");\n boolean first = true;\n for (Predicate p : preds) {\n if (!first) {\n sb.append(\" \").append(joinWord).append(\" \");\n }\n sb.append(p.toSql());\n first = false;\n }\n return sb.append(\")\").toString();\n }\n };\n }"
] |
Query a player to determine the port on which its database server is running.
@param announcement the device announcement with which we detected a new player on the network. | [
"private void requestPlayerDBServerPort(DeviceAnnouncement announcement) {\n Socket socket = null;\n try {\n InetSocketAddress address = new InetSocketAddress(announcement.getAddress(), DB_SERVER_QUERY_PORT);\n socket = new Socket();\n socket.connect(address, socketTimeout.get());\n InputStream is = socket.getInputStream();\n OutputStream os = socket.getOutputStream();\n socket.setSoTimeout(socketTimeout.get());\n os.write(DB_SERVER_QUERY_PACKET);\n byte[] response = readResponseWithExpectedSize(is, 2, \"database server port query packet\");\n if (response.length == 2) {\n setPlayerDBServerPort(announcement.getNumber(), (int)Util.bytesToNumber(response, 0, 2));\n }\n } catch (java.net.ConnectException ce) {\n logger.info(\"Player \" + announcement.getNumber() +\n \" doesn't answer rekordbox port queries, connection refused. Won't attempt to request metadata.\");\n } catch (Exception e) {\n logger.warn(\"Problem requesting database server port number\", e);\n } finally {\n if (socket != null) {\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing database server port request socket\", e);\n }\n }\n }\n }"
] | [
"public List<ServerGroup> tableServerGroups(int profileId) {\n ArrayList<ServerGroup> serverGroups = new ArrayList<>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ? \" +\n \"ORDER BY \" + Constants.GENERIC_NAME\n );\n queryStatement.setInt(1, profileId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n ServerGroup curServerGroup = new ServerGroup(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.GENERIC_NAME),\n results.getInt(Constants.GENERIC_PROFILE_ID));\n curServerGroup.setServers(tableServers(profileId, curServerGroup.getId()));\n serverGroups.add(curServerGroup);\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 return serverGroups;\n }",
"public void forAllValuePairs(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME, \"attributes\");\r\n String defaultValue = attributes.getProperty(ATTRIBUTE_DEFAULT_RIGHT, \"\");\r\n String attributePairs = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), name);\r\n\r\n if ((attributePairs == null) || (attributePairs.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n String token;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(attributePairs); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos >= 0)\r\n {\r\n _curPairLeft = token.substring(0, pos);\r\n _curPairRight = (pos < token.length() - 1 ? token.substring(pos + 1) : defaultValue);\r\n }\r\n else\r\n {\r\n _curPairLeft = token;\r\n _curPairRight = defaultValue;\r\n }\r\n if (_curPairLeft.length() > 0)\r\n {\r\n generate(template);\r\n }\r\n }\r\n _curPairLeft = null;\r\n _curPairRight = null;\r\n }",
"private void validateSameDay(ProjectCalendar calendar, LinkedList<TimephasedWork> list)\n {\n for (TimephasedWork assignment : list)\n {\n Date assignmentStart = assignment.getStart();\n Date calendarStartTime = calendar.getStartTime(assignmentStart);\n Date assignmentStartTime = DateHelper.getCanonicalTime(assignmentStart);\n Date assignmentFinish = assignment.getFinish();\n Date calendarFinishTime = calendar.getFinishTime(assignmentFinish);\n Date assignmentFinishTime = DateHelper.getCanonicalTime(assignmentFinish);\n double totalWork = assignment.getTotalAmount().getDuration();\n\n if (assignmentStartTime != null && calendarStartTime != null)\n {\n if ((totalWork == 0 && assignmentStartTime.getTime() != calendarStartTime.getTime()) || (assignmentStartTime.getTime() < calendarStartTime.getTime()))\n {\n assignmentStart = DateHelper.setTime(assignmentStart, calendarStartTime);\n assignment.setStart(assignmentStart);\n }\n }\n\n if (assignmentFinishTime != null && calendarFinishTime != null)\n {\n if ((totalWork == 0 && assignmentFinishTime.getTime() != calendarFinishTime.getTime()) || (assignmentFinishTime.getTime() > calendarFinishTime.getTime()))\n {\n assignmentFinish = DateHelper.setTime(assignmentFinish, calendarFinishTime);\n assignment.setFinish(assignmentFinish);\n }\n }\n }\n }",
"public static String renderJson(Object o) {\n\n Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()\n .create();\n return gson.toJson(o);\n }",
"private void addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n try\n {\n switch (fieldType)\n {\n case TASK:\n TaskField taskField;\n\n do\n {\n taskField = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (m_taskFields.containsKey(taskField) || m_wbsFields.containsKey(taskField));\n\n m_project.getCustomFields().getCustomField(taskField).setAlias(name);\n\n break;\n case RESOURCE:\n ResourceField resourceField;\n\n do\n {\n resourceField = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n }\n while (m_resourceFields.containsKey(resourceField));\n\n m_project.getCustomFields().getCustomField(resourceField).setAlias(name);\n\n break;\n case ASSIGNMENT:\n AssignmentField assignmentField;\n\n do\n {\n assignmentField = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n }\n while (m_assignmentFields.containsKey(assignmentField));\n\n m_project.getCustomFields().getCustomField(assignmentField).setAlias(name);\n\n break;\n default:\n break;\n }\n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\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 }",
"@SuppressWarnings(\"deprecation\")\n\tpublic static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getDate() == d2.getDate()\n && d1.getMonth() == d2.getMonth()\n && d1.getYear() == d2.getYear()\n && d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }",
"public static void mainInternal(String[] args) throws Exception {\n\n Options options = new Options();\n CmdLineParser parser = new CmdLineParser(options);\n try {\n parser.parseArgument(args);\n } catch (CmdLineException e) {\n helpScreen(parser);\n return;\n }\n\n try {\n List<String> configs = new ArrayList<>();\n if (options.configs != null) {\n configs.addAll(Arrays.asList(options.configs.split(\",\")));\n }\n ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);\n } catch (ConfigException ex) {\n ConfigLogger.error(ex);\n throw ex;\n } catch (Throwable th) {\n ConfigLogger.error(th);\n throw th;\n }\n }",
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static byte checkByte(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInByteRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), BYTE_MIN, BYTE_MAX);\n\t\t}\n\n\t\treturn number.byteValue();\n\t}"
] |
Pauses the file upload. This is a blocking function that would try to wait till the assembly file uploads
have actually been paused if possible.
@throws LocalOperationException if the method is called while no upload is going on. | [
"public void pauseUpload() throws LocalOperationException {\n if (state == State.UPLOADING) {\n setState(State.PAUSED);\n executor.hardStop();\n } else {\n throw new LocalOperationException(\"Attempt to pause upload while assembly is not uploading\");\n }\n }"
] | [
"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 }",
"@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }",
"public int getHistoryCount(int profileId, String clientUUID, HashMap<String, String[]> searchFilter) {\n int count = 0;\n Statement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n\n sqlQuery += \";\";\n\n logger.info(\"Query: {}\", sqlQuery);\n\n query = sqlConnection.createStatement();\n results = query.executeQuery(sqlQuery);\n if (results.next()) {\n count = results.getInt(1);\n }\n query.close();\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n return count;\n }",
"private static Map<String, Object> processConf(Map<String, ?> conf) {\n Map<String, Object> m = new HashMap<String, Object>(conf.size());\n for (String s : conf.keySet()) {\n Object o = conf.get(s);\n if (s.startsWith(\"act.\")) s = s.substring(4);\n m.put(s, o);\n m.put(Config.canonical(s), o);\n }\n return m;\n }",
"@Api\n\tpublic void setNamedRoles(Map<String, List<NamedRoleInfo>> namedRoles) {\n\t\tthis.namedRoles = namedRoles;\n\t\tldapRoleMapping = new HashMap<String, Set<String>>();\n\t\tfor (String roleName : namedRoles.keySet()) {\n\t\t\tif (!ldapRoleMapping.containsKey(roleName)) {\n\t\t\t\tldapRoleMapping.put(roleName, new HashSet<String>());\n\t\t\t}\n\t\t\tfor (NamedRoleInfo role : namedRoles.get(roleName)) {\n\t\t\t\tldapRoleMapping.get(roleName).add(role.getName());\n\t\t\t}\n\t\t}\n\t}",
"private void addTables(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Table table : file.getTables())\n {\n final Table t = table;\n MpxjTreeNode childNode = new MpxjTreeNode(table, TABLE_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return t.getName();\n }\n };\n parentNode.add(childNode);\n\n addColumns(childNode, table);\n }\n }",
"public RandomVariable[]\tgetParameter() {\n\t\tdouble[] parameterAsDouble = this.getParameterAsDouble();\n\t\tRandomVariable[] parameter = new RandomVariable[parameterAsDouble.length];\n\t\tfor(int i=0; i<parameter.length; i++) {\n\t\t\tparameter[i] = new Scalar(parameterAsDouble[i]);\n\t\t}\n\t\treturn parameter;\n\t}",
"private static void checkPreconditions(List<String> requiredSubStrings) {\n\t\tif( requiredSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"requiredSubStrings List should not be null\");\n\t\t} else if( requiredSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"requiredSubStrings List should not be empty\");\n\t\t}\n\t}",
"private Map<String, String> mergeItem(\r\n String item,\r\n Map<String, String> localeValues,\r\n Map<String, String> resultLocaleValues) {\r\n\r\n if (resultLocaleValues.get(item) != null) {\r\n if (localeValues.get(item) != null) {\r\n localeValues.put(item, localeValues.get(item) + \" \" + resultLocaleValues.get(item));\r\n } else {\r\n localeValues.put(item, resultLocaleValues.get(item));\r\n }\r\n }\r\n\r\n return localeValues;\r\n }"
] |
Use this API to create sslfipskey. | [
"public static base_response create(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey createresource = new sslfipskey();\n\t\tcreateresource.fipskeyname = resource.fipskeyname;\n\t\tcreateresource.modulus = resource.modulus;\n\t\tcreateresource.exponent = resource.exponent;\n\t\treturn createresource.perform_operation(client,\"create\");\n\t}"
] | [
"public void deleteModule(final String moduleId) {\n final DbModule module = getModule(moduleId);\n repositoryHandler.deleteModule(module.getId());\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n repositoryHandler.deleteArtifact(gavc);\n }\n }",
"protected View postDeclineView() {\n\t\treturn new TopLevelWindowRedirect() {\n\t\t\t@Override\n\t\t\tprotected String getRedirectUrl(Map<String, ?> model) {\n\t\t\t\treturn postDeclineUrl;\n\t\t\t}\n\t\t};\n\t}",
"@SuppressWarnings(\"unchecked\")\n public static <T> AttachmentKey<T> create(final Class<? super T> valueClass) {\n return new SimpleAttachmentKey(valueClass);\n }",
"public void bindDelete(PreparedStatement stmt, Identity oid, ClassDescriptor cld) throws SQLException\r\n {\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n int i = 0;\r\n try\r\n {\r\n for (; i < pkValues.length; i++)\r\n {\r\n setObjectForStatement(stmt, i + 1, pkValues[i], pkFields[i].getJdbcType().getType());\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n m_log.error(\"bindDelete failed for: \" + oid.toString() + \", while set value '\" +\r\n pkValues[i] + \"' for column \" + pkFields[i].getColumnName());\r\n throw e;\r\n }\r\n }",
"MongoCollection<BsonDocument> getUndoCollection(final MongoNamespace namespace) {\n return localClient\n .getDatabase(String.format(\"sync_undo_%s\", namespace.getDatabaseName()))\n .getCollection(namespace.getCollectionName(), BsonDocument.class)\n .withCodecRegistry(MongoClientSettings.getDefaultCodecRegistry());\n }",
"public static CmsPair<String, Map<String, String>> parseEmbeddedGalleryOptions(String configuration) {\n\n final Map<String, String> galleryOptions = Maps.newHashMap();\n String resultConfig = CmsStringUtil.substitute(\n PATTERN_EMBEDDED_GALLERY_CONFIG,\n configuration,\n new I_CmsRegexSubstitution() {\n\n public String substituteMatch(String string, Matcher matcher) {\n\n String galleryName = string.substring(matcher.start(1), matcher.end(1));\n String embeddedConfig = string.substring(matcher.start(2), matcher.end(2));\n galleryOptions.put(galleryName, embeddedConfig);\n return galleryName;\n }\n });\n return CmsPair.create(resultConfig, galleryOptions);\n }",
"@SuppressWarnings(\"unchecked\")\n private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,\n HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());\n // Get an Enumeration of all of the header names sent by the client\n Boolean stripTransferEncoding = false;\n Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();\n while (enumerationOfHeaderNames.hasMoreElements()) {\n String stringHeaderName = enumerationOfHeaderNames.nextElement();\n if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) {\n // don't add this header\n continue;\n }\n\n // The forwarding proxy may supply a POST encoding hint in ODO-POST-TYPE\n if (stringHeaderName.equalsIgnoreCase(\"ODO-POST-TYPE\") &&\n httpServletRequest.getHeader(\"ODO-POST-TYPE\").startsWith(\"content-length:\")) {\n stripTransferEncoding = true;\n }\n\n logger.info(\"Current header: {}\", stringHeaderName);\n // As per the Java Servlet API 2.5 documentation:\n // Some headers, such as Accept-Language can be sent by clients\n // as several headers each with a different value rather than\n // sending the header as a comma separated list.\n // Thus, we get an Enumeration of the header values sent by the\n // client\n Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);\n\n while (enumerationOfHeaderValues.hasMoreElements()) {\n String stringHeaderValue = enumerationOfHeaderValues.nextElement();\n // In case the proxy host is running multiple virtual servers,\n // rewrite the Host header to ensure that we get content from\n // the correct virtual server\n if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) &&\n requestInfo.handle) {\n String hostValue = getHostHeaderForHost(hostName);\n if (hostValue != null) {\n stringHeaderValue = hostValue;\n }\n }\n\n Header header = new Header(stringHeaderName, stringHeaderValue);\n // Set the same header on the proxy request\n httpMethodProxyRequest.addRequestHeader(header);\n }\n }\n\n // this strips transfer encoding headers and adds in the appropriate content-length header\n // based on the hint provided in the ODO-POST-TYPE header(sent from BrowserMobProxyHandler)\n if (stripTransferEncoding) {\n httpMethodProxyRequest.removeRequestHeader(\"transfer-encoding\");\n\n // add content length back in based on the ODO information\n String contentLengthHint = httpServletRequest.getHeader(\"ODO-POST-TYPE\");\n String[] contentLengthParts = contentLengthHint.split(\":\");\n httpMethodProxyRequest.addRequestHeader(\"content-length\", contentLengthParts[1]);\n\n // remove the odo-post-type header\n httpMethodProxyRequest.removeRequestHeader(\"ODO-POST-TYPE\");\n }\n\n // bail if we aren't fully handling this request\n if (!requestInfo.handle) {\n return;\n }\n\n // deal with header overrides for the request\n processRequestHeaderOverrides(httpMethodProxyRequest);\n }",
"public void setRoles(List<NamedRoleInfo> roles) {\n\t\tthis.roles = roles;\n\t\tList<AuthorizationInfo> authorizations = new ArrayList<AuthorizationInfo>();\n\t\tfor (NamedRoleInfo role : roles) {\n\t\t\tauthorizations.addAll(role.getAuthorizations());\n\t\t}\n\t\tsuper.setAuthorizations(authorizations);\n\t}",
"public void startServer() throws Exception {\n if (!externalDatabaseHost) {\n try {\n this.port = Utils.getSystemPort(Constants.SYS_DB_PORT);\n server = Server.createTcpServer(\"-tcpPort\", String.valueOf(port), \"-tcpAllowOthers\").start();\n } catch (SQLException e) {\n if (e.toString().contains(\"java.net.UnknownHostException\")) {\n logger.error(\"Startup failure. Potential bug in OSX & Java7. Workaround: add name of local machine to '/etc/hosts.'\");\n logger.error(\"Example: 127.0.0.1 MacBook\");\n throw e;\n }\n }\n }\n }"
] |
Returns a diagonal matrix with the specified diagonal elements.
@param values values of diagonal elements
@return A diagonal matrix | [
"public static DMatrixSparseCSC diag(double... values ) {\n int N = values.length;\n return diag(new DMatrixSparseCSC(N,N,N),values,0,N);\n }"
] | [
"private void unmarshalDescriptor() throws CmsXmlException, CmsException {\n\n if (null != m_desc) {\n\n // unmarshal descriptor\n m_descContent = CmsXmlContentFactory.unmarshal(m_cms, m_cms.readFile(m_desc));\n\n // configure messages if wanted\n CmsProperty bundleProp = m_cms.readPropertyObject(m_desc, PROPERTY_BUNDLE_DESCRIPTOR_LOCALIZATION, true);\n if (!(bundleProp.isNullProperty() || bundleProp.getValue().trim().isEmpty())) {\n m_configuredBundle = bundleProp.getValue();\n }\n }\n\n }",
"private static synchronized StreamHandler getStreamHandler() {\n if (methodHandler == null) {\n methodHandler = new ConsoleHandler();\n methodHandler.setFormatter(new Formatter() {\n @Override\n public String format(LogRecord record) {\n return record.getMessage() + \"\\n\";\n }\n });\n methodHandler.setLevel(Level.FINE);\n }\n return methodHandler;\n }",
"private Renderer getPrototypeByIndex(final int prototypeIndex) {\n Renderer prototypeSelected = null;\n int i = 0;\n for (Renderer prototype : prototypes) {\n if (i == prototypeIndex) {\n prototypeSelected = prototype;\n }\n i++;\n }\n return prototypeSelected;\n }",
"public final void notifyFooterItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= footerItemCount || toPosition >= footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition\n + \" or toPosition \" + toPosition + \" is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition + headerItemCount + contentItemCount, toPosition + headerItemCount + contentItemCount);\n }",
"public B importContext(AbstractContext context, boolean overwriteDuplicates){\n for (Map.Entry<String, Object> en : context.data.entrySet()) {\n if (overwriteDuplicates) {\n this.data.put(en.getKey(), en.getValue());\n }else{\n this.data.putIfAbsent(en.getKey(), en.getValue());\n }\n }\n return (B) this;\n }",
"public ResourceAssignmentWorkgroupFields addWorkgroupAssignment() throws MPXJException\n {\n if (m_workgroup != null)\n {\n throw new MPXJException(MPXJException.MAXIMUM_RECORDS);\n }\n\n m_workgroup = new ResourceAssignmentWorkgroupFields();\n\n return (m_workgroup);\n }",
"public T withAlias(String text, String languageCode) {\n\t\twithAlias(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}",
"public List<CmsProject> getAllAccessibleProjects(CmsObject cms, String ouFqn, boolean includeSubOus)\n throws CmsException {\n\n CmsOrganizationalUnit orgUnit = readOrganizationalUnit(cms, ouFqn);\n return (m_securityManager.getAllAccessibleProjects(cms.getRequestContext(), orgUnit, includeSubOus));\n }",
"private ReferenceDescriptorDef cloneReference(ReferenceDescriptorDef refDef, String prefix)\r\n {\r\n ReferenceDescriptorDef copyRefDef = new ReferenceDescriptorDef(refDef, prefix);\r\n\r\n copyRefDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyRefDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n \r\n Properties mod = getModification(copyRefDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyRefDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included reference \"+\r\n copyRefDef.getName()+\" from class \"+refDef.getOwner().getName()); \r\n }\r\n copyRefDef.applyModifications(mod);\r\n }\r\n return copyRefDef;\r\n }"
] |
Exchange an auth token from the old Authentication API, to an OAuth access token.
Calling this method will delete the auth token used to make the request.
@param authToken
@throws FlickrException
@see "http://www.flickr.com/services/api/flickr.auth.oauth.getAccessToken.html" | [
"public OAuth1RequestToken exchangeAuthToken(String authToken) throws FlickrException {\r\n\r\n // Use TreeMap so keys are automatically sorted alphabetically\r\n Map<String, String> parameters = new TreeMap<String, String>();\r\n parameters.put(\"method\", METHOD_EXCHANGE_TOKEN);\r\n parameters.put(Flickr.API_KEY, apiKey);\r\n // This method call must be signed using Flickr (not OAuth) style signing\r\n parameters.put(\"api_sig\", getSignature(sharedSecret, parameters));\r\n\r\n Response response = transportAPI.getNonOAuth(transportAPI.getPath(), parameters);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n OAuth1RequestToken accessToken = constructToken(response);\r\n\r\n return accessToken;\r\n }"
] | [
"private PlayState1 findPlayState1() {\n PlayState1 result = PLAY_STATE_1_MAP.get(packetBytes[123]);\n if (result == null) {\n return PlayState1.UNKNOWN;\n }\n return result;\n }",
"public void bind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service);\n updateSortedServices();\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 }",
"public static void acceptsFile(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_F, OPT_FILE), \"file path for input/output\")\n .withRequiredArg()\n .describedAs(\"file-path\")\n .ofType(String.class);\n }",
"public Request option(String key, Object value) {\n this.options.put(key, value);\n return this;\n }",
"public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }",
"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 ChannelInfo getChannel(String name) {\n final URI uri = uriWithPath(\"./channels/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ChannelInfo.class);\n }",
"public Map<String, CmsJspCategoryAccessBean> getReadAllSubCategories() {\n\n if (null == m_allSubCategories) {\n m_allSubCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n @Override\n public Object transform(Object categoryPath) {\n\n try {\n List<CmsCategory> categories = CmsCategoryService.getInstance().readCategories(\n m_cms,\n (String)categoryPath,\n true,\n m_cms.getRequestContext().getUri());\n CmsJspCategoryAccessBean result = new CmsJspCategoryAccessBean(\n m_cms,\n categories,\n (String)categoryPath);\n return result;\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n\n });\n }\n return m_allSubCategories;\n }"
] |
Checks if the given group of statements contains the given value as the
value of a main snak of some statement.
@param statementGroup
the statement group to scan
@param value
the value to scan for
@return true if value was found | [
"private boolean containsValue(StatementGroup statementGroup, Value value) {\n\t\tfor (Statement s : statementGroup) {\n\t\t\tif (value.equals(s.getValue())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}"
] | [
"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 removeJobType(final Class<?> jobType) {\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n this.jobTypes.values().remove(jobType);\n }",
"public 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}",
"public long nextUniqueTransaction(long timeMs) {\n long id = timeMs;\n for (; ; ) {\n long old = transactionID.get();\n if (old >= id)\n id = old + 1;\n if (transactionID.compareAndSet(old, id))\n break;\n }\n return id;\n }",
"public static String nameFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).name() : null;\n }",
"public Client setFriendlyName(int profileId, String clientUUID, String friendlyName) throws Exception {\n // first see if this friendlyName is already in use\n Client client = this.findClientFromFriendlyName(profileId, friendlyName);\n if (client != null && !client.getUUID().equals(clientUUID)) {\n throw new Exception(\"Friendly name already in use\");\n }\n\n PreparedStatement statement = null;\n int rowsAffected = 0;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_CLIENT +\n \" SET \" + Constants.CLIENT_FRIENDLY_NAME + \" = ?\" +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = ?\" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \" = ?\"\n );\n statement.setString(1, friendlyName);\n statement.setString(2, clientUUID);\n statement.setInt(3, profileId);\n\n rowsAffected = statement.executeUpdate();\n } catch (Exception e) {\n\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (rowsAffected == 0) {\n return null;\n }\n return this.findClient(clientUUID, profileId);\n }",
"public void extractFieldTypes(DatabaseType databaseType) throws SQLException {\n\t\tif (fieldTypes == null) {\n\t\t\tif (fieldConfigs == null) {\n\t\t\t\tfieldTypes = extractFieldTypes(databaseType, dataClass, tableName);\n\t\t\t} else {\n\t\t\t\tfieldTypes = convertFieldConfigs(databaseType, tableName, fieldConfigs);\n\t\t\t}\n\t\t}\n\t}",
"public static String getOffsetCodeFromSchedule(Schedule schedule) {\r\n\r\n\t\tdouble doubleLength = 0;\r\n\t\tfor(int i = 0; i < schedule.getNumberOfPeriods(); i ++) {\r\n\t\t\tdoubleLength += schedule.getPeriodLength(i);\r\n\t\t}\r\n\t\tdoubleLength /= schedule.getNumberOfPeriods();\r\n\r\n\t\tdoubleLength *= 12;\r\n\t\tint periodLength = (int) Math.round(doubleLength);\r\n\r\n\r\n\t\tString offsetCode = periodLength + \"M\";\r\n\t\treturn offsetCode;\r\n\t}",
"@Override\r\n public V get(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 V deltaResult = deltaMap.get(key);\r\n if (deltaResult == null) {\r\n return originalMap.get(key);\r\n }\r\n if (deltaResult == nullValue) {\r\n return null;\r\n }\r\n if (deltaResult == removedValue) {\r\n return null;\r\n }\r\n return deltaResult;\r\n }"
] |
Resolves the configuration.
@param config The specified configuration.
@return The resolved configuration. | [
"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 }"
] | [
"public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url,\n String fileName, long fileSize) throws InterruptedException, IOException {\n //Create a upload session\n BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize);\n return this.uploadHelper(session, stream, fileSize);\n }",
"public static double elementSumSq( DMatrixD1 m ) {\n\n // minimize round off error\n double maxAbs = CommonOps_DDRM.elementMaxAbs(m);\n if( maxAbs == 0)\n return 0;\n\n double total = 0;\n \n int N = m.getNumElements();\n for( int i = 0; i < N; i++ ) {\n double d = m.data[i]/maxAbs;\n total += d*d;\n }\n\n return maxAbs*total*maxAbs;\n }",
"public GeoShapeMapper transform(GeoTransformation... transformations) {\n if (this.transformations == null) {\n this.transformations = Arrays.asList(transformations);\n } else {\n this.transformations.addAll(Arrays.asList(transformations));\n }\n return this;\n }",
"public final void draw() {\n AffineTransform transform = new AffineTransform(this.transform);\n transform.concatenate(getAlignmentTransform());\n\n // draw the background box\n this.graphics2d.setTransform(transform);\n this.graphics2d.setColor(this.params.getBackgroundColor());\n this.graphics2d.fillRect(0, 0, this.settings.getSize().width, this.settings.getSize().height);\n\n //draw the labels\n this.graphics2d.setColor(this.params.getFontColor());\n drawLabels(transform, this.params.getOrientation(), this.params.getLabelRotation());\n\n //sets the transformation for drawing the bar and do it\n final AffineTransform lineTransform = new AffineTransform(transform);\n setLineTranslate(lineTransform);\n\n if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT ||\n this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) {\n final AffineTransform rotate = AffineTransform.getQuadrantRotateInstance(1);\n lineTransform.concatenate(rotate);\n }\n\n this.graphics2d.setTransform(lineTransform);\n this.graphics2d.setStroke(new BasicStroke(this.settings.getLineWidth()));\n this.graphics2d.setColor(this.params.getColor());\n drawBar();\n }",
"public void setOnQueryTextListener(@NonNull final SearchView.OnQueryTextListener listener) {\n if (searchView != null) {\n searchView.setOnQueryTextListener(listener);\n } else if (supportView != null) {\n supportView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {\n @Override public boolean onQueryTextSubmit(String query) {\n return listener.onQueryTextSubmit(query);\n }\n\n @Override public boolean onQueryTextChange(String newText) {\n return listener.onQueryTextChange(newText);\n }\n });\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }",
"private void setHint() {\n if (mPhoneEdit != null && mSelectedCountry != null && mSelectedCountry.getIso() != null) {\n Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.getExampleNumberForType(mSelectedCountry.getIso(), PhoneNumberUtil.PhoneNumberType.MOBILE);\n if (phoneNumber != null) {\n mPhoneEdit.setHint(mPhoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL));\n }\n }\n }",
"public void set( T a ) {\n if( a.getType() == getType() )\n mat.set(a.getMatrix());\n else {\n setMatrix(a.mat.copy());\n }\n }",
"private void handleIncomingRequestMessage(SerialMessage incomingMessage) {\n\t\tlogger.debug(\"Message type = REQUEST\");\n\t\tswitch (incomingMessage.getMessageClass()) {\n\t\t\tcase ApplicationCommandHandler:\n\t\t\t\thandleApplicationCommandRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase SendData:\n\t\t\t\thandleSendDataRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase ApplicationUpdate:\n\t\t\t\thandleApplicationUpdateRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\tdefault:\n\t\t\tlogger.warn(String.format(\"TODO: Implement processing of Request Message = %s (0x%02X)\",\n\t\t\t\t\tincomingMessage.getMessageClass().getLabel(),\n\t\t\t\t\tincomingMessage.getMessageClass().getKey()));\n\t\t\tbreak;\t\n\t\t}\n\t}",
"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}"
] |
Extracts the service name from a Server.
@param server
@return | [
"private static QName getServiceName(Server server) {\n QName serviceName;\n String bindingId = getBindingId(server);\n EndpointInfo eInfo = server.getEndpoint().getEndpointInfo();\n \n if (JAXRS_BINDING_ID.equals(bindingId)) {\n serviceName = eInfo.getName();\n } else {\n ServiceInfo serviceInfo = eInfo.getService();\n serviceName = serviceInfo.getName();\n }\n return serviceName;\n }"
] | [
"private void writeExceptions12(Project.Calendars.Calendar calendar, List<ProjectCalendarException> exceptions)\n {\n Exceptions ce = m_factory.createProjectCalendarsCalendarExceptions();\n calendar.setExceptions(ce);\n List<Exceptions.Exception> el = ce.getException();\n\n for (ProjectCalendarException exception : exceptions)\n {\n Exceptions.Exception ex = m_factory.createProjectCalendarsCalendarExceptionsException();\n el.add(ex);\n\n ex.setName(exception.getName());\n boolean working = exception.getWorking();\n ex.setDayWorking(Boolean.valueOf(working));\n\n if (exception.getRecurring() == null)\n {\n ex.setEnteredByOccurrences(Boolean.FALSE);\n ex.setOccurrences(BigInteger.ONE);\n ex.setType(BigInteger.ONE);\n }\n else\n {\n populateRecurringException(exception, ex);\n }\n\n Project.Calendars.Calendar.Exceptions.Exception.TimePeriod period = m_factory.createProjectCalendarsCalendarExceptionsExceptionTimePeriod();\n ex.setTimePeriod(period);\n period.setFromDate(exception.getFromDate());\n period.setToDate(exception.getToDate());\n\n if (working)\n {\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimes();\n ex.setWorkingTimes(times);\n List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n for (DateRange range : exception)\n {\n Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }",
"private void populateCalendar(Record record, ProjectCalendar calendar, boolean isBaseCalendar)\n {\n if (isBaseCalendar == true)\n {\n calendar.setName(record.getString(0));\n }\n else\n {\n calendar.setParent(m_projectFile.getCalendarByName(record.getString(0)));\n }\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.getInstance(record.getInteger(1)));\n calendar.setWorkingDay(Day.MONDAY, DayType.getInstance(record.getInteger(2)));\n calendar.setWorkingDay(Day.TUESDAY, DayType.getInstance(record.getInteger(3)));\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.getInstance(record.getInteger(4)));\n calendar.setWorkingDay(Day.THURSDAY, DayType.getInstance(record.getInteger(5)));\n calendar.setWorkingDay(Day.FRIDAY, DayType.getInstance(record.getInteger(6)));\n calendar.setWorkingDay(Day.SATURDAY, DayType.getInstance(record.getInteger(7)));\n\n m_eventManager.fireCalendarReadEvent(calendar);\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 }",
"private void readResources(Project plannerProject) throws MPXJException\n {\n Resources resources = plannerProject.getResources();\n if (resources != null)\n {\n for (net.sf.mpxj.planner.schema.Resource res : resources.getResource())\n {\n readResource(res);\n }\n }\n }",
"public static linkset get(nitro_service service, String id) throws Exception{\n\t\tlinkset obj = new linkset();\n\t\tobj.set_id(id);\n\t\tlinkset response = (linkset) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void sendMessage(Message message) throws IOException {\n logger.debug(\"Sending> {}\", message);\n int totalSize = 0;\n for (Field field : message.fields) {\n totalSize += field.getBytes().remaining();\n }\n ByteBuffer combined = ByteBuffer.allocate(totalSize);\n for (Field field : message.fields) {\n logger.debug(\"..sending> {}\", field);\n combined.put(field.getBytes());\n }\n combined.flip();\n Util.writeFully(combined, channel);\n }",
"public static String objectToColumnString(Object object, String delimiter, String[] fieldNames)\r\n throws IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException\r\n {\r\n StringBuilder sb = new StringBuilder();\r\n for (int i = 0; i < fieldNames.length; i++) {\r\n if (sb.length() > 0) {\r\n sb.append(delimiter);\r\n }\r\n try {\r\n Field field = object.getClass().getDeclaredField(fieldNames[i]);\r\n sb.append(field.get(object)) ;\r\n } catch (IllegalAccessException ex) {\r\n Method method = object.getClass().getDeclaredMethod(\"get\" + StringUtils.capitalize(fieldNames[i]));\r\n sb.append(method.invoke(object));\r\n }\r\n }\r\n return sb.toString();\r\n }",
"public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}",
"public ItemRequest<User> findById(String user) {\n \n String path = String.format(\"/users/%s\", user);\n return new ItemRequest<User>(this, User.class, path, \"GET\");\n }"
] |
Ends the transition | [
"public void end() {\n if (TransitionConfig.isPrintDebug()) {\n getTransitionStateHolder().end();\n getTransitionStateHolder().print();\n }\n\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).end();\n }\n }"
] | [
"public void postProcess() {\n\t\tif (foreignColumnName != null) {\n\t\t\tforeignAutoRefresh = true;\n\t\t}\n\t\tif (foreignAutoRefresh && maxForeignAutoRefreshLevel == NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED) {\n\t\t\tmaxForeignAutoRefreshLevel = DatabaseField.DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL;\n\t\t}\n\t}",
"boolean callbackUnregistered(final TransactionalProtocolClient old, final boolean shuttingDown) {\n // Disconnect the remote connection.\n // WFCORE-196 Do this out of the sync block to avoid deadlocks where in-flight requests can't\n // be informed that the channel has closed\n protocolClient.disconnected(old);\n\n synchronized (this) {\n // If the connection dropped without us stopping the process ask for reconnection\n if (!shuttingDown && requiredState == InternalState.SERVER_STARTED) {\n final InternalState state = internalState;\n if (state == InternalState.PROCESS_STOPPED\n || state == InternalState.PROCESS_STOPPING\n || state == InternalState.STOPPED) {\n // In case it stopped we don't reconnect\n return true;\n }\n // In case we are reloading, it will reconnect automatically\n if (state == InternalState.RELOADING) {\n return true;\n }\n try {\n ROOT_LOGGER.logf(DEBUG_LEVEL, \"trying to reconnect to %s current-state (%s) required-state (%s)\", serverName, state, requiredState);\n internalSetState(new ReconnectTask(), state, InternalState.SEND_STDIN);\n } catch (Exception e) {\n ROOT_LOGGER.logf(DEBUG_LEVEL, e, \"failed to send reconnect task\");\n }\n return false;\n } else {\n return true;\n }\n }\n }",
"public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }",
"public static String getContext(final PObject[] objs) {\n StringBuilder result = new StringBuilder(\"(\");\n boolean first = true;\n for (PObject obj: objs) {\n if (!first) {\n result.append('|');\n }\n first = false;\n result.append(obj.getCurrentPath());\n }\n result.append(')');\n return result.toString();\n }",
"@SuppressWarnings(\"unchecked\")\n protected <T extends Indexable> T taskResult(String key) {\n Indexable result = this.taskGroup.taskResult(key);\n if (result == null) {\n return null;\n } else {\n T castedResult = (T) result;\n return castedResult;\n }\n }",
"protected String classOf(List<IN> lineInfos, int pos) {\r\n Datum<String, String> d = makeDatum(lineInfos, pos, featureFactory);\r\n return classifier.classOf(d);\r\n }",
"public boolean isActive(int profileId) {\n boolean active = false;\n PreparedStatement queryStatement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.CLIENT_IS_ACTIVE + \" FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= '-1' \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ? \"\n );\n queryStatement.setInt(1, profileId);\n logger.info(queryStatement.toString());\n ResultSet results = queryStatement.executeQuery();\n if (results.next()) {\n active = results.getBoolean(Constants.CLIENT_IS_ACTIVE);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return active;\n }",
"public static boolean checkConfiguredInModules() {\n\n Boolean result = m_moduleCheckCache.get();\n if (result == null) {\n result = Boolean.valueOf(getConfiguredTemplateMapping() != null);\n m_moduleCheckCache.set(result);\n }\n return result.booleanValue();\n }",
"public final void reset()\n {\n for (int i = 0; i < permutationIndices.length; i++)\n {\n permutationIndices[i] = i;\n }\n remainingPermutations = totalPermutations;\n }"
] |
Set the style for the widgets in the panel according to the chosen style option.
@param widget the widget that should be styled.
@return the styled widget. | [
"private Widget setStyle(Widget widget) {\n\n widget.setWidth(m_width);\n widget.getElement().getStyle().setDisplay(Display.INLINE_BLOCK);\n return widget;\n }"
] | [
"protected void checkConflictingRoles() {\n if (getType().isAnnotationPresent(Interceptor.class)) {\n throw BeanLogger.LOG.ejbCannotBeInterceptor(getType());\n }\n if (getType().isAnnotationPresent(Decorator.class)) {\n throw BeanLogger.LOG.ejbCannotBeDecorator(getType());\n }\n }",
"protected MethodVisitor makeDelegateCall(final String name, final String desc, final String signature, final String[] exceptions, final int accessFlags) {\n MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions);\n mv.visitVarInsn(ALOAD, 0); // load this\n mv.visitFieldInsn(GETFIELD, proxyName, DELEGATE_OBJECT_FIELD, BytecodeHelper.getTypeDescription(delegateClass)); // load delegate\n // using InvokerHelper to allow potential intercepted calls\n int size;\n mv.visitLdcInsn(name); // method name\n Type[] args = Type.getArgumentTypes(desc);\n BytecodeHelper.pushConstant(mv, args.length);\n mv.visitTypeInsn(ANEWARRAY, \"java/lang/Object\");\n size = 6;\n int idx = 1;\n for (int i = 0; i < args.length; i++) {\n Type arg = args[i];\n mv.visitInsn(DUP);\n BytecodeHelper.pushConstant(mv, i);\n // primitive types must be boxed\n if (isPrimitive(arg)) {\n mv.visitIntInsn(getLoadInsn(arg), idx);\n String wrappedType = getWrappedClassDescriptor(arg);\n mv.visitMethodInsn(INVOKESTATIC, wrappedType, \"valueOf\", \"(\" + arg.getDescriptor() + \")L\" + wrappedType + \";\", false);\n } else {\n mv.visitVarInsn(ALOAD, idx); // load argument i\n }\n size = Math.max(size, 5+registerLen(arg));\n idx += registerLen(arg);\n mv.visitInsn(AASTORE); // store value into array\n }\n mv.visitMethodInsn(INVOKESTATIC, \"org/codehaus/groovy/runtime/InvokerHelper\", \"invokeMethod\", \"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;\", false);\n unwrapResult(mv, desc);\n mv.visitMaxs(size, registerLen(args) + 1);\n\n return mv;\n }",
"public Map<String, String> getSitePath() {\n\n if (m_sitePaths == null) {\n m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object rootPath) {\n\n if (rootPath instanceof String) {\n return getRequestContext().removeSiteRoot((String)rootPath);\n }\n return null;\n }\n });\n }\n return m_sitePaths;\n }",
"private void buildTransformers_3_0(ResourceTransformationDescriptionBuilder builder) {\n /*\n ====== Resource root address: [\"subsystem\" => \"remoting\"] - Current version: 4.0.0; legacy version: 3.0.0 =======\n --- Problems for relative address to root [\"configuration\" => \"endpoint\"]:\n Different 'default' for attribute 'sasl-protocol'. Current: \"remote\"; legacy: \"remoting\" ## both are valid also for legacy servers\n --- Problems for relative address to root [\"connector\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [sasl-authentication-factory, ssl-context]\n Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory, ssl-context]\n --- Problems for relative address to root [\"http-connector\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [sasl-authentication-factory]\n Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory]\n --- Problems for relative address to root [\"remote-outbound-connection\" => \"*\"]:\n Missing attributes in current: []; missing in legacy [authentication-context]\n Different 'alternatives' for attribute 'protocol'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for attribute 'security-realm'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for attribute 'username'. Current: [\"authentication-context\"]; legacy: undefined\n Missing parameters for operation 'add' in current: []; missing in legacy [authentication-context]\n Different 'alternatives' for parameter 'protocol' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for parameter 'security-realm' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n Different 'alternatives' for parameter 'username' of operation 'add'. Current: [\"authentication-context\"]; legacy: undefined\n */\n\n builder.addChildResource(ConnectorResource.PATH).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT)\n .addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT);\n\n builder.addChildResource(RemotingEndpointResource.ENDPOINT_PATH).getAttributeBuilder()\n .setValueConverter(new AttributeConverter.DefaultAttributeConverter() {\n @Override\n protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) {\n if (!attributeValue.isDefined()) {\n attributeValue.set(\"remoting\"); //if value is not defined, set it to EAP 7.0 default valueRemotingSubsystemTransformersTestCase\n }\n }\n }, RemotingSubsystemRootResource.SASL_PROTOCOL);\n\n builder.addChildResource(HttpConnectorResource.PATH).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)\n .addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY);\n\n builder.addChildResource(RemoteOutboundConnectionResourceDefinition.ADDRESS).getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)\n .addRejectCheck(RejectAttributeChecker.DEFINED, RemoteOutboundConnectionResourceDefinition.AUTHENTICATION_CONTEXT);\n }",
"public static long wrapped(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n double valA;\n int indexCbase= 0;\n int endOfKLoop = b.numRows*b.numCols;\n\n for( int i = 0; i < a.numRows; i++ ) {\n int indexA = i*a.numCols;\n\n // need to assign dataC to a value initially\n int indexB = 0;\n int indexC = indexCbase;\n int end = indexB + b.numCols;\n\n valA = a.get(indexA++);\n\n while( indexB < end ) {\n c.set( indexC++ , valA*b.get(indexB++));\n }\n\n // now add to it\n while( indexB != endOfKLoop ) { // k loop\n indexC = indexCbase;\n end = indexB + b.numCols;\n\n valA = a.get(indexA++);\n\n while( indexB < end ) { // j loop\n c.plus( indexC++ , valA*b.get(indexB++));\n }\n }\n indexCbase += c.numCols;\n }\n\n return System.currentTimeMillis() - timeBefore;\n }",
"protected static PatchElement createRollbackElement(final PatchEntry entry) {\n final PatchElement patchElement = entry.element;\n final String patchId;\n final Patch.PatchType patchType = patchElement.getProvider().getPatchType();\n if (patchType == Patch.PatchType.CUMULATIVE) {\n patchId = entry.getCumulativePatchID();\n } else {\n patchId = patchElement.getId();\n }\n return createPatchElement(entry, patchId, entry.rollbackActions);\n }",
"@Override\n public PaxDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"private List<Row> getTable(String name)\n {\n List<Row> result = m_tables.get(name);\n if (result == null)\n {\n result = Collections.emptyList();\n }\n return result;\n }",
"private List<Point2D> merge(final List<Point2D> one, final List<Point2D> two) {\n final Set<Point2D> oneSet = new HashSet<Point2D>(one);\n for (Point2D item : two) {\n if (!oneSet.contains(item)) {\n one.add(item);\n }\n }\n return one;\n }"
] |
Format a calendar instance that is parseable from JavaScript, according to ISO-8601.
@param cal the calendar to format to a JSON string
@return a formatted date in the form of a string | [
"public static String toJson(Calendar cal) {\n if (cal == null) {\n return NULL_VALUE;\n }\n\n CharBuf buffer = CharBuf.create(26);\n writeDate(cal.getTime(), buffer);\n\n return buffer.toString();\n }"
] | [
"void endIfStarted(CodeAttribute b, ClassMethod method) {\n b.aload(getLocalVariableIndex(0));\n b.dup();\n final BranchEnd ifnotnull = b.ifnull();\n b.checkcast(Stack.class);\n b.invokevirtual(Stack.class.getName(), END_INTERCEPTOR_CONTEXT_METHOD_NAME, EMPTY_PARENTHESES + VOID_CLASS_DESCRIPTOR);\n BranchEnd ifnull = b.gotoInstruction();\n b.branchEnd(ifnotnull);\n b.pop(); // remove null Stack\n b.branchEnd(ifnull);\n }",
"public static double getDaycount(LocalDate startDate, LocalDate endDate, String convention) {\n\t\tDayCountConventionInterface daycountConvention = getDayCountConvention(convention);\n\t\treturn daycountConvention.getDaycount(startDate, endDate);\n\t}",
"public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) {\r\n String[] coVariables = action.getCoVariables().split(\",\");\r\n int n = Integer.valueOf(action.getN());\n\r\n List<Map<String, String>> newPossibleStateList = new ArrayList<>();\n\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n Map<String, String[]> variableDomains = new HashMap<>();\r\n Map<String, String> defaultVariableValues = new HashMap<>();\r\n for (String variable : coVariables) {\r\n String variableMetaInfo = possibleState.get(variable);\r\n String[] variableDomain = variableMetaInfo.split(\",\");\r\n variableDomains.put(variable, variableDomain);\r\n defaultVariableValues.put(variable, variableDomain[0]);\r\n }\n\r\n List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains);\r\n for (Map<String, String> nWiseCombination : nWiseCombinations) {\r\n Map<String, String> newPossibleState = new HashMap<>(possibleState);\r\n newPossibleState.putAll(defaultVariableValues);\r\n newPossibleState.putAll(nWiseCombination);\r\n newPossibleStateList.add(newPossibleState);\r\n }\r\n }\n\r\n return newPossibleStateList;\r\n }",
"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 void animate(float timeInSec)\n {\n GVRSkeleton skel = getSkeleton();\n GVRPose pose = skel.getPose();\n computePose(timeInSec,pose);\n skel.poseToBones();\n skel.updateBonePose();\n skel.updateSkinPose();\n }",
"public static boolean isBeanProxyable(Bean<?> bean, BeanManagerImpl manager) {\n if (bean instanceof RIBean<?>) {\n return ((RIBean<?>) bean).isProxyable();\n } else {\n return Proxies.isTypesProxyable(bean.getTypes(), manager.getServices());\n }\n }",
"public static Thumbor create(String host, String key) {\n if (key == null || key.length() == 0) {\n throw new IllegalArgumentException(\"Key must not be blank.\");\n }\n return new Thumbor(host, key);\n }",
"private void readResources(Storepoint phoenixProject)\n {\n Resources resources = phoenixProject.getResources();\n if (resources != null)\n {\n for (net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res : resources.getResource())\n {\n Resource resource = readResource(res);\n readAssignments(resource, res);\n }\n }\n }",
"private List<Variable> parseAssignRange(Sequence sequence, TokenList tokens, TokenList.Token t0) {\n // find assignment symbol\n TokenList.Token tokenAssign = t0.next;\n while( tokenAssign != null && tokenAssign.symbol != Symbol.ASSIGN ) {\n tokenAssign = tokenAssign.next;\n }\n\n if( tokenAssign == null )\n throw new ParseError(\"Can't find assignment operator\");\n\n // see if it is a sub matrix before\n if( tokenAssign.previous.symbol == Symbol.PAREN_RIGHT ) {\n TokenList.Token start = t0.next;\n if( start.symbol != Symbol.PAREN_LEFT )\n throw new ParseError((\"Expected left param for assignment\"));\n TokenList.Token end = tokenAssign.previous;\n TokenList subTokens = tokens.extractSubList(start,end);\n subTokens.remove(subTokens.getFirst());\n subTokens.remove(subTokens.getLast());\n\n handleParentheses(subTokens,sequence);\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(subTokens, sequence);\n\n if (inputs.isEmpty())\n throw new ParseError(\"Empty function input parameters\");\n\n List<Variable> range = new ArrayList<>();\n addSubMatrixVariables(inputs, range);\n if( range.size() != 1 && range.size() != 2 ) {\n throw new ParseError(\"Unexpected number of range variables. 1 or 2 expected\");\n }\n return range;\n }\n\n return null;\n }"
] |
Select the default currency properties from the database.
@param currencyID default currency ID | [
"private void processDefaultCurrency(Integer currencyID) throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"currtype where curr_id=?\", currencyID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_reader.processDefaultCurrency(row);\n }\n }"
] | [
"private ArrayList<RunListener> instantiateRunListeners() throws Exception {\n ArrayList<RunListener> instances = new ArrayList<>();\n\n if (runListeners != null) {\n for (String className : Arrays.asList(runListeners.split(\",\"))) {\n instances.add((RunListener) this.instantiate(className).newInstance());\n }\n }\n\n return instances;\n }",
"@Override\n public AccountingDate date(int prolepticYear, int month, int dayOfMonth) {\n return AccountingDate.of(this, prolepticYear, month, dayOfMonth);\n }",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl,\n boolean followRedirects) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setInstanceFollowRedirects(followRedirects);\n \n InputStream is = conn.getInputStream();\n if (\"gzip\".equals(conn.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>(conn.getHeaderFields());\n headers.put(\"X-Content\", Arrays.asList(MyStreamUtils.readContent(is)));\n headers.put(\"X-URL\", Arrays.asList(conn.getURL().toString()));\n headers.put(\"X-Status\", Arrays.asList(String.valueOf(conn.getResponseCode())));\n \n return headers;\n }",
"private void computeUnnamedParams() {\n unnamedParams.addAll(rawArgs.stream().filter(arg -> !isNamedParam(arg)).collect(Collectors.toList()));\n }",
"private void writeAssignmentTimephasedData(ResourceAssignment mpx, Project.Assignments.Assignment xml)\n {\n if (m_writeTimphasedData && mpx.getHasTimephasedData())\n {\n List<TimephasedDataType> list = xml.getTimephasedData();\n ProjectCalendar calendar = mpx.getCalendar();\n BigInteger assignmentID = xml.getUID();\n\n List<TimephasedWork> complete = mpx.getTimephasedActualWork();\n List<TimephasedWork> planned = mpx.getTimephasedWork();\n\n if (m_splitTimephasedAsDays)\n {\n TimephasedWork lastComplete = null;\n if (complete != null && !complete.isEmpty())\n {\n lastComplete = complete.get(complete.size() - 1);\n }\n\n TimephasedWork firstPlanned = null;\n if (planned != null && !planned.isEmpty())\n {\n firstPlanned = planned.get(0);\n }\n\n if (planned != null)\n {\n planned = splitDays(calendar, mpx.getTimephasedWork(), null, lastComplete);\n }\n\n if (complete != null)\n {\n complete = splitDays(calendar, complete, firstPlanned, null);\n }\n }\n\n if (planned != null)\n {\n writeAssignmentTimephasedData(assignmentID, list, planned, 1);\n }\n\n if (complete != null)\n {\n writeAssignmentTimephasedData(assignmentID, list, complete, 2);\n }\n }\n }",
"private void handleGlobalArguments(Section section) {\n\t\tfor (String key : section.keySet()) {\n\t\t\tswitch (key) {\n\t\t\tcase OPTION_OFFLINE_MODE:\n\t\t\t\tif (section.get(key).toLowerCase().equals(\"true\")) {\n\t\t\t\t\tthis.offlineMode = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OPTION_QUIET:\n\t\t\t\tif (section.get(key).toLowerCase().equals(\"true\")) {\n\t\t\t\t\tthis.quiet = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OPTION_CREATE_REPORT:\n\t\t\t\tthis.reportFilename = section.get(key);\n\t\t\t\tbreak;\n\t\t\tcase OPTION_DUMP_LOCATION:\n\t\t\t\tthis.dumpDirectoryLocation = section.get(key);\n\t\t\t\tbreak;\n\t\t\tcase OPTION_FILTER_LANGUAGES:\n\t\t\t\tsetLanguageFilters(section.get(key));\n\t\t\t\tbreak;\n\t\t\tcase OPTION_FILTER_SITES:\n\t\t\t\tsetSiteFilters(section.get(key));\n\t\t\t\tbreak;\n\t\t\tcase OPTION_FILTER_PROPERTIES:\n\t\t\t\tsetPropertyFilters(section.get(key));\n\t\t\t\tbreak;\n\t\t\tcase OPTION_LOCAL_DUMPFILE:\n\t\t\t\tthis.inputDumpLocation = section.get(key);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\"Unrecognized option: \" + key);\n\t\t\t}\n\t\t}\n\t}",
"public void init( DMatrixRMaj A ) {\n if( A.numRows != A.numCols)\n throw new IllegalArgumentException(\"Must be square\");\n\n if( A.numCols != N ) {\n N = A.numCols;\n QT.reshape(N,N, false);\n\n if( w.length < N ) {\n w = new double[ N ];\n gammas = new double[N];\n b = new double[N];\n }\n }\n\n // just copy the top right triangle\n QT.set(A);\n }",
"public String getRandomHoliday(String earliest, String latest) {\n String dateString = \"\";\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime earlyDate = parser.parseDateTime(earliest);\n DateTime lateDate = parser.parseDateTime(latest);\n List<Holiday> holidays = new LinkedList<>();\n\n int min = Integer.parseInt(earlyDate.toString().substring(0, 4));\n int max = Integer.parseInt(lateDate.toString().substring(0, 4));\n int range = max - min + 1;\n int randomYear = (int) (Math.random() * range) + min;\n\n for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) {\n holidays.add(s);\n }\n Collections.shuffle(holidays);\n\n for (Holiday holiday : holidays) {\n dateString = convertToReadableDate(holiday.forYear(randomYear));\n if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) {\n break;\n }\n }\n return dateString;\n }",
"public void processTasks(List<Row> bars, List<Row> expandedTasks, List<Row> tasks, List<Row> milestones)\n {\n List<Row> parentBars = buildRowHierarchy(bars, expandedTasks, tasks, milestones);\n createTasks(m_project, \"\", parentBars);\n deriveProjectCalendar();\n updateStructure();\n }"
] |
Checks each available roll strategy in turn, starting at the per-minute
strategy, next per-hour, and so on for increasing units of time until a
match is found. If no match is found, the error strategy is returned.
@param properties
@return The appropriate roll strategy. | [
"static final TimeBasedRollStrategy findRollStrategy(\n final AppenderRollingProperties properties) {\n if (properties.getDatePattern() == null) {\n LogLog.error(\"null date pattern\");\n return ROLL_ERROR;\n }\n // Strip out quoted sections so that we may safely scan the undecorated\n // pattern for characters that are meaningful to SimpleDateFormat.\n final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(\n properties.getDatePatternLocale());\n final String undecoratedDatePattern = localizedDateFormatPatternHelper\n .excludeQuoted(properties.getDatePattern());\n if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MINUTE;\n }\n if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HOUR;\n }\n if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HALF_DAY;\n }\n if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_DAY;\n }\n if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_WEEK;\n }\n if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MONTH;\n }\n return ROLL_ERROR;\n }"
] | [
"protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n queue.add(event);\n }",
"@UiHandler(\"m_wholeDayCheckBox\")\n void onWholeDayChange(ValueChangeEvent<Boolean> event) {\n\n //TODO: Improve - adjust time selections?\n if (handleChange()) {\n m_controller.setWholeDay(event.getValue());\n }\n }",
"List getGroupby()\r\n {\r\n List result = _getGroupby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getGroupby());\r\n }\r\n }\r\n\r\n return result;\r\n }",
"public static void archiveFile(@NotNull final ArchiveOutputStream out,\n @NotNull final VirtualFileDescriptor source,\n final long fileSize) throws IOException {\n if (!source.hasContent()) {\n throw new IllegalArgumentException(\"Provided source is not a file: \" + source.getPath());\n }\n //noinspection ChainOfInstanceofChecks\n if (out instanceof TarArchiveOutputStream) {\n final TarArchiveEntry entry = new TarArchiveEntry(source.getPath() + source.getName());\n entry.setSize(fileSize);\n entry.setModTime(source.getTimeStamp());\n out.putArchiveEntry(entry);\n } else if (out instanceof ZipArchiveOutputStream) {\n final ZipArchiveEntry entry = new ZipArchiveEntry(source.getPath() + source.getName());\n entry.setSize(fileSize);\n entry.setTime(source.getTimeStamp());\n out.putArchiveEntry(entry);\n } else {\n throw new IOException(\"Unknown archive output stream\");\n }\n final InputStream input = source.getInputStream();\n try {\n IOUtil.copyStreams(input, fileSize, out, IOUtil.BUFFER_ALLOCATOR);\n } finally {\n if (source.shouldCloseStream()) {\n input.close();\n }\n }\n out.closeArchiveEntry();\n }",
"protected String escapeApostrophes(String text) {\r\n\t\tString resultString;\r\n\t\tif (text.contains(\"'\")) {\r\n\t\t\tStringBuilder stringBuilder = new StringBuilder();\r\n\t\t\tstringBuilder.append(\"concat('\");\r\n\t\t\tstringBuilder.append(text.replace(\"'\", \"',\\\"'\\\",'\"));\r\n\t\t\tstringBuilder.append(\"')\");\r\n\t\t\tresultString = stringBuilder.toString();\r\n\t\t} else {\r\n\t\t\tresultString = \"'\" + text + \"'\";\r\n\t\t}\r\n\t\treturn resultString;\r\n\t}",
"protected boolean appendWhereStatement(StringBuilder sb, List<ArgumentHolder> argList, WhereOperation operation)\n\t\t\tthrows SQLException {\n\t\tif (where == null) {\n\t\t\treturn operation == WhereOperation.FIRST;\n\t\t}\n\t\toperation.appendBefore(sb);\n\t\twhere.appendSql((addTableName ? getTableName() : null), sb, argList);\n\t\toperation.appendAfter(sb);\n\t\treturn false;\n\t}",
"public static RowColumn toRowColumn(Key key) {\n if (key == null) {\n return RowColumn.EMPTY;\n }\n if ((key.getRow() == null) || key.getRow().getLength() == 0) {\n return RowColumn.EMPTY;\n }\n Bytes row = ByteUtil.toBytes(key.getRow());\n if ((key.getColumnFamily() == null) || key.getColumnFamily().getLength() == 0) {\n return new RowColumn(row);\n }\n Bytes cf = ByteUtil.toBytes(key.getColumnFamily());\n if ((key.getColumnQualifier() == null) || key.getColumnQualifier().getLength() == 0) {\n return new RowColumn(row, new Column(cf));\n }\n Bytes cq = ByteUtil.toBytes(key.getColumnQualifier());\n if ((key.getColumnVisibility() == null) || key.getColumnVisibility().getLength() == 0) {\n return new RowColumn(row, new Column(cf, cq));\n }\n Bytes cv = ByteUtil.toBytes(key.getColumnVisibility());\n return new RowColumn(row, new Column(cf, cq, cv));\n }",
"@Override\n public final Double optDouble(final String key, final Double defaultValue) {\n Double result = optDouble(key);\n return result == null ? defaultValue : result;\n }",
"protected ZipEntry getZipEntry(String filename) throws ZipException {\n\n // yes\n ZipEntry entry = getZipFile().getEntry(filename);\n // path to file might be relative, too\n if ((entry == null) && filename.startsWith(\"/\")) {\n entry = m_zipFile.getEntry(filename.substring(1));\n }\n if (entry == null) {\n throw new ZipException(\n Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_FILE_NOT_FOUND_IN_ZIP_1, filename));\n }\n return entry;\n }"
] |
Sets an Integer attribute.
@param key the key, non null.
@param value the value
@return the Builder, for chaining. | [
"public B set(String key, int value) {\n this.data.put(key, value);\n return (B) this;\n }"
] | [
"public static String[] tokenizeUnquoted(String s) {\r\n List tokens = new LinkedList();\r\n int first = 0;\r\n while (first < s.length()) {\r\n first = skipWhitespace(s, first);\r\n int last = scanToken(s, first);\r\n if (first < last) {\r\n tokens.add(s.substring(first, last));\r\n }\r\n first = last;\r\n }\r\n return (String[])tokens.toArray(new String[tokens.size()]);\r\n }",
"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 }",
"void addSomeValuesRestriction(Resource subject, String propertyUri,\n\t\t\tString rangeUri) {\n\t\tthis.someValuesQueue.add(new PropertyRestriction(subject, propertyUri,\n\t\t\t\trangeUri));\n\t}",
"public T copy() {\n T ret = createLike();\n ret.getMatrix().set(this.getMatrix());\n return ret;\n }",
"public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }",
"public ParallelTaskBuilder setSshPassword(String password) {\n this.sshMeta.setPassword(password);\n this.sshMeta.setSshLoginType(SshLoginType.PASSWORD);\n return this;\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 final void setHost(final String host) throws UnknownHostException {\n this.host = host;\n final InetAddress[] inetAddresses = InetAddress.getAllByName(host);\n\n for (InetAddress address: inetAddresses) {\n final AddressHostMatcher matcher = new AddressHostMatcher();\n matcher.setIp(address.getHostAddress());\n this.matchersForHost.add(matcher);\n }\n }",
"public static <T> Set<T> toSet(Iterator<? extends T> iterator) {\n\t\treturn Sets.newLinkedHashSet(toIterable(iterator));\n\t}"
] |
Retrieves the cost rate table entry active on a given date.
@param date target date
@return cost rate table entry | [
"private CostRateTableEntry getCostRateTableEntry(Date date)\n {\n CostRateTableEntry result;\n\n CostRateTable table = getCostRateTable();\n if (table == null)\n {\n Resource resource = getResource();\n result = new CostRateTableEntry(resource.getStandardRate(), TimeUnit.HOURS, resource.getOvertimeRate(), TimeUnit.HOURS, resource.getCostPerUse(), null);\n }\n else\n {\n if (table.size() == 1)\n {\n result = table.get(0);\n }\n else\n {\n result = table.getEntryByDate(date);\n }\n }\n\n return result;\n }"
] | [
"public void rollback()\r\n {\r\n try\r\n {\r\n Iterator iter = mvOrderOfIds.iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n if(log.isDebugEnabled())\r\n log.debug(\"rollback: \" + mod);\r\n // if the Object has been modified by transaction, mark object as dirty\r\n if(mod.hasChanged(transaction.getBroker()))\r\n {\r\n mod.setModificationState(mod.getModificationState().markDirty());\r\n }\r\n mod.getModificationState().rollback(mod);\r\n }\r\n }\r\n finally\r\n {\r\n needsCommit = false;\r\n }\r\n afterWriteCleanup();\r\n }",
"public boolean hasNodeWithId(int nodeId) {\n Node node = nodesById.get(nodeId);\n if(node == null) {\n return false;\n }\n return true;\n }",
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n private void cleanupSessions(List<String> storeNamesToCleanUp) {\n\n logger.info(\"Performing cleanup\");\n for(String store: storeNamesToCleanUp) {\n\n for(Node node: nodesToStream) {\n try {\n SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store,\n node.getId()));\n close(sands.getSocket());\n SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,\n node.getId()));\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n }\n\n }\n\n cleanedUp = true;\n\n }",
"public static CmsShell getTopShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.isEmpty()) {\n return null;\n }\n return shells.get(shells.size() - 1);\n\n }",
"@SuppressWarnings(\"unchecked\")\r\n public static boolean addPropertyDefault(PropertiesImpl props, PropertyDefinition<?> propDef) {\r\n\r\n if ((props == null) || (props.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Props must not be null!\");\r\n }\r\n\r\n if (propDef == null) {\r\n return false;\r\n }\r\n\r\n List<?> defaultValue = propDef.getDefaultValue();\r\n if ((defaultValue != null) && (!defaultValue.isEmpty())) {\r\n switch (propDef.getPropertyType()) {\r\n case BOOLEAN:\r\n props.addProperty(new PropertyBooleanImpl(propDef.getId(), (List<Boolean>)defaultValue));\r\n break;\r\n case DATETIME:\r\n props.addProperty(new PropertyDateTimeImpl(propDef.getId(), (List<GregorianCalendar>)defaultValue));\r\n break;\r\n case DECIMAL:\r\n props.addProperty(new PropertyDecimalImpl(propDef.getId(), (List<BigDecimal>)defaultValue));\r\n break;\r\n case HTML:\r\n props.addProperty(new PropertyHtmlImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case ID:\r\n props.addProperty(new PropertyIdImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case INTEGER:\r\n props.addProperty(new PropertyIntegerImpl(propDef.getId(), (List<BigInteger>)defaultValue));\r\n break;\r\n case STRING:\r\n props.addProperty(new PropertyStringImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case URI:\r\n props.addProperty(new PropertyUriImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n default:\r\n throw new RuntimeException(\"Unknown datatype! Spec change?\");\r\n }\r\n\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"public static final Date parseFinishDateTime(String value)\n {\n Date result = parseDateTime(value);\n if (result != null)\n {\n result = DateHelper.addDays(result, -1);\n }\n return result;\n }",
"public static void addStory(File caseManager, String storyName,\n String testPath, String user, String feature, String benefit) throws BeastException {\n FileWriter caseManagerWriter;\n\n String storyClass = SystemReader.createClassName(storyName);\n try {\n BufferedReader reader = new BufferedReader(new FileReader(\n caseManager));\n String targetLine1 = \" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\";\n String targetLine2 = \" Result result = JUnitCore.runClasses(\" + testPath + \".\"\n + storyClass + \".class);\";\n String in;\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine1)) {\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine2)) {\n reader.close();\n // This test is already written in the case manager.\n return;\n }\n }\n reader.close();\n throw new BeastException(\"Two different stories with the same name (same method name) are being created in the same CaseManager file. That is not possible. Please, change the name of the story: \" + testPath + \".\"\n + storyClass + \".java\");\n }\n }\n reader.close();\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\" /**\\n\");\n caseManagerWriter.write(\" * This is the story: \" + storyName\n + \"\\n\");\n caseManagerWriter.write(\" * requested by: \" + user + \"\\n\");\n caseManagerWriter.write(\" * providing the feature: \" + feature\n + \"\\n\");\n caseManagerWriter.write(\" * so the user gets the benefit: \"\n + benefit + \"\\n\");\n caseManagerWriter.write(\" */\\n\");\n caseManagerWriter.write(\" @Test\\n\");\n caseManagerWriter.write(\" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\\n\");\n caseManagerWriter.write(\" Result result = JUnitCore.runClasses(\" + testPath\n + \".\" + storyClass + \".class);\\n\");\n caseManagerWriter.write(\" Assert.assertTrue(result.wasSuccessful());\\n\");\n caseManagerWriter.write(\" }\\n\");\n caseManagerWriter.write(\"\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger.getLogger(\"CreateMASCaseManager.createTest\");\n logger.info(\"ERROR writing the file\");\n }\n\n }",
"private void addApiDocRoots(String packageListUrl) {\n\tBufferedReader br = null;\n\tpackageListUrl = fixApiDocRoot(packageListUrl);\n\ttry {\n\t URL url = new URL(packageListUrl + \"/package-list\");\n\t br = new BufferedReader(new InputStreamReader(url.openStream()));\n\t String line;\n\t while((line = br.readLine()) != null) {\n\t\tline = line + \".\";\n\t\tPattern pattern = Pattern.compile(line.replace(\".\", \"\\\\.\") + \"[^\\\\.]*\");\n\t\tapiDocMap.put(pattern, packageListUrl);\n\t }\n\t} catch(IOException e) {\n\t System.err.println(\"Errors happened while accessing the package-list file at \"\n\t\t + packageListUrl);\n\t} finally {\n\t if(br != null)\n\t\ttry {\n\t\t br.close();\n\t\t} catch (IOException e) {}\n\t}\n\t\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 }"
] |
Extract a Class from the given Type. | [
"private static Class<?> extractClass(Class<?> ownerClass, Type arg) {\n\t\tif (arg instanceof ParameterizedType) {\n\t\t\treturn extractClass(ownerClass, ((ParameterizedType) arg).getRawType());\n\t\t}\n\t\telse if (arg instanceof GenericArrayType) {\n\t\t\tGenericArrayType gat = (GenericArrayType) arg;\n\t\t\tType gt = gat.getGenericComponentType();\n\t\t\tClass<?> componentClass = extractClass(ownerClass, gt);\n\t\t\treturn Array.newInstance(componentClass, 0).getClass();\n\t\t}\n\t\telse if (arg instanceof TypeVariable) {\n\t\t\tTypeVariable tv = (TypeVariable) arg;\n\t\t\targ = getTypeVariableMap(ownerClass).get(tv);\n\t\t\tif (arg == null) {\n\t\t\t\targ = extractBoundForTypeVariable(tv);\n\t\t\t\tif (arg instanceof ParameterizedType) {\n\t\t\t\t\treturn extractClass(ownerClass, ((ParameterizedType) arg).getRawType());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn extractClass(ownerClass, arg);\n\t\t\t}\n\t\t}\n\t\treturn (arg instanceof Class ? (Class) arg : Object.class);\n\t}"
] | [
"@RequestMapping(value = \"/api/scripts\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getScripts(Model model,\n @RequestParam(required = false) Integer type) throws Exception {\n Script[] scripts = ScriptService.getInstance().getScripts(type);\n return Utils.getJQGridJSON(scripts, \"scripts\");\n }",
"private final boolean matchPattern(byte[][] patterns, int bufferIndex)\n {\n boolean match = false;\n for (byte[] pattern : patterns)\n {\n int index = 0;\n match = true;\n for (byte b : pattern)\n {\n if (b != m_buffer[bufferIndex + index])\n {\n match = false;\n break;\n }\n ++index;\n }\n if (match)\n {\n break;\n }\n }\n return match;\n }",
"public static Properties loadProperties(String[] filesToLoad)\n {\n Properties p = new Properties();\n InputStream fis = null;\n for (String path : filesToLoad)\n {\n try\n {\n fis = Db.class.getClassLoader().getResourceAsStream(path);\n if (fis != null)\n {\n p.load(fis);\n jqmlogger.info(\"A jqm.properties file was found at {}\", path);\n }\n }\n catch (IOException e)\n {\n // We allow no configuration files, but not an unreadable configuration file.\n throw new DatabaseException(\"META-INF/jqm.properties file is invalid\", e);\n }\n finally\n {\n closeQuietly(fis);\n }\n }\n\n // Overload the datasource name from environment variable if any (tests only).\n String dbName = System.getenv(\"DB\");\n if (dbName != null)\n {\n p.put(\"com.enioka.jqm.jdbc.datasource\", \"jdbc/\" + dbName);\n }\n\n // Done\n return p;\n }",
"public List<ModelNode> getAllowedValues() {\n if (allowedValues == null) {\n return Collections.emptyList();\n }\n return Arrays.asList(this.allowedValues);\n }",
"public void setBaselineStartText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_STARTS, baselineNumber), value);\n }",
"@SuppressWarnings(\"unchecked\")\n private void addPrivateFieldsAccessors(ClassNode node) {\n Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);\n if (accessedFields==null) return;\n Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS);\n if (privateConstantAccessors!=null) {\n // already added\n return;\n }\n int acc = -1;\n privateConstantAccessors = new HashMap<String, MethodNode>();\n final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC;\n for (FieldNode fieldNode : node.getFields()) {\n if (accessedFields.contains(fieldNode)) {\n\n acc++;\n Parameter param = new Parameter(node.getPlainNodeReference(), \"$that\");\n Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param);\n Statement stmt = new ExpressionStatement(new PropertyExpression(\n receiver,\n fieldNode.getName()\n ));\n MethodNode accessor = node.addMethod(\"pfaccess$\"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt);\n privateConstantAccessors.put(fieldNode.getName(), accessor);\n }\n }\n node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors);\n }",
"private int countCharsStart(final char ch, final boolean allowSpaces)\n {\n int count = 0;\n for (int i = 0; i < this.value.length(); i++)\n {\n final char c = this.value.charAt(i);\n if (c == ' ' && allowSpaces)\n {\n continue;\n }\n if (c == ch)\n {\n count++;\n }\n else\n {\n break;\n }\n }\n return count;\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 }",
"private boolean isZonesSatisfied() {\n boolean zonesSatisfied = false;\n if(pipelineData.getZonesRequired() == null) {\n zonesSatisfied = true;\n } else {\n int numZonesSatisfied = pipelineData.getZoneResponses().size();\n if(numZonesSatisfied >= (pipelineData.getZonesRequired() + 1)) {\n zonesSatisfied = true;\n }\n }\n return zonesSatisfied;\n }"
] |
Creates a new Table instance from data extracted from an MPP file.
@param file parent project file
@param data fixed data
@param varMeta var meta
@param varData var data
@return Table instance | [
"public Table createTable(ProjectFile file, byte[] data, VarMeta varMeta, Var2Data varData)\n {\n Table table = new Table();\n\n table.setID(MPPUtility.getInt(data, 0));\n table.setResourceFlag(MPPUtility.getShort(data, 108) == 1);\n table.setName(MPPUtility.removeAmpersands(MPPUtility.getUnicodeString(data, 4)));\n\n byte[] columnData = null;\n Integer tableID = Integer.valueOf(table.getID());\n if (m_tableColumnDataBaseline != null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataBaseline));\n }\n\n if (columnData == null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataEnterprise));\n if (columnData == null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataStandard));\n }\n }\n\n processColumnData(file, table, columnData);\n\n //System.out.println(table);\n\n return (table);\n }"
] | [
"public int bindShader(GVRContext context, GVRShaderData material, String vertexDesc)\n {\n String signature = getClass().getSimpleName();\n GVRShaderManager shaderManager = context.getShaderManager();\n\n synchronized (shaderManager)\n {\n int nativeShader = shaderManager.getShader(signature);\n if (nativeShader == 0)\n {\n nativeShader = addShader(shaderManager, signature, material);\n }\n return nativeShader;\n }\n }",
"public final PJsonObject getJSONObject(final int i) {\n JSONObject val = this.array.optJSONObject(i);\n final String context = \"[\" + i + \"]\";\n if (val == null) {\n throw new ObjectMissingException(this, context);\n }\n return new PJsonObject(this, val, context);\n }",
"public static AdminClient getAdminClient(String url) {\n ClientConfig config = new ClientConfig().setBootstrapUrls(url)\n .setConnectionTimeout(5, TimeUnit.SECONDS);\n\n AdminClientConfig adminConfig = new AdminClientConfig().setAdminSocketTimeoutSec(5);\n return new AdminClient(adminConfig, config);\n }",
"public void setEnterpriseCost(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_COST, index), value);\n }",
"public static base_response delete(nitro_service client, String sitename) throws Exception {\n\t\tgslbsite deleteresource = new gslbsite();\n\t\tdeleteresource.sitename = sitename;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private static JsonParser newJsonParserForNode(JsonNode jsonNode) throws IOException {\n JsonParser parser = new JsonFactory().createParser(jsonNode.toString());\n parser.nextToken();\n return parser;\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 postConstruct() throws URISyntaxException {\n WmsVersion.lookup(this.version);\n Assert.isTrue(validateBaseUrl(), \"invalid baseURL\");\n\n Assert.isTrue(this.layers.length > 0, \"There must be at least one layer defined for a WMS request\" +\n \" to make sense\");\n\n // OpenLayers 2 compatibility. It will post a single empty style no matter how many layers there are\n\n if (this.styles != null && this.styles.length != this.layers.length && this.styles.length == 1 &&\n this.styles[0].trim().isEmpty()) {\n this.styles = null;\n } else {\n Assert.isTrue(this.styles == null || this.layers.length == this.styles.length,\n String.format(\n \"If styles are defined then there must be one for each layer. Number of\" +\n \" layers: %s\\nStyles: %s\", this.layers.length,\n Arrays.toString(this.styles)));\n }\n\n if (this.imageFormat.indexOf('/') < 0) {\n LOGGER.warn(\"The format {} should be a mime type\", this.imageFormat);\n this.imageFormat = \"image/\" + this.imageFormat;\n }\n\n Assert.isTrue(this.method == HttpMethod.GET || this.method == HttpMethod.POST,\n String.format(\"Unsupported method %s for WMS layer\", this.method.toString()));\n }",
"public GroovyFieldDoc[] fields() {\n Collections.sort(fields);\n return fields.toArray(new GroovyFieldDoc[fields.size()]);\n }"
] |
This method reads a six byte long from the input array.
@param data the input array
@param offset offset of integer data in the array
@return integer value | [
"public static final long getLong6(byte[] data, int offset)\n {\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 48; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }"
] | [
"public Query getPKQuery(Identity oid)\r\n {\r\n Object[] values = oid.getPrimaryKeyValues();\r\n ClassDescriptor cld = pb.getClassDescriptor(oid.getObjectsTopLevelClass());\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n Criteria criteria = new Criteria();\r\n\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fld = fields[i];\r\n criteria.addEqualTo(fld.getAttributeName(), values[i]);\r\n }\r\n return QueryFactory.newQuery(cld.getClassOfObject(), criteria);\r\n }",
"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 }",
"@Override\n public DMatrixRMaj getV(DMatrixRMaj V , boolean transpose , boolean compact ) {\n V = handleV(V, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(V);\n\n// UBV.print();\n\n // todo the very first multiplication can be avoided by setting to the rank1update output\n for( int j = min-1; j >= 0; j-- ) {\n u[j+1] = 1;\n for( int i = j+2; i < n; i++ ) {\n u[i] = UBV.get(j,i);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(V, u, gammasV[j], j + 1, j + 1, n);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(V, u, gammasV[j], j + 1, j + 1, n, this.b);\n }\n\n return V;\n }",
"private List<Event> filterEvents(List<Event> events) {\n List<Event> filteredEvents = new ArrayList<Event>();\n for (Event event : events) {\n if (!filter(event)) {\n filteredEvents.add(event);\n }\n }\n return filteredEvents;\n }",
"@Override\n\tpublic String toNormalizedWildcardString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.normalizedWildcardString) == null) {\n\t\t\tif(hasZone()) {\n\t\t\t\tstringCache.normalizedWildcardString = result = toNormalizedString(IPv6StringCache.wildcardNormalizedParams);\n\t\t\t} else {\n\t\t\t\tresult = getSection().toNormalizedWildcardString();//the cache is shared so no need to update it here\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"public static <K,V> MultiValueMap<K,V> unmodifiableMultiValueMap(MultiValueMap<? extends K, ? extends V> map) {\n\t\tAssert.notNull(map, \"'map' must not be null\");\n\t\tMap<K, List<V>> result = new LinkedHashMap<K, List<V>>(map.size());\n\t\tfor (Map.Entry<? extends K, ? extends List<? extends V>> entry : map.entrySet()) {\n\t\t\tList<V> values = Collections.unmodifiableList(entry.getValue());\n\t\t\tresult.put(entry.getKey(), values);\n\t\t}\n\t\tMap<K, List<V>> unmodifiableMap = Collections.unmodifiableMap(result);\n\t\treturn toMultiValueMap(unmodifiableMap);\n\t}",
"private static void invokeSetter(final Object bean, final Method setMethod, final Object fieldValue) {\n\t\ttry {\n\t\t\tsetMethod.setAccessible(true);\n\t\t\tsetMethod.invoke(bean, fieldValue);\n\t\t}\n\t\tcatch(final Exception e) {\n\t\t\tthrow new SuperCsvReflectionException(String.format(\"error invoking method %s()\", setMethod.getName()), e);\n\t\t}\n\t}",
"public byte[] getResource(String pluginName, String fileName) throws Exception {\n // TODO: This is going to be slow.. future improvement is to cache the data instead of searching all jars\n for (String jarFilename : jarInformation) {\n JarFile jarFile = new JarFile(new File(jarFilename));\n Enumeration<?> enumer = jarFile.entries();\n\n // Use the Plugin-Name manifest entry to match with the provided pluginName\n String jarPluginName = jarFile.getManifest().getMainAttributes().getValue(\"Plugin-Name\");\n\n if (!jarPluginName.equals(pluginName)) {\n continue;\n }\n\n while (enumer.hasMoreElements()) {\n Object element = enumer.nextElement();\n String elementName = element.toString();\n\n // Skip items in the jar that don't start with \"resources/\"\n if (!elementName.startsWith(\"resources/\")) {\n continue;\n }\n\n elementName = elementName.replace(\"resources/\", \"\");\n if (elementName.equals(fileName)) {\n // get the file from the jar\n ZipEntry ze = jarFile.getEntry(element.toString());\n\n InputStream fileStream = jarFile.getInputStream(ze);\n byte[] data = new byte[(int) ze.getSize()];\n DataInputStream dataIs = new DataInputStream(fileStream);\n dataIs.readFully(data);\n dataIs.close();\n return data;\n }\n }\n }\n throw new FileNotFoundException(\"Could not find resource\");\n }",
"public static boolean isAscii(Slice utf8)\n {\n int length = utf8.length();\n int offset = 0;\n\n // Length rounded to 8 bytes\n int length8 = length & 0x7FFF_FFF8;\n for (; offset < length8; offset += 8) {\n if ((utf8.getLongUnchecked(offset) & TOP_MASK64) != 0) {\n return false;\n }\n }\n // Enough bytes left for 32 bits?\n if (offset + 4 < length) {\n if ((utf8.getIntUnchecked(offset) & TOP_MASK32) != 0) {\n return false;\n }\n\n offset += 4;\n }\n // Do the rest one by one\n for (; offset < length; offset++) {\n if ((utf8.getByteUnchecked(offset) & 0x80) != 0) {\n return false;\n }\n }\n\n return true;\n }"
] |
Returns the compression type of this kind of dump file using file suffixes
@param fileName the name of the file
@return compression type
@throws IllegalArgumentException
if the given dump file type is not known | [
"public static CompressionType getDumpFileCompressionType(String fileName) {\n\t\tif (fileName.endsWith(\".gz\")) {\n\t\t\treturn CompressionType.GZIP;\n\t\t} else if (fileName.endsWith(\".bz2\")) {\n\t\t\treturn CompressionType.BZ2;\n\t\t} else {\n\t\t\treturn CompressionType.NONE;\n\t\t}\n\t}"
] | [
"@Override\n\tpublic boolean isKeyColumn(String columnName) {\n\t\tfor ( String keyColumName : getColumnNames() ) {\n\t\t\tif ( keyColumName.equals( columnName ) ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}",
"private void executePlan(RebalancePlan rebalancePlan) {\n logger.info(\"Starting to execute rebalance Plan!\");\n\n int batchCount = 0;\n int partitionStoreCount = 0;\n long totalTimeMs = 0;\n\n List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan();\n int numBatches = entirePlan.size();\n int numPartitionStores = rebalancePlan.getPartitionStoresMoved();\n\n for(RebalanceBatchPlan batchPlan: entirePlan) {\n logger.info(\"======== REBALANCING BATCH \" + (batchCount + 1)\n + \" ========\");\n RebalanceUtils.printBatchLog(batchCount,\n logger,\n batchPlan.toString());\n\n long startTimeMs = System.currentTimeMillis();\n // ACTUALLY DO A BATCH OF REBALANCING!\n executeBatch(batchCount, batchPlan);\n totalTimeMs += (System.currentTimeMillis() - startTimeMs);\n\n // Bump up the statistics\n batchCount++;\n partitionStoreCount += batchPlan.getPartitionStoreMoves();\n batchStatusLog(batchCount,\n numBatches,\n partitionStoreCount,\n numPartitionStores,\n totalTimeMs);\n }\n }",
"private static boolean isPredefinedConstant(Expression expression) {\r\n if (expression instanceof PropertyExpression) {\r\n Expression object = ((PropertyExpression) expression).getObjectExpression();\r\n Expression property = ((PropertyExpression) expression).getProperty();\r\n\r\n if (object instanceof VariableExpression) {\r\n List<String> predefinedConstantNames = PREDEFINED_CONSTANTS.get(((VariableExpression) object).getName());\r\n if (predefinedConstantNames != null && predefinedConstantNames.contains(property.getText())) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }",
"@SuppressWarnings(\"unchecked\")\n protected void addPostRunDependent(Executable<? extends Indexable> executable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) executable;\n this.addPostRunDependent(dependency);\n }",
"private Auth constructAuth(String authToken, String tokenSecret, String username) throws IOException {\n\n Auth auth = new Auth();\n auth.setToken(authToken);\n auth.setTokenSecret(tokenSecret);\n\n // Prompt to ask what permission is needed: read, update or delete.\n auth.setPermission(Permission.fromString(\"delete\"));\n\n User user = new User();\n // Later change the following 3. Either ask user to pass on command line or read\n // from saved file.\n user.setId(nsid);\n user.setUsername((username));\n user.setRealName(\"\");\n auth.setUser(user);\n this.authStore.store(auth);\n return auth;\n }",
"public static int cudnnGetConvolutionNdDescriptor(\n cudnnConvolutionDescriptor convDesc, \n int arrayLengthRequested, \n int[] arrayLength, \n int[] padA, \n int[] strideA, \n int[] dilationA, \n int[] mode, \n int[] computeType)/** convolution data type */\n {\n return checkResult(cudnnGetConvolutionNdDescriptorNative(convDesc, arrayLengthRequested, arrayLength, padA, strideA, dilationA, mode, computeType));\n }",
"private void _handleMultiValues(ArrayList<String> values, String key, String command) {\n if (key == null) return;\n\n if (values == null || values.isEmpty()) {\n _generateEmptyMultiValueError(key);\n return;\n }\n\n ValidationResult vr;\n\n // validate the key\n vr = validator.cleanMultiValuePropertyKey(key);\n\n // Check for an error\n if (vr.getErrorCode() != 0) {\n pushValidationResult(vr);\n }\n\n // reset the key\n Object _key = vr.getObject();\n String cleanKey = (_key != null) ? vr.getObject().toString() : null;\n\n // if key is empty generate an error and return\n if (cleanKey == null || cleanKey.isEmpty()) {\n _generateInvalidMultiValueKeyError(key);\n return;\n }\n\n key = cleanKey;\n\n try {\n JSONArray currentValues = _constructExistingMultiValue(key, command);\n JSONArray newValues = _cleanMultiValues(values, key);\n _validateAndPushMultiValue(currentValues, newValues, values, key, command);\n\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Error handling multi value operation for key \" + key, t);\n }\n }",
"public static base_response update(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 updateresource = new nsacl6();\n\t\tupdateresource.acl6name = resource.acl6name;\n\t\tupdateresource.aclaction = resource.aclaction;\n\t\tupdateresource.srcipv6 = resource.srcipv6;\n\t\tupdateresource.srcipop = resource.srcipop;\n\t\tupdateresource.srcipv6val = resource.srcipv6val;\n\t\tupdateresource.srcport = resource.srcport;\n\t\tupdateresource.srcportop = resource.srcportop;\n\t\tupdateresource.srcportval = resource.srcportval;\n\t\tupdateresource.destipv6 = resource.destipv6;\n\t\tupdateresource.destipop = resource.destipop;\n\t\tupdateresource.destipv6val = resource.destipv6val;\n\t\tupdateresource.destport = resource.destport;\n\t\tupdateresource.destportop = resource.destportop;\n\t\tupdateresource.destportval = resource.destportval;\n\t\tupdateresource.srcmac = resource.srcmac;\n\t\tupdateresource.protocol = resource.protocol;\n\t\tupdateresource.protocolnumber = resource.protocolnumber;\n\t\tupdateresource.icmptype = resource.icmptype;\n\t\tupdateresource.icmpcode = resource.icmpcode;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.Interface = resource.Interface;\n\t\tupdateresource.priority = resource.priority;\n\t\tupdateresource.established = resource.established;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public IPv6Address getIPv6Address(IPv6AddressSegment segs[]) {\n\t\tIPv6AddressCreator creator = getIPv6Network().getAddressCreator();\n\t\treturn creator.createAddress(IPv6AddressSection.createSection(creator, segs, this)); /* address creation */\n\t}"
] |
Obtains a local date in Pax calendar system from the
proleptic-year, month-of-year and day-of-month fields.
@param prolepticYear the proleptic-year
@param month the month-of-year
@param dayOfMonth the day-of-month
@return the Pax local date, not null
@throws DateTimeException if unable to create the date | [
"@Override\n public PaxDate date(int prolepticYear, int month, int dayOfMonth) {\n return PaxDate.of(prolepticYear, month, dayOfMonth);\n }"
] | [
"public static List<Integer> toIntegerList(List<String> strList, boolean failOnException){\n\t\tList<Integer> intList = new ArrayList<Integer>();\n\t\tfor(String str : strList){\n\t\t\ttry{\n\t\t\t\tintList.add(Integer.parseInt(str));\n\t\t\t}\n\t\t\tcatch(NumberFormatException nfe){\n\t\t\t\tif(failOnException){\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tintList.add(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn intList;\n\t}",
"public static CharSequence getRelativeTimeSpanString(Context context, ReadableInstant time, int flags) {\n boolean abbrevRelative = (flags & (FORMAT_ABBREV_RELATIVE | FORMAT_ABBREV_ALL)) != 0;\n\n // We set the millis to 0 so we aren't off by a fraction of a second when counting intervals\n DateTime now = DateTime.now(time.getZone()).withMillisOfSecond(0);\n DateTime timeDt = new DateTime(time).withMillisOfSecond(0);\n boolean past = !now.isBefore(timeDt);\n Interval interval = past ? new Interval(timeDt, now) : new Interval(now, timeDt);\n\n int resId;\n long count;\n if (Minutes.minutesIn(interval).isLessThan(Minutes.ONE)) {\n count = Seconds.secondsIn(interval).getSeconds();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_seconds_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_seconds_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_seconds;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_seconds;\n }\n }\n }\n else if (Hours.hoursIn(interval).isLessThan(Hours.ONE)) {\n count = Minutes.minutesIn(interval).getMinutes();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_minutes_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_minutes_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_minutes;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_minutes;\n }\n }\n }\n else if (Days.daysIn(interval).isLessThan(Days.ONE)) {\n count = Hours.hoursIn(interval).getHours();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_hours_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_hours_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_hours;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_hours;\n }\n }\n }\n else if (Weeks.weeksIn(interval).isLessThan(Weeks.ONE)) {\n count = Days.daysIn(interval).getDays();\n if (past) {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_num_days_ago;\n }\n else {\n resId = R.plurals.joda_time_android_num_days_ago;\n }\n }\n else {\n if (abbrevRelative) {\n resId = R.plurals.joda_time_android_abbrev_in_num_days;\n }\n else {\n resId = R.plurals.joda_time_android_in_num_days;\n }\n }\n }\n else {\n return formatDateRange(context, time, time, flags);\n }\n\n String format = context.getResources().getQuantityString(resId, (int) count);\n return String.format(format, count);\n }",
"public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(String enterpriseId, String clientId,\n String clientSecret, JWTEncryptionPreferences encryptionPref, IAccessTokenCache accessTokenCache) {\n\n BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection(enterpriseId,\n DeveloperEditionEntityType.ENTERPRISE, clientId, clientSecret, encryptionPref, accessTokenCache);\n\n connection.tryRestoreUsingAccessTokenCache();\n\n return connection;\n }",
"private static void defineField(Map<String, FieldType> container, String name, FieldType type, String alias)\n {\n container.put(name, type);\n if (alias != null)\n {\n ALIASES.put(type, alias);\n }\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 }",
"public void runOnBrowserCreatedPlugins(EmbeddedBrowser newBrowser) {\n\t\tLOGGER.debug(\"Running OnBrowserCreatedPlugins...\");\n\t\tcounters.get(OnBrowserCreatedPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnBrowserCreatedPlugin.class)) {\n\t\t\tif (plugin instanceof OnBrowserCreatedPlugin) {\n\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\ttry {\n\t\t\t\t\t((OnBrowserCreatedPlugin) plugin)\n\t\t\t\t\t\t\t.onBrowserCreated(newBrowser);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"private void handleIncomingMessage(SerialMessage incomingMessage) {\n\t\t\n\t\tlogger.debug(\"Incoming message to process\");\n\t\tlogger.debug(incomingMessage.toString());\n\t\t\n\t\tswitch (incomingMessage.getMessageType()) {\n\t\t\tcase Request:\n\t\t\t\thandleIncomingRequestMessage(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase Response:\n\t\t\t\thandleIncomingResponseMessage(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\"Unsupported incomingMessageType: 0x%02X\", incomingMessage.getMessageType());\n\t\t}\n\t}",
"public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }",
"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 }"
] |
this class loader interface can be used by other plugins to lookup
resources from the bundles. A temporary class loader interface is set
during other configuration loading as well
@return ClassLoaderInterface (BundleClassLoaderInterface) | [
"private ClassLoaderInterface getClassLoader() {\n\t\tMap<String, Object> application = ActionContext.getContext().getApplication();\n\t\tif (application != null) {\n\t\t\treturn (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE);\n\t\t}\n\t\treturn null;\n\t}"
] | [
"public void setEnterpriseCost(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_COST, index), value);\n }",
"public MaterialAccount getAccountByTitle(String title) {\n for(MaterialAccount account : accountManager)\n if(currentAccount.getTitle().equals(title))\n return account;\n\n return null;\n }",
"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 ResourceKey key(Enum<?> value) {\n return new ResourceKey(value.getClass().getName(), value.name());\n }",
"public LogStreamResponse getLogs(String appName, Boolean tail) {\n return connection.execute(new Log(appName, tail), apiKey);\n }",
"public Set<Class> entityClasses() {\n EntityMetaInfoRepo repo = app().entityMetaInfoRepo().forDb(id);\n return null == repo ? C.<Class>set() : repo.entityClasses();\n }",
"public static File newFile(File baseDir, String... segments) {\n File f = baseDir;\n for (String segment : segments) {\n f = new File(f, segment);\n }\n return f;\n }",
"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 }",
"@SuppressWarnings(\"deprecation\")\n private void cancelRequestAndWorkerOnHost(List<String> targetHosts) {\n\n List<String> validTargetHosts = new ArrayList<String>(workers.keySet());\n validTargetHosts.retainAll(targetHosts);\n logger.info(\"targetHosts for cancel: Total: {}\"\n + \" Valid in current manager with worker threads: {}\",\n targetHosts.size(), validTargetHosts.size());\n\n for (String targetHost : validTargetHosts) {\n\n ActorRef worker = workers.get(targetHost);\n\n if (worker != null && !worker.isTerminated()) {\n worker.tell(OperationWorkerMsgType.CANCEL, getSelf());\n logger.info(\"Submitted CANCEL request on Host {}\", targetHost);\n } else {\n logger.info(\n \"Did NOT Submitted \"\n + \"CANCEL request on Host {} as worker on this host is null or already killed\",\n targetHost);\n }\n\n }\n\n }"
] |
Calculate a shift value that can be used to create a power-of-two value between
the specified maximum and minimum values.
@param minimumValue the minimum value
@param maximumValue the maximum value
@return the calculated shift (use {@code 1 << shift} to obtain a value) | [
"protected static int calculateShift(int minimumValue, int maximumValue) {\n\t\tint shift = 0;\n\t\tint value = 1;\n\t\twhile (value < minimumValue && value < maximumValue) {\n\t\t\tvalue <<= 1;\n\t\t\tshift++;\n\t\t}\n\t\treturn shift;\n\t}"
] | [
"public static UriComponentsBuilder fromPath(String path) {\n\t\tUriComponentsBuilder builder = new UriComponentsBuilder();\n\t\tbuilder.path(path);\n\t\treturn builder;\n\t}",
"public void seekToDayOfYear(String dayOfYear) {\n int dayOfYearInt = Integer.parseInt(dayOfYear);\n assert(dayOfYearInt >= 1 && dayOfYearInt <= 366);\n \n markDateInvocation();\n \n dayOfYearInt = Math.min(dayOfYearInt, _calendar.getActualMaximum(Calendar.DAY_OF_YEAR));\n _calendar.set(Calendar.DAY_OF_YEAR, dayOfYearInt);\n }",
"private OAuth1RequestToken constructToken(Response response) {\r\n Element authElement = response.getPayload();\r\n String oauthToken = XMLUtilities.getChildValue(authElement, \"oauth_token\");\r\n String oauthTokenSecret = XMLUtilities.getChildValue(authElement, \"oauth_token_secret\");\r\n\r\n OAuth1RequestToken token = new OAuth1RequestToken(oauthToken, oauthTokenSecret);\r\n return token;\r\n }",
"private void registerRows() {\n\t\tfor (int i = 0; i < rows.length; i++) {\n\t\t\tDJCrosstabRow crosstabRow = rows[i];\n\n\t\t\tJRDesignCrosstabRowGroup ctRowGroup = new JRDesignCrosstabRowGroup();\n\n\t\t\tctRowGroup.setWidth(crosstabRow.getHeaderWidth());\n\n\t\t\tctRowGroup.setName(crosstabRow.getProperty().getProperty());\n\n\t\t\tJRDesignCrosstabBucket rowBucket = new JRDesignCrosstabBucket();\n\n //New in JR 4.1+\n rowBucket.setValueClassName(crosstabRow.getProperty().getValueClassName());\n\n\t\t\tctRowGroup.setBucket(rowBucket);\n\n\t\t\tJRDesignExpression bucketExp = ExpressionUtils.createExpression(\"$F{\"+crosstabRow.getProperty().getProperty()+\"}\", crosstabRow.getProperty().getValueClassName());\n\t\t\trowBucket.setExpression(bucketExp);\n\n\n\t\t\tJRDesignCellContents rowHeaderContents = new JRDesignCellContents();\n\t\t\tJRDesignTextField rowTitle = new JRDesignTextField();\n\n\t\t\tJRDesignExpression rowTitExp = new JRDesignExpression();\n\t\t\trowTitExp.setValueClassName(crosstabRow.getProperty().getValueClassName());\n\t\t\trowTitExp.setText(\"$V{\"+crosstabRow.getProperty().getProperty()+\"}\");\n\n\t\t\trowTitle.setExpression(rowTitExp);\n\t\t\trowTitle.setWidth(crosstabRow.getHeaderWidth());\n\n\t\t\t//The width can be the sum of the with of all the rows starting from the current one, up to the inner most one.\n\t\t\tint auxHeight = getRowHeaderMaxHeight(crosstabRow);\n//\t\t\tint auxHeight = crosstabRow.getHeight(); //FIXME getRowHeaderMaxHeight() must be FIXED because it breaks when 1rs row shows total and 2nd doesn't\n\t\t\trowTitle.setHeight(auxHeight);\n\n\t\t\tStyle headerstyle = crosstabRow.getHeaderStyle() == null ? this.djcross.getRowHeaderStyle(): crosstabRow.getHeaderStyle();\n\n\t\t\tif (headerstyle != null){\n\t\t\t\tlayoutManager.applyStyleToElement(headerstyle, rowTitle);\n\t\t\t\trowHeaderContents.setBackcolor(headerstyle.getBackgroundColor());\n\t\t\t}\n\n\t\t\trowHeaderContents.addElement(rowTitle);\n\t\t\trowHeaderContents.setMode( ModeEnum.OPAQUE );\n\n\t\t\tboolean fullBorder = i <= 0; //Only outer most will have full border\n\t\t\tapplyCellBorder(rowHeaderContents, false, fullBorder);\n\n\t\t\tctRowGroup.setHeader(rowHeaderContents );\n\n\t\t\tif (crosstabRow.isShowTotals())\n\t\t\t\tcreateRowTotalHeader(ctRowGroup,crosstabRow,fullBorder);\n\n\n\t\t\ttry {\n\t\t\t\tjrcross.addRowGroup(ctRowGroup);\n\t\t\t} catch (JRException e) {\n\t\t\t\tlog.error(e.getMessage(),e);\n\t\t\t}\n\n\t\t}\n\t}",
"public List<TimephasedCost> getTimephasedActualCost()\n {\n if (m_timephasedActualCost == 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_timephasedActualWork != null && m_timephasedActualWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedActualCost = getTimephasedCostMultipleRates(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n else\n {\n m_timephasedActualCost = getTimephasedCostSingleRate(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedActualCost = getTimephasedActualCostFixedAmount();\n }\n\n }\n\n return m_timephasedActualCost;\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 }",
"public void setFrustum(float[] frustum)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.setFrustum(frustum[0], frustum[3], frustum[1], frustum[4], frustum[2], frustum[5]);\n setFrustum(projMatrix);\n }",
"public static base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}",
"@Override\n public List<String> setTargetHostsFromLineByLineText(String sourcePath,\n HostsSourceType sourceType) throws TargetHostsLoadException {\n\n List<String> targetHosts = new ArrayList<String>();\n try {\n String content = getContentFromPath(sourcePath, sourceType);\n\n targetHosts = setTargetHostsFromString(content);\n\n } catch (IOException e) {\n throw new TargetHostsLoadException(\"IEException when reading \"\n + sourcePath, e);\n }\n\n return targetHosts;\n\n }"
] |
Moves the given row up.
@param row the row to move | [
"public void moveUp(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index > 0) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index - 1);\n }\n updateButtonBars();\n }"
] | [
"public void setDateOnly(boolean dateOnly) {\n\n if (m_dateOnly != dateOnly) {\n m_dateOnly = dateOnly;\n if (m_dateOnly) {\n m_time.removeFromParent();\n m_am.removeFromParent();\n m_pm.removeFromParent();\n } else {\n m_timeField.add(m_time);\n m_timeField.add(m_am);\n m_timeField.add(m_pm);\n }\n }\n }",
"public static ModelNode createReadResourceOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createOperation(READ_RESOURCE_OPERATION, address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }",
"public Metadata add(String path, List<String> values) {\n JsonArray arr = new JsonArray();\n for (String value : values) {\n arr.add(value);\n }\n this.values.add(this.pathToProperty(path), arr);\n this.addOp(\"add\", path, arr);\n return this;\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 }",
"public void releaseAll() {\n synchronized(this) {\n Object[] refSet = allocatedMemoryReferences.values().toArray();\n if(refSet.length != 0) {\n logger.finer(\"Releasing allocated memory regions\");\n }\n for(Object ref : refSet) {\n release((MemoryReference) ref);\n }\n }\n }",
"public static List<File> extract(File zipFile, File outputFolder) throws IOException {\n List<File> extracted = new ArrayList<File>();\n\n byte[] buffer = new byte[2048];\n\n if (!outputFolder.exists()) {\n outputFolder.mkdir();\n }\n\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));\n\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n\n String neFileNameName = zipEntry.getName();\n File newFile = new File(outputFolder + File.separator + neFileNameName);\n\n newFile.getParentFile().mkdirs();\n\n if (!zipEntry.isDirectory()) {\n FileOutputStream fos = new FileOutputStream(newFile);\n\n int size;\n while ((size = zipInput.read(buffer)) > 0) {\n fos.write(buffer, 0, size);\n }\n\n fos.close();\n extracted.add(newFile);\n }\n\n zipEntry = zipInput.getNextEntry();\n }\n\n zipInput.closeEntry();\n zipInput.close();\n\n return extracted;\n\n }",
"@Inject\n public void setQueue(EventQueue queue) {\n if (epi == null) {\n MessageToEventMapper mapper = new MessageToEventMapper();\n mapper.setMaxContentLength(maxContentLength);\n\n epi = new EventProducerInterceptor(mapper, queue);\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 }",
"public void setTotalColorForColumn(int column, Color color){\r\n\t\tint map = (colors.length-1) - column;\r\n\t\tcolors[map][colors[0].length-1]=color;\r\n\t}"
] |
Set the degrees of rotation. Value will be set to -1, if not available.
@param rotation | [
"public void setRotation(String rotation) {\r\n if (rotation != null) {\r\n try {\r\n setRotation(Integer.parseInt(rotation));\r\n } catch (NumberFormatException e) {\r\n setRotation(-1);\r\n }\r\n }\r\n }"
] | [
"public ComplexDouble divi(ComplexDouble c, ComplexDouble result) {\n double d = c.r * c.r + c.i * c.i;\n double newR = (r * c.r + i * c.i) / d;\n double newI = (i * c.r - r * c.i) / d;\n result.r = newR;\n result.i = newI;\n return result;\n }",
"public T mapRow(ResultSet rs) throws SQLException {\n Map<String, Object> map = new HashMap<String, Object>();\n ResultSetMetaData metadata = rs.getMetaData();\n\n for (int i = 1; i <= metadata.getColumnCount(); ++i) {\n String label = metadata.getColumnLabel(i);\n\n final Object value;\n // calling getObject on a BLOB/CLOB produces weird results\n switch (metadata.getColumnType(i)) {\n case Types.BLOB:\n value = rs.getBytes(i);\n break;\n case Types.CLOB:\n value = rs.getString(i);\n break;\n default:\n value = rs.getObject(i);\n }\n\n // don't use table name extractor because we don't want aliased table name\n boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i));\n String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i);\n if (tableName != null && !tableName.isEmpty()) {\n String qualifiedName = tableName + \".\" + metadata.getColumnName(i);\n add(map, qualifiedName, value, overwrite);\n }\n\n add(map, label, value, overwrite);\n }\n\n return objectMapper.convertValue(map, type);\n }",
"@Pure\n\tpublic static <P1, RESULT> Function0<RESULT> curry(final Function1<? super P1, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function0<RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply() {\n\t\t\t\treturn function.apply(argument);\n\t\t\t}\n\t\t};\n\t}",
"public static base_response disable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature disableresource = new nsfeature();\n\t\tdisableresource.feature = resource.feature;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public void check(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureReferencedKeys(modelDef, checkLevel);\r\n checkReferenceForeignkeys(modelDef, checkLevel);\r\n checkCollectionForeignkeys(modelDef, checkLevel);\r\n checkKeyModifications(modelDef, checkLevel);\r\n }",
"@Override\n public boolean decompose( ZMatrixRMaj A )\n {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be square.\");\n if( A.numRows <= 0 )\n return false;\n\n QH = A;\n\n N = A.numCols;\n\n if( b.length < N*2 ) {\n b = new double[ N*2 ];\n gammas = new double[ N ];\n u = new double[ N*2 ];\n }\n return _decompose();\n }",
"private static int tribus(int version, int a, int b, int c) {\n if (version < 10) {\n return a;\n } else if (version >= 10 && version <= 26) {\n return b;\n } else {\n return c;\n }\n }",
"protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\n }",
"public String objectToString(T object) {\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tsb.append(object.getClass().getSimpleName());\n\t\tfor (FieldType fieldType : fieldTypes) {\n\t\t\tsb.append(' ').append(fieldType.getColumnName()).append('=');\n\t\t\ttry {\n\t\t\t\tsb.append(fieldType.extractJavaFieldValue(object));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not generate toString of field \" + fieldType, e);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}"
] |
Set the color for each total for the column
@param column the number of the column (starting from 1)
@param color | [
"public void setTotalColorForColumn(int column, Color color){\r\n\t\tint map = (colors.length-1) - column;\r\n\t\tcolors[map][colors[0].length-1]=color;\r\n\t}"
] | [
"public Object getRealValue()\r\n {\r\n if(valueRealSubject != null)\r\n {\r\n return valueRealSubject;\r\n }\r\n else\r\n {\r\n TransactionExt tx = getTransaction();\r\n\r\n if((tx != null) && tx.isOpen())\r\n {\r\n prepareValueRealSubject(tx.getBroker());\r\n }\r\n else\r\n {\r\n if(getPBKey() != null)\r\n {\r\n PBCapsule capsule = new PBCapsule(getPBKey(), null);\r\n\r\n try\r\n {\r\n prepareValueRealSubject(capsule.getBroker());\r\n }\r\n finally\r\n {\r\n capsule.destroy();\r\n }\r\n }\r\n else\r\n {\r\n getLog().warn(\"No tx, no PBKey - can't materialise value with Identity \" + getKeyOid());\r\n }\r\n }\r\n }\r\n return valueRealSubject;\r\n }",
"public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}",
"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 }",
"private <T> ServiceResponse<T> getPutOrPatchResult(Observable<Response<ResponseBody>> observable, Type resourceType) throws CloudException, InterruptedException, IOException {\n Observable<ServiceResponse<T>> asyncObservable = getPutOrPatchResultAsync(observable, resourceType);\n return asyncObservable.toBlocking().last();\n }",
"protected float transformLength(float w)\n {\n Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();\n Matrix m = new Matrix();\n m.setValue(2, 0, w);\n return m.multiply(ctm).getTranslateX();\n }",
"public String updateContextAndGetFavoriteUrl(CmsObject cms) throws CmsException {\n\n CmsResourceFilter filter = CmsResourceFilter.IGNORE_EXPIRATION;\n CmsProject project = null;\n switch (getType()) {\n case explorerFolder:\n CmsResource folder = cms.readResource(getStructureId(), filter);\n project = cms.readProject(getProjectId());\n cms.getRequestContext().setSiteRoot(getSiteRoot());\n cms.getRequestContext().setCurrentProject(project);\n String explorerLink = CmsVaadinUtils.getWorkplaceLink()\n + \"#!\"\n + CmsFileExplorerConfiguration.APP_ID\n + \"/\"\n + getProjectId()\n + \"!!\"\n + getSiteRoot()\n + \"!!\"\n + cms.getSitePath(folder);\n return explorerLink;\n case page:\n project = cms.readProject(getProjectId());\n CmsResource target = cms.readResource(getStructureId(), filter);\n CmsResource detailContent = null;\n String link = null;\n cms.getRequestContext().setCurrentProject(project);\n cms.getRequestContext().setSiteRoot(getSiteRoot());\n if (getDetailId() != null) {\n detailContent = cms.readResource(getDetailId());\n link = OpenCms.getLinkManager().substituteLinkForUnknownTarget(\n cms,\n cms.getSitePath(detailContent),\n cms.getSitePath(target),\n false);\n } else {\n link = OpenCms.getLinkManager().substituteLink(cms, target);\n }\n return link;\n default:\n return null;\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 List<List<String>> getAllScopes() {\n this.checkInitialized();\n final ImmutableList.Builder<List<String>> builder = ImmutableList.<List<String>>builder();\n final Consumer<Integer> _function = (Integer it) -> {\n List<String> _get = this.scopes.get(it);\n StringConcatenation _builder = new StringConcatenation();\n _builder.append(\"No scopes are available for index: \");\n _builder.append(it);\n builder.add(Preconditions.<List<String>>checkNotNull(_get, _builder));\n };\n this.scopes.keySet().forEach(_function);\n return builder.build();\n }",
"private void bindProcedure(PreparedStatement stmt, ClassDescriptor cld, Object obj, ProcedureDescriptor proc)\r\n throws SQLException\r\n {\r\n int valueSub = 0;\r\n\r\n // Figure out if we are using a callable statement. If we are, then we\r\n // will need to register one or more output parameters.\r\n CallableStatement callable = null;\r\n try\r\n {\r\n callable = (CallableStatement) stmt;\r\n }\r\n catch(Exception e)\r\n {\r\n m_log.error(\"Error while bind values for class '\" + (cld != null ? cld.getClassNameOfObject() : null)\r\n + \"', using stored procedure: \"+ proc, e);\r\n if(e instanceof SQLException)\r\n {\r\n throw (SQLException) e;\r\n }\r\n else\r\n {\r\n throw new PersistenceBrokerException(\"Unexpected error while bind values for class '\"\r\n + (cld != null ? cld.getClassNameOfObject() : null) + \"', using stored procedure: \"+ proc);\r\n }\r\n }\r\n\r\n // If we have a return value, then register it.\r\n if ((proc.hasReturnValue()) && (callable != null))\r\n {\r\n int jdbcType = proc.getReturnValueFieldRef().getJdbcType().getType();\r\n m_platform.setNullForStatement(stmt, valueSub + 1, jdbcType);\r\n callable.registerOutParameter(valueSub + 1, jdbcType);\r\n valueSub++;\r\n }\r\n\r\n // Process all of the arguments.\r\n Iterator iterator = proc.getArguments().iterator();\r\n while (iterator.hasNext())\r\n {\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iterator.next();\r\n Object val = arg.getValue(obj);\r\n int jdbcType = arg.getJdbcType();\r\n setObjectForStatement(stmt, valueSub + 1, val, jdbcType);\r\n if ((arg.getIsReturnedByProcedure()) && (callable != null))\r\n {\r\n callable.registerOutParameter(valueSub + 1, jdbcType);\r\n }\r\n valueSub++;\r\n }\r\n }"
] |
Execute a partitioned query using an index and a query selector.
Only available in partitioned databases. To verify a database is partitioned call
{@link Database#info()} and check that {@link DbInfo.Props#getPartitioned()} returns
{@code true}.
<p>Example usage:</p>
<pre>
{@code
// Query database partition 'Coppola'.
QueryResult<Movie> movies = db.query("Coppola", new QueryBuilder(and(
gt("Movie_year", 1960),
eq("Person_name", "Al Pacino"))).
fields("Movie_name", "Movie_year").
build(), Movie.class);
}
</pre>
@param partitionKey Database partition to query.
@param query String representation of a JSON object describing criteria used to
select documents.
@param classOfT The class of Java objects to be returned in the {@code docs} field of
result.
@param <T> The type of the Java object to be returned in the {@code docs} field of
result.
@return A {@link QueryResult} object, containing the documents matching the query
in the {@code docs} field.
@see com.cloudant.client.api.Database#query(String, Class) | [
"public <T> QueryResult<T> query(String partitionKey, String query, final Class<T> classOfT) {\n URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).path(\"_find\").build();\n return this.query(uri, query, classOfT);\n }"
] | [
"public void setPublishQueueShutdowntime(String publishQueueShutdowntime) {\n\n if (m_frozen) {\n throw new CmsRuntimeException(Messages.get().container(Messages.ERR_CONFIG_FROZEN_0));\n }\n m_publishQueueShutdowntime = Integer.parseInt(publishQueueShutdowntime);\n }",
"@DELETE\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response removeCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an remove a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to remove!\");\n return Response.serverError().status(HttpStatus.BAD_REQUEST_400).build();\n }\n\n getOrganizationHandler().removeCorporateGroupId(organizationId, corporateGroupId);\n\n return Response.ok(\"done\").build();\n }",
"okhttp3.Response get(String url, Map<String, Object> params)\n throws RequestException, LocalOperationException {\n\n String fullUrl = getFullUrl(url);\n okhttp3.Request request = new okhttp3.Request.Builder()\n .url(addUrlParams(fullUrl, toPayload(params)))\n .addHeader(\"Transloadit-Client\", version)\n .build();\n\n try {\n return httpClient.newCall(request).execute();\n } catch (IOException e) {\n throw new RequestException(e);\n }\n }",
"public int delete(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedDelete == null) {\n\t\t\tmappedDelete = MappedDelete.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedDelete.delete(databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}",
"public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName,\n String filePrefix) {\n dumpClusterToFile(outputDirName, filePrefix + currentClusterFileName, currentCluster);\n dumpClusterToFile(outputDirName, filePrefix + finalClusterFileName, finalCluster);\n }",
"protected DataSource wrapAsDataSource(JdbcConnectionDescriptor jcd,\r\n ObjectPool connectionPool)\r\n {\r\n final boolean allowConnectionUnwrap;\r\n if (jcd == null)\r\n {\r\n allowConnectionUnwrap = false;\r\n }\r\n else\r\n {\r\n final Properties properties = jcd.getConnectionPoolDescriptor().getDbcpProperties();\r\n final String allowConnectionUnwrapParam;\r\n allowConnectionUnwrapParam = properties.getProperty(PARAM_NAME_UNWRAP_ALLOWED);\r\n allowConnectionUnwrap = allowConnectionUnwrapParam != null &&\r\n Boolean.valueOf(allowConnectionUnwrapParam).booleanValue();\r\n }\r\n final PoolingDataSource dataSource;\r\n dataSource = new PoolingDataSource(connectionPool);\r\n dataSource.setAccessToUnderlyingConnectionAllowed(allowConnectionUnwrap);\r\n\r\n if(jcd != null)\r\n {\r\n final AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();\r\n if (ac.getRemoveAbandoned() && ac.getLogAbandoned()) {\r\n final LoggerWrapperPrintWriter loggerPiggyBack;\r\n loggerPiggyBack = new LoggerWrapperPrintWriter(log, Logger.ERROR);\r\n dataSource.setLogWriter(loggerPiggyBack);\r\n }\r\n }\r\n return dataSource;\r\n }",
"private void createTimephasedData(ProjectFile file, ResourceAssignment assignment, List<TimephasedWork> timephasedPlanned, List<TimephasedWork> timephasedComplete)\n {\n if (timephasedPlanned.isEmpty() && timephasedComplete.isEmpty())\n {\n Duration totalMinutes = assignment.getWork().convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n\n Duration workPerDay;\n\n if (assignment.getResource() == null || assignment.getResource().getType() == ResourceType.WORK)\n {\n workPerDay = totalMinutes.getDuration() == 0 ? totalMinutes : ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n int units = NumberHelper.getInt(assignment.getUnits());\n if (units != 100)\n {\n workPerDay = Duration.getInstance((workPerDay.getDuration() * units) / 100.0, workPerDay.getUnits());\n }\n }\n else\n {\n if (assignment.getVariableRateUnits() == null)\n {\n Duration workingDays = assignment.getCalendar().getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.DAYS);\n double units = NumberHelper.getDouble(assignment.getUnits());\n double unitsPerDayAsMinutes = (units * 60) / (workingDays.getDuration() * 100);\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n else\n {\n double unitsPerHour = NumberHelper.getDouble(assignment.getUnits());\n workPerDay = ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n Duration hoursPerDay = workPerDay.convertUnits(TimeUnit.HOURS, file.getProjectProperties());\n double unitsPerDayAsHours = (unitsPerHour * hoursPerDay.getDuration()) / 100;\n double unitsPerDayAsMinutes = unitsPerDayAsHours * 60;\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n }\n\n Duration overtimeWork = assignment.getOvertimeWork();\n if (overtimeWork != null && overtimeWork.getDuration() != 0)\n {\n Duration totalOvertimeMinutes = overtimeWork.convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n totalMinutes = Duration.getInstance(totalMinutes.getDuration() - totalOvertimeMinutes.getDuration(), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(assignment.getStart());\n tra.setAmountPerDay(workPerDay);\n tra.setModified(false);\n tra.setFinish(assignment.getFinish());\n tra.setTotalAmount(totalMinutes);\n timephasedPlanned.add(tra);\n }\n }",
"List<CmsFavoriteEntry> getEntries() {\n\n List<CmsFavoriteEntry> result = new ArrayList<>();\n for (I_CmsEditableGroupRow row : m_group.getRows()) {\n CmsFavoriteEntry entry = ((CmsFavInfo)row).getEntry();\n result.add(entry);\n }\n return result;\n }",
"String buildSelect(String htmlAttributes, SelectOptions options) {\n\n return buildSelect(htmlAttributes, options.getOptions(), options.getValues(), options.getSelectedIndex());\n }"
] |
Use this API to unset the properties of tmsessionparameter resource.
Properties that need to be unset are specified in args array. | [
"public static base_response unset(nitro_service client, tmsessionparameter resource, String[] args) throws Exception{\n\t\ttmsessionparameter unsetresource = new tmsessionparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] | [
"public void add(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n BinderDescriptor binderDescriptor = new BinderDescriptor(declarationBinderRef);\n declarationBinders.put(declarationBinderRef, binderDescriptor);\n }",
"public Integer getEnd() {\n if (mtasPositionType.equals(POSITION_RANGE)\n || mtasPositionType.equals(POSITION_SET)) {\n return mtasPositionEnd;\n } else if (mtasPositionType.equals(POSITION_SINGLE)) {\n return mtasPositionStart;\n } else {\n return null;\n }\n }",
"public static <E> Collection<E> collectify(ObjectMapper mapper, Object source, Class<? extends Collection> targetCollectionType, Class<E> targetElementType) {\n CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(targetCollectionType, targetElementType);\n return objectify(mapper, convertToCollection(source), collectionType);\n }",
"public static int cudnnGetReductionIndicesSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionIndicesSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }",
"public static vpnvserver_authenticationsamlpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationsamlpolicy_binding obj = new vpnvserver_authenticationsamlpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationsamlpolicy_binding response[] = (vpnvserver_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public double estimateExcludedVolumeFraction(){\n\t\t//Calculate volume/area of the of the scene without obstacles\n\t\tif(recalculateVolumeFraction){\n\t\t\tCentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();\n\t\t\tboolean firstRandomDraw = false;\n\t\t\tif(randomNumbers==null){\n\t\t\t\trandomNumbers = new double[nRandPoints*dimension];\n\t\t\t\tfirstRandomDraw = true;\n\t\t\t}\n\t\t\tint countCollision = 0;\n\t\t\tfor(int i = 0; i< nRandPoints; i++){\n\t\t\t\tdouble[] pos = new double[dimension];\n\t\t\t\tfor(int j = 0; j < dimension; j++){\n\t\t\t\t\tif(firstRandomDraw){\n\t\t\t\t\t\trandomNumbers[i*dimension + j] = r.nextDouble();\n\t\t\t\t\t}\n\t\t\t\t\tpos[j] = randomNumbers[i*dimension + j]*size[j];\n\t\t\t\t}\n\t\t\t\tif(checkCollision(pos)){\n\t\t\t\t\tcountCollision++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfraction = countCollision*1.0/nRandPoints;\n\t\t\trecalculateVolumeFraction = false;\n\t\t}\n\t\treturn fraction;\n\t}",
"private PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>\n getMatchedDestination(List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations,\n HttpMethod targetHttpMethod, String requestUri) {\n\n LOG.trace(\"Routable destinations for request {}: {}\", requestUri, routableDestinations);\n Iterable<String> requestUriParts = splitAndOmitEmpty(requestUri, '/');\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations = new ArrayList<>();\n long maxScore = 0;\n\n for (PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> destination : routableDestinations) {\n HttpResourceModel resourceModel = destination.getDestination();\n\n for (HttpMethod httpMethod : resourceModel.getHttpMethod()) {\n if (targetHttpMethod.equals(httpMethod)) {\n long score = getWeightedMatchScore(requestUriParts, splitAndOmitEmpty(resourceModel.getPath(), '/'));\n LOG.trace(\"Max score = {}. Weighted score for {} is {}. \", maxScore, destination, score);\n if (score > maxScore) {\n maxScore = score;\n matchedDestinations.clear();\n matchedDestinations.add(destination);\n } else if (score == maxScore) {\n matchedDestinations.add(destination);\n }\n }\n }\n }\n\n if (matchedDestinations.size() > 1) {\n throw new IllegalStateException(String.format(\"Multiple matched handlers found for request uri %s: %s\",\n requestUri, matchedDestinations));\n } else if (matchedDestinations.size() == 1) {\n return matchedDestinations.get(0);\n }\n return null;\n }",
"private synchronized Constructor getIndirectionHandlerConstructor()\r\n {\r\n if(_indirectionHandlerConstructor == null)\r\n {\r\n Class[] paramType = {PBKey.class, Identity.class};\r\n\r\n try\r\n {\r\n _indirectionHandlerConstructor = getIndirectionHandlerClass().getConstructor(paramType);\r\n }\r\n catch(NoSuchMethodException ex)\r\n {\r\n throw new MetadataException(\"The class \"\r\n + _indirectionHandlerClass.getName()\r\n + \" specified for IndirectionHandlerClass\"\r\n + \" is required to have a public constructor with signature (\"\r\n + PBKey.class.getName()\r\n + \", \"\r\n + Identity.class.getName()\r\n + \").\");\r\n }\r\n }\r\n return _indirectionHandlerConstructor;\r\n }",
"private static Point getScreenSize(Context context, Point p) {\n if (p == null) {\n p = new Point();\n }\n WindowManager windowManager = (WindowManager) context\n .getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n display.getSize(p);\n return p;\n }"
] |
Set the depth of the cursor.
This is the length of the ray from the origin
to the cursor.
@param depth default cursor depth | [
"@Override\n public void setCursorDepth(float depth)\n {\n super.setCursorDepth(depth);\n if (mRayModel != null)\n {\n mRayModel.getTransform().setScaleZ(mCursorDepth);\n }\n }"
] | [
"static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) {\n\n Map<String, Set<String>> result = new HashMap<>();\n Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType);\n\n if (resource != null) {\n for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) {\n if (validChildTypeFilter.test(childType)) {\n List<String> list = new ArrayList<>();\n for (String child : resource.getChildrenNames(childType)) {\n if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) {\n list.add(child);\n }\n }\n result.put(childType, new LinkedHashSet<>(list));\n }\n }\n }\n\n Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);\n for (PathElement path : paths) {\n String childType = path.getKey();\n if (validChildTypeFilter.test(childType)) {\n Set<String> children = result.get(childType);\n if (children == null) {\n // WFLY-3306 Ensure we have an entry for any valid child type\n children = new LinkedHashSet<>();\n result.put(childType, children);\n }\n ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path));\n if (childRegistration != null) {\n AliasEntry aliasEntry = childRegistration.getAliasEntry();\n if (aliasEntry != null) {\n PathAddress childAddr = addr.append(path);\n PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context));\n assert !childAddr.equals(target) : \"Alias was not translated\";\n PathAddress targetParent = target.getParent();\n Resource parentResource = context.readResourceFromRoot(targetParent, false);\n if (parentResource != null) {\n PathElement targetElement = target.getLastElement();\n if (targetElement.isWildcard()) {\n children.addAll(parentResource.getChildrenNames(targetElement.getKey()));\n } else if (parentResource.hasChild(targetElement)) {\n children.add(path.getValue());\n }\n }\n }\n if (!path.isWildcard() && childRegistration.isRemote()) {\n children.add(path.getValue());\n }\n }\n }\n }\n\n return result;\n }",
"private void checkExistingTracks() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n checkIfSignatureReady(entry.getKey().player);\n }\n }\n }\n });\n }",
"private ProjectFile readProjectFile(ProjectReader reader, File file) throws MPXJException\n {\n addListeners(reader);\n return reader.read(file);\n }",
"@Override\n public void registerCapabilities(ManagementResourceRegistration resourceRegistration) {\n if (capabilities!=null) {\n for (RuntimeCapability c : capabilities) {\n resourceRegistration.registerCapability(c);\n }\n }\n if (incorporatingCapabilities != null) {\n resourceRegistration.registerIncorporatingCapabilities(incorporatingCapabilities);\n }\n assert requirements != null;\n resourceRegistration.registerRequirements(requirements);\n }",
"public static String getStringOption(Map<String, String> configOptions, String optionKey, String defaultValue) {\n\n String result = configOptions.get(optionKey);\n return null != result ? result : defaultValue;\n }",
"public static int[] insertArray(int[] original, int index, int[] inserted) {\n int[] modified = new int[original.length + inserted.length];\n System.arraycopy(original, 0, modified, 0, index);\n System.arraycopy(inserted, 0, modified, index, inserted.length);\n System.arraycopy(original, index, modified, index + inserted.length, modified.length - index - inserted.length);\n return modified;\n }",
"public static SQLService getInstance() throws Exception {\n if (_instance == null) {\n _instance = new SQLService();\n _instance.startServer();\n\n // default pool size is 20\n // can be overriden by env variable\n int dbPool = 20;\n if (Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE) != null) {\n dbPool = Integer.valueOf(Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE));\n }\n\n // initialize connection pool\n PoolProperties p = new PoolProperties();\n String connectString = \"jdbc:h2:tcp://\" + _instance.databaseHost + \":\" + String.valueOf(_instance.port) + \"/\" +\n _instance.databaseName + \"/proxydb;MULTI_THREADED=true;AUTO_RECONNECT=TRUE;AUTOCOMMIT=ON\";\n p.setUrl(connectString);\n p.setDriverClassName(\"org.h2.Driver\");\n p.setUsername(\"sa\");\n p.setJmxEnabled(true);\n p.setTestWhileIdle(false);\n p.setTestOnBorrow(true);\n p.setValidationQuery(\"SELECT 1\");\n p.setTestOnReturn(false);\n p.setValidationInterval(5000);\n p.setTimeBetweenEvictionRunsMillis(30000);\n p.setMaxActive(dbPool);\n p.setInitialSize(5);\n p.setMaxWait(30000);\n p.setRemoveAbandonedTimeout(60);\n p.setMinEvictableIdleTimeMillis(30000);\n p.setMinIdle(10);\n p.setLogAbandoned(true);\n p.setRemoveAbandoned(true);\n _instance.datasource = new DataSource();\n _instance.datasource.setPoolProperties(p);\n }\n return _instance;\n }",
"private static boolean checkModifiers(Class<? extends AbstractPlugin> pluginClass) {\n int modifiers = pluginClass.getModifiers();\n return !Modifier.isAbstract(modifiers) &&\n !Modifier.isInterface(modifiers) &&\n !Modifier.isPrivate(modifiers);\n }",
"@Override\n\tpublic String getFirst(String headerName) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\treturn headerValues != null ? headerValues.get(0) : null;\n\t}"
] |
Gets constructors with given annotation type
@param annotationType The annotation type to match
@return A set of abstracted constructors with given annotation type. If
the constructors set is empty, initialize it first. Returns an
empty set if there are no matches.
@see org.jboss.weld.annotated.enhanced.EnhancedAnnotatedType#getEnhancedConstructors(Class) | [
"@Override\n public Collection<EnhancedAnnotatedConstructor<T>> getEnhancedConstructors(Class<? extends Annotation> annotationType) {\n Set<EnhancedAnnotatedConstructor<T>> ret = new HashSet<EnhancedAnnotatedConstructor<T>>();\n for (EnhancedAnnotatedConstructor<T> constructor : constructors) {\n if (constructor.isAnnotationPresent(annotationType)) {\n ret.add(constructor);\n }\n }\n return ret;\n }"
] | [
"public static DataPersister lookupForField(Field field) {\n\n\t\t// see if the any of the registered persisters are valid first\n\t\tif (registeredPersisters != null) {\n\t\t\tfor (DataPersister persister : registeredPersisters) {\n\t\t\t\tif (persister.isValidForField(field)) {\n\t\t\t\t\treturn persister;\n\t\t\t\t}\n\t\t\t\t// check the classes instead\n\t\t\t\tfor (Class<?> clazz : persister.getAssociatedClasses()) {\n\t\t\t\t\tif (field.getType() == clazz) {\n\t\t\t\t\t\treturn persister;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// look it up in our built-in map by class\n\t\tDataPersister dataPersister = builtInMap.get(field.getType().getName());\n\t\tif (dataPersister != null) {\n\t\t\treturn dataPersister;\n\t\t}\n\n\t\t/*\n\t\t * Special case for enum types. We can't put this in the registered persisters because we want people to be able\n\t\t * to override it.\n\t\t */\n\t\tif (field.getType().isEnum()) {\n\t\t\treturn DEFAULT_ENUM_PERSISTER;\n\t\t} else {\n\t\t\t/*\n\t\t\t * Serializable classes return null here because we don't want them to be automatically configured for\n\t\t\t * forwards compatibility with future field types that happen to be Serializable.\n\t\t\t */\n\t\t\treturn null;\n\t\t}\n\t}",
"@Override\n protected URL getDefinitionsURL() {\n try {\n URL url = CustomEPSGCodes.class.getResource(CUSTOM_EPSG_CODES_FILE);\n // quickly test url\n try (InputStream stream = url.openStream()) {\n //noinspection ResultOfMethodCallIgnored\n stream.read();\n }\n return url;\n } catch (Throwable e) {\n throw new AssertionError(\"Unable to load /epsg.properties file from root of classpath.\");\n }\n }",
"static Parameter createParameter(final String name, final String value) {\n if (value != null && isQuoted(value)) {\n return new QuotedParameter(name, value);\n }\n return new Parameter(name, value);\n }",
"public static Bounds getSymmetricBounds(int dim, double l, double u) {\n double [] L = new double[dim];\n double [] U = new double[dim];\n for(int i=0; i<dim; i++) {\n L[i] = l;\n U[i] = u;\n }\n return new Bounds(L, U);\n }",
"public AdminClient checkout() {\n if (isClosed.get()) {\n throw new IllegalStateException(\"Pool is closing\");\n }\n\n AdminClient client;\n\n // Try to get one from the Cache.\n while ((client = clientCache.poll()) != null) {\n if (!client.isClusterModified()) {\n return client;\n } else {\n // Cluster is Modified, after the AdminClient is created. Close it\n client.close();\n }\n }\n\n // None is available, create new one.\n return createAdminClient();\n }",
"private void writePredecessors(Task task)\n {\n List<Relation> relations = task.getPredecessors();\n for (Relation mpxj : relations)\n {\n RelationshipType xml = m_factory.createRelationshipType();\n m_project.getRelationship().add(xml);\n\n xml.setLag(getDuration(mpxj.getLag()));\n xml.setObjectId(Integer.valueOf(++m_relationshipObjectID));\n xml.setPredecessorActivityObjectId(mpxj.getTargetTask().getUniqueID());\n xml.setSuccessorActivityObjectId(mpxj.getSourceTask().getUniqueID());\n xml.setPredecessorProjectObjectId(PROJECT_OBJECT_ID);\n xml.setSuccessorProjectObjectId(PROJECT_OBJECT_ID);\n xml.setType(RELATION_TYPE_MAP.get(mpxj.getType()));\n }\n }",
"private static Future<?> spawn(final int priority, final Runnable threadProc) {\n return threadPool.submit(new Runnable() {\n\n @Override\n public void run() {\n Thread current = Thread.currentThread();\n int defaultPriority = current.getPriority();\n\n try {\n current.setPriority(priority);\n\n /*\n * We yield to give the foreground process a chance to run.\n * This also means that the new priority takes effect RIGHT\n * AWAY, not after the next blocking call or quantum\n * timeout.\n */\n Thread.yield();\n\n try {\n threadProc.run();\n } catch (Exception e) {\n logException(TAG, e);\n }\n } finally {\n current.setPriority(defaultPriority);\n }\n\n }\n\n });\n }",
"protected void layoutChild(final int dataIndex) {\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n float offset = mOffset.get(Axis.X);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.X, offset);\n }\n\n offset = mOffset.get(Axis.Y);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Y, offset);\n }\n\n offset = mOffset.get(Axis.Z);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Z, offset);\n }\n }\n }",
"private CoreLabel makeCoreLabel(String line) {\r\n CoreLabel wi = new CoreLabel();\r\n // wi.line = line;\r\n String[] bits = line.split(\"\\\\s+\");\r\n switch (bits.length) {\r\n case 0:\r\n case 1:\r\n wi.setWord(BOUNDARY);\r\n wi.set(AnswerAnnotation.class, OTHER);\r\n break;\r\n case 2:\r\n wi.setWord(bits[0]);\r\n wi.set(AnswerAnnotation.class, bits[1]);\r\n break;\r\n case 3:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(AnswerAnnotation.class, bits[2]);\r\n break;\r\n case 4:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(ChunkAnnotation.class, bits[2]);\r\n wi.set(AnswerAnnotation.class, bits[3]);\r\n break;\r\n case 5:\r\n if (flags.useLemmaAsWord) {\r\n wi.setWord(bits[1]);\r\n } else {\r\n wi.setWord(bits[0]);\r\n }\r\n wi.set(LemmaAnnotation.class, bits[1]);\r\n wi.setTag(bits[2]);\r\n wi.set(ChunkAnnotation.class, bits[3]);\r\n wi.set(AnswerAnnotation.class, bits[4]);\r\n break;\r\n default:\r\n throw new RuntimeIOException(\"Unexpected input (many fields): \" + line);\r\n }\r\n wi.set(OriginalAnswerAnnotation.class, wi.get(AnswerAnnotation.class));\r\n return wi;\r\n }"
] |
This method performs a set of queries to retrieve information
from the an MPP or an MPX file.
@param filename name of the MPX file
@throws Exception on file read error | [
"private static void query(String filename) throws Exception\n {\n ProjectFile mpx = new UniversalProjectReader().read(filename);\n\n listProjectProperties(mpx);\n\n listResources(mpx);\n\n listTasks(mpx);\n\n listAssignments(mpx);\n\n listAssignmentsByTask(mpx);\n\n listAssignmentsByResource(mpx);\n\n listHierarchy(mpx);\n\n listTaskNotes(mpx);\n\n listResourceNotes(mpx);\n\n listRelationships(mpx);\n\n listSlack(mpx);\n\n listCalendars(mpx);\n\n }"
] | [
"public void put(final String key, final Object value) {\n if (TASK_DIRECTORY_KEY.equals(key) && this.values.keySet().contains(TASK_DIRECTORY_KEY)) {\n // ensure that no one overwrites the task directory\n throw new IllegalArgumentException(\"Invalid key: \" + key);\n }\n\n if (value == null) {\n throw new IllegalArgumentException(\n \"A null value was attempted to be put into the values object under key: \" + key);\n }\n this.values.put(key, value);\n }",
"private void addTasks(MpxjTreeNode parentNode, ChildTaskContainer parent)\n {\n for (Task task : parent.getChildTasks())\n {\n final Task t = task;\n MpxjTreeNode childNode = new MpxjTreeNode(task, TASK_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return t.getName();\n }\n };\n parentNode.add(childNode);\n addTasks(childNode, task);\n }\n }",
"public static final void setPosition(UIObject o, Rect pos) {\n Style style = o.getElement().getStyle();\n style.setPropertyPx(\"left\", pos.x);\n style.setPropertyPx(\"top\", pos.y);\n }",
"private double Noise(int x, int y) {\n int n = x + y * 57;\n n = (n << 13) ^ n;\n\n return (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0);\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 }",
"@GET\n @Produces(MediaType.APPLICATION_JSON)\n @Path(\"/graph/{name}/{version}\")\n public Response getModuleGraph(@PathParam(\"name\") final String moduleName,\n @PathParam(\"version\") final String moduleVersion,\n @Context final UriInfo uriInfo){\n\n LOG.info(\"Dependency Checker got a get module graph export request.\");\n\n if(moduleName == null || moduleVersion == null){\n return Response.serverError().status(HttpStatus.NOT_ACCEPTABLE_406).build();\n }\n\n final FiltersHolder filters = new FiltersHolder();\n filters.init(uriInfo.getQueryParameters());\n\n final String moduleId = DbModule.generateID(moduleName, moduleVersion);\n final AbstractGraph moduleGraph = getGraphsHandler(filters).getModuleGraph(moduleId);\n\n return Response.ok(moduleGraph).build();\n }",
"public void applyXMLDSigAsFirstChild (@Nonnull final PrivateKey aPrivateKey,\n @Nonnull final X509Certificate aCertificate,\n @Nonnull final Document aDocument) throws Exception\n {\n ValueEnforcer.notNull (aPrivateKey, \"privateKey\");\n ValueEnforcer.notNull (aCertificate, \"certificate\");\n ValueEnforcer.notNull (aDocument, \"document\");\n ValueEnforcer.notNull (aDocument.getDocumentElement (), \"Document is missing a document element\");\n if (aDocument.getDocumentElement ().getChildNodes ().getLength () == 0)\n throw new IllegalArgumentException (\"Document element has no children!\");\n\n // Check that the document does not contain another Signature element\n final NodeList aNodeList = aDocument.getElementsByTagNameNS (XMLSignature.XMLNS, XMLDSigSetup.ELEMENT_SIGNATURE);\n if (aNodeList.getLength () > 0)\n throw new IllegalArgumentException (\"Document already contains an XMLDSig Signature element!\");\n\n // Create the XMLSignature, but don't sign it yet.\n final XMLSignature aXMLSignature = createXMLSignature (aCertificate);\n\n // Create a DOMSignContext and specify the RSA PrivateKey and\n // location of the resulting XMLSignature's parent element.\n // -> The signature is always the first child element of the document\n // element for ebInterface\n final DOMSignContext aDOMSignContext = new DOMSignContext (aPrivateKey,\n aDocument.getDocumentElement (),\n aDocument.getDocumentElement ().getFirstChild ());\n\n // The namespace prefix to be used for the signed XML\n aDOMSignContext.setDefaultNamespacePrefix (DEFAULT_NS_PREFIX);\n\n // Marshal, generate, and sign the enveloped signature.\n aXMLSignature.sign (aDOMSignContext);\n }",
"public void add(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n boolean matchFilter = declarationFilter.matches(declaration.getMetadata());\n declarations.put(declarationSRef, matchFilter);\n }",
"public Weld addPackage(boolean scanRecursively, Class<?> packageClass) {\n packages.add(new PackInfo(packageClass, scanRecursively));\n return this;\n }"
] |
used by Error template | [
"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 }"
] | [
"private void addAllWithFilter(Map<String, String> toMap, Map<String, String> fromMap, IncludeExcludePatterns pattern) {\n for (Object o : fromMap.entrySet()) {\n Map.Entry entry = (Map.Entry) o;\n String key = (String) entry.getKey();\n if (PatternMatcher.pathConflicts(key, pattern)) {\n continue;\n }\n toMap.put(key, (String) entry.getValue());\n }\n }",
"public <L extends Listener> void popEvent(Event<?, L> expected) {\n synchronized (this.stack) {\n final Event<?, ?> actual = this.stack.pop();\n if (actual != expected) {\n throw new IllegalStateException(String.format(\n \"Unbalanced pop: expected '%s' but encountered '%s'\",\n expected.getListenerClass(), actual));\n }\n }\n }",
"private void readPredecessor(Task currTask, Project.Tasks.Task.PredecessorLink link)\n {\n BigInteger uid = link.getPredecessorUID();\n if (uid != null)\n {\n Task prevTask = m_projectFile.getTaskByUniqueID(Integer.valueOf(uid.intValue()));\n if (prevTask != null)\n {\n RelationType type;\n if (link.getType() != null)\n {\n type = RelationType.getInstance(link.getType().intValue());\n }\n else\n {\n type = RelationType.FINISH_START;\n }\n\n TimeUnit lagUnits = DatatypeConverter.parseDurationTimeUnits(link.getLagFormat());\n\n Duration lagDuration;\n int lag = NumberHelper.getInt(link.getLinkLag());\n if (lag == 0)\n {\n lagDuration = Duration.getInstance(0, lagUnits);\n }\n else\n {\n if (lagUnits == TimeUnit.PERCENT || lagUnits == TimeUnit.ELAPSED_PERCENT)\n {\n lagDuration = Duration.getInstance(lag, lagUnits);\n }\n else\n {\n lagDuration = Duration.convertUnits(lag / 10.0, TimeUnit.MINUTES, lagUnits, m_projectFile.getProjectProperties());\n }\n }\n\n Relation relation = currTask.addPredecessor(prevTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }",
"private static ClosableIterator<Tuple> doDistinct(final MongoDBQueryDescriptor queryDescriptor, final MongoCollection<Document> collection) {\n\t\tDistinctIterable<?> distinctFieldValues = collection.distinct( queryDescriptor.getDistinctFieldName(), queryDescriptor.getCriteria(), String.class );\n\t\tCollation collation = getCollation( queryDescriptor.getOptions() );\n\n\t\tdistinctFieldValues = collation != null ? distinctFieldValues.collation( collation ) : distinctFieldValues;\n\n\t\tMongoCursor<?> cursor = distinctFieldValues.iterator();\n\t\tList<Object> documents = new ArrayList<>();\n\t\twhile ( cursor.hasNext() ) {\n\t\t\tdocuments.add( cursor.next() );\n\t\t}\n\t\tMapTupleSnapshot snapshot = new MapTupleSnapshot( Collections.<String, Object>singletonMap( \"n\", documents ) );\n\t\treturn CollectionHelper.newClosableIterator( Collections.singletonList( new Tuple( snapshot, SnapshotType.UNKNOWN ) ) );\n\t}",
"public Clob toClob(String stringName, Connection sqlConnection) {\n Clob clobName = null;\n try {\n clobName = sqlConnection.createClob();\n clobName.setString(1, stringName);\n } catch (SQLException e) {\n // TODO Auto-generated catch block\n logger.info(\"Unable to create clob object\");\n e.printStackTrace();\n }\n return clobName;\n }",
"public static int ptb2Text(Reader ptbText, Writer w) throws IOException {\r\n int numTokens = 0;\r\n PTB2TextLexer lexer = new PTB2TextLexer(ptbText);\r\n for (String token; (token = lexer.next()) != null; ) {\r\n numTokens++;\r\n w.write(token);\r\n }\r\n return numTokens;\r\n }",
"private static void waitUntilFinished(FluoConfiguration config) {\n try (Environment env = new Environment(config)) {\n List<TableRange> ranges = getRanges(env);\n\n outer: while (true) {\n long ts1 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n for (TableRange range : ranges) {\n boolean sawNotifications = waitTillNoNotifications(env, range);\n if (sawNotifications) {\n ranges = getRanges(env);\n // This range had notifications. Processing those notifications may have created\n // notifications in previously scanned ranges, so start over.\n continue outer;\n }\n }\n long ts2 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n\n // Check to ensure the Oracle issued no timestamps during the scan for notifications.\n if (ts2 - ts1 == 1) {\n break;\n }\n }\n } catch (Exception e) {\n log.error(\"An exception was thrown -\", e);\n System.exit(-1);\n }\n }",
"public static final UUID parseUUID(String value)\n {\n return value == null || value.isEmpty() ? null : UUID.fromString(value);\n }",
"public static base_response add(nitro_service client, policydataset resource) throws Exception {\n\t\tpolicydataset addresource = new policydataset();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.indextype = resource.indextype;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Calculates the rho of a digital option under a Black-Scholes model
@param initialStockValue The initial value of the underlying, i.e., the spot.
@param riskFreeRate The risk free rate of the bank account numerarie.
@param volatility The Black-Scholes volatility.
@param optionMaturity The option maturity T.
@param optionStrike The option strike.
@return The rho of the digital option | [
"public static double blackScholesDigitalOptionRho(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse if(optionStrike <= 0.0) {\n\t\t\tdouble rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity);\n\n\t\t\treturn rho;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate rho\n\t\t\tdouble dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\n\t\t\tdouble rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus)\n\t\t\t\t\t+ Math.sqrt(optionMaturity)/volatility * Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI);\n\n\t\t\treturn rho;\n\t\t}\n\t}"
] | [
"private String getPropertyName(Method method)\n {\n String result = method.getName();\n if (result.startsWith(\"get\"))\n {\n result = result.substring(3);\n }\n return result;\n }",
"protected void getBatch(int batchSize){\r\n\r\n// if (numCalls == 0) {\r\n// for (int i = 0; i < 1538*\\15; i++) {\r\n// randGenerator.nextInt(this.dataDimension());\r\n// }\r\n// }\r\n// numCalls++;\r\n\r\n if (thisBatch == null || thisBatch.length != batchSize){\r\n thisBatch = new int[batchSize];\r\n }\r\n\r\n //-----------------------------\r\n //RANDOM WITH REPLACEMENT\r\n //-----------------------------\r\n if (sampleMethod.equals(SamplingMethod.RandomWithReplacement)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = randGenerator.nextInt(this.dataDimension()); //Just generate a random index\r\n// System.err.println(\"numCalls = \"+(numCalls++));\r\n }\r\n //-----------------------------\r\n //ORDERED\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.Ordered)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = (curElement + i) % this.dataDimension() ; //Take the next batchSize points in order\r\n }\r\n curElement = (curElement + batchSize) % this.dataDimension(); //watch out for overflow\r\n\r\n //-----------------------------\r\n //RANDOM WITHOUT REPLACEMENT\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.RandomWithoutReplacement)){\r\n //Declare the indices array if needed.\r\n if (allIndices == null || allIndices.size()!= this.dataDimension()){\r\n\r\n allIndices = new ArrayList<Integer>();\r\n for(int i=0;i<this.dataDimension();i++){\r\n allIndices.add(i);\r\n }\r\n Collections.shuffle(allIndices,randGenerator);\r\n }\r\n\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = allIndices.get((curElement + i) % allIndices.size()); //Grab the next batchSize indices\r\n }\r\n\r\n if (curElement + batchSize > this.dataDimension()){\r\n Collections.shuffle(Arrays.asList(allIndices),randGenerator); //Shuffle if we got to the end of the list\r\n }\r\n\r\n //watch out for overflow\r\n curElement = (curElement + batchSize) % allIndices.size(); //Rollover\r\n\r\n\r\n }else{\r\n System.err.println(\"NO SAMPLING METHOD SELECTED\");\r\n System.exit(1);\r\n }\r\n\r\n\r\n }",
"private static void checkPreconditions(final Map<Object, Object> mapping) {\n\t\tif( mapping == null ) {\n\t\t\tthrow new NullPointerException(\"mapping should not be null\");\n\t\t} else if( mapping.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"mapping should not be empty\");\n\t\t}\n\t}",
"public <T> DiffNode compare(final T working, final T base)\n\t{\n\t\tdispatcher.resetInstanceMemory();\n\t\ttry\n\t\t{\n\t\t\treturn dispatcher.dispatch(DiffNode.ROOT, Instances.of(working, base), RootAccessor.getInstance());\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tdispatcher.clearInstanceMemory();\n\t\t}\n\t}",
"public Client setFriendlyName(int profileId, String clientUUID, String friendlyName) throws Exception {\n // first see if this friendlyName is already in use\n Client client = this.findClientFromFriendlyName(profileId, friendlyName);\n if (client != null && !client.getUUID().equals(clientUUID)) {\n throw new Exception(\"Friendly name already in use\");\n }\n\n PreparedStatement statement = null;\n int rowsAffected = 0;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_CLIENT +\n \" SET \" + Constants.CLIENT_FRIENDLY_NAME + \" = ?\" +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = ?\" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \" = ?\"\n );\n statement.setString(1, friendlyName);\n statement.setString(2, clientUUID);\n statement.setInt(3, profileId);\n\n rowsAffected = statement.executeUpdate();\n } catch (Exception e) {\n\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (rowsAffected == 0) {\n return null;\n }\n return this.findClient(clientUUID, profileId);\n }",
"private static String wordShapeChris2Long(String s, boolean omitIfInBoundary, int len, Collection<String> knownLCWords) {\r\n final char[] beginChars = new char[BOUNDARY_SIZE];\r\n final char[] endChars = new char[BOUNDARY_SIZE];\r\n int beginUpto = 0;\r\n int endUpto = 0;\r\n final Set<Character> seenSet = new TreeSet<Character>(); // TreeSet guarantees stable ordering; has no size parameter\r\n\r\n boolean nonLetters = false;\r\n\r\n for (int i = 0; i < len; i++) {\r\n int iIncr = 0;\r\n char c = s.charAt(i);\r\n char m = c;\r\n if (Character.isDigit(c)) {\r\n m = 'd';\r\n } else if (Character.isLowerCase(c)) {\r\n m = 'x';\r\n } else if (Character.isUpperCase(c) || Character.isTitleCase(c)) {\r\n m = 'X';\r\n }\r\n for (String gr : greek) {\r\n if (s.startsWith(gr, i)) {\r\n m = 'g';\r\n //System.out.println(s + \" :: \" + s.substring(i+1));\r\n iIncr = gr.length() - 1;\r\n break;\r\n }\r\n }\r\n if (m != 'x' && m != 'X') {\r\n nonLetters = true;\r\n }\r\n\r\n if (i < BOUNDARY_SIZE) {\r\n beginChars[beginUpto++] = m;\r\n } else if (i < len - BOUNDARY_SIZE) {\r\n seenSet.add(Character.valueOf(m));\r\n } else {\r\n endChars[endUpto++] = m;\r\n }\r\n i += iIncr;\r\n // System.out.println(\"Position skips to \" + i);\r\n }\r\n\r\n // Calculate size. This may be an upperbound, but is often correct\r\n int sbSize = beginUpto + endUpto + seenSet.size();\r\n if (knownLCWords != null) { sbSize++; }\r\n final StringBuilder sb = new StringBuilder(sbSize);\r\n // put in the beginning chars\r\n sb.append(beginChars, 0, beginUpto);\r\n // put in the stored ones sorted\r\n if (omitIfInBoundary) {\r\n for (Character chr : seenSet) {\r\n char ch = chr.charValue();\r\n boolean insert = true;\r\n for (int i = 0; i < beginUpto; i++) {\r\n if (beginChars[i] == ch) {\r\n insert = false;\r\n break;\r\n }\r\n }\r\n for (int i = 0; i < endUpto; i++) {\r\n if (endChars[i] == ch) {\r\n insert = false;\r\n break;\r\n }\r\n }\r\n if (insert) {\r\n sb.append(ch);\r\n }\r\n }\r\n } else {\r\n for (Character chr : seenSet) {\r\n sb.append(chr.charValue());\r\n }\r\n }\r\n // and add end ones\r\n sb.append(endChars, 0, endUpto);\r\n\r\n if (knownLCWords != null) {\r\n if (!nonLetters && knownLCWords.contains(s.toLowerCase())) {\r\n sb.append('k');\r\n }\r\n }\r\n // System.out.println(s + \" became \" + sb);\r\n return sb.toString();\r\n }",
"public void remove(Identity oid)\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Remove object \" + oid);\r\n sessionCache.remove(oid);\r\n getApplicationCache().remove(oid);\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 List<CRFCliqueTree> getCliqueTrees(String filename, DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n List<CRFCliqueTree> cts = new ArrayList<CRFCliqueTree>();\r\n ObjectBank<List<IN>> docs = makeObjectBankFromFile(filename, readerAndWriter);\r\n for (List<IN> doc : docs) {\r\n cts.add(getCliqueTree(doc));\r\n }\r\n\r\n return cts;\r\n }"
] |
Delete the first n items from the list
@param newStart the logsegment who's index smaller than newStart will be deleted.
@return the deleted segment | [
"public List<LogSegment> trunc(int newStart) {\n if (newStart < 0) {\n throw new IllegalArgumentException(\"Starting index must be positive.\");\n }\n while (true) {\n List<LogSegment> curr = contents.get();\n int newLength = Math.max(curr.size() - newStart, 0);\n List<LogSegment> updatedList = new ArrayList<LogSegment>(curr.subList(Math.min(newStart, curr.size() - 1),\n curr.size()));\n if (contents.compareAndSet(curr, updatedList)) {\n return curr.subList(0, curr.size() - newLength);\n }\n }\n }"
] | [
"public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }",
"private <T> T readIntoBean(final T bean, final String[] nameMapping, final CellProcessor[] processors)\n\t\tthrows IOException {\n\t\t\n\t\tif( readRow() ) {\n\t\t\tif( nameMapping.length != length() ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\n\t\t\t\t\t\"the nameMapping array and the number of columns read \"\n\t\t\t\t\t\t+ \"should be the same size (nameMapping length = %d, columns = %d)\", nameMapping.length,\n\t\t\t\t\tlength()));\n\t\t\t}\n\t\t\t\n\t\t\tif( processors == null ) {\n\t\t\t\tprocessedColumns.clear();\n\t\t\t\tprocessedColumns.addAll(getColumns());\n\t\t\t} else {\n\t\t\t\texecuteProcessors(processedColumns, processors);\n\t\t\t}\n\t\t\t\n\t\t\treturn populateBean(bean, nameMapping);\n\t\t}\n\t\t\n\t\treturn null; // EOF\n\t}",
"private float colorToAngle(int color) {\n\t\tfloat[] colors = new float[3];\n\t\tColor.colorToHSV(color, colors);\n\t\t\n\t\treturn (float) Math.toRadians(-colors[0]);\n\t}",
"public SwaptionDataLattice append(SwaptionDataLattice other, AnalyticModel model) {\r\n\r\n\t\tSwaptionDataLattice combined = new SwaptionDataLattice(referenceDate, quotingConvention, displacement,\r\n\t\t\t\tforwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule);\r\n\t\tcombined.entryMap.putAll(entryMap);\r\n\r\n\t\tif(quotingConvention == other.quotingConvention && displacement == other.displacement) {\r\n\t\t\tcombined.entryMap.putAll(other.entryMap);\r\n\t\t} else {\r\n\t\t\tSwaptionDataLattice converted = other.convertLattice(quotingConvention, displacement, model);\r\n\t\t\tcombined.entryMap.putAll(converted.entryMap);\r\n\t\t}\r\n\r\n\t\treturn combined;\r\n\t}",
"private void updateWorkTimeUnit(FastTrackColumn column)\n {\n if (m_workTimeUnit == null && isWorkColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_workTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }",
"public Set<String> getAttributeNames() {\n if (attributes == null) {\n return Collections.emptySet();\n } else {\n return Collections.unmodifiableSet(attributes.keySet());\n }\n }",
"private void populateTask(Row row, Task task)\n {\n task.setUniqueID(row.getInteger(\"Z_PK\"));\n task.setName(row.getString(\"ZTITLE\"));\n task.setPriority(Priority.getInstance(row.getInt(\"ZPRIORITY\")));\n task.setMilestone(row.getBoolean(\"ZISMILESTONE\"));\n task.setActualFinish(row.getTimestamp(\"ZGIVENACTUALENDDATE_\"));\n task.setActualStart(row.getTimestamp(\"ZGIVENACTUALSTARTDATE_\"));\n task.setNotes(row.getString(\"ZOBJECTDESCRIPTION\"));\n task.setDuration(row.getDuration(\"ZGIVENDURATION_\"));\n task.setOvertimeWork(row.getWork(\"ZGIVENWORKOVERTIME_\"));\n task.setWork(row.getWork(\"ZGIVENWORK_\"));\n task.setLevelingDelay(row.getDuration(\"ZLEVELINGDELAY_\"));\n task.setActualOvertimeWork(row.getWork(\"ZGIVENACTUALWORKOVERTIME_\"));\n task.setActualWork(row.getWork(\"ZGIVENACTUALWORK_\"));\n task.setRemainingWork(row.getWork(\"ZGIVENACTUALWORK_\"));\n task.setGUID(row.getUUID(\"ZUNIQUEID\"));\n\n Integer calendarID = row.getInteger(\"ZGIVENCALENDAR\");\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n if (calendar != null)\n {\n task.setCalendar(calendar);\n }\n }\n\n populateConstraints(row, task);\n\n // Percent complete is calculated bottom up from assignments and actual work vs. planned work\n\n m_eventManager.fireTaskReadEvent(task);\n }",
"protected static void error(\n final HttpServletResponse httpServletResponse, final String message, final HttpStatus code) {\n try {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(code.value());\n setNoCache(httpServletResponse);\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n out.println(message);\n }\n\n LOGGER.error(\"Error while processing request: {}\", message);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }",
"protected void initializeJdbcConnection(Connection con, JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n try\r\n {\r\n PlatformFactory.getPlatformFor(jcd).initializeJdbcConnection(jcd, con);\r\n }\r\n catch (PlatformException e)\r\n {\r\n throw new LookupException(\"Platform dependent initialization of connection failed\", e);\r\n }\r\n }"
] |
Performs a standard bidiagonal decomposition just on the outer blocks of the provided matrix
@param blockLength
@param A
@param gammasU | [
"public static boolean bidiagOuterBlocks( final int blockLength ,\n final DSubmatrixD1 A ,\n final double gammasU[],\n final double gammasV[])\n {\n// System.out.println(\"---------- Orig\");\n// A.original.print();\n\n int width = Math.min(blockLength,A.col1-A.col0);\n int height = Math.min(blockLength,A.row1-A.row0);\n\n int min = Math.min(width,height);\n\n for( int i = 0; i < min; i++ ) {\n //--- Apply reflector to the column\n\n // compute the householder vector\n if (!computeHouseHolderCol(blockLength, A, gammasU, i))\n return false;\n\n // apply to rest of the columns in the column block\n rank1UpdateMultR_Col(blockLength,A,i,gammasU[A.col0+i]);\n\n // apply to the top row block\n rank1UpdateMultR_TopRow(blockLength,A,i,gammasU[A.col0+i]);\n\n System.out.println(\"After column stuff\");\n A.original.print();\n\n //-- Apply reflector to the row\n if(!computeHouseHolderRow(blockLength,A,gammasV,i))\n return false;\n \n // apply to rest of the rows in the row block\n rank1UpdateMultL_Row(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After update row\");\n A.original.print();\n\n // apply to the left column block\n // TODO THIS WON'T WORK!!!!!!!!!!!!!\n // Needs the whole matrix to have been updated by the left reflector to compute the correct solution\n// rank1UpdateMultL_LeftCol(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After row stuff\");\n A.original.print();\n }\n\n return true;\n }"
] | [
"public void setPath(int pathId, String path) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_ACTUAL_PATH + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, path);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public void deploySchema(String generatedProtobufName, RemoteCache<String, String> protobufCache, SchemaCapture schemaCapture, SchemaOverride schemaOverrideService,\n\t\t\tURL schemaOverrideResource) {\n\t\t// user defined schema\n\t\tif ( schemaOverrideService != null || schemaOverrideResource != null ) {\n\t\t\tcachedSchema = new SchemaValidator( this, schemaOverrideService, schemaOverrideResource, generatedProtobufName ).provideSchema();\n\t\t}\n\n\t\t// or generate them\n\t\tgenerateProtoschema();\n\n\t\ttry {\n\t\t\tprotobufCache.put( generatedProtobufName, cachedSchema );\n\t\t\tString errors = protobufCache.get( generatedProtobufName + \".errors\" );\n\t\t\tif ( errors != null ) {\n\t\t\t\tthrow LOG.errorAtSchemaDeploy( generatedProtobufName, errors );\n\t\t\t}\n\t\t\tLOG.successfulSchemaDeploy( generatedProtobufName );\n\t\t}\n\t\tcatch (HotRodClientException hrce) {\n\t\t\tthrow LOG.errorAtSchemaDeploy( generatedProtobufName, hrce );\n\t\t}\n\t\tif ( schemaCapture != null ) {\n\t\t\tschemaCapture.put( generatedProtobufName, cachedSchema );\n\t\t}\n\t}",
"private void updateWorkTimeUnit(FastTrackColumn column)\n {\n if (m_workTimeUnit == null && isWorkColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_workTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }",
"public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) {\n return getSharedItem(api, sharedLink, null);\n }",
"Map<UUID, UUID> getActivityCodes(Activity activity)\n {\n Map<UUID, UUID> map = m_activityCodeCache.get(activity);\n if (map == null)\n {\n map = new HashMap<UUID, UUID>();\n m_activityCodeCache.put(activity, map);\n for (CodeAssignment ca : activity.getCodeAssignment())\n {\n UUID code = getUUID(ca.getCodeUuid(), ca.getCode());\n UUID value = getUUID(ca.getValueUuid(), ca.getValue());\n map.put(code, value);\n }\n }\n return map;\n }",
"private static String wordShapeChris4(String s, boolean omitIfInBoundary, Collection<String> knownLCWords) {\r\n int len = s.length();\r\n if (len <= BOUNDARY_SIZE * 2) {\r\n return wordShapeChris4Short(s, len, knownLCWords);\r\n } else {\r\n return wordShapeChris4Long(s, omitIfInBoundary, len, knownLCWords);\r\n }\r\n }",
"public void credentialsMigration(T overrider, Class overriderClass) {\n try {\n deployerMigration(overrider, overriderClass);\n resolverMigration(overrider, overriderClass);\n } catch (NoSuchFieldException | IllegalAccessException | IOException e) {\n converterErrors.add(getConversionErrorMessage(overrider, e));\n }\n }",
"public static sslcertlink[] get(nitro_service service) throws Exception{\n\t\tsslcertlink obj = new sslcertlink();\n\t\tsslcertlink[] response = (sslcertlink[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void writeAttributeTypes(String name, FieldType[] types) throws IOException\n {\n m_writer.writeStartObject(name);\n for (FieldType field : types)\n {\n m_writer.writeNameValuePair(field.name().toLowerCase(), field.getDataType().getValue());\n }\n m_writer.writeEndObject();\n }"
] |
Set default interval for sending events to monitoring service. DefaultInterval will be used by
scheduler.
@param defaultInterval the new default interval | [
"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 final static void appendCode(final StringBuilder out, final String in, final int start, final int end)\n {\n for (int i = start; i < end; i++)\n {\n final char c;\n switch (c = in.charAt(i))\n {\n case '&':\n out.append(\"&\");\n break;\n case '<':\n out.append(\"<\");\n break;\n case '>':\n out.append(\">\");\n break;\n default:\n out.append(c);\n break;\n }\n }\n }",
"protected void prepForWrite(SelectionKey selectionKey) {\n if(logger.isTraceEnabled())\n traceInputBufferState(\"About to clear read buffer\");\n\n if(requestHandlerFactory.shareReadWriteBuffer() == false) {\n inputStream.clear();\n }\n\n if(logger.isTraceEnabled())\n traceInputBufferState(\"Cleared read buffer\");\n\n outputStream.getBuffer().flip();\n selectionKey.interestOps(SelectionKey.OP_WRITE);\n }",
"private ArrayList<RunListener> instantiateRunListeners() throws Exception {\n ArrayList<RunListener> instances = new ArrayList<>();\n\n if (runListeners != null) {\n for (String className : Arrays.asList(runListeners.split(\",\"))) {\n instances.add((RunListener) this.instantiate(className).newInstance());\n }\n }\n\n return instances;\n }",
"public static CmsUUID readId(JSONObject obj, String key) {\n\n String strValue = obj.optString(key);\n if (!CmsUUID.isValidUUID(strValue)) {\n return null;\n }\n return new CmsUUID(strValue);\n }",
"public static void waitForDomain(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForDomain(null, client, startupTimeout);\n }",
"protected void init(EnhancedAnnotation<T> annotatedAnnotation) {\n initType(annotatedAnnotation);\n initValid(annotatedAnnotation);\n check(annotatedAnnotation);\n }",
"public static String capitalize( String text ) {\n if( text == null || text.isEmpty() ) {\n return text;\n }\n return text.substring( 0, 1 ).toUpperCase().concat( text.substring( 1, text.length() ) );\n }",
"public void awaitStartupCompletion() {\n try {\n Object obj = startedStatusQueue.take();\n if(obj instanceof Throwable)\n throw new VoldemortException((Throwable) obj);\n } catch(InterruptedException e) {\n // this is okay, if we are interrupted we can stop waiting\n }\n }",
"private void populateDefaultData(FieldItem[] defaultData)\n {\n for (FieldItem item : defaultData)\n {\n m_map.put(item.getType(), item);\n }\n }"
] |
Execute the physical query and initialize the various entities and collections
@param session the session
@param qp the query parameters
@param ogmLoadingContext the loading context
@param returnProxies when {@code true}, get an existing proxy for each collection element (if there is one)
@return the result of the query | [
"private List<Object> doQuery(\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tQueryParameters qp,\n\t\t\tOgmLoadingContext ogmLoadingContext,\n\t\t\tboolean returnProxies) {\n\t\t//TODO support lock timeout\n\n\t\tint entitySpan = entityPersisters.length;\n\t\tfinal List<Object> hydratedObjects = entitySpan == 0 ? null : new ArrayList<Object>( entitySpan * 10 );\n\t\t//TODO yuk! Is there a cleaner way to access the id?\n\t\tfinal Serializable id;\n\t\t// see if we use batching first\n\t\t// then look for direct id\n\t\t// then for a tuple based result set we could extract the id\n\t\t// otherwise that's a collection so we use the collection key\n\t\tboolean loadSeveralIds = loadSeveralIds( qp );\n\t\tboolean isCollectionLoader;\n\t\tif ( loadSeveralIds ) {\n\t\t\t// need to be set to null otherwise the optionalId has precedence\n\t\t\t// and is used for all tuples regardless of their actual ids\n\t\t\tid = null;\n\t\t\tisCollectionLoader = false;\n\t\t}\n\t\telse if ( qp.getOptionalId() != null ) {\n\t\t\tid = qp.getOptionalId();\n\t\t\tisCollectionLoader = false;\n\t\t}\n\t\telse if ( ogmLoadingContext.hasResultSet() ) {\n\t\t\t// extract the ids from the tuples directly\n\t\t\tid = null;\n\t\t\tisCollectionLoader = false;\n\t\t}\n\t\telse {\n\t\t\tid = qp.getCollectionKeys()[0];\n\t\t\tisCollectionLoader = true;\n\t\t}\n\t\tTupleAsMapResultSet resultset = getResultSet( id, qp, ogmLoadingContext, session );\n\n\t\t//Todo implement lockmode\n\t\t//final LockMode[] lockModesArray = getLockModes( queryParameters.getLockOptions() );\n\t\t//FIXME should we use subselects as it's closer to this process??\n\n\t\t//TODO is resultset a good marker, or should it be an ad-hoc marker??\n\t\t//It likely all depends on what resultset ends up being\n\t\thandleEmptyCollections( qp.getCollectionKeys(), resultset, session );\n\n\t\tfinal org.hibernate.engine.spi.EntityKey[] keys = new org.hibernate.engine.spi.EntityKey[entitySpan];\n\n\t\t//for each element in resultset\n\t\t//TODO should we collect List<Object> as result? Not necessary today\n\t\tObject result = null;\n\t\tList<Object> results = new ArrayList<Object>();\n\n\t\tif ( isCollectionLoader ) {\n\t\t\tpreLoadBatchFetchingQueue( session, resultset );\n\n\t\t}\n\n\t\ttry {\n\t\t\twhile ( resultset.next() ) {\n\t\t\t\tresult = getRowFromResultSet(\n\t\t\t\t\t\tresultset,\n\t\t\t\t\t\tsession,\n\t\t\t\t\t\tqp,\n\t\t\t\t\t\togmLoadingContext,\n\t\t\t\t\t\t//lockmodeArray,\n\t\t\t\t\t\tid,\n\t\t\t\t\t\thydratedObjects,\n\t\t\t\t\t\tkeys,\n\t\t\t\t\t\treturnProxies );\n\t\t\t\tresults.add( result );\n\t\t\t}\n\t\t\t//TODO collect subselect result key\n\t\t}\n\t\tcatch ( SQLException e ) {\n\t\t\t//never happens this is not a regular ResultSet\n\t\t}\n\n\t\t//end of for each element in resultset\n\n\t\tinitializeEntitiesAndCollections( hydratedObjects, resultset, session, qp.isReadOnly( session ) );\n\t\t//TODO create subselects\n\t\treturn results;\n\t}"
] | [
"static final TimeBasedRollStrategy findRollStrategy(\n final AppenderRollingProperties properties) {\n if (properties.getDatePattern() == null) {\n LogLog.error(\"null date pattern\");\n return ROLL_ERROR;\n }\n // Strip out quoted sections so that we may safely scan the undecorated\n // pattern for characters that are meaningful to SimpleDateFormat.\n final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(\n properties.getDatePatternLocale());\n final String undecoratedDatePattern = localizedDateFormatPatternHelper\n .excludeQuoted(properties.getDatePattern());\n if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MINUTE;\n }\n if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HOUR;\n }\n if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HALF_DAY;\n }\n if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_DAY;\n }\n if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_WEEK;\n }\n if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MONTH;\n }\n return ROLL_ERROR;\n }",
"public static IndexedContainer getPrincipalContainer(\n CmsObject cms,\n List<? extends I_CmsPrincipal> list,\n String captionID,\n String descID,\n String iconID,\n String ouID,\n String icon,\n List<FontIcon> iconList) {\n\n IndexedContainer res = new IndexedContainer();\n\n res.addContainerProperty(captionID, String.class, \"\");\n res.addContainerProperty(ouID, String.class, \"\");\n res.addContainerProperty(iconID, FontIcon.class, new CmsCssIcon(icon));\n if (descID != null) {\n res.addContainerProperty(descID, String.class, \"\");\n }\n\n for (I_CmsPrincipal group : list) {\n\n Item item = res.addItem(group);\n item.getItemProperty(captionID).setValue(group.getSimpleName());\n item.getItemProperty(ouID).setValue(group.getOuFqn());\n if (descID != null) {\n item.getItemProperty(descID).setValue(group.getDescription(A_CmsUI.get().getLocale()));\n }\n }\n\n for (int i = 0; i < iconList.size(); i++) {\n res.getItem(res.getIdByIndex(i)).getItemProperty(iconID).setValue(iconList.get(i));\n }\n\n return res;\n }",
"public void send(ProducerPoolData<V> ppd) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"send message: \" + ppd);\n }\n if (sync) {\n Message[] messages = new Message[ppd.data.size()];\n int index = 0;\n for (V v : ppd.data) {\n messages[index] = serializer.toMessage(v);\n index++;\n }\n ByteBufferMessageSet bbms = new ByteBufferMessageSet(config.getCompressionCodec(), messages);\n ProducerRequest request = new ProducerRequest(ppd.topic, ppd.partition.partId, bbms);\n SyncProducer producer = syncProducers.get(ppd.partition.brokerId);\n if (producer == null) {\n throw new UnavailableProducerException(\"Producer pool has not been initialized correctly. \" + \"Sync Producer for broker \"\n + ppd.partition.brokerId + \" does not exist in the pool\");\n }\n producer.send(request.topic, request.partition, request.messages);\n } else {\n AsyncProducer<V> asyncProducer = asyncProducers.get(ppd.partition.brokerId);\n for (V v : ppd.data) {\n asyncProducer.send(ppd.topic, v, ppd.partition.partId);\n }\n }\n }",
"private void writeActivity(Task mpxj)\n {\n ActivityType xml = m_factory.createActivityType();\n m_project.getActivity().add(xml);\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setActualStartDate(mpxj.getActualStart());\n xml.setActualFinishDate(mpxj.getActualFinish());\n xml.setAtCompletionDuration(getDuration(mpxj.getDuration()));\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getCalendar()));\n xml.setDurationPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setDurationType(DURATION_TYPE_MAP.get(mpxj.getType()));\n xml.setFinishDate(mpxj.getFinish());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(getActivityID(mpxj));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setPercentComplete(getPercentage(mpxj.getPercentageComplete()));\n xml.setPercentCompleteType(\"Duration\");\n xml.setPrimaryConstraintType(CONSTRAINT_TYPE_MAP.get(mpxj.getConstraintType()));\n xml.setPrimaryConstraintDate(mpxj.getConstraintDate());\n xml.setPlannedDuration(getDuration(mpxj.getDuration()));\n xml.setPlannedFinishDate(mpxj.getFinish());\n xml.setPlannedStartDate(mpxj.getStart());\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setRemainingDuration(getDuration(mpxj.getRemainingDuration()));\n xml.setRemainingEarlyFinishDate(mpxj.getEarlyFinish());\n xml.setRemainingEarlyStartDate(mpxj.getResume());\n xml.setRemainingLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborCost(NumberHelper.DOUBLE_ZERO);\n xml.setRemainingNonLaborUnits(NumberHelper.DOUBLE_ZERO);\n xml.setStartDate(mpxj.getStart());\n xml.setStatus(getActivityStatus(mpxj));\n xml.setType(extractAndConvertTaskType(mpxj));\n xml.setWBSObjectId(parentObjectID);\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.TASK, mpxj));\n\n writePredecessors(mpxj);\n }",
"public static final Rate parseRate(BigDecimal value)\n {\n Rate result = null;\n\n if (value != null)\n {\n result = new Rate(value, TimeUnit.HOURS);\n }\n\n return (result);\n }",
"private CmsTemplateMapperConfiguration getConfiguration(final CmsObject cms) {\n\n if (!m_enabled) {\n return CmsTemplateMapperConfiguration.EMPTY_CONFIG;\n }\n\n if (m_configPath == null) {\n m_configPath = OpenCms.getSystemInfo().getConfigFilePath(cms, \"template-mapping.xml\");\n }\n\n return (CmsTemplateMapperConfiguration)(CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().loadVfsObject(\n cms,\n m_configPath,\n new Transformer() {\n\n @Override\n public Object transform(Object input) {\n\n try {\n CmsFile file = cms.readFile(m_configPath, CmsResourceFilter.IGNORE_EXPIRATION);\n SAXReader saxBuilder = new SAXReader();\n try (ByteArrayInputStream stream = new ByteArrayInputStream(file.getContents())) {\n Document document = saxBuilder.read(stream);\n CmsTemplateMapperConfiguration config = new CmsTemplateMapperConfiguration(cms, document);\n return config;\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return new CmsTemplateMapperConfiguration(); // empty configuration, does not do anything\n }\n\n }\n }));\n }",
"public String putProperty(String key,\n String value) {\n return this.getProperties().put(key,\n value);\n }",
"public String makeReport(String name, String report) {\n long increment = Long.valueOf(report);\n long currentLineCount = globalLineCounter.addAndGet(increment);\n\n if (currentLineCount >= maxScenarios) {\n return \"exit\";\n } else {\n return \"ok\";\n }\n }",
"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 }"
] |
Adds a JSON string to the DB.
@param obj the JSON to record
@param table the table to insert into
@return the number of rows in the table, or DB_OUT_OF_MEMORY_ERROR/DB_UPDATE_ERROR | [
"synchronized int storeObject(JSONObject obj, Table table) {\n if (!this.belowMemThreshold()) {\n Logger.v(\"There is not enough space left on the device to store data, data discarded\");\n return DB_OUT_OF_MEMORY_ERROR;\n }\n\n final String tableName = table.getName();\n\n Cursor cursor = null;\n int count = DB_UPDATE_ERROR;\n\n //noinspection TryFinallyCanBeTryWithResources\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(KEY_CREATED_AT, System.currentTimeMillis());\n db.insert(tableName, null, cv);\n cursor = db.rawQuery(\"SELECT COUNT(*) FROM \" + tableName, null);\n cursor.moveToFirst();\n count = cursor.getInt(0);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n\n if (cursor != null) {\n cursor.close();\n cursor = null;\n }\n dbHelper.deleteDatabase();\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n dbHelper.close();\n }\n return count;\n }"
] | [
"private void initXmlBundle() throws CmsException {\n\n CmsFile file = m_cms.readFile(m_resource);\n m_bundleFiles.put(null, m_resource);\n m_xmlBundle = CmsXmlContentFactory.unmarshal(m_cms, file);\n initKeySetForXmlBundle();\n\n }",
"@Override\n public final boolean getBool(final int i) {\n try {\n return this.array.getBoolean(i);\n } catch (JSONException e) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n }",
"public PhotoContext getContext(String photoId, String groupId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"group_id\", groupId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Collection<Element> payload = response.getPayloadCollection();\r\n PhotoContext photoContext = new PhotoContext();\r\n for (Element element : payload) {\r\n String elementName = element.getTagName();\r\n if (elementName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (elementName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setNextPhoto(photo);\r\n } else if (!elementName.equals(\"count\")) {\r\n _log.warn(\"unsupported element name: \" + elementName);\r\n }\r\n }\r\n return photoContext;\r\n }",
"@Nullable\n public final String getStringContent(final long blobHandle, @NotNull final Transaction txn) throws IOException {\n String result;\n result = stringContentCache.tryKey(this, blobHandle);\n if (result == null) {\n final InputStream content = getContent(blobHandle, txn);\n if (content == null) {\n logger.error(\"Blob string not found: \" + getBlobLocation(blobHandle), new FileNotFoundException());\n }\n result = content == null ? null : UTFUtil.readUTF(content);\n if (result != null && result.length() <= config.getBlobStringsCacheMaxValueSize()) {\n if (stringContentCache.getObject(this, blobHandle) == null) {\n stringContentCache.cacheObject(this, blobHandle, result);\n }\n }\n }\n return result;\n }",
"public static Object toObject(Class<?> clazz, Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (clazz == null) {\n return value;\n }\n\n if (java.sql.Date.class.isAssignableFrom(clazz)) {\n return toDate(value);\n }\n if (java.sql.Time.class.isAssignableFrom(clazz)) {\n return toTime(value);\n }\n if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {\n return toTimestamp(value);\n }\n if (java.util.Date.class.isAssignableFrom(clazz)) {\n return toDateTime(value);\n }\n\n return value;\n }",
"private void populateResourceAssignment(Record record, ResourceAssignment assignment) throws MPXJException\n {\n //\n // Handle malformed MPX files - ensure that we can locate the resource\n // using either the Unique ID attribute or the ID attribute.\n //\n Resource resource = m_projectFile.getResourceByUniqueID(record.getInteger(12));\n if (resource == null)\n {\n resource = m_projectFile.getResourceByID(record.getInteger(0));\n }\n\n assignment.setUnits(record.getUnits(1));\n assignment.setWork(record.getDuration(2));\n assignment.setBaselineWork(record.getDuration(3));\n assignment.setActualWork(record.getDuration(4));\n assignment.setOvertimeWork(record.getDuration(5));\n assignment.setCost(record.getCurrency(6));\n assignment.setBaselineCost(record.getCurrency(7));\n assignment.setActualCost(record.getCurrency(8));\n assignment.setStart(record.getDateTime(9));\n assignment.setFinish(record.getDateTime(10));\n assignment.setDelay(record.getDuration(11));\n\n //\n // Calculate the remaining work\n //\n Duration work = assignment.getWork();\n Duration actualWork = assignment.getActualWork();\n if (work != null && actualWork != null)\n {\n if (work.getUnits() != actualWork.getUnits())\n {\n actualWork = actualWork.convertUnits(work.getUnits(), m_projectFile.getProjectProperties());\n }\n\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }",
"public boolean deleteWithCustomTimeout(CompositeVoldemortRequest<K, V> deleteRequestObject) {\n List<Versioned<V>> versionedValues;\n\n validateTimeout(deleteRequestObject.getRoutingTimeoutInMs());\n boolean hasVersion = deleteRequestObject.getVersion() == null ? false : true;\n String keyHexString = \"\";\n if(!hasVersion) {\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"DELETE without version requested for key: \" + keyHexString\n + \" , for store: \" + this.storeName + \" at time(in ms): \"\n + startTimeInMs + \" . Nested GET and DELETE requests to follow ---\");\n }\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent delete might be faster all the\n // steps might finish within the allotted time\n deleteRequestObject.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(deleteRequestObject);\n Versioned<V> versioned = getItemOrThrow(deleteRequestObject.getKey(),\n null,\n versionedValues);\n\n if(versioned == null) {\n return false;\n }\n\n long timeLeft = deleteRequestObject.getRoutingTimeoutInMs()\n - (System.currentTimeMillis() - startTimeInMs);\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n if(timeLeft < 0) {\n throw new StoreTimeoutException(\"DELETE request timed out\");\n }\n\n // Update the version and the new timeout\n deleteRequestObject.setVersion(versioned.getVersion());\n deleteRequestObject.setRoutingTimeoutInMs(timeLeft);\n\n }\n long deleteVersionStartTimeInNs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n keyHexString);\n }\n boolean result = store.delete(deleteRequestObject);\n if(logger.isDebugEnabled()) {\n debugLogEnd(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n System.currentTimeMillis(),\n keyHexString,\n 0);\n }\n if(!hasVersion && logger.isDebugEnabled()) {\n logger.debug(\"DELETE without version response received for key: \" + keyHexString\n + \", for store: \" + this.storeName + \" at time(in ms): \"\n + System.currentTimeMillis());\n }\n return result;\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 IPv6Address toLinkLocalIPv6() {\r\n\t\tIPv6AddressNetwork network = getIPv6Network();\r\n\t\tIPv6AddressSection linkLocalPrefix = network.getLinkLocalPrefix();\r\n\t\tIPv6AddressCreator creator = network.getAddressCreator();\r\n\t\treturn creator.createAddress(linkLocalPrefix.append(toEUI64IPv6()));\r\n\t}"
] |
Merge the two maps.
<p>
The replied map is a view on the given map. It means that any change
in the original map is reflected to the result of this operation.
</p>
<p>
If a key exists in the left and right operands, the value in the right operand is preferred.
</p>
@param <K> type of the map keys.
@param <V> type of the map values.
@param left the left map.
@param right the right map.
@return a map with the merged contents from the two maps.
@throws IllegalArgumentException - when a right operand key exists in the left operand.
@since 2.15 | [
"@Pure\n\t@Inline(value = \"$3.union($1, $2)\", imported = MapExtensions.class)\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, Map<? extends K, ? extends V> right) {\n\t\treturn union(left, right);\n\t}"
] | [
"private void postTraversalProcessing() {\n\t\tint nc1 = treeSize;\n\t\tinfo[KR] = new int[leafCount];\n\t\tinfo[RKR] = new int[leafCount];\n\n\t\tint lc = leafCount;\n\t\tint i = 0;\n\n\t\t// compute left-most leaf descendants\n\t\t// go along the left-most path, remember each node and assign to it the path's\n\t\t// leaf\n\t\t// compute right-most leaf descendants (in reversed postorder)\n\t\tfor (i = 0; i < treeSize; i++) {\n\t\t\tif (paths[LEFT][i] == -1) {\n\t\t\t\tinfo[POST2_LLD][i] = i;\n\t\t\t} else {\n\t\t\t\tinfo[POST2_LLD][i] = info[POST2_LLD][paths[LEFT][i]];\n\t\t\t}\n\t\t\tif (paths[RIGHT][i] == -1) {\n\t\t\t\tinfo[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =\n\t\t\t\t\t\t(treeSize - 1 - info[POST2_PRE][i]);\n\t\t\t} else {\n\t\t\t\tinfo[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =\n\t\t\t\t\t\tinfo[RPOST2_RLD][treeSize - 1\n\t\t\t\t\t\t\t\t- info[POST2_PRE][paths[RIGHT][i]]];\n\t\t\t}\n\t\t}\n\n\t\t// compute key root nodes\n\t\t// compute reversed key root nodes (in revrsed postorder)\n\t\tboolean[] visited = new boolean[nc1];\n\t\tboolean[] visitedR = new boolean[nc1];\n\t\tArrays.fill(visited, false);\n\t\tint k = lc - 1;\n\t\tint kR = lc - 1;\n\t\tfor (i = nc1 - 1; i >= 0; i--) {\n\t\t\tif (!visited[info[POST2_LLD][i]]) {\n\t\t\t\tinfo[KR][k] = i;\n\t\t\t\tvisited[info[POST2_LLD][i]] = true;\n\t\t\t\tk--;\n\t\t\t}\n\t\t\tif (!visitedR[info[RPOST2_RLD][i]]) {\n\t\t\t\tinfo[RKR][kR] = i;\n\t\t\t\tvisitedR[info[RPOST2_RLD][i]] = true;\n\t\t\t\tkR--;\n\t\t\t}\n\t\t}\n\n\t\t// compute minimal key roots for every subtree\n\t\t// compute minimal reversed key roots for every subtree (in reversed postorder)\n\t\tint parent = -1;\n\t\tint parentR = -1;\n\t\tfor (i = 0; i < leafCount; i++) {\n\t\t\tparent = info[KR][i];\n\t\t\twhile (parent > -1 && info[POST2_MIN_KR][parent] == -1) {\n\t\t\t\tinfo[POST2_MIN_KR][parent] = i;\n\t\t\t\tparent = info[POST2_PARENT][parent];\n\t\t\t}\n\t\t\tparentR = info[RKR][i];\n\t\t\twhile (parentR > -1 && info[RPOST2_MIN_RKR][parentR] == -1) {\n\t\t\t\tinfo[RPOST2_MIN_RKR][parentR] = i;\n\t\t\t\tparentR =\n\t\t\t\t\t\tinfo[POST2_PARENT][info[RPOST2_POST][parentR]]; // get parent's postorder\n\t\t\t\tif (parentR > -1) {\n\t\t\t\t\tparentR = treeSize - 1 - info[POST2_PRE][parentR]; // if parent exists get its\n\t\t\t\t\t// rev. postorder\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"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 }",
"protected void setProperty(String propertyName, JavascriptObject propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getJSObject());\n }",
"public static String makePropertyName(String name) {\n char[] buf = new char[name.length() + 3];\n int pos = 0;\n buf[pos++] = 's';\n buf[pos++] = 'e';\n buf[pos++] = 't';\n\n for (int ix = 0; ix < name.length(); ix++) {\n char ch = name.charAt(ix);\n if (ix == 0)\n ch = Character.toUpperCase(ch);\n else if (ch == '-') {\n ix++;\n if (ix == name.length())\n break;\n ch = Character.toUpperCase(name.charAt(ix));\n }\n\n buf[pos++] = ch;\n }\n\n return new String(buf, 0, pos);\n }",
"public static CmsShell getTopShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.isEmpty()) {\n return null;\n }\n return shells.get(shells.size() - 1);\n\n }",
"private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }",
"private void WebPageCloseOnClick(GVRViewSceneObject gvrWebViewSceneObject, GVRSceneObject gvrSceneObjectAnchor, String url) {\n final String urlFinal = url;\n\n webPagePlusUISceneObject = new GVRSceneObject(gvrContext);\n webPagePlusUISceneObject.getTransform().setPosition(webPagePlusUIPosition[0], webPagePlusUIPosition[1], webPagePlusUIPosition[2]);\n\n GVRScene mainScene = gvrContext.getMainScene();\n\n Sensor webPageSensor = new Sensor(urlFinal, Sensor.Type.TOUCH, gvrWebViewSceneObject, true);\n final GVRSceneObject gvrSceneObjectAnchorFinal = gvrSceneObjectAnchor;\n final GVRSceneObject gvrWebViewSceneObjectFinal = gvrWebViewSceneObject;\n final GVRSceneObject webPagePlusUISceneObjectFinal = webPagePlusUISceneObject;\n\n webPagePlusUISceneObjectFinal.addChildObject(gvrWebViewSceneObjectFinal);\n gvrSceneObjectAnchorFinal.addChildObject(webPagePlusUISceneObjectFinal);\n\n\n webPageSensor.addISensorEvents(new ISensorEvents() {\n boolean uiObjectIsActive = false;\n boolean clickDown = true;\n\n @Override\n public void onSensorEvent(SensorEvent event) {\n if (event.isActive()) {\n clickDown = !clickDown;\n if (clickDown) {\n // Delete the WebView page\n gvrSceneObjectAnchorFinal.removeChildObject(webPagePlusUISceneObjectFinal);\n webPageActive = false;\n webPagePlusUISceneObject = null;\n webPageClosed = true; // Make sure click up doesn't open web page behind it\n }\n }\n }\n });\n }",
"public final void printClientConfig(final JSONWriter json) throws JSONException {\n json.key(\"attributes\");\n json.array();\n for (Map.Entry<String, Attribute> entry: this.attributes.entrySet()) {\n Attribute attribute = entry.getValue();\n if (attribute.getClass().getAnnotation(InternalAttribute.class) == null) {\n json.object();\n attribute.printClientConfig(json, this);\n json.endObject();\n }\n }\n json.endArray();\n }",
"public static base_response delete(nitro_service client, String network) throws Exception {\n\t\troute6 deleteresource = new route6();\n\t\tdeleteresource.network = network;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] |
Runs the server. | [
"@Override\n public void run() {\n ExecutorService executorService = Executors.newFixedThreadPool(maxClients);\n try {\n serverSocket = new ServerSocket(port, maxClients);\n while (!shuttingDown) {\n try {\n Socket socket = serverSocket.accept();\n debugConnection = new DebugConnection(socket);\n executorService.submit(debugConnection);\n } catch (SocketException e) {\n // closed\n debugConnection = null;\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n debugConnection = null;\n serverSocket.close();\n } catch (Exception e) {\n }\n executorService.shutdownNow();\n }\n }"
] | [
"public void moveRectangleTo(Rectangle rect, float x, float y) {\n\t\tfloat width = rect.getWidth();\n\t\tfloat height = rect.getHeight();\n\t\trect.setLeft(x);\n\t\trect.setBottom(y);\n\t\trect.setRight(rect.getLeft() + width);\n\t\trect.setTop(rect.getBottom() + height);\n\t}",
"public static vrid6 get(nitro_service service, Long id) throws Exception{\n\t\tvrid6 obj = new vrid6();\n\t\tobj.set_id(id);\n\t\tvrid6 response = (vrid6) obj.get_resource(service);\n\t\treturn response;\n\t}",
"@Override\n public Optional<String> hash(final Optional<URL> url) throws IOException {\n if (!url.isPresent()) {\n return Optional.absent();\n }\n logger.debug(\"Calculating md5 hash, url:{}\", url);\n if (isHotReloadModeOff()) {\n final String md5 = cache.getIfPresent(url.get());\n\n logger.debug(\"md5 hash:{}\", md5);\n\n if (md5 != null) {\n return Optional.of(md5);\n }\n }\n\n final InputStream is = url.get().openStream();\n final String md5 = getMD5Checksum(is);\n\n if (isHotReloadModeOff()) {\n logger.debug(\"caching url:{} with hash:{}\", url, md5);\n\n cache.put(url.get(), md5);\n }\n\n return Optional.fromNullable(md5);\n }",
"public AsciiTable setPaddingTopChar(Character paddingTopChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTopChar(paddingTopChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static ComplexNumber Add(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real + scalar, z1.imaginary);\r\n }",
"public String getMessage(Locale locale) {\n\t\tif (getCause() != null) {\n\t\t\tString message = getShortMessage(locale) + \", \" + translate(\"ROOT_CAUSE\", locale) + \" \";\n\t\t\tif (getCause() instanceof GeomajasException) {\n\t\t\t\treturn message + ((GeomajasException) getCause()).getMessage(locale);\n\t\t\t}\n\t\t\treturn message + getCause().getMessage();\n\t\t} else {\n\t\t\treturn getShortMessage(locale);\n\t\t}\n\t}",
"public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl),\n\t\t\t\tfilterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}",
"public void waitForAsyncFlush() {\n long numAdded = asyncBatchesAdded.get();\n\n synchronized (this) {\n while (numAdded > asyncBatchesProcessed) {\n try {\n wait();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n }",
"public Info getInfo() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new Info(jsonObject);\n }"
] |
Print a work contour.
@param value WorkContour instance
@return work contour value | [
"public static final String printWorkContour(WorkContour value)\n {\n return (Integer.toString(value == null ? WorkContour.FLAT.getValue() : value.getValue()));\n }"
] | [
"public void logAttributeWarning(PathAddress address, ModelNode operation, String message, String attribute) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attribute));\n }",
"private static byte calculateChecksum(byte[] buffer) {\n\t\tbyte checkSum = (byte)0xFF;\n\t\tfor (int i=1; i<buffer.length-1; i++) {\n\t\t\tcheckSum = (byte) (checkSum ^ buffer[i]);\n\t\t}\n\t\tlogger.trace(String.format(\"Calculated checksum = 0x%02X\", checkSum));\n\t\treturn checkSum;\n\t}",
"public Set<String> getKeys(Class<?> type) {\n return data.entrySet().stream().filter(val -> type.isAssignableFrom(val.getValue()\n .getClass())).map(Map.Entry::getKey).collect(Collectors\n .toSet());\n }",
"public static double diagProd( DMatrix1Row T )\n {\n double prod = 1.0;\n int N = Math.min(T.numRows,T.numCols);\n for( int i = 0; i < N; i++ ) {\n prod *= T.unsafe_get(i,i);\n }\n\n return prod;\n }",
"public Map<String, CmsJspCategoryAccessBean> getSubCategories() {\n\n if (m_subCategories == null) {\n m_subCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n @SuppressWarnings(\"synthetic-access\")\n public Object transform(Object pathPrefix) {\n\n return new CmsJspCategoryAccessBean(m_cms, m_categories, (String)pathPrefix);\n }\n\n });\n }\n return m_subCategories;\n }",
"private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings)\n throws IOException\n {\n final String outputDirectory = settings.getOutputDirectory();\n\n final String fileName = type.getName() + settings.getLanguage().getFileExtension();\n final String packageName = type.getPackageName();\n\n // foo.Bar -> foo/Bar.java\n final String subDir = StringUtils.defaultIfEmpty(packageName, \"\").replace('.', File.separatorChar);\n final String outputPath = PathHelper.combine(outputDirectory, subDir, fileName);\n\n final File outputFile = new File(outputPath);\n final File parentDir = outputFile.getParentFile();\n\n if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs())\n {\n throw new IllegalStateException(\"Could not create directory:\" + parentDir);\n }\n\n if (!outputFile.exists() && !outputFile.createNewFile())\n {\n throw new IllegalStateException(\"Could not create output file: \" + outputPath);\n }\n\n return new FileOutputWriter(outputFile, settings);\n }",
"private List<ResourceField> getAllResourceExtendedAttributes()\n {\n ArrayList<ResourceField> result = new ArrayList<ResourceField>();\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_TEXT));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(ResourceFieldLists.CUSTOM_OUTLINE_CODE));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(ResourceFieldLists.ENTERPRISE_TEXT));\n return result;\n }",
"private void readPattern(JSONObject patternJson) {\n\n setPatternType(readPatternType(patternJson));\n setInterval(readOptionalInt(patternJson, JsonKey.PATTERN_INTERVAL));\n setWeekDays(readWeekDays(patternJson));\n setDayOfMonth(readOptionalInt(patternJson, JsonKey.PATTERN_DAY_OF_MONTH));\n setEveryWorkingDay(readOptionalBoolean(patternJson, JsonKey.PATTERN_EVERYWORKINGDAY));\n setWeeksOfMonth(readWeeksOfMonth(patternJson));\n setIndividualDates(readDates(readOptionalArray(patternJson, JsonKey.PATTERN_DATES)));\n setMonth(readOptionalMonth(patternJson, JsonKey.PATTERN_MONTH));\n\n }",
"protected void appendTableWithJoins(TableAlias alias, StringBuffer where, StringBuffer buf)\r\n {\r\n int stmtFromPos = 0;\r\n byte joinSyntax = getJoinSyntaxType();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n stmtFromPos = buf.length(); // store position of join (by: Terry Dexter)\r\n }\r\n\r\n if (alias == getRoot())\r\n {\r\n // BRJ: also add indirection table to FROM-clause for MtoNQuery \r\n if (getQuery() instanceof MtoNQuery)\r\n {\r\n MtoNQuery mnQuery = (MtoNQuery)m_query; \r\n buf.append(getTableAliasForPath(mnQuery.getIndirectionTable(), null).getTableAndAlias());\r\n buf.append(\", \");\r\n } \r\n buf.append(alias.getTableAndAlias());\r\n }\r\n else if (joinSyntax != SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n buf.append(alias.getTableAndAlias());\r\n }\r\n\r\n if (!alias.hasJoins())\r\n {\r\n return;\r\n }\r\n\r\n for (Iterator it = alias.iterateJoins(); it.hasNext();)\r\n {\r\n Join join = (Join) it.next();\r\n\r\n if (joinSyntax == SQL92_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92(join, where, buf);\r\n if (it.hasNext())\r\n {\r\n buf.insert(stmtFromPos, \"(\");\r\n buf.append(\")\");\r\n }\r\n }\r\n else if (joinSyntax == SQL92_NOPAREN_JOIN_SYNTAX)\r\n {\r\n appendJoinSQL92NoParen(join, where, buf);\r\n }\r\n else\r\n {\r\n appendJoin(where, buf, join);\r\n }\r\n\r\n }\r\n }"
] |
Support the subscript operator for String.
@param text a String
@param index the index of the Character to get
@return the Character at the given index
@since 1.0 | [
"public static String getAt(String text, int index) {\n index = normaliseIndex(index, text.length());\n return text.substring(index, index + 1);\n }"
] | [
"private void processCurrency(Row row)\n {\n String currencyName = row.getString(\"curr_short_name\");\n DecimalFormatSymbols symbols = new DecimalFormatSymbols();\n symbols.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n symbols.setGroupingSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n DecimalFormat nf = new DecimalFormat();\n nf.setDecimalFormatSymbols(symbols);\n nf.applyPattern(\"#.#\");\n m_currencyMap.put(currencyName, nf);\n\n if (currencyName.equalsIgnoreCase(m_defaultCurrencyName))\n {\n m_numberFormat = nf;\n m_defaultCurrencyData = row;\n }\n }",
"private boolean isSplit(ProjectCalendar calendar, List<TimephasedWork> list)\n {\n boolean result = false;\n for (TimephasedWork assignment : list)\n {\n if (calendar != null && assignment.getTotalAmount().getDuration() == 0)\n {\n Duration calendarWork = calendar.getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.MINUTES);\n if (calendarWork.getDuration() != 0)\n {\n result = true;\n break;\n }\n }\n }\n return result;\n }",
"public static base_response unset(nitro_service client, nsrpcnode resource, String[] args) throws Exception{\n\t\tnsrpcnode unsetresource = new nsrpcnode();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static void applyDecidedIconOrSetGone(ImageHolder imageHolder, ImageView imageView, int iconColor, boolean tint) {\n if (imageHolder != null && imageView != null) {\n Drawable drawable = ImageHolder.decideIcon(imageHolder, imageView.getContext(), iconColor, tint);\n if (drawable != null) {\n imageView.setImageDrawable(drawable);\n imageView.setVisibility(View.VISIBLE);\n } else if (imageHolder.getBitmap() != null) {\n imageView.setImageBitmap(imageHolder.getBitmap());\n imageView.setVisibility(View.VISIBLE);\n } else {\n imageView.setVisibility(View.GONE);\n }\n } else if (imageView != null) {\n imageView.setVisibility(View.GONE);\n }\n }",
"public int getMinutesPerDay()\n {\n return m_minutesPerDay == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerDay()) : m_minutesPerDay.intValue();\n }",
"public static UriComponentsBuilder fromPath(String path) {\n\t\tUriComponentsBuilder builder = new UriComponentsBuilder();\n\t\tbuilder.path(path);\n\t\treturn builder;\n\t}",
"public ChangesResult getChanges() {\n final URI uri = this.databaseHelper.changesUri(\"feed\", \"normal\");\n return client.get(uri, ChangesResult.class);\n }",
"public void propagateAsErrorIfCancelException(final Throwable t) {\n if ((t instanceof OperationCanceledError)) {\n throw ((OperationCanceledError)t);\n }\n final RuntimeException opCanceledException = this.getPlatformOperationCanceledException(t);\n if ((opCanceledException != null)) {\n throw new OperationCanceledError(opCanceledException);\n }\n }",
"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 }"
] |
Searches for a declared method with a given name. If the class declares multiple methods with the given name,
there is no guarantee as of which methods is returned. Null is returned if the class does not declare a method
with the given name.
@param clazz the given class
@param methodName the given method name
@return method method with the given name declared by the given class or null if no such method exists | [
"public static Method findDeclaredMethodByName(Class<?> clazz, String methodName) {\n for (Method method : AccessController.doPrivileged(new GetDeclaredMethodsAction(clazz))) {\n if (methodName.equals(method.getName())) {\n return method;\n }\n }\n return null;\n }"
] | [
"@Deprecated\n public void parseAndSetParameter(String value, ModelNode operation, XMLStreamReader reader) throws XMLStreamException {\n //we use manual parsing here, and not #getParser().. to preserve backward compatibility.\n if (value != null) {\n for (String element : value.split(\",\")) {\n parseAndAddParameterElement(element.trim(), operation, reader);\n }\n }\n }",
"public static UserStub getStubWithRandomParams(UserTypeVal userType) {\r\n // Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles!\r\n // Oh the joys of type erasure.\r\n Tuple2<Double, Double> tuple = SocialNetworkUtilities.getRandomGeographicalLocation();\r\n return new UserStub(userType, new Tuple2<>((Double) tuple._1(), (Double) tuple._2()),\r\n SocialNetworkUtilities.getRandomIsSecret());\r\n }",
"public static String writeMultipleClientConfigAvro(Map<String, Properties> mapStoreToProps) {\n // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json...\n String avroConfig = \"\";\n Boolean firstStore = true;\n for(String storeName: mapStoreToProps.keySet()) {\n if(firstStore) {\n firstStore = false;\n } else {\n avroConfig = avroConfig + \",\\n\";\n }\n Properties props = mapStoreToProps.get(storeName);\n avroConfig = avroConfig + \"\\t\\\"\" + storeName + \"\\\": \"\n + writeSingleClientConfigAvro(props);\n\n }\n return \"{\\n\" + avroConfig + \"\\n}\";\n }",
"public static void mark(DeploymentUnit unit) {\n unit = DeploymentUtils.getTopDeploymentUnit(unit);\n unit.putAttachment(MARKER, Boolean.TRUE);\n }",
"@Pure\n\tpublic static <P1, P2, P3, P4, RESULT> Function3<P2, P3, P4, RESULT> curry(\n\t\t\tfinal Function4<? super P1, ? super P2, ? super P3, ? super P4, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function3<P2, P3, P4, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3, P4 p4) {\n\t\t\t\treturn function.apply(argument, p2, p3, p4);\n\t\t\t}\n\t\t};\n\t}",
"private StitchUserT doLogin(final StitchCredential credential, final boolean asLinkRequest) {\n final Response response = doLoginRequest(credential, asLinkRequest);\n\n final StitchUserT previousUser = activeUser;\n final StitchUserT user = processLoginResponse(credential, response, asLinkRequest);\n\n if (asLinkRequest) {\n onUserLinked(user);\n } else {\n onUserLoggedIn(user);\n onActiveUserChanged(activeUser, previousUser);\n }\n\n return user;\n }",
"public Widget addControl(String name, int resId, String label, Widget.OnTouchListener listener) {\n return addControl(name, resId, label, listener, -1);\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 }",
"public static List<String> parse(final String[] args, final Object... objs) throws IOException\n {\n final List<String> ret = Colls.list();\n\n final List<Arg> allArgs = Colls.list();\n final HashMap<String, Arg> shortArgs = new HashMap<String, Arg>();\n final HashMap<String, Arg> longArgs = new HashMap<String, Arg>();\n\n parseArgs(objs, allArgs, shortArgs, longArgs);\n\n for (int i = 0; i < args.length; i++)\n {\n final String s = args[i];\n\n final Arg a;\n\n if (s.startsWith(\"--\"))\n {\n a = longArgs.get(s.substring(2));\n if (a == null)\n {\n throw new IOException(\"Unknown switch: \" + s);\n }\n }\n else if (s.startsWith(\"-\"))\n {\n a = shortArgs.get(s.substring(1));\n if (a == null)\n {\n throw new IOException(\"Unknown switch: \" + s);\n }\n }\n else\n {\n a = null;\n ret.add(s);\n }\n\n if (a != null)\n {\n if (a.isSwitch)\n {\n a.setField(\"true\");\n }\n else\n {\n if (i + 1 >= args.length)\n {\n System.out.println(\"Missing parameter for: \" + s);\n }\n if (a.isCatchAll())\n {\n final List<String> ca = Colls.list();\n for (++i; i < args.length; ++i)\n {\n ca.add(args[i]);\n }\n a.setCatchAll(ca);\n }\n else\n {\n ++i;\n a.setField(args[i]);\n }\n }\n a.setPresent();\n }\n }\n\n for (final Arg a : allArgs)\n {\n if (!a.isOk())\n {\n throw new IOException(\"Missing mandatory argument: \" + a);\n }\n }\n\n return ret;\n }"
] |
Create a Map composed of the entries of the first map minus the
entries of the given map.
@param self a map object
@param removeMe the entries to remove from the map
@return the resulting map
@since 1.7.4 | [
"public static <K,V> Map<K,V> minus(Map<K,V> self, Map removeMe) {\n final Map<K,V> ansMap = createSimilarMap(self);\n ansMap.putAll(self);\n if (removeMe != null && removeMe.size() > 0) {\n for (Map.Entry<K, V> e1 : self.entrySet()) {\n for (Object e2 : removeMe.entrySet()) {\n if (DefaultTypeTransformation.compareEqual(e1, e2)) {\n ansMap.remove(e1.getKey());\n }\n }\n }\n }\n return ansMap;\n }"
] | [
"public void start() {\n if (this.started) {\n throw new IllegalStateException(\"Cannot start the EventStream because it isn't stopped.\");\n }\n\n final long initialPosition;\n\n if (this.startingPosition == STREAM_POSITION_NOW) {\n BoxAPIRequest request = new BoxAPIRequest(this.api, EVENT_URL.build(this.api.getBaseURL(), \"now\"), \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n initialPosition = jsonObject.get(\"next_stream_position\").asLong();\n } else {\n assert this.startingPosition >= 0 : \"Starting position must be non-negative\";\n initialPosition = this.startingPosition;\n }\n\n this.poller = new Poller(initialPosition);\n\n this.pollerThread = new Thread(this.poller);\n this.pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {\n public void uncaughtException(Thread t, Throwable e) {\n EventStream.this.notifyException(e);\n }\n });\n this.pollerThread.start();\n\n this.started = true;\n }",
"public static dnssuffix[] get(nitro_service service, String Dnssuffix[]) throws Exception{\n\t\tif (Dnssuffix !=null && Dnssuffix.length>0) {\n\t\t\tdnssuffix response[] = new dnssuffix[Dnssuffix.length];\n\t\t\tdnssuffix obj[] = new dnssuffix[Dnssuffix.length];\n\t\t\tfor (int i=0;i<Dnssuffix.length;i++) {\n\t\t\t\tobj[i] = new dnssuffix();\n\t\t\t\tobj[i].set_Dnssuffix(Dnssuffix[i]);\n\t\t\t\tresponse[i] = (dnssuffix) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"@Override\n public Iterator<BoxItem.Info> iterator() {\n URL url = GET_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxFolder.this.getID());\n return new BoxItemIterator(BoxFolder.this.getAPI(), url);\n }",
"public static base_response delete(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey deleteresource = new sslcertkey();\n\t\tdeleteresource.certkey = resource.certkey;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"protected GVRPickedObject findCollider(GVRPickedObject[] pickList, GVRCollider findme)\n {\n if (pickList == null)\n {\n return null;\n }\n for (GVRPickedObject hit : pickList)\n {\n if ((hit != null) && (hit.hitCollider == findme))\n {\n return hit;\n }\n }\n return null;\n }",
"public Map<String, ImplT> convertToUnmodifiableMap(List<InnerT> innerList) {\n Map<String, ImplT> result = new HashMap<>();\n for (InnerT inner : innerList) {\n result.put(name(inner), impl(inner));\n }\n\n return Collections.unmodifiableMap(result);\n }",
"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 }",
"public static base_responses renumber(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 renumberresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trenumberresources[i] = new nspbr6();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, renumberresources,\"renumber\");\n\t\t}\n\t\treturn result;\n\t}",
"protected <T, A> ActiveOperation<T, A> registerActiveOperation(final Integer id, A attachment, ActiveOperation.CompletedCallback<T> callback) {\n lock.lock();\n try {\n // Check that we still allow registration\n // TODO WFCORE-199 distinguish client uses from server uses and limit this check to server uses\n // Using id==null may be one way to do this, but we need to consider ops that involve multiple requests\n // TODO WFCORE-845 consider using an IllegalStateException for this\n //assert ! shutdown;\n final Integer operationId;\n if(id == null) {\n // If we did not get an operationId, create a new one\n operationId = operationIdManager.createBatchId();\n } else {\n // Check that the operationId is not already taken\n if(! operationIdManager.lockBatchId(id)) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(id);\n }\n operationId = id;\n }\n final ActiveOperationImpl<T, A> request = new ActiveOperationImpl<T, A>(operationId, attachment, getCheckedCallback(callback), this);\n final ActiveOperation<?, ?> existing = activeRequests.putIfAbsent(operationId, request);\n if(existing != null) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(operationId);\n }\n ProtocolLogger.ROOT_LOGGER.tracef(\"Registered active operation %d\", operationId);\n activeCount++; // condition.signalAll();\n return request;\n } finally {\n lock.unlock();\n }\n }"
] |
Create the navigation frame.
@param outputDirectory The target directory for the generated file(s). | [
"private void createSuiteList(List<ISuite> suites,\n File outputDirectory,\n boolean onlyFailures) throws Exception\n {\n VelocityContext context = createContext();\n context.put(SUITES_KEY, suites);\n context.put(ONLY_FAILURES_KEY, onlyFailures);\n generateFile(new File(outputDirectory, SUITES_FILE),\n SUITES_FILE + TEMPLATE_EXTENSION,\n context);\n }"
] | [
"public static Range toRange(Span span) {\n return new Range(toKey(span.getStart()), span.isStartInclusive(), toKey(span.getEnd()),\n span.isEndInclusive());\n }",
"public boolean startsWith(Bytes prefix) {\n Objects.requireNonNull(prefix, \"startWith(Bytes prefix) cannot have null parameter\");\n\n if (prefix.length > this.length) {\n return false;\n } else {\n int end = this.offset + prefix.length;\n for (int i = this.offset, j = prefix.offset; i < end; i++, j++) {\n if (this.data[i] != prefix.data[j]) {\n return false;\n }\n }\n }\n return true;\n }",
"@Api\n\tpublic void restoreSecurityContext(SavedAuthorization savedAuthorization) {\n\t\tList<Authentication> auths = new ArrayList<Authentication>();\n\t\tif (null != savedAuthorization) {\n\t\t\tfor (SavedAuthentication sa : savedAuthorization.getAuthentications()) {\n\t\t\t\tAuthentication auth = new Authentication();\n\t\t\t\tauth.setSecurityServiceId(sa.getSecurityServiceId());\n\t\t\t\tauth.setAuthorizations(sa.getAuthorizations());\n\t\t\t\tauths.add(auth);\n\t\t\t}\n\t\t}\n\t\tsetAuthentications(null, auths);\n\t\tuserInfoInit();\n\t}",
"public static String getJavaCommand(final Path javaHome) {\n final Path resolvedJavaHome = javaHome == null ? findJavaHome() : javaHome;\n final String exe;\n if (resolvedJavaHome == null) {\n exe = \"java\";\n } else {\n exe = resolvedJavaHome.resolve(\"bin\").resolve(\"java\").toString();\n }\n if (exe.contains(\" \")) {\n return \"\\\"\" + exe + \"\\\"\";\n }\n if (WINDOWS) {\n return exe + \".exe\";\n }\n return exe;\n }",
"public RandomVariable[] getValues(double[] times) {\n\t\tRandomVariable[] values = new RandomVariable[times.length];\n\n\t\tfor(int i=0; i<times.length; i++) {\n\t\t\tvalues[i] = getValue(null, times[i]);\n\t\t}\n\n\t\treturn values;\n\t}",
"public Map<String, String> getSitePath() {\n\n if (m_sitePaths == null) {\n m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object rootPath) {\n\n if (rootPath instanceof String) {\n return getRequestContext().removeSiteRoot((String)rootPath);\n }\n return null;\n }\n });\n }\n return m_sitePaths;\n }",
"@UiThread\n protected void collapseView() {\n setExpanded(false);\n onExpansionToggled(true);\n\n if (mParentViewHolderExpandCollapseListener != null) {\n mParentViewHolderExpandCollapseListener.onParentCollapsed(getAdapterPosition());\n }\n }",
"public List<ServerRedirect> tableServers(int clientId) {\n List<ServerRedirect> servers = new ArrayList<>();\n\n try {\n Client client = ClientService.getInstance().getClient(clientId);\n servers = tableServers(client.getProfile().getId(), client.getActiveServerGroup());\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return servers;\n }",
"public Integer getGroupIdFromName(String groupName) {\n return (Integer) sqlService.getFromTable(Constants.GENERIC_ID, Constants.GROUPS_GROUP_NAME, groupName,\n Constants.DB_TABLE_GROUPS);\n }"
] |
Performs DBSCAN cluster analysis.
@param points the points to cluster
@return the list of clusters
@throws NullArgumentException if the data points are null | [
"public List<Cluster> cluster(final Collection<Point2D> points) {\n \tfinal List<Cluster> clusters = new ArrayList<Cluster>();\n final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>();\n\n KDTree<Point2D> tree = new KDTree<Point2D>(2);\n \n // Populate the kdTree\n for (final Point2D point : points) {\n \tdouble[] key = {point.x, point.y};\n \ttree.insert(key, point);\n }\n \n for (final Point2D point : points) {\n if (visited.get(point) != null) {\n continue;\n }\n final List<Point2D> neighbors = getNeighbors(point, tree);\n if (neighbors.size() >= minPoints) {\n // DBSCAN does not care about center points\n final Cluster cluster = new Cluster(clusters.size());\n clusters.add(expandCluster(cluster, point, neighbors, tree, visited));\n } else {\n visited.put(point, PointStatus.NOISE);\n }\n }\n\n for (Cluster cluster : clusters) {\n \tcluster.calculateCentroid();\n }\n \n return clusters;\n }"
] | [
"List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory, List<File> files) throws IOException {\n HashFunction hashFun = Hashing.md5();\n File dir = new File(new File(project.getFile().getParent(), \"target\"), outputDirectory);\n if (dir.exists()) {\n URI baseDir = getFileURI(dir);\n for (File f : findThriftFilesInDirectory(dir)) {\n URI fileURI = getFileURI(f);\n String relPath = baseDir.relativize(fileURI).getPath();\n File destFolder = getResourcesOutputDirectory();\n destFolder.mkdirs();\n File destFile = new File(destFolder, relPath);\n if (!destFile.exists() || (destFile.isFile() && !Files.hash(f, hashFun).equals(Files.hash(destFile, hashFun)))) {\n getLog().info(format(\"copying %s to %s\", f.getCanonicalPath(), destFile.getCanonicalPath()));\n copyFile(f, destFile);\n }\n files.add(destFile);\n }\n }\n Map<String, MavenProject> refs = project.getProjectReferences();\n for (String name : refs.keySet()) {\n getRecursiveThriftFiles(refs.get(name), outputDirectory, files);\n }\n return files;\n }",
"public static void copyProperties(Object dest, Object orig){\n\t\ttry {\n\t\t\tif (orig != null && dest != null){\n\t\t\t\tBeanUtils.copyProperties(dest, orig);\n\n\t\t\t\tPropertyUtils putils = new PropertyUtils();\n\t PropertyDescriptor origDescriptors[] = putils.getPropertyDescriptors(orig);\n\n\t\t\t\tfor (PropertyDescriptor origDescriptor : origDescriptors) {\n\t\t\t\t\tString name = origDescriptor.getName();\n\t\t\t\t\tif (\"class\".equals(name)) {\n\t\t\t\t\t\tcontinue; // No point in trying to set an object's class\n\t\t\t\t\t}\n\n\t\t\t\t\tClass propertyType = origDescriptor.getPropertyType();\n\t\t\t\t\tif (!Boolean.class.equals(propertyType) && !(Boolean.class.equals(propertyType)))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tif (!putils.isReadable(orig, name)) { //because of bad convention\n\t\t\t\t\t\tMethod m = orig.getClass().getMethod(\"is\" + name.substring(0, 1).toUpperCase() + name.substring(1), (Class<?>[]) null);\n\t\t\t\t\t\tObject value = m.invoke(orig, (Object[]) null);\n\n\t\t\t\t\t\tif (putils.isWriteable(dest, name)) {\n\t\t\t\t\t\t\tBeanUtilsBean.getInstance().copyProperty(dest, name, value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new DJException(\"Could not copy properties for shared object: \" + orig +\", message: \" + e.getMessage(),e);\n\t\t}\n\t}",
"@SuppressWarnings(\"WeakerAccess\")\n public int findBeatAtTime(long milliseconds) {\n int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);\n if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number\n return found + 1;\n } else if (found == -1) { // We are before the first beat\n return found;\n } else { // We are after some beat, report its beat number\n return -(found + 1);\n }\n }",
"public static ServiceController<InstallationManager> installService(ServiceTarget serviceTarget) {\n final InstallationManagerService service = new InstallationManagerService();\n return serviceTarget.addService(InstallationManagerService.NAME, service)\n .addDependency(JBOSS_PRODUCT_CONFIG_SERVICE, ProductConfig.class, service.productConfig)\n .setInitialMode(ServiceController.Mode.ACTIVE)\n .install();\n }",
"void processBeat(Beat beat) {\n if (isRunning() && beat.isTempoMaster()) {\n setMasterTempo(beat.getEffectiveTempo());\n deliverBeatAnnouncement(beat);\n }\n }",
"private void serializeEPR(EndpointReferenceType wsAddr, Node parent) throws ServiceLocatorException {\n try {\n JAXBElement<EndpointReferenceType> ep =\n WSA_OBJECT_FACTORY.createEndpointReference(wsAddr);\n createMarshaller().marshal(ep, parent);\n } catch (JAXBException e) {\n if (LOG.isLoggable(Level.SEVERE)) {\n LOG.log(Level.SEVERE,\n \"Failed to serialize endpoint data\", e);\n }\n throw new ServiceLocatorException(\"Failed to serialize endpoint data\", e);\n }\n }",
"public int getFaceNumIndices(int face) {\n if (null == m_faceOffsets) {\n if (face >= m_numFaces || face < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + face + \n \", Size: \" + m_numFaces);\n }\n return 3;\n }\n else {\n /* \n * no need to perform bound checks here as the array access will\n * throw IndexOutOfBoundsExceptions if the index is invalid\n */\n \n if (face == m_numFaces - 1) {\n return m_faces.capacity() / 4 - m_faceOffsets.getInt(face * 4);\n }\n \n return m_faceOffsets.getInt((face + 1) * 4) - \n m_faceOffsets.getInt(face * 4);\n }\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(required = false) String friendlyName) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n // make sure client with this name does not already exist\n if (null != clientService.findClientFromFriendlyName(profileId, friendlyName)) {\n \tthrow new Exception(\"Cannot add client. Friendly name already in use.\");\n }\n \n Client client = clientService.add(profileId);\n\n // set friendly name if it was specified\n if (friendlyName != null) {\n clientService.setFriendlyName(profileId, client.getUUID(), friendlyName);\n client.setFriendlyName(friendlyName);\n }\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", client);\n return valueHash;\n }",
"private void readTasks(Project project)\n {\n Project.Tasks tasks = project.getTasks();\n if (tasks != null)\n {\n int tasksWithoutIDCount = 0;\n\n for (Project.Tasks.Task task : tasks.getTask())\n {\n Task mpxjTask = readTask(task);\n if (mpxjTask.getID() == null)\n {\n ++tasksWithoutIDCount;\n }\n }\n\n for (Project.Tasks.Task task : tasks.getTask())\n {\n readPredecessors(task);\n }\n\n //\n // MS Project will happily read tasks from an MSPDI file without IDs,\n // it will just generate ID values based on the task order in the file.\n // If we find that there are no ID values present, we'll do the same.\n //\n if (tasksWithoutIDCount == tasks.getTask().size())\n {\n m_projectFile.getTasks().renumberIDs();\n }\n }\n\n m_projectFile.updateStructure();\n }"
] |
Get a list of path transformers for a given address.
@param address the path address
@param placeholderResolver a placeholder resolver used to resolve children of a placeholder registration
@return a list of path transformations | [
"public List<PathAddressTransformer> getPathTransformations(final PathAddress address, PlaceholderResolver placeholderResolver) {\n final List<PathAddressTransformer> list = new ArrayList<PathAddressTransformer>();\n final Iterator<PathElement> iterator = address.iterator();\n resolvePathTransformers(iterator, list, placeholderResolver);\n if(iterator.hasNext()) {\n while(iterator.hasNext()) {\n iterator.next();\n list.add(PathAddressTransformer.DEFAULT);\n }\n }\n return list;\n }"
] | [
"protected void sendPageBreakToBottom(JRDesignBand band) {\n\t\tJRElement[] elems = band.getElements();\n\t\tJRElement aux = null;\n\t\tfor (JRElement elem : elems) {\n\t\t\tif ((\"\" + elem.getKey()).startsWith(PAGE_BREAK_FOR_)) {\n\t\t\t\taux = elem;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aux != null)\n\t\t\t((JRDesignElement)aux).setY(band.getHeight());\n\t}",
"private void readRelationships()\n {\n for (MapRow row : getTable(\"CONTAB\"))\n {\n Task task1 = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID_1\"));\n Task task2 = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID_2\"));\n\n if (task1 != null && task2 != null)\n {\n RelationType type = row.getRelationType(\"TYPE\");\n Duration lag = row.getDuration(\"LAG\");\n Relation relation = task2.addPredecessor(task1, type, lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }",
"private List<Row> createWorkPatternAssignmentRowList(String workPatterns) throws ParseException\n {\n List<Row> list = new ArrayList<Row>();\n String[] patterns = workPatterns.split(\",|:\");\n int index = 1;\n while (index < patterns.length)\n {\n Integer workPattern = Integer.valueOf(patterns[index + 1]);\n Date startDate = DatatypeConverter.parseBasicTimestamp(patterns[index + 3]);\n Date endDate = DatatypeConverter.parseBasicTimestamp(patterns[index + 4]);\n\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"WORK_PATTERN\", workPattern);\n map.put(\"START_DATE\", startDate);\n map.put(\"END_DATE\", endDate);\n\n list.add(new MapRow(map));\n\n index += 5;\n }\n\n return list;\n }",
"public static Iterable<BoxCollection.Info> getAllCollections(final BoxAPIConnection api) {\n return new Iterable<BoxCollection.Info>() {\n public Iterator<BoxCollection.Info> iterator() {\n URL url = GET_COLLECTIONS_URL_TEMPLATE.build(api.getBaseURL());\n return new BoxCollectionIterator(api, url);\n }\n };\n }",
"protected String buildErrorSetMsg(Object obj, Object value, Field aField)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer buf = new StringBuffer();\r\n buf\r\n .append(eol + \"[try to set 'object value' in 'target object'\")\r\n .append(eol + \"target obj class: \" + (obj != null ? obj.getClass().getName() : null))\r\n .append(eol + \"target field name: \" + (aField != null ? aField.getName() : null))\r\n .append(eol + \"target field type: \" + (aField != null ? aField.getType() : null))\r\n .append(eol + \"target field declared in: \" + (aField != null ? aField.getDeclaringClass().getName() : null))\r\n .append(eol + \"object value class: \" + (value != null ? value.getClass().getName() : null))\r\n .append(eol + \"object value: \" + (value != null ? value : null))\r\n .append(eol + \"]\");\r\n return buf.toString();\r\n }",
"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 }",
"@Override\n public void begin(String namespace, String name, Attributes attributes) throws Exception {\n\n // not now: 6.0.0\n // digester.setLogger(CmsLog.getLog(digester.getClass()));\n\n // Push an array to capture the parameter values if necessary\n if (m_paramCount > 0) {\n Object[] parameters = new Object[m_paramCount];\n for (int i = 0; i < parameters.length; i++) {\n parameters[i] = null;\n }\n getDigester().pushParams(parameters);\n }\n }",
"public void racRent() {\n\t\tpos = pos - 1;\n\t\tString userName = CarSearch.getLastSearchParams()[0];\n\t\tString pickupDate = CarSearch.getLastSearchParams()[1];\n\t\tString returnDate = CarSearch.getLastSearchParams()[2];\n\t\tthis.searcher.search(userName, pickupDate, returnDate);\n\t\tif (searcher!=null && searcher.getCars()!= null && pos < searcher.getCars().size() && searcher.getCars().get(pos) != null) {\n\t\t\tRESStatusType resStatus = reserver.reserveCar(searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\t\t\tConfirmationType confirm = reserver.getConfirmation(resStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\n\t\t\tRESCarType car = confirm.getCar();\n\t\t\tCustomerDetailsType customer = confirm.getCustomer();\n\t\t\t\n\t\t\tSystem.out.println(MessageFormat.format(CONFIRMATION\n\t\t\t\t\t, confirm.getDescription()\n\t\t\t\t\t, confirm.getReservationId()\n\t\t\t\t\t, customer.getName()\n\t\t\t\t\t, customer.getEmail()\n\t\t\t\t\t, customer.getCity()\n\t\t\t\t\t, customer.getStatus()\n\t\t\t\t\t, car.getBrand()\n\t\t\t\t\t, car.getDesignModel()\n\t\t\t\t\t, confirm.getFromDate()\n\t\t\t\t\t, confirm.getToDate()\n\t\t\t\t\t, padl(car.getRateDay(), 10)\n\t\t\t\t\t, padl(car.getRateWeekend(), 10)\n\t\t\t\t\t, padl(confirm.getCreditPoints().toString(), 7)));\n\t\t} else {\n\t\t\tSystem.out.println(\"Invalid selection: \" + (pos+1)); //$NON-NLS-1$\n\t\t}\n\t}",
"public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) {\n assertNumericArgument(timeout, true);\n this.requestTimeout = unit.toMillis(timeout);\n return this;\n }"
] |
Create the required services according to the server setup
@param config Service configuration
@return Services map | [
"protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) {\r\n Map<String, AbstractServer> srvc = new HashMap<>();\r\n for (ServerSetup setup : config) {\r\n if (srvc.containsKey(setup.getProtocol())) {\r\n throw new IllegalArgumentException(\"Server '\" + setup.getProtocol() + \"' was found at least twice in the array\");\r\n }\r\n final String protocol = setup.getProtocol();\r\n if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) {\r\n srvc.put(protocol, new SmtpServer(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) {\r\n srvc.put(protocol, new Pop3Server(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) {\r\n srvc.put(protocol, new ImapServer(setup, mgr));\r\n }\r\n }\r\n return srvc;\r\n }"
] | [
"public int getIgnoredCount() {\n int count = 0;\n for (AggregatedTestResultEvent t : getTests()) {\n if (t.getStatus() == TestStatus.IGNORED ||\n t.getStatus() == TestStatus.IGNORED_ASSUMPTION) {\n count++;\n }\n }\n return count;\n }",
"private void updateWorkTimeUnit(FastTrackColumn column)\n {\n if (m_workTimeUnit == null && isWorkColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_workTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }",
"public void process(ProjectFile file, Var2Data varData, byte[] fixedData) throws IOException\n {\n Props props = getProps(varData);\n //System.out.println(props);\n if (props != null)\n {\n String viewName = MPPUtility.removeAmpersands(props.getUnicodeString(VIEW_NAME));\n byte[] listData = props.getByteArray(VIEW_CONTENTS);\n List<Integer> uniqueIdList = new LinkedList<Integer>();\n if (listData != null)\n {\n for (int index = 0; index < listData.length; index += 4)\n {\n Integer uniqueID = Integer.valueOf(MPPUtility.getInt(listData, index));\n\n //\n // Ensure that we have a valid task, and that if we have and\n // ID of zero, this is the first task shown.\n //\n if (file.getTaskByUniqueID(uniqueID) != null && (uniqueID.intValue() != 0 || index == 0))\n {\n uniqueIdList.add(uniqueID);\n }\n }\n }\n\n int filterID = MPPUtility.getShort(fixedData, 128);\n\n ViewState state = new ViewState(file, viewName, uniqueIdList, filterID);\n file.getViews().setViewState(state);\n }\n }",
"@Deprecated\n public ApnsServiceBuilder withProxySocket(Socket proxySocket) {\n return this.withProxy(new Proxy(Proxy.Type.SOCKS,\n proxySocket.getRemoteSocketAddress()));\n }",
"protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }",
"private String commaSeparate(Collection<String> strings)\n {\n StringBuilder buffer = new StringBuilder();\n Iterator<String> iterator = strings.iterator();\n while (iterator.hasNext())\n {\n String string = iterator.next();\n buffer.append(string);\n if (iterator.hasNext())\n {\n buffer.append(\", \");\n }\n }\n return buffer.toString();\n }",
"private static String removeLastDot(final String pkgName) {\n\t\treturn pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName;\n\t}",
"public UriComponentsBuilder uri(URI uri) {\n\t\tAssert.notNull(uri, \"'uri' must not be null\");\n\t\tthis.scheme = uri.getScheme();\n\t\tif (uri.isOpaque()) {\n\t\t\tthis.ssp = uri.getRawSchemeSpecificPart();\n\t\t\tresetHierarchicalComponents();\n\t\t}\n\t\telse {\n\t\t\tif (uri.getRawUserInfo() != null) {\n\t\t\t\tthis.userInfo = uri.getRawUserInfo();\n\t\t\t}\n\t\t\tif (uri.getHost() != null) {\n\t\t\t\tthis.host = uri.getHost();\n\t\t\t}\n\t\t\tif (uri.getPort() != -1) {\n\t\t\t\tthis.port = String.valueOf(uri.getPort());\n\t\t\t}\n\t\t\tif (StringUtils.hasLength(uri.getRawPath())) {\n\t\t\t\tthis.pathBuilder = new CompositePathComponentBuilder(uri.getRawPath());\n\t\t\t}\n\t\t\tif (StringUtils.hasLength(uri.getRawQuery())) {\n\t\t\t\tthis.queryParams.clear();\n\t\t\t\tquery(uri.getRawQuery());\n\t\t\t}\n\t\t\tresetSchemeSpecificPart();\n\t\t}\n\t\tif (uri.getRawFragment() != null) {\n\t\t\tthis.fragment = uri.getRawFragment();\n\t\t}\n\t\treturn this;\n\t}",
"protected RendererViewHolder buildRendererViewHolder() {\n validateAttributesToCreateANewRendererViewHolder();\n\n Renderer renderer = getPrototypeByIndex(viewType).copy();\n renderer.onCreate(null, layoutInflater, parent);\n return new RendererViewHolder(renderer);\n }"
] |
Make this item active. | [
"@Override\n public void setActive(boolean active) {\n this.active = active;\n\n if (parent != null) {\n fireCollapsibleHandler();\n removeStyleName(CssName.ACTIVE);\n if (header != null) {\n header.removeStyleName(CssName.ACTIVE);\n }\n if (active) {\n if (parent != null && parent.isAccordion()) {\n parent.clearActive();\n }\n addStyleName(CssName.ACTIVE);\n\n if (header != null) {\n header.addStyleName(CssName.ACTIVE);\n }\n }\n\n if (body != null) {\n body.setDisplay(active ? Display.BLOCK : Display.NONE);\n }\n } else {\n GWT.log(\"Please make sure that the Collapsible parent is attached or existed.\", new IllegalStateException());\n }\n }"
] | [
"public void add(final IndexableTaskItem taskItem) {\n this.dependsOnTaskGroup.addPostRunDependentTaskGroup(taskItem.taskGroup());\n this.collection.add(taskItem);\n }",
"public static String decodeUrl(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"UTF-8\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }",
"@Deprecated\n public static <T> ServiceBuilder<T> addServerExecutorDependency(ServiceBuilder<T> builder, Injector<ExecutorService> injector) {\n return builder.addDependency(ServerService.MANAGEMENT_EXECUTOR, ExecutorService.class, injector);\n }",
"public BoxFile.Info uploadFile(FileUploadParams uploadParams) {\n URL uploadURL = UPLOAD_FILE_URL.build(this.getAPI().getBaseUploadURL());\n BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL);\n\n JsonObject fieldJSON = new JsonObject();\n JsonObject parentIdJSON = new JsonObject();\n parentIdJSON.add(\"id\", getID());\n fieldJSON.add(\"name\", uploadParams.getName());\n fieldJSON.add(\"parent\", parentIdJSON);\n\n if (uploadParams.getCreated() != null) {\n fieldJSON.add(\"content_created_at\", BoxDateFormat.format(uploadParams.getCreated()));\n }\n\n if (uploadParams.getModified() != null) {\n fieldJSON.add(\"content_modified_at\", BoxDateFormat.format(uploadParams.getModified()));\n }\n\n if (uploadParams.getSHA1() != null && !uploadParams.getSHA1().isEmpty()) {\n request.setContentSHA1(uploadParams.getSHA1());\n }\n\n if (uploadParams.getDescription() != null) {\n fieldJSON.add(\"description\", uploadParams.getDescription());\n }\n\n request.putField(\"attributes\", fieldJSON.toString());\n\n if (uploadParams.getSize() > 0) {\n request.setFile(uploadParams.getContent(), uploadParams.getName(), uploadParams.getSize());\n } else if (uploadParams.getContent() != null) {\n request.setFile(uploadParams.getContent(), uploadParams.getName());\n } else {\n request.setUploadFileCallback(uploadParams.getUploadFileCallback(), uploadParams.getName());\n }\n\n BoxJSONResponse response;\n if (uploadParams.getProgressListener() == null) {\n response = (BoxJSONResponse) request.send();\n } else {\n response = (BoxJSONResponse) request.send(uploadParams.getProgressListener());\n }\n JsonObject collection = JsonObject.readFrom(response.getJSON());\n JsonArray entries = collection.get(\"entries\").asArray();\n JsonObject fileInfoJSON = entries.get(0).asObject();\n String uploadedFileID = fileInfoJSON.get(\"id\").asString();\n\n BoxFile uploadedFile = new BoxFile(getAPI(), uploadedFileID);\n return uploadedFile.new Info(fileInfoJSON);\n }",
"private void registerProxyCreator(Node source,\n BeanDefinitionHolder holder,\n ParserContext context) {\n\n String beanName = holder.getBeanName();\n String proxyName = beanName + \"Proxy\";\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(BeanNameAutoProxyCreator.class);\n\n initializer.addPropertyValue(\"beanNames\", beanName);\n initializer.addPropertyValue(\"interceptorNames\", interceptorName);\n\n BeanDefinitionRegistry registry = context.getRegistry();\n registry.registerBeanDefinition(proxyName, initializer.getBeanDefinition());\n }",
"static AbstractLazyPatchableTarget createPatchableTarget(final String name, final LayerPathConfig layer, final File metadata, final InstalledImage image) throws IOException {\n // patchable target\n return new AbstractLazyPatchableTarget() {\n\n @Override\n public InstalledImage getInstalledImage() {\n return image;\n }\n\n @Override\n public File getModuleRoot() {\n return layer.modulePath;\n }\n\n @Override\n public File getBundleRepositoryRoot() {\n return layer.bundlePath;\n }\n\n public File getPatchesMetadata() {\n return metadata;\n }\n\n @Override\n public String getName() {\n return name;\n }\n };\n }",
"public int consume(Map<String, String> initialVars) {\r\n this.dataPipe = new DataPipe(this);\n\r\n // Set initial variables\r\n for (Map.Entry<String, String> ent : initialVars.entrySet()) {\r\n dataPipe.getDataMap().put(ent.getKey(), ent.getValue());\r\n }\n\r\n // Call transformers\r\n for (DataTransformer dc : dataTransformers) {\r\n dc.transform(dataPipe);\r\n }\n\r\n // Call writers\r\n for (DataWriter oneOw : dataWriters) {\r\n try {\r\n oneOw.writeOutput(dataPipe);\r\n } catch (Exception e) { //NOPMD\r\n log.error(\"Exception in DataWriter\", e);\r\n }\r\n }\n\r\n return 1;\r\n }",
"@Pure\n\tpublic static <K, V> Pair<K, V> of(K k, V v) {\n\t\treturn new Pair<K, V>(k, v);\n\t}",
"public boolean absolute(int row) throws PersistenceBrokerException\r\n {\r\n boolean retval;\r\n if (supportsAdvancedJDBCCursorControl())\r\n {\r\n retval = absoluteAdvanced(row);\r\n }\r\n else\r\n {\r\n retval = absoluteBasic(row);\r\n }\r\n return retval;\r\n }"
] |
Use the universal project reader to open the file.
Throw an exception if we can't determine the file type.
@param inputFile file name
@return ProjectFile instance | [
"private ProjectFile readFile(String inputFile) throws MPXJException\n {\n ProjectReader reader = new UniversalProjectReader();\n ProjectFile projectFile = reader.read(inputFile);\n if (projectFile == null)\n {\n throw new IllegalArgumentException(\"Unsupported file type\");\n }\n return projectFile;\n }"
] | [
"public static String getParentDirectory(String filePath) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, filePath))\n return getURLParentDirectory(filePath);\n\n return new File(filePath).getParent();\n }",
"public Set<? extends AbstractBean<?, ?>> resolveSpecializedBeans(Bean<?> specializingBean) {\n if (specializingBean instanceof AbstractClassBean<?>) {\n AbstractClassBean<?> abstractClassBean = (AbstractClassBean<?>) specializingBean;\n if (abstractClassBean.isSpecializing()) {\n return specializedBeans.getValue(specializingBean);\n }\n }\n if (specializingBean instanceof ProducerMethod<?, ?>) {\n ProducerMethod<?, ?> producerMethod = (ProducerMethod<?, ?>) specializingBean;\n if (producerMethod.isSpecializing()) {\n return specializedBeans.getValue(specializingBean);\n }\n }\n return Collections.emptySet();\n }",
"public static CallSite bootstrapCurrent(Lookup caller, String name, MethodType type) {\n return realBootstrap(caller, name, CALL_TYPES.METHOD.ordinal(), type, false, true, false);\n }",
"public Duration getTotalSlack()\n {\n Duration totalSlack = (Duration) getCachedValue(TaskField.TOTAL_SLACK);\n if (totalSlack == null)\n {\n Duration duration = getDuration();\n if (duration == null)\n {\n duration = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n TimeUnit units = duration.getUnits();\n\n Duration startSlack = getStartSlack();\n if (startSlack == null)\n {\n startSlack = Duration.getInstance(0, units);\n }\n else\n {\n if (startSlack.getUnits() != units)\n {\n startSlack = startSlack.convertUnits(units, getParentFile().getProjectProperties());\n }\n }\n\n Duration finishSlack = getFinishSlack();\n if (finishSlack == null)\n {\n finishSlack = Duration.getInstance(0, units);\n }\n else\n {\n if (finishSlack.getUnits() != units)\n {\n finishSlack = finishSlack.convertUnits(units, getParentFile().getProjectProperties());\n }\n }\n\n double startSlackDuration = startSlack.getDuration();\n double finishSlackDuration = finishSlack.getDuration();\n\n if (startSlackDuration == 0 || finishSlackDuration == 0)\n {\n if (startSlackDuration != 0)\n {\n totalSlack = startSlack;\n }\n else\n {\n totalSlack = finishSlack;\n }\n }\n else\n {\n if (startSlackDuration < finishSlackDuration)\n {\n totalSlack = startSlack;\n }\n else\n {\n totalSlack = finishSlack;\n }\n }\n\n set(TaskField.TOTAL_SLACK, totalSlack);\n }\n\n return (totalSlack);\n }",
"public MwDumpFile findMostRecentDump(DumpContentType dumpContentType) {\n\t\tList<MwDumpFile> dumps = findAllDumps(dumpContentType);\n\n\t\tfor (MwDumpFile dump : dumps) {\n\t\t\tif (dump.isAvailable()) {\n\t\t\t\treturn dump;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public BoxLock lock(Date expiresAt, boolean isDownloadPrevented) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", \"lock\").toString();\n URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject lockConfig = new JsonObject();\n lockConfig.add(\"type\", \"lock\");\n if (expiresAt != null) {\n lockConfig.add(\"expires_at\", BoxDateFormat.format(expiresAt));\n }\n lockConfig.add(\"is_download_prevented\", isDownloadPrevented);\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"lock\", lockConfig);\n request.setBody(requestJSON.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n JsonValue lockValue = responseJSON.get(\"lock\");\n JsonObject lockJSON = JsonObject.readFrom(lockValue.toString());\n\n return new BoxLock(lockJSON, this.getAPI());\n }",
"public static base_response unset(nitro_service client, responderpolicy resource, String[] args) throws Exception{\n\t\tresponderpolicy unsetresource = new responderpolicy();\n\t\tunsetresource.name = resource.name;\n\t\treturn unsetresource.unset_resource(client,args);\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 }",
"private void readRelationships()\n {\n for (MapRow row : getTable(\"CONTAB\"))\n {\n Task task1 = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID_1\"));\n Task task2 = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID_2\"));\n\n if (task1 != null && task2 != null)\n {\n RelationType type = row.getRelationType(\"TYPE\");\n Duration lag = row.getDuration(\"LAG\");\n Relation relation = task2.addPredecessor(task1, type, lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }"
] |
Check if information model entity referenced by archetype
has right name or type | [
"void checkRmModelConformance() {\n final AmVisitor<AmObject, AmConstraintContext> visitor = AmVisitors.preorder(new ConformanceVisitor());\n ArchetypeWalker.walkConstraints(visitor, archetype, new AmConstraintContext());\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 List<String> splitAndTrimAsList(String text, String sep) {\n ArrayList<String> answer = new ArrayList<>();\n if (text != null && text.length() > 0) {\n for (String v : text.split(sep)) {\n String trim = v.trim();\n if (trim.length() > 0) {\n answer.add(trim);\n }\n }\n }\n return answer;\n }",
"public static String regexFindFirst(String pattern, String str) {\n return regexFindFirst(Pattern.compile(pattern), str, 1);\n }",
"public static int[] Unique(int[] values) {\r\n HashSet<Integer> lst = new HashSet<Integer>();\r\n for (int i = 0; i < values.length; i++) {\r\n lst.add(values[i]);\r\n }\r\n\r\n int[] v = new int[lst.size()];\r\n Iterator<Integer> it = lst.iterator();\r\n for (int i = 0; i < v.length; i++) {\r\n v[i] = it.next();\r\n }\r\n\r\n return v;\r\n }",
"public Double getAvgEventValue() {\n resetIfNeeded();\n synchronized(this) {\n long eventsLastInterval = numEventsLastInterval - numEventsLastLastInterval;\n if(eventsLastInterval > 0)\n return ((totalEventValueLastInterval - totalEventValueLastLastInterval) * 1.0)\n / eventsLastInterval;\n else\n return 0.0;\n }\n }",
"public static boolean isRevisionDumpFile(DumpContentType dumpContentType) {\n\t\tif (WmfDumpFile.REVISION_DUMP.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.REVISION_DUMP.get(dumpContentType);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}",
"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 }",
"public App on(Heroku.Stack stack) {\n App newApp = copy();\n newApp.stack = new App.Stack(stack);\n return newApp;\n }",
"@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addPostRunDependent(dependency);\n }"
] |
Set hint number for country | [
"private void setHint() {\n if (mPhoneEdit != null && mSelectedCountry != null && mSelectedCountry.getIso() != null) {\n Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.getExampleNumberForType(mSelectedCountry.getIso(), PhoneNumberUtil.PhoneNumberType.MOBILE);\n if (phoneNumber != null) {\n mPhoneEdit.setHint(mPhoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL));\n }\n }\n }"
] | [
"@SuppressWarnings({\"deprecation\", \"WeakerAccess\"})\n protected void removeShutdownHook(ClassLoaderLeakPreventor preventor, Thread shutdownHook) {\n final String displayString = \"'\" + shutdownHook + \"' of type \" + shutdownHook.getClass().getName();\n preventor.error(\"Removing shutdown hook: \" + displayString);\n Runtime.getRuntime().removeShutdownHook(shutdownHook);\n\n if(executeShutdownHooks) { // Shutdown hooks should be executed\n \n preventor.info(\"Executing shutdown hook now: \" + displayString);\n // Make sure it's from protected ClassLoader\n shutdownHook.start(); // Run cleanup immediately\n \n if(shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish\n try {\n shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run\n }\n catch (InterruptedException e) {\n // Do nothing\n }\n if(shutdownHook.isAlive()) {\n preventor.warn(shutdownHook + \"still running after \" + shutdownHookWaitMs + \" ms - Stopping!\");\n shutdownHook.stop();\n }\n }\n }\n }",
"boolean applyDomainModel(ModelNode result) {\n if(! result.hasDefined(ModelDescriptionConstants.RESULT)) {\n return false;\n }\n final List<ModelNode> bootOperations= result.get(ModelDescriptionConstants.RESULT).asList();\n return callback.applyDomainModel(bootOperations);\n }",
"public void addAuxHandler(Object handler, String prefix) {\n if (handler == null) {\n throw new NullPointerException();\n }\n auxHandlers.put(prefix, handler);\n allHandlers.add(handler);\n\n addDeclaredMethods(handler, prefix);\n inputConverter.addDeclaredConverters(handler);\n outputConverter.addDeclaredConverters(handler);\n\n if (handler instanceof ShellDependent) {\n ((ShellDependent)handler).cliSetShell(this);\n }\n }",
"public static void launchPermissionSettings(Activity activity) {\n Intent intent = new Intent();\n intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);\n intent.setData(Uri.fromParts(\"package\", activity.getPackageName(), null));\n activity.startActivity(intent);\n }",
"public static tmglobal_tmsessionpolicy_binding[] get(nitro_service service) throws Exception{\n\t\ttmglobal_tmsessionpolicy_binding obj = new tmglobal_tmsessionpolicy_binding();\n\t\ttmglobal_tmsessionpolicy_binding response[] = (tmglobal_tmsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static double KumarJohnsonDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n r += Math.pow(p[i] * p[i] - q[i] * q[i], 2) / 2 * Math.pow(p[i] * q[i], 1.5);\n }\n }\n return r;\n }",
"public UriComponentsBuilder uri(URI uri) {\n\t\tAssert.notNull(uri, \"'uri' must not be null\");\n\t\tthis.scheme = uri.getScheme();\n\t\tif (uri.isOpaque()) {\n\t\t\tthis.ssp = uri.getRawSchemeSpecificPart();\n\t\t\tresetHierarchicalComponents();\n\t\t}\n\t\telse {\n\t\t\tif (uri.getRawUserInfo() != null) {\n\t\t\t\tthis.userInfo = uri.getRawUserInfo();\n\t\t\t}\n\t\t\tif (uri.getHost() != null) {\n\t\t\t\tthis.host = uri.getHost();\n\t\t\t}\n\t\t\tif (uri.getPort() != -1) {\n\t\t\t\tthis.port = String.valueOf(uri.getPort());\n\t\t\t}\n\t\t\tif (StringUtils.hasLength(uri.getRawPath())) {\n\t\t\t\tthis.pathBuilder = new CompositePathComponentBuilder(uri.getRawPath());\n\t\t\t}\n\t\t\tif (StringUtils.hasLength(uri.getRawQuery())) {\n\t\t\t\tthis.queryParams.clear();\n\t\t\t\tquery(uri.getRawQuery());\n\t\t\t}\n\t\t\tresetSchemeSpecificPart();\n\t\t}\n\t\tif (uri.getRawFragment() != null) {\n\t\t\tthis.fragment = uri.getRawFragment();\n\t\t}\n\t\treturn this;\n\t}",
"public WebSocketContext sendJsonToUser(Object data, String username) {\n return sendToTagged(JSON.toJSONString(data), username);\n }",
"public ModelNode translateOperationForProxy(final ModelNode op) {\n return translateOperationForProxy(op, PathAddress.pathAddress(op.get(OP_ADDR)));\n }"
] |
Checks the given class descriptor for correct procedure settings.
@param classDef The class descriptor
@param checkLevel The current check level (this constraint is checked in basic and strict)
@exception ConstraintException If the constraint has been violated | [
"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 void copyTo(ColumnBuffer dest, LongPredicate timestampTest) {\n dest.clear();\n\n if (key != null) {\n dest.key = new Key(key);\n }\n\n for (int i = 0; i < timeStamps.size(); i++) {\n long time = timeStamps.get(i);\n if (timestampTest.test(time)) {\n dest.add(time, values.get(i));\n }\n }\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 }",
"public SimplifySpanBuild append(String text) {\n if (TextUtils.isEmpty(text)) return this;\n\n mNormalSizeText.append(text);\n mStringBuilder.append(text);\n return this;\n }",
"public void setStringValue(String value) {\n\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) {\n try {\n m_editValue = CmsLocationValue.parse(value);\n m_currentValue = m_editValue.cloneValue();\n displayValue();\n if ((m_popup != null) && m_popup.isVisible()) {\n m_popupContent.displayValues(m_editValue);\n updateMarkerPosition();\n }\n } catch (Exception e) {\n CmsLog.log(e.getLocalizedMessage() + \"\\n\" + CmsClientStringUtil.getStackTrace(e, \"\\n\"));\n }\n } else {\n m_currentValue = null;\n displayValue();\n }\n }",
"public boolean canBeLinked(D declaration, ServiceReference<S> declarationBinderRef) {\n // Evaluate the target filter of the ImporterService on the Declaration\n Filter filter = bindersManager.getTargetFilter(declarationBinderRef);\n return filter.matches(declaration.getMetadata());\n }",
"private 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 static base_responses unset(nitro_service client, String ipaddress[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ipaddress != null && ipaddress.length > 0) {\n\t\t\tnsrpcnode unsetresources[] = new nsrpcnode[ipaddress.length];\n\t\t\tfor (int i=0;i<ipaddress.length;i++){\n\t\t\t\tunsetresources[i] = new nsrpcnode();\n\t\t\t\tunsetresources[i].ipaddress = ipaddress[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CMMClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CMMClassifier cmm = new CMMClassifier<CoreLabel>(props);\r\n String testFile = cmm.flags.testFile;\r\n String textFile = cmm.flags.textFile;\r\n String loadPath = cmm.flags.loadClassifier;\r\n String serializeTo = cmm.flags.serializeTo;\r\n\r\n // cmm.crossValidateTrainAndTest(trainFile);\r\n if (loadPath != null) {\r\n cmm.loadClassifierNoExceptions(loadPath, props);\r\n } else if (cmm.flags.loadJarClassifier != null) {\r\n cmm.loadJarClassifier(cmm.flags.loadJarClassifier, props);\r\n } else if (cmm.flags.trainFile != null) {\r\n if (cmm.flags.biasedTrainFile != null) {\r\n cmm.trainSemiSup();\r\n } else {\r\n cmm.train();\r\n }\r\n } else {\r\n cmm.loadDefaultClassifier();\r\n }\r\n\r\n if (serializeTo != null) {\r\n cmm.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (testFile != null) {\r\n cmm.classifyAndWriteAnswers(testFile, cmm.makeReaderAndWriter());\r\n } else if (cmm.flags.testFiles != null) {\r\n cmm.classifyAndWriteAnswers(cmm.flags.baseTestDir, cmm.flags.testFiles,\r\n cmm.makeReaderAndWriter());\r\n }\r\n\r\n if (textFile != null) {\r\n DocumentReaderAndWriter readerAndWriter =\r\n new PlainTextDocumentReaderAndWriter();\r\n cmm.classifyAndWriteAnswers(textFile, readerAndWriter);\r\n }\r\n }",
"public static int[] convertBytesToInts(byte[] bytes)\n {\n if (bytes.length % 4 != 0)\n {\n throw new IllegalArgumentException(\"Number of input bytes must be a multiple of 4.\");\n }\n int[] ints = new int[bytes.length / 4];\n for (int i = 0; i < ints.length; i++)\n {\n ints[i] = convertBytesToInt(bytes, i * 4);\n }\n return ints;\n }"
] |
Gets the txinfo cache weight
@param conf The FluoConfiguration
@return The size of the cache value from the property value {@value #TX_INFO_CACHE_WEIGHT} if
it is set, else the value of the default value {@value #TX_INFO_CACHE_WEIGHT_DEFAULT} | [
"public static long getTxInfoCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(TX_INFO_CACHE_WEIGHT, TX_INFO_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\"Cache size must be positive for \" + TX_INFO_CACHE_WEIGHT);\n }\n return size;\n }"
] | [
"public void updateConfig(String appName, Map<String, String> config) {\n connection.execute(new ConfigUpdate(appName, config), apiKey);\n }",
"public void createProposals(final Collection<ContentAssistContext> contexts, final IIdeContentProposalAcceptor acceptor) {\n Iterable<ContentAssistContext> _filteredContexts = this.getFilteredContexts(contexts);\n for (final ContentAssistContext context : _filteredContexts) {\n ImmutableList<AbstractElement> _firstSetGrammarElements = context.getFirstSetGrammarElements();\n for (final AbstractElement element : _firstSetGrammarElements) {\n {\n boolean _canAcceptMoreProposals = acceptor.canAcceptMoreProposals();\n boolean _not = (!_canAcceptMoreProposals);\n if (_not) {\n return;\n }\n this.createProposals(element, context, acceptor);\n }\n }\n }\n }",
"private String getCachedETag(HttpHost host, String file) {\n Map<String, Object> cachedETags = readCachedETags();\n\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> hostMap =\n (Map<String, Object>)cachedETags.get(host.toURI());\n if (hostMap == null) {\n return null;\n }\n\n @SuppressWarnings(\"unchecked\")\n Map<String, String> etagMap = (Map<String, String>)hostMap.get(file);\n if (etagMap == null) {\n return null;\n }\n\n return etagMap.get(\"ETag\");\n }",
"public static sslfipskey[] get(nitro_service service) throws Exception{\n\t\tsslfipskey obj = new sslfipskey();\n\t\tsslfipskey[] response = (sslfipskey[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n // Create a list of all the possible element values\n int N = numCols*numRows;\n if( N < 0 )\n throw new IllegalArgumentException(\"matrix size is too large\");\n nz_total = Math.min(N,nz_total);\n\n int selected[] = new int[N];\n for (int i = 0; i < N; i++) {\n selected[i] = i;\n }\n\n for (int i = 0; i < nz_total; i++) {\n int s = rand.nextInt(N);\n int tmp = selected[s];\n selected[s] = selected[i];\n selected[i] = tmp;\n }\n\n // Create a sparse matrix\n DMatrixSparseTriplet ret = new DMatrixSparseTriplet(numRows,numCols,nz_total);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]/numCols;\n int col = selected[i]%numCols;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n ret.addItem(row,col, value);\n }\n\n return ret;\n }",
"public String getValueSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String valueSchema = schema.getField(valueFieldName).schema().toString();\n return valueSchema;\n }",
"public static base_responses flush(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject flushresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cacheobject();\n\t\t\t\tflushresources[i].locator = resources[i].locator;\n\t\t\t\tflushresources[i].url = resources[i].url;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].port = resources[i].port;\n\t\t\t\tflushresources[i].groupname = resources[i].groupname;\n\t\t\t\tflushresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}",
"public static boolean setCustomResponseForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, true, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public boolean matches(PathAddress address) {\n if (address == null) {\n return false;\n }\n if (equals(address)) {\n return true;\n }\n if (size() != address.size()) {\n return false;\n }\n for (int i = 0; i < size(); i++) {\n PathElement pe = getElement(i);\n PathElement other = address.getElement(i);\n if (!pe.matches(other)) {\n // Could be a multiTarget with segments\n if (pe.isMultiTarget() && !pe.isWildcard()) {\n boolean matched = false;\n for (String segment : pe.getSegments()) {\n if (segment.equals(other.getValue())) {\n matched = true;\n break;\n }\n }\n if (!matched) {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n return true;\n }"
] |
Write the standard set of day types.
@param calendars parent collection of calendars | [
"private void writeDayTypes(Calendars calendars)\n {\n DayTypes dayTypes = m_factory.createDayTypes();\n calendars.setDayTypes(dayTypes);\n List<DayType> typeList = dayTypes.getDayType();\n\n DayType dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"0\");\n dayType.setName(\"Working\");\n dayType.setDescription(\"A default working day\");\n\n dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"1\");\n dayType.setName(\"Nonworking\");\n dayType.setDescription(\"A default non working day\");\n\n dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"2\");\n dayType.setName(\"Use base\");\n dayType.setDescription(\"Use day from base calendar\");\n }"
] | [
"public GVRAnimator animate(int animIndex, float timeInSec)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n anim.animate(timeInSec);\n return anim;\n }",
"private void readTableBlock(int startIndex, int blockLength)\n {\n for (int index = startIndex; index < (startIndex + blockLength - 11); index++)\n {\n if (matchPattern(TABLE_BLOCK_PATTERNS, index))\n {\n int offset = index + 7;\n int nameLength = FastTrackUtility.getInt(m_buffer, offset);\n offset += 4;\n String name = new String(m_buffer, offset, nameLength, CharsetHelper.UTF16LE).toUpperCase();\n FastTrackTableType type = REQUIRED_TABLES.get(name);\n if (type != null)\n {\n m_currentTable = new FastTrackTable(type, this);\n m_tables.put(type, m_currentTable);\n }\n else\n {\n m_currentTable = null;\n }\n m_currentFields.clear();\n break;\n }\n }\n }",
"public float getNormalZ(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }",
"private void logBinaryStringInfo(StringBuilder binaryString) {\n\n encodeInfo += \"Binary Length: \" + binaryString.length() + \"\\n\";\n encodeInfo += \"Binary String: \";\n\n int nibble = 0;\n for (int i = 0; i < binaryString.length(); i++) {\n switch (i % 4) {\n case 0:\n if (binaryString.charAt(i) == '1') {\n nibble += 8;\n }\n break;\n case 1:\n if (binaryString.charAt(i) == '1') {\n nibble += 4;\n }\n break;\n case 2:\n if (binaryString.charAt(i) == '1') {\n nibble += 2;\n }\n break;\n case 3:\n if (binaryString.charAt(i) == '1') {\n nibble += 1;\n }\n encodeInfo += Integer.toHexString(nibble);\n nibble = 0;\n break;\n }\n }\n\n if ((binaryString.length() % 4) != 0) {\n encodeInfo += Integer.toHexString(nibble);\n }\n\n encodeInfo += \"\\n\";\n }",
"public static void acceptsZone(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_Z, OPT_ZONE), \"zone id\")\n .withRequiredArg()\n .describedAs(\"zone-id\")\n .ofType(Integer.class);\n }",
"public boolean hasForeignkey(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public static OptionalString ofNullable(ResourceKey key, String value) {\n return new GenericOptionalString(RUNTIME_SOURCE, key, value);\n }",
"public static boolean xpathExists(Node document, String xpathExpression, Map<String, String> namespaceMapping) throws XPathException,\n MarshallingException\n {\n Boolean result = (Boolean) executeXPath(document, xpathExpression, namespaceMapping, XPathConstants.BOOLEAN);\n return result != null && result;\n }",
"private static void updateBaseCalendarNames(List<Pair<ProjectCalendar, BigInteger>> baseCalendars, HashMap<BigInteger, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, BigInteger> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n BigInteger baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null)\n {\n cal.setParent(baseCal);\n }\n }\n\n }"
] |
Convenience method for retrieving an Integer resource.
@param locale locale identifier
@param key resource key
@return resource value | [
"public static final Integer getInteger(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return ((Integer) bundle.getObject(key));\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 static base_response update(nitro_service client, clusterinstance resource) throws Exception {\n\t\tclusterinstance updateresource = new clusterinstance();\n\t\tupdateresource.clid = resource.clid;\n\t\tupdateresource.deadinterval = resource.deadinterval;\n\t\tupdateresource.hellointerval = resource.hellointerval;\n\t\tupdateresource.preemption = resource.preemption;\n\t\treturn updateresource.update_resource(client);\n\t}",
"@Override\n public EnvironmentConfig setSetting(@NotNull final String key, @NotNull final Object value) {\n return (EnvironmentConfig) super.setSetting(key, value);\n }",
"private Long fetchServiceId(ServiceReference serviceReference) {\n return (Long) serviceReference.getProperty(org.osgi.framework.Constants.SERVICE_ID);\n }",
"public List<TimephasedWork> getCompleteWork(ProjectCalendar calendar, ResourceAssignment resourceAssignment, byte[] data)\n {\n LinkedList<TimephasedWork> list = new LinkedList<TimephasedWork>();\n\n if (calendar != null && data != null && data.length > 2 && MPPUtility.getShort(data, 0) > 0)\n {\n Date startDate = resourceAssignment.getStart();\n double finishTime = MPPUtility.getInt(data, 24);\n\n int blockCount = MPPUtility.getShort(data, 0);\n double previousCumulativeWork = 0;\n TimephasedWork previousAssignment = null;\n\n int index = 32;\n int currentBlock = 0;\n while (currentBlock < blockCount && index + 20 <= data.length)\n {\n double time = MPPUtility.getInt(data, index + 0);\n\n // If the start of this block is before the start of the assignment, or after the end of the assignment\n // the values don't make sense, so we'll just set the start of this block to be the start of the assignment.\n // This deals with an issue where odd timephased data like this was causing an MPP file to be read\n // extremely slowly.\n if (time < 0 || time > finishTime)\n {\n time = 0;\n }\n else\n {\n time /= 80;\n }\n Duration startWork = Duration.getInstance(time, TimeUnit.MINUTES);\n\n double currentCumulativeWork = (long) MPPUtility.getDouble(data, index + 4);\n double assignmentDuration = currentCumulativeWork - previousCumulativeWork;\n previousCumulativeWork = currentCumulativeWork;\n assignmentDuration /= 1000;\n Duration totalWork = Duration.getInstance(assignmentDuration, TimeUnit.MINUTES);\n time = (long) MPPUtility.getDouble(data, index + 12);\n time /= 125;\n time *= 6;\n Duration workPerDay = Duration.getInstance(time, TimeUnit.MINUTES);\n\n Date start;\n if (startWork.getDuration() == 0)\n {\n start = startDate;\n }\n else\n {\n start = calendar.getDate(startDate, startWork, true);\n }\n\n TimephasedWork assignment = new TimephasedWork();\n assignment.setStart(start);\n assignment.setAmountPerDay(workPerDay);\n assignment.setTotalAmount(totalWork);\n\n if (previousAssignment != null)\n {\n Date finish = calendar.getDate(startDate, startWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n\n list.add(assignment);\n previousAssignment = assignment;\n\n index += 20;\n ++currentBlock;\n }\n\n if (previousAssignment != null)\n {\n Duration finishWork = Duration.getInstance(finishTime / 80, TimeUnit.MINUTES);\n Date finish = calendar.getDate(startDate, finishWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n }\n\n return list;\n }",
"synchronized void transitionFailed(final InternalState state) {\n final InternalState current = this.internalState;\n if(state == current) {\n // Revert transition and mark as failed\n switch (current) {\n case PROCESS_ADDING:\n this.internalState = InternalState.PROCESS_STOPPED;\n break;\n case PROCESS_STARTED:\n internalSetState(getTransitionTask(InternalState.PROCESS_STOPPING), InternalState.PROCESS_STARTED, InternalState.PROCESS_ADDED);\n break;\n case PROCESS_STARTING:\n this.internalState = InternalState.PROCESS_ADDED;\n break;\n case SEND_STDIN:\n case SERVER_STARTING:\n this.internalState = InternalState.PROCESS_STARTED;\n break;\n }\n this.requiredState = InternalState.FAILED;\n notifyAll();\n }\n }",
"private RandomVariable getValueUnderlyingNumeraireRelative(LIBORModelMonteCarloSimulationModel model, Schedule legSchedule, boolean paysFloat, double swaprate, double notional) throws CalculationException {\r\n\t\tRandomVariable value\t= model.getRandomVariableForConstant(0.0);\r\n\r\n\t\tfor(int periodIndex = legSchedule.getNumberOfPeriods() - 1; periodIndex >= 0; periodIndex--) {\r\n\r\n\t\t\tdouble fixingTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getFixing());\r\n\t\t\tdouble paymentTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getPayment());\r\n\t\t\tdouble periodLength\t= legSchedule.getPeriodLength(periodIndex);\r\n\r\n\t\t\tRandomVariable\tnumeraireAtPayment = model.getNumeraire(paymentTime);\r\n\t\t\tRandomVariable\tmonteCarloProbabilitiesAtPayment = model.getMonteCarloWeights(paymentTime);\r\n\t\t\tif(swaprate != 0.0) {\r\n\t\t\t\tRandomVariable periodCashFlowFix = model.getRandomVariableForConstant(swaprate * periodLength * notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);\r\n\t\t\t\tvalue = value.add(periodCashFlowFix);\r\n\t\t\t}\r\n\t\t\tif(paysFloat) {\r\n\t\t\t\tRandomVariable libor = model.getLIBOR(fixingTime, fixingTime, paymentTime);\r\n\t\t\t\tRandomVariable periodCashFlowFloat = libor.mult(periodLength).mult(notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);\r\n\t\t\t\tvalue = value.add(periodCashFlowFloat);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn value;\r\n\t}",
"@Override\n public void finish() {\n if (started.get() && !finished.getAndSet(true)) {\n waitUntilFinished();\n super.finish();\n // recreate thread (don't start) for processor reuse\n createProcessorThread();\n clearQueues();\n started.set(false);\n }\n }",
"public static void setFilterBoxStyle(TextField searchBox) {\n\n searchBox.setIcon(FontOpenCms.FILTER);\n\n searchBox.setPlaceholder(\n org.opencms.ui.apps.Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n org.opencms.ui.apps.Messages.GUI_EXPLORER_FILTER_0));\n searchBox.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);\n }"
] |
Creates a style definition used for the body element.
@return The body style definition. | [
"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 long getTime(Date start1, Date end1, Date start2, Date end2)\n {\n long total = 0;\n\n if (start1 != null && end1 != null && start2 != null && end2 != null)\n {\n long start;\n long end;\n\n if (start1.getTime() < start2.getTime())\n {\n start = start2.getTime();\n }\n else\n {\n start = start1.getTime();\n }\n\n if (end1.getTime() < end2.getTime())\n {\n end = end1.getTime();\n }\n else\n {\n end = end2.getTime();\n }\n\n if (start < end)\n {\n total = end - start;\n }\n }\n\n return (total);\n }",
"public void setShadow(float radius, float dx, float dy, int color) {\n\t\tshadowRadius = radius;\n\t\tshadowDx = dx;\n\t\tshadowDy = dy;\n\t\tshadowColor = color;\n\t\tupdateShadow();\n\t}",
"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}",
"public static String getDefaultConversionFor(String javaType)\r\n {\r\n return _jdbcConversions.containsKey(javaType) ? (String)_jdbcConversions.get(javaType) : null;\r\n }",
"@SuppressWarnings(\"unchecked\")\n public Map<BsonValue, ChangeEvent<BsonDocument>> getEvents() {\n nsLock.readLock().lock();\n final Map<BsonValue, ChangeEvent<BsonDocument>> events;\n try {\n events = new HashMap<>(this.events);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.clear();\n return events;\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"protected boolean isReserved( String name ) {\n if( functions.isFunctionName(name))\n return true;\n\n for (int i = 0; i < name.length(); i++) {\n if( !isLetter(name.charAt(i)) )\n return true;\n }\n return false;\n }",
"@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 }",
"public boolean preHandle(HttpServletRequest request,\n HttpServletResponse response, Object handler) throws Exception {\n\n String queryString = request.getQueryString() == null ? \"\" : request.getQueryString();\n\n if (ConfigurationService.getInstance().isValid()\n || request.getServletPath().startsWith(\"/configuration\")\n || request.getServletPath().startsWith(\"/resources\")\n || queryString.contains(\"requestFromConfiguration=true\")) {\n return true;\n } else {\n response.sendRedirect(\"configuration\");\n return false;\n }\n }",
"public long getTimeFor(int player) {\n TrackPositionUpdate update = positions.get(player);\n if (update != null) {\n return interpolateTimeSinceUpdate(update, System.nanoTime());\n }\n return -1; // We don't know.\n }"
] |
Return the current working directory
@return the current working directory | [
"public File curDir() {\n File file = session().attribute(ATTR_PWD);\n if (null == file) {\n file = new File(System.getProperty(\"user.dir\"));\n session().attribute(ATTR_PWD, file);\n }\n return file;\n }"
] | [
"public static Node updateNode(Node node, List<Integer> partitionsList) {\n return new Node(node.getId(),\n node.getHost(),\n node.getHttpPort(),\n node.getSocketPort(),\n node.getAdminPort(),\n node.getZoneId(),\n partitionsList);\n }",
"public PropertiesEnvelope getUserProperties(String userId, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = getUserPropertiesWithHttpInfo(userId, aid);\n return resp.getData();\n }",
"public static <E extends Style.HasCssName, F extends Enum<? extends Style.HasCssName>> void addUniqueEnumStyleName(final UIObject uiObject,\n final Class<F> enumClass,\n final E style) {\n removeEnumStyleNames(uiObject, enumClass);\n addEnumStyleName(uiObject, style);\n }",
"public int scrollToNextPage() {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToNextPage getCurrentPage() = %d currentIndex = %d\",\n getCurrentPage(), mCurrentItemIndex);\n\n if (mSupportScrollByPage) {\n scrollToPage(getCurrentPage() + 1);\n } else {\n Log.w(TAG, \"Pagination is not enabled!\");\n }\n\n return mCurrentItemIndex;\n\t}",
"public String save() {\n JsonObject state = new JsonObject()\n .add(\"accessToken\", this.accessToken)\n .add(\"refreshToken\", this.refreshToken)\n .add(\"lastRefresh\", this.lastRefresh)\n .add(\"expires\", this.expires)\n .add(\"userAgent\", this.userAgent)\n .add(\"tokenURL\", this.tokenURL)\n .add(\"baseURL\", this.baseURL)\n .add(\"baseUploadURL\", this.baseUploadURL)\n .add(\"autoRefresh\", this.autoRefresh)\n .add(\"maxRequestAttempts\", this.maxRequestAttempts);\n return state.toString();\n }",
"private void readCalendar(Project.Calendars.Calendar calendar, HashMap<BigInteger, ProjectCalendar> map, List<Pair<ProjectCalendar, BigInteger>> baseCalendars)\n {\n ProjectCalendar bc = m_projectFile.addCalendar();\n bc.setUniqueID(NumberHelper.getInteger(calendar.getUID()));\n bc.setName(calendar.getName());\n BigInteger baseCalendarID = calendar.getBaseCalendarUID();\n if (baseCalendarID != null)\n {\n baseCalendars.add(new Pair<ProjectCalendar, BigInteger>(bc, baseCalendarID));\n }\n\n readExceptions(calendar, bc);\n boolean readExceptionsFromDays = bc.getCalendarExceptions().isEmpty();\n\n Project.Calendars.Calendar.WeekDays days = calendar.getWeekDays();\n if (days != null)\n {\n for (Project.Calendars.Calendar.WeekDays.WeekDay weekDay : days.getWeekDay())\n {\n readDay(bc, weekDay, readExceptionsFromDays);\n }\n }\n else\n {\n bc.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n bc.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n }\n\n readWorkWeeks(calendar, bc);\n\n map.put(calendar.getUID(), bc);\n\n m_eventManager.fireCalendarReadEvent(bc);\n }",
"public synchronized boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"LM.checkWrite(tx-\" + tx.getGUID() + \", \" + new Identity(obj, tx.getBroker()).toString() + \")\");\r\n LockStrategy lockStrategy = LockStrategyFactory.getStrategyFor(obj);\r\n return lockStrategy.checkWrite(tx, obj);\r\n }",
"public ParallelTaskBuilder setHttpPollerProcessor(\n HttpPollerProcessor httpPollerProcessor) {\n this.httpMeta.setHttpPollerProcessor(httpPollerProcessor);\n this.httpMeta.setPollable(true);\n return this;\n }",
"public void set_protocol(String protocol) throws nitro_exception\n\t{\n\t\tif (protocol == null || !(protocol.equalsIgnoreCase(\"http\") ||protocol.equalsIgnoreCase(\"https\"))) {\n\t\t\tthrow new nitro_exception(\"error: protocol value \" + protocol + \" is not supported\");\n\t\t}\n\t\tthis.protocol = protocol;\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.