query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Returns a map from a category path to the wrapper of all the sub-categories of the category with the path given as key.
@return a map from a category path to all sub-categories of the path's category. | [
"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 void printKeySet() {\r\n Set<?> keys = keySet();\r\n System.out.println(\"printing keyset:\");\r\n for (Object o: keys) {\r\n //System.out.println(Arrays.asList((Object[]) i.next()));\r\n System.out.println(o);\r\n }\r\n }",
"public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy, boolean convertToSql) throws PersistenceBrokerException\r\n {\r\n IndirectionHandler handler = ProxyHelper.getIndirectionHandler(objectOrProxy);\r\n\r\n if(handler != null)\r\n {\r\n return getKeyValues(cld, handler.getIdentity(), convertToSql); //BRJ: convert Identity\r\n }\r\n else\r\n {\r\n ClassDescriptor realCld = getRealClassDescriptor(cld, objectOrProxy);\r\n return getValuesForObject(realCld.getPkFields(), objectOrProxy, convertToSql);\r\n }\r\n }",
"protected void setColumnsFinalWidth() {\n log.debug(\"Setting columns final width.\");\n float factor;\n int printableArea = report.getOptions().getColumnWidth();\n\n //Create a list with only the visible columns.\n List visibleColums = getVisibleColumns();\n\n\n if (report.getOptions().isUseFullPageWidth()) {\n int columnsWidth = 0;\n int notRezisableWidth = 0;\n\n //Store in a variable the total with of all visible columns\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n columnsWidth += col.getWidth();\n if (col.isFixedWidth())\n notRezisableWidth += col.getWidth();\n }\n\n\n factor = (float) (printableArea - notRezisableWidth) / (float) (columnsWidth - notRezisableWidth);\n\n log.debug(\"printableArea = \" + printableArea\n + \", columnsWidth = \" + columnsWidth\n + \", columnsWidth = \" + columnsWidth\n + \", notRezisableWidth = \" + notRezisableWidth\n + \", factor = \" + factor);\n\n int acumulated = 0;\n int colFinalWidth;\n\n //Select the non-resizable columns\n Collection resizableColumns = CollectionUtils.select(visibleColums, new Predicate() {\n public boolean evaluate(Object arg0) {\n return !((AbstractColumn) arg0).isFixedWidth();\n }\n\n });\n\n //Finally, set the new width to the resizable columns\n for (Iterator iter = resizableColumns.iterator(); iter.hasNext(); ) {\n AbstractColumn col = (AbstractColumn) iter.next();\n\n if (!iter.hasNext()) {\n col.setWidth(printableArea - notRezisableWidth - acumulated);\n } else {\n colFinalWidth = (new Float(col.getWidth() * factor)).intValue();\n acumulated += colFinalWidth;\n col.setWidth(colFinalWidth);\n }\n }\n }\n\n // If the columns width changed, the X position must be setted again.\n int posx = 0;\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n col.setPosX(posx);\n posx += col.getWidth();\n }\n }",
"@Override\n public Configuration configuration() {\n return new MostUsefulConfiguration()\n // where to find the stories\n .useStoryLoader(new LoadFromClasspath(this.getClass())) \n // CONSOLE and TXT reporting\n .useStoryReporterBuilder(new StoryReporterBuilder().withDefaultFormats().withFormats(Format.CONSOLE, Format.TXT)); \n }",
"private void doExecute(Connection conn) throws SQLException\r\n {\r\n PreparedStatement stmt;\r\n int size;\r\n\r\n size = _methods.size();\r\n if ( size == 0 )\r\n {\r\n return;\r\n }\r\n stmt = conn.prepareStatement(_sql);\r\n try\r\n {\r\n m_platform.afterStatementCreate(stmt);\r\n }\r\n catch ( PlatformException e )\r\n {\r\n if ( e.getCause() instanceof SQLException )\r\n {\r\n throw (SQLException)e.getCause();\r\n }\r\n else\r\n {\r\n throw new SQLException(e.getMessage());\r\n }\r\n }\r\n try\r\n {\r\n m_platform.beforeBatch(stmt);\r\n }\r\n catch ( PlatformException e )\r\n {\r\n if ( e.getCause() instanceof SQLException )\r\n {\r\n throw (SQLException)e.getCause();\r\n }\r\n else\r\n {\r\n throw new SQLException(e.getMessage());\r\n }\r\n }\r\n try\r\n {\r\n for ( int i = 0; i < size; i++ )\r\n {\r\n Method method = (Method) _methods.get(i);\r\n try\r\n {\r\n if ( method.equals(ADD_BATCH) )\r\n {\r\n /**\r\n * we invoke on the platform and pass the stmt as an arg.\r\n */\r\n m_platform.addBatch(stmt);\r\n }\r\n else\r\n {\r\n method.invoke(stmt, (Object[]) _params.get(i));\r\n }\r\n }\r\n catch (IllegalArgumentException ex)\r\n {\r\n\t\t\t\t\tStringBuffer buffer = generateExceptionMessage(i, stmt, ex);\r\n\t\t\t\t\tthrow new SQLException(buffer.toString());\r\n }\r\n catch ( IllegalAccessException ex )\r\n {\r\n\t\t\t\t\tStringBuffer buffer = generateExceptionMessage(i, stmt, ex);\r\n throw new SQLException(buffer.toString());\r\n }\r\n catch ( InvocationTargetException ex )\r\n {\r\n Throwable th = ex.getTargetException();\r\n\r\n if ( th == null )\r\n {\r\n th = ex;\r\n }\r\n if ( th instanceof SQLException )\r\n {\r\n throw ((SQLException) th);\r\n }\r\n else\r\n {\r\n throw new SQLException(th.toString());\r\n }\r\n }\r\n\t\t\t\tcatch (PlatformException e)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow new SQLException(e.toString());\r\n\t\t\t\t}\r\n }\r\n try\r\n {\r\n /**\r\n * this will call the platform specific call\r\n */\r\n m_platform.executeBatch(stmt);\r\n }\r\n catch ( PlatformException e )\r\n {\r\n if ( e.getCause() instanceof SQLException )\r\n {\r\n throw (SQLException)e.getCause();\r\n }\r\n else\r\n {\r\n throw new SQLException(e.getMessage());\r\n }\r\n }\r\n\r\n }\r\n finally\r\n {\r\n stmt.close();\r\n _methods.clear();\r\n _params.clear();\r\n }\r\n }",
"public int size() {\n\t\tint size = cleared ? 0 : snapshot.size();\n\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\tcase PUT:\n\t\t\t\t\tif ( cleared || !snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize++;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tif ( !cleared && snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize--;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn size;\n\t}",
"synchronized void setServerProcessStopping() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(null, InternalState.STOPPED, InternalState.PROCESS_STOPPING);\n }",
"public static List<DockerImage> getImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId && image.hasManifest()) {\n list.add(image);\n }\n }\n return list;\n }",
"public static String minus(CharSequence self, Object target) {\n String s = self.toString();\n String text = DefaultGroovyMethods.toString(target);\n int index = s.indexOf(text);\n if (index == -1) return s;\n int end = index + text.length();\n if (s.length() > end) {\n return s.substring(0, index) + s.substring(end);\n }\n return s.substring(0, index);\n }"
] |
Unescape and unquote the path. Ready for translation. | [
"private static String clearPath(String path) {\n try {\n ExpressionBaseState state = new ExpressionBaseState(\"EXPR\", true, false);\n if (Util.isWindows()) {\n // to not require escaping FS name separator\n state.setDefaultHandler(WordCharacterHandler.IGNORE_LB_ESCAPE_OFF);\n } else {\n state.setDefaultHandler(WordCharacterHandler.IGNORE_LB_ESCAPE_ON);\n }\n // Remove escaping characters\n path = ArgumentWithValue.resolveValue(path, state);\n } catch (CommandFormatException ex) {\n // XXX OK, continue translation\n }\n // Remove quote to retrieve candidates.\n if (path.startsWith(\"\\\"\")) {\n path = path.substring(1);\n }\n // Could be an escaped \" character. We don't take into account this corner case.\n // concider it the end of the quoted part.\n if (path.endsWith(\"\\\"\")) {\n path = path.substring(0, path.length() - 1);\n }\n return path;\n }"
] | [
"public static float[][] toFloat(int[][] array) {\n float[][] n = new float[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (float) array[i][j];\n }\n }\n return n;\n }",
"Object readResolve() throws ObjectStreamException {\n Bean<?> bean = Container.instance(contextId).services().get(ContextualStore.class).<Bean<Object>, Object>getContextual(beanId);\n if (bean == null) {\n throw BeanLogger.LOG.proxyDeserializationFailure(beanId);\n }\n return Container.instance(contextId).deploymentManager().getClientProxyProvider().getClientProxy(bean);\n }",
"public ItemRequest<Task> delete(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"DELETE\");\n }",
"public static String constructSerializerInfoXml(StoreDefinition storeDefinition) {\n Element store = new Element(StoreDefinitionsMapper.STORE_ELMT);\n store.addContent(new Element(StoreDefinitionsMapper.STORE_NAME_ELMT).setText(storeDefinition.getName()));\n Element keySerializer = new Element(StoreDefinitionsMapper.STORE_KEY_SERIALIZER_ELMT);\n StoreDefinitionsMapper.addSerializer(keySerializer, storeDefinition.getKeySerializer());\n store.addContent(keySerializer);\n\n Element valueSerializer = new Element(StoreDefinitionsMapper.STORE_VALUE_SERIALIZER_ELMT);\n StoreDefinitionsMapper.addSerializer(valueSerializer, storeDefinition.getValueSerializer());\n store.addContent(valueSerializer);\n\n XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());\n return serializer.outputString(store);\n }",
"private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) {\n final ModelNode op = ServerOperations.createAddOperation(address);\n for (Map.Entry<String, String> prop : properties.entrySet()) {\n final String[] props = prop.getKey().split(\",\");\n if (props.length == 0) {\n throw new RuntimeException(\"Invalid property \" + prop);\n }\n ModelNode node = op;\n for (int i = 0; i < props.length - 1; ++i) {\n node = node.get(props[i]);\n }\n final String value = prop.getValue() == null ? \"\" : prop.getValue();\n if (value.startsWith(\"!!\")) {\n handleDmrString(node, props[props.length - 1], value);\n } else {\n node.get(props[props.length - 1]).set(value);\n }\n }\n return op;\n }",
"private void throwExceptionIfSafetyRestrictionsAreViolated(CmsObject cms, CmsSolrQuery query, boolean isSpell)\r\n throws CmsSearchException {\r\n\r\n if (!isDebug(cms, query)) {\r\n if (isSpell) {\r\n if (m_handlerSpellDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n } else {\r\n if (m_handlerSelectDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n int start = null != query.getStart() ? query.getStart().intValue() : 0;\r\n int rows = null != query.getRows() ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();\r\n if ((m_handlerMaxAllowedResultsAtAll >= 0) && ((rows + start) > m_handlerMaxAllowedResultsAtAll)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_AT_ALL_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsAtAll),\r\n Integer.valueOf(rows + start)));\r\n }\r\n if ((m_handlerMaxAllowedResultsPerPage >= 0) && (rows > m_handlerMaxAllowedResultsPerPage)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_PER_PAGE_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsPerPage),\r\n Integer.valueOf(rows)));\r\n }\r\n if ((null != m_handlerAllowedFields) && (Stream.of(m_handlerAllowedFields).anyMatch(x -> true))) {\r\n if (query.getFields().equals(CmsSolrQuery.ALL_RETURN_FIELDS)) {\r\n query.setFields(m_handlerAllowedFields);\r\n } else {\r\n for (String requestedField : query.getFields().split(\",\")) {\r\n if (Stream.of(m_handlerAllowedFields).noneMatch(\r\n allowedField -> allowedField.equals(requestedField))) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_REQUESTED_FIELD_NOT_ALLOWED_2,\r\n requestedField,\r\n Stream.of(m_handlerAllowedFields).reduce(\"\", (a, b) -> a + \",\" + b)));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }",
"protected void createKeystore() {\n\n\t\tjava.security.cert.Certificate signingCert = null;\n\t\tPrivateKey caPrivKey = null;\n\n\t\tif(_caCert == null || _caPrivKey == null)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tlog.debug(\"Keystore or signing cert & keypair not found. Generating...\");\n\n\t\t\t\tKeyPair caKeypair = getRSAKeyPair();\n\t\t\t\tcaPrivKey = caKeypair.getPrivate();\n\t\t\t\tsigningCert = CertificateCreator.createTypicalMasterCert(caKeypair);\n\n\t\t\t\tlog.debug(\"Done generating signing cert\");\n\t\t\t\tlog.debug(signingCert);\n\n\t\t\t\t_ks.load(null, _keystorepass);\n\n\t\t\t\t_ks.setCertificateEntry(_caCertAlias, signingCert);\n\t\t\t\t_ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new java.security.cert.Certificate[] {signingCert});\n\n\t\t\t\tFile caKsFile = new File(root, _caPrivateKeystore);\n\n\t\t\t\tOutputStream os = new FileOutputStream(caKsFile);\n\t\t\t\t_ks.store(os, _keystorepass);\n\n\t\t\t\tlog.debug(\"Wrote JKS keystore to: \" +\n\t\t\t\t\t\tcaKsFile.getAbsolutePath());\n\n\t\t\t\t// also export a .cer that can be imported as a trusted root\n\t\t\t\t// to disable all warning dialogs for interception\n\n\t\t\t\tFile signingCertFile = new File(root, EXPORTED_CERT_NAME);\n\n\t\t\t\tFileOutputStream cerOut = new FileOutputStream(signingCertFile);\n\n\t\t\t\tbyte[] buf = signingCert.getEncoded();\n\n\t\t\t\tlog.debug(\"Wrote signing cert to: \" + signingCertFile.getAbsolutePath());\n\n\t\t\t\tcerOut.write(buf);\n\t\t\t\tcerOut.flush();\n\t\t\t\tcerOut.close();\n\n\t\t\t\t_caCert = (X509Certificate)signingCert;\n\t\t\t\t_caPrivKey = caPrivKey;\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tlog.error(\"Fatal error creating/storing keystore or signing cert.\", e);\n\t\t\t\tthrow new Error(e);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlog.debug(\"Successfully loaded keystore.\");\n\t\t\tlog.debug(_caCert);\n\n\t\t}\n\n\t}",
"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 void updateWaveform(WaveformPreview preview) {\n this.preview.set(preview);\n if (preview == null) {\n waveformImage.set(null);\n } else {\n BufferedImage image = new BufferedImage(preview.segmentCount, preview.maxHeight, BufferedImage.TYPE_INT_RGB);\n Graphics g = image.getGraphics();\n g.setColor(Color.BLACK);\n g.fillRect(0, 0, preview.segmentCount, preview.maxHeight);\n for (int segment = 0; segment < preview.segmentCount; segment++) {\n g.setColor(preview.segmentColor(segment, false));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, false));\n if (preview.isColor) { // We have a front color segment to draw on top.\n g.setColor(preview.segmentColor(segment, true));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, true));\n }\n }\n waveformImage.set(image);\n }\n }"
] |
Read an individual Phoenix task relationship.
@param relation Phoenix task relationship | [
"private void readRelation(Relationship relation)\n {\n Task predecessor = m_activityMap.get(relation.getPredecessor());\n Task successor = m_activityMap.get(relation.getSuccessor());\n if (predecessor != null && successor != null)\n {\n Duration lag = relation.getLag();\n RelationType type = relation.getType();\n successor.addPredecessor(predecessor, type, lag);\n }\n }"
] | [
"public List<TimephasedCost> getTimephasedCost()\n {\n if (m_timephasedCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedWork != null && m_timephasedWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedCost = getTimephasedCostMultipleRates(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n else\n {\n m_timephasedCost = getTimephasedCostSingleRate(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedCost = getTimephasedCostFixedAmount();\n }\n\n }\n return m_timephasedCost;\n }",
"@Override\n public void start(String[] arguments) {\n boolean notStarted = !started.getAndSet(true);\n if (notStarted) {\n start(new MultiInstanceWorkloadStrategy(factory, name, arguments, endpointRegistry, execService));\n }\n }",
"public static rsskeytype get(nitro_service service) throws Exception{\n\t\trsskeytype obj = new rsskeytype();\n\t\trsskeytype[] response = (rsskeytype[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static base_response update(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager updateresource = new snmpmanager();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void checkAnonymous(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);\r\n\r\n if (!\"anonymous\".equals(access))\r\n {\r\n throw new ConstraintException(\"The access property of the field \"+fieldDef.getName()+\" defined in class \"+fieldDef.getOwner().getName()+\" cannot be changed\");\r\n }\r\n\r\n if ((fieldDef.getName() == null) || (fieldDef.getName().length() == 0))\r\n {\r\n throw new ConstraintException(\"An anonymous field defined in class \"+fieldDef.getOwner().getName()+\" has no name\");\r\n }\r\n }",
"public Widget findChildByName(final String name) {\n final List<Widget> groups = new ArrayList<>();\n groups.add(this);\n\n return findChildByNameInAllGroups(name, groups);\n }",
"public void setBackgroundColor(int color) {\n colorUnpressed = color;\n\n if(!isSelected()) {\n if (rippleAnimationSupport()) {\n ripple.setRippleBackground(colorUnpressed);\n }\n else {\n view.setBackgroundColor(colorUnpressed);\n }\n }\n }",
"public static Method findSetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)\n\t\t\tthrows IllegalArgumentException {\n\t\tMethod fieldSetMethod = findMethodFromNames(field, false, throwExceptions,\n\t\t\t\tmethodFromField(field, \"set\", databaseType, true), methodFromField(field, \"set\", databaseType, false));\n\t\tif (fieldSetMethod == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (fieldSetMethod.getReturnType() != void.class) {\n\t\t\tif (throwExceptions) {\n\t\t\t\tthrow new IllegalArgumentException(\"Return type of set method \" + fieldSetMethod.getName() + \" returns \"\n\t\t\t\t\t\t+ fieldSetMethod.getReturnType() + \" instead of void\");\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn fieldSetMethod;\n\t}",
"public List<Object> getAll(int dataSet) throws SerializationException {\r\n\t\tList<Object> result = new ArrayList<Object>();\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult.add(getData(ds));\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}"
] |
Send get request.
@param url the url
@param customHeaders the customHeaders
@param params the params
@return the string
@throws URISyntaxException the uri syntax exception
@throws IOException the io exception | [
"public static String get(String url, Map<String, String> customHeaders, Map<String, String> params) throws URISyntaxException, IOException, HTTPException {\n LOGGER.log(Level.INFO, \"Sending GET request to the url {0}\", url);\n\n URIBuilder uriBuilder = new URIBuilder(url);\n\n if (params != null && params.size() > 0) {\n for (Map.Entry<String, String> param : params.entrySet()) {\n uriBuilder.setParameter(param.getKey(), param.getValue());\n }\n }\n\n HttpGet httpGet = new HttpGet(uriBuilder.build());\n\n populateHeaders(httpGet, customHeaders);\n\n HttpClient httpClient = HttpClientBuilder.create().build();\n\n HttpResponse httpResponse = httpClient.execute(httpGet);\n\n int statusCode = httpResponse.getStatusLine().getStatusCode();\n if (isErrorStatus(statusCode)) {\n String jsonErrorResponse = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n throw new HTTPException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), jsonErrorResponse);\n }\n\n return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n }"
] | [
"public static void write(Path self, String text, String charset) throws IOException {\n Writer writer = null;\n try {\n writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.forName(charset));\n writer.write(text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }",
"public void animate(GVRHybridObject object, float animationTime)\n {\n GVRMeshMorph morph = (GVRMeshMorph) mTarget;\n\n mKeyInterpolator.animate(animationTime * mDuration, mCurrentValues);\n morph.setWeights(mCurrentValues);\n\n }",
"public static NodeList evaluateXpathExpression(String domStr, String xpathExpr)\n\t\t\tthrows XPathExpressionException, IOException {\n\t\tDocument dom = DomUtils.asDocument(domStr);\n\t\treturn evaluateXpathExpression(dom, xpathExpr);\n\t}",
"public static vpnsessionaction[] get(nitro_service service) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tvpnsessionaction[] response = (vpnsessionaction[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void addWSAddressingInterceptors(InterceptorProvider provider) {\n MAPAggregator mapAggregator = new MAPAggregator();\n MAPCodec mapCodec = new MAPCodec();\n\n provider.getInInterceptors().add(mapAggregator);\n provider.getInInterceptors().add(mapCodec);\n\n provider.getOutInterceptors().add(mapAggregator);\n provider.getOutInterceptors().add(mapCodec);\n\n provider.getInFaultInterceptors().add(mapAggregator);\n provider.getInFaultInterceptors().add(mapCodec);\n\n provider.getOutFaultInterceptors().add(mapAggregator);\n provider.getOutFaultInterceptors().add(mapCodec);\n }",
"public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) {\n // this is all the partitions the key replicates to.\n List<Integer> partitionIds = getReplicatingPartitionList(key);\n for(Integer partitionId: partitionIds) {\n // check which of the replicating partitions belongs to the node in\n // question\n if(getNodeIdForPartitionId(partitionId) == nodeId) {\n return partitionId;\n }\n }\n return null;\n }",
"public static base_response enable(nitro_service client, String trapname) throws Exception {\n\t\tsnmpalarm enableresource = new snmpalarm();\n\t\tenableresource.trapname = trapname;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}",
"public static void checkSvdMatrixSize(DMatrixRMaj U, boolean tranU, DMatrixRMaj W, DMatrixRMaj V, boolean tranV ) {\n int numSingular = Math.min(W.numRows,W.numCols);\n boolean compact = W.numRows == W.numCols;\n\n if( compact ) {\n if( U != null ) {\n if( tranU && U.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n else if( !tranU && U.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n }\n\n if( V != null ) {\n if( tranV && V.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n else if( !tranV && V.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n }\n } else {\n if( U != null && U.numRows != U.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n if( V != null && V.numRows != V.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n if( U != null && U.numRows != W.numRows )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n if( V != null && V.numRows != W.numCols )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n }\n }",
"private boolean isRelated(Task task, List<Relation> list)\n {\n boolean result = false;\n for (Relation relation : list)\n {\n if (relation.getTargetTask().getUniqueID().intValue() == task.getUniqueID().intValue())\n {\n result = true;\n break;\n }\n }\n return result;\n }"
] |
Get info for a given topic reply
@param topicId
Unique identifier of a topic for a given group {@link Topic}.
@param replyId
Unique identifier of a reply for a given topic {@link Reply}.
@return A group topic
@throws FlickrException
@see <a href="http://www.flickr.com/services/api/flickr.groups.discuss.replies.getInfo.html">API Documentation</a> | [
"public Reply getReplyInfo(String topicId, String replyId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REPLIES_GET_INFO);\r\n parameters.put(\"topic_id\", topicId);\r\n parameters.put(\"reply_id\", replyId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element replyElement = response.getPayload();\r\n\r\n return parseReply(replyElement);\r\n }"
] | [
"public static tmsessionpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\ttmsessionpolicy_binding obj = new tmsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\ttmsessionpolicy_binding response = (tmsessionpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public int getTrailingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong back = network ? 0 : getDivision(0).getMaxValue();\n\t\tint bitLen = 0;\n\t\tfor(int i = count - 1; i >= 0; i--) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != back) {\n\t\t\t\treturn bitLen + seg.getTrailingBitCount(network);\n\t\t\t}\n\t\t\tbitLen += seg.getBitCount();\n\t\t}\n\t\treturn bitLen;\n\t}",
"public void overrideCubeProperties(DockerCompositions overrideDockerCompositions) {\n final Set<String> containerIds = overrideDockerCompositions.getContainerIds();\n for (String containerId : containerIds) {\n\n // main definition of containers contains a container that must be overrode\n if (containers.containsKey(containerId)) {\n final CubeContainer cubeContainer = containers.get(containerId);\n final CubeContainer overrideCubeContainer = overrideDockerCompositions.get(containerId);\n\n cubeContainer.setRemoveVolumes(overrideCubeContainer.getRemoveVolumes());\n \n cubeContainer.setAlwaysPull(overrideCubeContainer.getAlwaysPull());\n\n if (overrideCubeContainer.hasAwait()) {\n cubeContainer.setAwait(overrideCubeContainer.getAwait());\n }\n\n if (overrideCubeContainer.hasBeforeStop()) {\n cubeContainer.setBeforeStop(overrideCubeContainer.getBeforeStop());\n }\n\n if (overrideCubeContainer.isManual()) {\n cubeContainer.setManual(overrideCubeContainer.isManual());\n }\n\n if (overrideCubeContainer.isKillContainer()) {\n cubeContainer.setKillContainer(overrideCubeContainer.isKillContainer());\n }\n } else {\n logger.warning(String.format(\"Overriding Container %s are not defined in main definition of containers.\",\n containerId));\n }\n }\n }",
"public ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine) {\n\t\tResult result = executionEngine.execute( getFindEntitiesQuery() );\n\t\treturn result.columnAs( BaseNeo4jEntityQueries.ENTITY_ALIAS );\n\t}",
"@Override\n\tpublic List<Object> loadEntitiesFromTuples(SharedSessionContractImplementor session, LockOptions lockOptions, OgmLoadingContext ogmContext) {\n\t\treturn loadEntity( null, null, session, lockOptions, ogmContext );\n\t}",
"protected static <S extends IPAddressSegment> void normalizePrefixBoundary(\n\t\t\tint sectionPrefixBits,\n\t\t\tS segments[],\n\t\t\tint segmentBitCount,\n\t\t\tint segmentByteCount,\n\t\t\tBiFunction<S, Integer, S> segProducer) {\n\t\t//we've already verified segment prefixes in super constructor. We simply need to check the case where the prefix is at a segment boundary,\n\t\t//whether the network side has the correct prefix\n\t\tint networkSegmentIndex = getNetworkSegmentIndex(sectionPrefixBits, segmentByteCount, segmentBitCount);\n\t\tif(networkSegmentIndex >= 0) {\n\t\t\tS segment = segments[networkSegmentIndex];\n\t\t\tif(!segment.isPrefixed()) {\n\t\t\t\tsegments[networkSegmentIndex] = segProducer.apply(segment, segmentBitCount);\n\t\t\t}\n\t\t}\n\t}",
"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 }",
"public static List<String> readLines(CharSequence self) throws IOException {\n return IOGroovyMethods.readLines(new StringReader(self.toString()));\n }",
"public void setBeliefValue(String agent_name, final String belief_name,\n final Object new_value, Connector connector) {\n\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Integer>() {\n\n public IFuture<Integer> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n bia.getBeliefbase().getBelief(belief_name)\n .setFact(new_value);\n return null;\n }\n }).get(new ThreadSuspendable());\n }"
] |
Wrap Statement with a proxy.
@param target statement handle
@param connectionHandle originating bonecp connection
@return Proxy to a statement. | [
"protected static Statement memorize(final Statement target, final ConnectionHandle connectionHandle) {\n\t\treturn (Statement) Proxy.newProxyInstance(\n\t\t\t\tStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {StatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}"
] | [
"private void writeCustomField(CustomField field) throws IOException\n {\n if (field.getAlias() != null)\n {\n m_writer.writeStartObject(null);\n m_writer.writeNameValuePair(\"field_type_class\", field.getFieldType().getFieldTypeClass().name().toLowerCase());\n m_writer.writeNameValuePair(\"field_type\", field.getFieldType().name().toLowerCase());\n m_writer.writeNameValuePair(\"field_alias\", field.getAlias());\n m_writer.writeEndObject();\n }\n }",
"@Modified(id = \"importerServices\")\n void modifiedImporterService(ServiceReference<ImporterService> serviceReference) {\n try {\n importersManager.modified(serviceReference);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.error(\"The ServiceProperty \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" of the ImporterService \"\n + bundleContext.getService(serviceReference) + \" doesn't provides a valid Filter.\"\n + \" To be used, it must provides a correct \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" ServiceProperty.\",\n invalidFilterException\n );\n importersManager.removeLinks(serviceReference);\n return;\n }\n if (importersManager.matched(serviceReference)) {\n importersManager.updateLinks(serviceReference);\n } else {\n importersManager.removeLinks(serviceReference);\n }\n }",
"public static base_responses save(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup saveresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tsaveresources[i] = new cachecontentgroup();\n\t\t\t\tsaveresources[i].name = resources[i].name;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, saveresources,\"save\");\n\t\t}\n\t\treturn result;\n\t}",
"private static Document objectForInsert(Tuple tuple, Document dbObject) {\n\t\tMongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();\n\t\tfor ( TupleOperation operation : tuple.getOperations() ) {\n\t\t\tString column = operation.getColumn();\n\t\t\tif ( notInIdField( snapshot, column ) ) {\n\t\t\t\tswitch ( operation.getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tMongoHelpers.setValue( dbObject, column, operation.getValue() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PUT_NULL:\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tMongoHelpers.resetValue( dbObject, column );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dbObject;\n\t}",
"public static AnnotationNode getAnnotation(AnnotatedNode node, String name) {\r\n List<AnnotationNode> annotations = node.getAnnotations();\r\n for (AnnotationNode annot : annotations) {\r\n if (annot.getClassNode().getName().equals(name)) {\r\n return annot;\r\n }\r\n }\r\n return null;\r\n }",
"static boolean matchPath(String[] tokenizedPattern, String[] strDirs, boolean isCaseSensitive) {\n int patIdxStart = 0;\n int patIdxEnd = tokenizedPattern.length - 1;\n int strIdxStart = 0;\n int strIdxEnd = strDirs.length - 1;\n\n // up to first '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxStart];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) {\n return false;\n }\n patIdxStart++;\n strIdxStart++;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n } else {\n if (patIdxStart > patIdxEnd) {\n // String not exhausted, but pattern is. Failure.\n return false;\n }\n }\n\n // up to last '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxEnd];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) {\n return false;\n }\n patIdxEnd--;\n strIdxEnd--;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n }\n\n while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {\n int patIdxTmp = -1;\n for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {\n if (tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n patIdxTmp = i;\n break;\n }\n }\n if (patIdxTmp == patIdxStart + 1) {\n // '**/**' situation, so skip one\n patIdxStart++;\n continue;\n }\n // Find the pattern between padIdxStart & padIdxTmp in str between\n // strIdxStart & strIdxEnd\n int patLength = (patIdxTmp - patIdxStart - 1);\n int strLength = (strIdxEnd - strIdxStart + 1);\n int foundIdx = -1;\n strLoop:\n for (int i = 0; i <= strLength - patLength; i++) {\n for (int j = 0; j < patLength; j++) {\n String subPat = tokenizedPattern[patIdxStart + j + 1];\n String subStr = strDirs[strIdxStart + i + j];\n if (!match(subPat, subStr, isCaseSensitive)) {\n continue strLoop;\n }\n }\n\n foundIdx = strIdxStart + i;\n break;\n }\n\n if (foundIdx == -1) {\n return false;\n }\n\n patIdxStart = patIdxTmp;\n strIdxStart = foundIdx + patLength;\n }\n\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n\n return true;\n }",
"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}",
"private void readTasks(Project gpProject)\n {\n Tasks tasks = gpProject.getTasks();\n readTaskCustomPropertyDefinitions(tasks);\n for (net.sf.mpxj.ganttproject.schema.Task task : tasks.getTask())\n {\n readTask(m_projectFile, task);\n }\n }",
"public GVRAnimation setOffset(float startOffset)\n {\n if(startOffset<0 || startOffset>mDuration){\n throw new IllegalArgumentException(\"offset should not be either negative or greater than duration\");\n }\n animationOffset = startOffset;\n mDuration = mDuration-animationOffset;\n return this;\n }"
] |
Used for initialization of the underlying map provider.
@param fragmentManager required for initialization | [
"public void initialize(FragmentManager fragmentManager) {\n AirMapInterface mapInterface = (AirMapInterface)\n fragmentManager.findFragmentById(R.id.map_frame);\n\n if (mapInterface != null) {\n initialize(fragmentManager, mapInterface);\n } else {\n initialize(fragmentManager, new DefaultAirMapViewBuilder(getContext()).builder().build());\n }\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 }",
"@Override\n public boolean decompose(DMatrixRBlock A) {\n if( A.numCols != A.numRows )\n throw new IllegalArgumentException(\"A must be square\");\n\n this.T = A;\n\n if( lower )\n return decomposeLower();\n else\n return decomposeUpper();\n }",
"private TransactionManager getTransactionManager()\r\n {\r\n TransactionManager retval = null;\r\n try\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"getTransactionManager called\");\r\n retval = TransactionManagerFactoryFactory.instance().getTransactionManager();\r\n }\r\n catch (TransactionManagerFactoryException e)\r\n {\r\n log.warn(\"Exception trying to obtain TransactionManager from Factory\", e);\r\n e.printStackTrace();\r\n }\r\n return retval;\r\n }",
"public Token add( Variable variable ) {\n Token t = new Token(variable);\n push( t );\n return t;\n }",
"public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"file\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n requestJSON.add(\"action\", action.toJSONString());\n\n if (message != null && !message.isEmpty()) {\n requestJSON.add(\"message\", message);\n }\n\n if (dueAt != null) {\n requestJSON.add(\"due_at\", BoxDateFormat.format(dueAt));\n }\n\n URL url = ADD_TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxTask addedTask = new BoxTask(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedTask.new Info(responseJSON);\n }",
"public VALUE get(KEY key) {\n CacheEntry<VALUE> entry;\n synchronized (this) {\n entry = values.get(key);\n }\n VALUE value;\n if (entry != null) {\n if (isExpiring) {\n long age = System.currentTimeMillis() - entry.timeCreated;\n if (age < expirationMillis) {\n value = getValue(key, entry);\n } else {\n countExpired++;\n synchronized (this) {\n values.remove(key);\n }\n value = null;\n }\n } else {\n value = getValue(key, entry);\n }\n } else {\n value = null;\n }\n if (value != null) {\n countHit++;\n } else {\n countMiss++;\n }\n return value;\n }",
"public static boolean doAcquireLock(final Jedis jedis, final String namespace, final String lockName, final String lockHolder, final int timeout) {\n final String key = JesqueUtils.createKey(namespace, lockName);\n // If lock already exists, extend it\n String existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n if (jedis.expire(key, timeout) == 1) {\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n }\n }\n // Check to see if the key exists and is expired for cleanup purposes\n if (jedis.exists(key) && (jedis.ttl(key) < 0)) {\n // It is expired, but it may be in the process of being created, so\n // sleep and check again\n try {\n Thread.sleep(2000);\n } catch (InterruptedException ie) {\n } // Ignore interruptions\n if (jedis.ttl(key) < 0) {\n existingLockHolder = jedis.get(key);\n // If it is our lock mark the time to live\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n if (jedis.expire(key, timeout) == 1) {\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n }\n } else { // The key is expired, whack it!\n jedis.del(key);\n }\n } else { // Someone else locked it while we were sleeping\n return false;\n }\n }\n // Ignore the cleanup steps above, start with no assumptions test\n // creating the key\n if (jedis.setnx(key, lockHolder) == 1) {\n // Created the lock, now set the expiration\n if (jedis.expire(key, timeout) == 1) { // Set the timeout\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n } else { // Don't know why it failed, but for now just report failed\n // acquisition\n return false;\n }\n }\n // Failed to create the lock\n return false;\n }",
"public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}",
"public PhotoList<Photo> getContactsPhotos(int count, boolean justFriends, boolean singlePhoto, boolean includeSelf) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTACTS_PHOTOS);\r\n\r\n if (count > 0) {\r\n parameters.put(\"count\", Integer.toString(count));\r\n }\r\n if (justFriends) {\r\n parameters.put(\"just_friends\", \"1\");\r\n }\r\n if (singlePhoto) {\r\n parameters.put(\"single_photo\", \"1\");\r\n }\r\n if (includeSelf) {\r\n parameters.put(\"include_self\", \"1\");\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n photos.setPage(\"1\");\r\n photos.setPages(\"1\");\r\n photos.setPerPage(\"\" + photoNodes.getLength());\r\n photos.setTotal(\"\" + photoNodes.getLength());\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }"
] |
seeks to a specified day of the week in the past or future.
@param direction the direction to seek: two possibilities
'<' go backward
'>' go forward
@param seekType the type of seek to perform (by_day or by_week)
by_day means we seek to the very next occurrence of the given day
by_week means we seek to the first occurrence of the given day week in the
next (or previous,) week (or multiple of next or previous week depending
on the seek amount.)
@param seekAmount the amount to seek. Must be guaranteed to parse as an integer
@param dayOfWeek the day of the week to seek to, represented as an integer from
1 to 7 (1 being Sunday, 7 being Saturday.) Must be guaranteed to parse as an Integer | [
"public void seekToDayOfWeek(String direction, String seekType, String seekAmount, String dayOfWeek) {\n int dayOfWeekInt = Integer.parseInt(dayOfWeek);\n int seekAmountInt = Integer.parseInt(seekAmount);\n assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT));\n assert(seekType.equals(SEEK_BY_DAY) || seekType.equals(SEEK_BY_WEEK));\n assert(dayOfWeekInt >= 1 && dayOfWeekInt <= 7);\n \n markDateInvocation();\n \n int sign = direction.equals(DIR_RIGHT) ? 1 : -1;\n if(seekType.equals(SEEK_BY_WEEK)) {\n // set our calendar to this weeks requested day of the week,\n // then add or subtract the week(s)\n _calendar.set(Calendar.DAY_OF_WEEK, dayOfWeekInt);\n _calendar.add(Calendar.DAY_OF_YEAR, seekAmountInt * 7 * sign);\n }\n \n else if(seekType.equals(SEEK_BY_DAY)) {\n // find the closest day\n do {\n _calendar.add(Calendar.DAY_OF_YEAR, sign);\n } while(_calendar.get(Calendar.DAY_OF_WEEK) != dayOfWeekInt);\n \n // now add/subtract any additional days\n if(seekAmountInt > 0) {\n _calendar.add(Calendar.WEEK_OF_YEAR, (seekAmountInt - 1) * sign);\n }\n }\n }"
] | [
"public ImageSource apply(ImageSource input) {\n ImageSource originalImage = input;\n\n int width = originalImage.getWidth();\n int height = originalImage.getHeight();\n\n boolean[][] matrix = new boolean[width][height]; // black n white boolean matrix; true = blck, false = white\n\n // Copy\n ImageSource filteredImage = new MatrixSource(input);\n\n int[] histogram = OtsuBinarize.imageHistogram(originalImage);\n\n int totalNumberOfpixels = height * width;\n\n int threshold = OtsuBinarize.threshold(histogram, totalNumberOfpixels);\n\n int black = 0;\n int white = 255;\n\n int gray;\n int alpha;\n int newColor;\n\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n gray = originalImage.getGray(i, j);\n\n if (gray > threshold) {\n matrix[i][j] = false;\n } else {\n matrix[i][j] = true;\n }\n\n }\n }\n\n int blackTreshold = letterThreshold(originalImage, matrix);\n\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n gray = originalImage.getGray(i, j);\n alpha = originalImage.getA(i, j);\n\n if (gray > blackTreshold) {\n newColor = white;\n } else {\n newColor = black;\n }\n\n newColor = ColorHelper.getARGB(newColor, newColor, newColor, alpha);\n filteredImage.setRGB(i, j, newColor);\n }\n }\n\n return filteredImage;\n }",
"public void loadClassifier(File file, Properties props) throws ClassCastException, IOException,\r\n ClassNotFoundException {\r\n Timing.startDoing(\"Loading classifier from \" + file.getAbsolutePath());\r\n BufferedInputStream bis;\r\n if (file.getName().endsWith(\".gz\")) {\r\n bis = new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)));\r\n } else {\r\n bis = new BufferedInputStream(new FileInputStream(file));\r\n }\r\n loadClassifier(bis, props);\r\n bis.close();\r\n Timing.endDoing();\r\n }",
"public static ManagementProtocolHeader parse(DataInput input) throws IOException {\n validateSignature(input);\n expectHeader(input, ManagementProtocol.VERSION_FIELD);\n int version = input.readInt();\n expectHeader(input, ManagementProtocol.TYPE);\n byte type = input.readByte();\n switch (type) {\n case ManagementProtocol.TYPE_REQUEST:\n return new ManagementRequestHeader(version, input);\n case ManagementProtocol.TYPE_RESPONSE:\n return new ManagementResponseHeader(version, input);\n case ManagementProtocol.TYPE_BYE_BYE:\n return new ManagementByeByeHeader(version);\n case ManagementProtocol.TYPE_PING:\n return new ManagementPingHeader(version);\n case ManagementProtocol.TYPE_PONG:\n return new ManagementPongHeader(version);\n default:\n throw ProtocolLogger.ROOT_LOGGER.invalidType(\"0x\" + Integer.toHexString(type));\n }\n }",
"public static String urlEncode(String path) throws URISyntaxException {\n if (isNullOrEmpty(path)) return path;\n\n return UrlEscapers.urlFragmentEscaper().escape(path);\n }",
"public int setPageCount(final int num) {\n int diff = num - getCheckableCount();\n if (diff > 0) {\n addIndicatorChildren(diff);\n } else if (diff < 0) {\n removeIndicatorChildren(-diff);\n }\n if (mCurrentPage >=num ) {\n mCurrentPage = 0;\n }\n setCurrentPage(mCurrentPage);\n return diff;\n }",
"public synchronized boolean undoRoleMappingRemove(final Object removalKey) {\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n RoleMappingImpl toRestore = removedRoles.remove(removalKey);\n if (toRestore != null && newRoles.containsKey(toRestore.getName()) == false) {\n newRoles.put(toRestore.getName(), toRestore);\n roleMappings = Collections.unmodifiableMap(newRoles);\n return true;\n }\n\n return false;\n }",
"private void addDirectSubTypes(XClass type, ArrayList subTypes)\r\n {\r\n if (type.isInterface())\r\n {\r\n if (type.getExtendingInterfaces() != null)\r\n {\r\n subTypes.addAll(type.getExtendingInterfaces());\r\n }\r\n // we have to traverse the implementing classes as these array contains all classes that\r\n // implement the interface, not only those who have an \"implement\" declaration\r\n // note that for whatever reason the declared interfaces are not exported via the XClass interface\r\n // so we have to get them via the underlying class which is hopefully a subclass of AbstractClass\r\n if (type.getImplementingClasses() != null)\r\n {\r\n Collection declaredInterfaces = null;\r\n XClass subType;\r\n\r\n for (Iterator it = type.getImplementingClasses().iterator(); it.hasNext(); )\r\n {\r\n subType = (XClass)it.next();\r\n if (subType instanceof AbstractClass)\r\n {\r\n declaredInterfaces = ((AbstractClass)subType).getDeclaredInterfaces();\r\n if ((declaredInterfaces != null) && declaredInterfaces.contains(type))\r\n {\r\n subTypes.add(subType);\r\n }\r\n }\r\n else\r\n {\r\n // Otherwise we have to live with the bug\r\n subTypes.add(subType);\r\n }\r\n }\r\n }\r\n }\r\n else\r\n {\r\n subTypes.addAll(type.getDirectSubclasses());\r\n }\r\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 void setMatrix(int[] matrix) {\n\t\tthis.matrix = matrix;\n\t\tsum = 0;\n\t\tfor (int i = 0; i < matrix.length; i++)\n\t\t\tsum += matrix[i];\n\t}"
] |
return a new managed connection. This connection is wrapped around the real connection and delegates to it
to get work done.
@param subject
@param info
@return | [
"public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo info)\r\n\t{\r\n\t\tUtil.log(\"In OTMJCAManagedConnectionFactory.createManagedConnection\");\r\n\t\ttry\r\n\t\t{\r\n\t\t\tKit kit = getKit();\r\n\t\t\tPBKey key = ((OTMConnectionRequestInfo) info).getPbKey();\r\n\t\t\tOTMConnection connection = kit.acquireConnection(key);\r\n\t\t\treturn new OTMJCAManagedConnection(this, connection, key);\r\n\t\t}\r\n\t\tcatch (ResourceException e)\r\n\t\t{\r\n\t\t\tthrow new OTMConnectionRuntimeException(e.getMessage());\r\n\t\t}\r\n\t}"
] | [
"public void removeVariable(String name)\n {\n Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();\n frame.remove(name);\n }",
"public Duration getDuration(int field) throws MPXJException\n {\n Duration result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = DurationUtility.getInstance(m_fields[field], m_formats.getDurationDecimalFormat(), m_locale);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"public Pair<int[][][][], int[][]> documentsToDataAndLabels(Collection<List<IN>> documents) {\r\n\r\n // first index is the number of the document\r\n // second index is position in the document also the index of the\r\n // clique/factor table\r\n // third index is the number of elements in the clique/window these features\r\n // are for (starting with last element)\r\n // fourth index is position of the feature in the array that holds them\r\n // element in data[i][j][k][m] is the index of the mth feature occurring in\r\n // position k of the jth clique of the ith document\r\n // int[][][][] data = new int[documentsSize][][][];\r\n List<int[][][]> data = new ArrayList<int[][][]>();\r\n\r\n // first index is the number of the document\r\n // second index is the position in the document\r\n // element in labels[i][j] is the index of the correct label (if it exists)\r\n // at position j in document i\r\n // int[][] labels = new int[documentsSize][];\r\n List<int[]> labels = new ArrayList<int[]>();\r\n\r\n int numDatums = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n Pair<int[][][], int[]> docPair = documentToDataAndLabels(doc);\r\n data.add(docPair.first());\r\n labels.add(docPair.second());\r\n numDatums += doc.size();\r\n }\r\n\r\n System.err.println(\"numClasses: \" + classIndex.size() + ' ' + classIndex);\r\n System.err.println(\"numDocuments: \" + data.size());\r\n System.err.println(\"numDatums: \" + numDatums);\r\n System.err.println(\"numFeatures: \" + featureIndex.size());\r\n printFeatures();\r\n\r\n int[][][][] dataA = new int[0][][][];\r\n int[][] labelsA = new int[0][];\r\n\r\n return new Pair<int[][][][], int[][]>(data.toArray(dataA), labels.toArray(labelsA));\r\n }",
"public void updateInfo(BoxWebLink.Info info) {\n URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n String body = info.getPendingChanges();\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }",
"public static Object lookup(String jndiName)\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"lookup(\"+jndiName+\") was called\");\r\n try\r\n {\r\n return getContext().lookup(jndiName);\r\n }\r\n catch (NamingException e)\r\n {\r\n throw new OJBRuntimeException(\"Lookup failed for: \" + jndiName, e);\r\n }\r\n catch(OJBRuntimeException e)\r\n {\r\n throw e;\r\n }\r\n }",
"private void buildJoinTree(Criteria crit)\r\n {\r\n Enumeration e = crit.getElements();\r\n\r\n while (e.hasMoreElements())\r\n {\r\n Object o = e.nextElement();\r\n if (o instanceof Criteria)\r\n {\r\n buildJoinTree((Criteria) o);\r\n }\r\n else\r\n {\r\n SelectionCriteria c = (SelectionCriteria) o;\r\n \r\n // BRJ skip SqlCriteria\r\n if (c instanceof SqlCriteria)\r\n {\r\n continue;\r\n }\r\n \r\n // BRJ: Outer join for OR\r\n boolean useOuterJoin = (crit.getType() == Criteria.OR);\r\n\r\n // BRJ: do not build join tree for subQuery attribute \r\n if (c.getAttribute() != null && c.getAttribute() instanceof String)\r\n {\r\n\t\t\t\t\t//buildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getAlias(), c.getPathClasses());\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n if (c instanceof FieldCriteria)\r\n {\r\n FieldCriteria cc = (FieldCriteria) c;\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) cc.getValue(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n }\r\n }\r\n }",
"protected byte[] getBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache() || (cached = valueCache.lowerBytes) == null) {\n\t\t\tvalueCache.lowerBytes = cached = getBytesImpl(true);\n\t\t}\n\t\treturn cached;\n\t}",
"public static String[] addStringToArray(String[] array, String str) {\n if (isEmpty(array)) {\n return new String[]{str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }",
"@Api\n\tpublic void setFeatureModel(FeatureModel featureModel) throws LayerException {\n\t\tthis.featureModel = featureModel;\n\t\tif (null != getLayerInfo()) {\n\t\t\tfeatureModel.setLayerInfo(getLayerInfo());\n\t\t}\n\t\tfilterService.registerFeatureModel(featureModel);\n\t}"
] |
Create a discount curve from forwards given by a LIBORMonteCarloModel. If the model uses multiple curves, return its discount curve.
@param forwardCurveName name of the forward curve.
@param model Monte Carlo model providing the forwards.
@param startTime time at which the curve starts, i.e. zero time for the curve
@return a discount curve from forwards given by a LIBORMonteCarloModel.
@throws CalculationException Thrown if the model failed to provide the forward rates. | [
"public static DiscountCurveInterface createDiscountCurveFromMonteCarloLiborModel(String forwardCurveName, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\t\t// Check if the LMM uses a discount curve which is created from a forward curve\n\t\tif(model.getModel().getDiscountCurve()==null || model.getModel().getDiscountCurve().getName().toLowerCase().contains(\"DiscountCurveFromForwardCurve\".toLowerCase())){\n\t\t\treturn new DiscountCurveFromForwardCurve(ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel(forwardCurveName, model, startTime));\n\t\t}\n\t\telse {\n\t\t\t// i.e. forward curve of Libor Model not OIS. In this case return the OIS curve.\n\t\t\t// Only at startTime 0!\n\t\t\treturn (DiscountCurveInterface) model.getModel().getDiscountCurve();\n\t\t}\n\n\t}"
] | [
"public Bundler put(String key, String[] value) {\n delegate.putStringArray(key, value);\n return this;\n }",
"void registerAlias(FieldType type, String alias)\n {\n m_aliasMap.put(new Pair<FieldTypeClass, String>(type.getFieldTypeClass(), alias), type);\n }",
"public static base_response add(nitro_service client, dnspolicylabel resource) throws Exception {\n\t\tdnspolicylabel addresource = new dnspolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.transform = resource.transform;\n\t\treturn addresource.add_resource(client);\n\t}",
"public Collection<HazeltaskTask<GROUP>> call() throws Exception {\n try {\n if(isShutdownNow)\n return this.getDistributedExecutorService().shutdownNowWithHazeltask();\n else\n this.getDistributedExecutorService().shutdown();\n } catch(IllegalStateException e) {}\n \n return Collections.emptyList();\n }",
"public final ProcessorDependencyGraph getProcessorGraph() {\n if (this.processorGraph == null) {\n synchronized (this) {\n if (this.processorGraph == null) {\n final Map<String, Class<?>> attcls = new HashMap<>();\n for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {\n attcls.put(attribute.getKey(), attribute.getValue().getValueType());\n }\n this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);\n }\n }\n }\n return this.processorGraph;\n }",
"public void addAll(@NonNull final Collection<T> collection) {\n final int length = collection.size();\n if (length == 0) {\n return;\n }\n synchronized (mLock) {\n final int position = getItemCount();\n mObjects.addAll(collection);\n notifyItemRangeInserted(position, length);\n }\n }",
"public ClassNode addInterface(String name) {\n ClassNode intf = infoBase.node(name);\n addInterface(intf);\n return this;\n }",
"public void notifyHeaderItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= headerItemCount || toPosition >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \" + toPosition + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition, toPosition);\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addFacet(String... attributes) {\n for (String attribute : attributes) {\n final Integer value = facetRequestCount.get(attribute);\n facetRequestCount.put(attribute, value == null ? 1 : value + 1);\n if (value == null || value == 0) {\n facets.add(attribute);\n }\n }\n rebuildQueryFacets();\n return this;\n }"
] |
See page 385 of Fundamentals of Matrix Computations 2nd | [
"public void symm2x2_fast( double a11 , double a12, double a22 )\n {\n// double p = (a11 - a22)*0.5;\n// double r = Math.sqrt(p*p + a12*a12);\n//\n// value0.real = a22 + a12*a12/(r-p);\n// value1.real = a22 - a12*a12/(r+p);\n// }\n//\n// public void symm2x2_std( double a11 , double a12, double a22 )\n// {\n double left = (a11+a22)*0.5;\n double b = (a11-a22)*0.5;\n double right = Math.sqrt(b*b+a12*a12);\n value0.real = left + right;\n value1.real = left - right;\n }"
] | [
"public Map<String, String> getTitleLocale() {\n\n if (m_localeTitles == null) {\n m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object inputLocale) {\n\n Locale locale = null;\n if (null != inputLocale) {\n if (inputLocale instanceof Locale) {\n locale = (Locale)inputLocale;\n } else if (inputLocale instanceof String) {\n try {\n locale = LocaleUtils.toLocale((String)inputLocale);\n } catch (IllegalArgumentException | NullPointerException e) {\n // do nothing, just go on without locale\n }\n }\n }\n return getLocaleSpecificTitle(locale);\n }\n\n });\n }\n return m_localeTitles;\n }",
"@Override\n public ConditionBuilder as(String variable)\n {\n Assert.notNull(variable, \"Variable name must not be null.\");\n this.setOutputVariablesName(variable);\n return this;\n }",
"public static nstrafficdomain_bridgegroup_binding[] get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@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 String checkRequiredProperties(Properties props,\r\n String ... requiredProps) {\r\n for (String required : requiredProps) {\r\n if (props.getProperty(required) == null) {\r\n return required;\r\n }\r\n }\r\n return null;\r\n }",
"private static void readAndAddDocumentsFromStream(\n final SolrClient client,\n final String lang,\n final InputStream is,\n final List<SolrInputDocument> documents,\n final boolean closeStream) {\n\n final BufferedReader br = new BufferedReader(new InputStreamReader(is));\n\n try {\n String line = br.readLine();\n while (null != line) {\n\n final SolrInputDocument document = new SolrInputDocument();\n // Each field is named after the schema \"entry_xx\" where xx denotes\n // the two digit language code. See the file spellcheck/conf/schema.xml.\n document.addField(\"entry_\" + lang, line);\n documents.add(document);\n\n // Prevent OutOfMemoryExceptions ...\n if (documents.size() >= MAX_LIST_SIZE) {\n addDocuments(client, documents, false);\n documents.clear();\n }\n\n line = br.readLine();\n }\n } catch (IOException e) {\n LOG.error(\"Could not read spellcheck dictionary from input stream.\");\n } catch (SolrServerException e) {\n LOG.error(\"Error while adding documents to Solr server. \");\n } finally {\n try {\n if (closeStream) {\n br.close();\n }\n } catch (Exception e) {\n // Nothing to do here anymore ....\n }\n }\n }",
"private void setViewPagerScroller() {\n try {\n Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n Field interpolatorField = ViewPager.class.getDeclaredField(\"sInterpolator\");\n interpolatorField.setAccessible(true);\n\n scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));\n scrollerField.set(this, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\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 }",
"public static List<Integer> getAllPartitions(AdminClient adminClient) {\n List<Integer> partIds = Lists.newArrayList();\n partIds = Lists.newArrayList();\n for(Node node: adminClient.getAdminClientCluster().getNodes()) {\n partIds.addAll(node.getPartitionIds());\n }\n return partIds;\n }"
] |
Use this API to fetch tmtrafficaction resource of given name . | [
"public static tmtrafficaction get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficaction obj = new tmtrafficaction();\n\t\tobj.set_name(name);\n\t\ttmtrafficaction response = (tmtrafficaction) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) {\n login(userIdentifier);\n RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl);\n }",
"private Number calculateDurationPercentComplete(Row row)\n {\n double result = 0;\n double targetDuration = row.getDuration(\"target_drtn_hr_cnt\").getDuration();\n double remainingDuration = row.getDuration(\"remain_drtn_hr_cnt\").getDuration();\n\n if (targetDuration == 0)\n {\n if (remainingDuration == 0)\n {\n if (\"TK_Complete\".equals(row.getString(\"status_code\")))\n {\n result = 100;\n }\n }\n }\n else\n {\n if (remainingDuration < targetDuration)\n {\n result = ((targetDuration - remainingDuration) * 100) / targetDuration;\n }\n }\n\n return NumberHelper.getDouble(result);\n }",
"public static base_response unset(nitro_service client, nsacl6 resource, String[] args) throws Exception{\n\t\tnsacl6 unsetresource = new nsacl6();\n\t\tunsetresource.acl6name = resource.acl6name;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"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 }",
"synchronized void reconnectServerProcess(final ManagedServerBootCmdFactory factory) {\n if(this.requiredState != InternalState.SERVER_STARTED) {\n this.bootConfiguration = factory;\n this.requiredState = InternalState.SERVER_STARTED;\n ROOT_LOGGER.reconnectingServer(serverName);\n internalSetState(new ReconnectTask(), InternalState.STOPPED, InternalState.SEND_STDIN);\n }\n }",
"public boolean containsEntryFor(int maturityInMonths, int tenorInMonths, int moneynessBP) {\r\n\t\treturn entryMap.containsKey(new DataKey(maturityInMonths, tenorInMonths, moneynessBP));\r\n\t}",
"protected final boolean isGLThread() {\n final Thread glThread = sGLThread.get();\n return glThread != null && glThread.equals(Thread.currentThread());\n }",
"public static final String printFinishDateTime(Date value)\n {\n if (value != null)\n {\n value = DateHelper.addDays(value, 1);\n }\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }",
"public static BoxCollaborationWhitelistExemptTarget.Info create(final BoxAPIConnection api, String userID) {\n URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"user\", new JsonObject()\n .add(\"type\", \"user\")\n .add(\"id\", userID));\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxCollaborationWhitelistExemptTarget userWhitelist = new BoxCollaborationWhitelistExemptTarget(api,\n responseJSON.get(\"id\").asString());\n\n return userWhitelist.new Info(responseJSON);\n }"
] |
Create users for the given array of addresses. The passwords will be set to the email addresses.
@param greenMail Greenmail instance to create users for
@param addresses Addresses | [
"public static void createUsers(GreenMailOperations greenMail, InternetAddress... addresses) {\n for (InternetAddress address : addresses) {\n greenMail.setUser(address.getAddress(), address.getAddress());\n }\n }"
] | [
"public static void popShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.size() > 0) {\n shells.remove(shells.size() - 1);\n }\n\n }",
"public void setHeader(String header, String value) {\n StringValidator.throwIfEmptyOrNull(\"header\", header);\n StringValidator.throwIfEmptyOrNull(\"value\", value);\n\n if (headers == null) {\n headers = new HashMap<String, String>();\n }\n\n headers.put(header, value);\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 Axis getOrientationAxis() {\n final Axis axis;\n switch(getOrientation()) {\n case HORIZONTAL:\n axis = Axis.X;\n break;\n case VERTICAL:\n axis = Axis.Y;\n break;\n case STACK:\n axis = Axis.Z;\n break;\n default:\n Log.w(TAG, \"Unsupported orientation %s\", mOrientation);\n axis = Axis.X;\n break;\n }\n return axis;\n }",
"public static final ProjectFile setProjectNameAndRead(File directory) throws MPXJException\n {\n List<String> projects = listProjectNames(directory);\n\n if (!projects.isEmpty())\n {\n P3DatabaseReader reader = new P3DatabaseReader();\n reader.setProjectName(projects.get(0));\n return reader.read(directory);\n }\n\n return null;\n }",
"private String getDestinationHostName(String hostName) {\n List<ServerRedirect> servers = serverRedirectService\n .tableServers(requestInformation.get().client.getId());\n for (ServerRedirect server : servers) {\n if (server.getSrcUrl().compareTo(hostName) == 0) {\n if (server.getDestUrl() != null && server.getDestUrl().compareTo(\"\") != 0) {\n return server.getDestUrl();\n } else {\n logger.warn(\"Using source URL as destination URL since no destination was specified for: {}\",\n server.getSrcUrl());\n }\n\n // only want to apply the first host name change found\n break;\n }\n }\n\n return hostName;\n }",
"public T transitFloat(int propertyId, float... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofFloat(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofFloat(property, vals));\n return self();\n }",
"public static String getParameter(DbConn cnx, String key, String defaultValue)\n {\n try\n {\n return cnx.runSelectSingle(\"globalprm_select_by_key\", 3, String.class, key);\n }\n catch (NoResultException e)\n {\n return defaultValue;\n }\n }",
"public static String getAt(GString text, Range range) {\n return getAt(text.toString(), range);\n }"
] |
This version assumes relativeIndices array no longer needs to
be copied. Further it is assumed that it has already been
checked or assured by construction that relativeIndices
is sorted. | [
"private static Clique valueOfHelper(int[] relativeIndices) {\r\n // if clique already exists, return that one\r\n Clique c = new Clique();\r\n c.relativeIndices = relativeIndices;\r\n return intern(c);\r\n }"
] | [
"protected boolean isChangedByMask(int maskValue, Integer segmentPrefixLength) throws IncompatibleAddressException {\r\n\t\tboolean hasBits = (segmentPrefixLength != null);\r\n\t\tif(hasBits && (segmentPrefixLength < 0 || segmentPrefixLength > getBitCount())) {\r\n\t\t\tthrow new PrefixLenException(this, segmentPrefixLength);\r\n\t\t}\r\n\t\t\r\n\t\t//note that the mask can represent a range (for example a CIDR mask), \r\n\t\t//but we use the lowest value (maskSegment.value) in the range when masking (ie we discard the range)\r\n\t\tint value = getSegmentValue();\r\n\t\tint upperValue = getUpperSegmentValue();\r\n\t\treturn value != (value & maskValue) ||\r\n\t\t\t\tupperValue != (upperValue & maskValue) ||\r\n\t\t\t\t\t\t(isPrefixed() ? !getSegmentPrefixLength().equals(segmentPrefixLength) : hasBits);\r\n\t}",
"protected String getJavaExecutablePath() {\n String executableName = isWindows() ? \"bin/java.exe\" : \"bin/java\";\n return PROPERTIES.getJavaHome().resolve(executableName).toAbsolutePath().toString();\n }",
"protected boolean isFiltered(AbstractElement canddiate, Param param) {\n\t\tif (canddiate instanceof Group) {\n\t\t\tGroup group = (Group) canddiate;\n\t\t\tif (group.getGuardCondition() != null) {\n\t\t\t\tSet<Parameter> context = param.getAssignedParametes();\n\t\t\t\tConditionEvaluator evaluator = new ConditionEvaluator(context);\n\t\t\t\tif (!evaluator.evaluate(group.getGuardCondition())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"protected void eciProcess() {\n\n EciMode eci = EciMode.of(content, \"ISO8859_1\", 3)\n .or(content, \"ISO8859_2\", 4)\n .or(content, \"ISO8859_3\", 5)\n .or(content, \"ISO8859_4\", 6)\n .or(content, \"ISO8859_5\", 7)\n .or(content, \"ISO8859_6\", 8)\n .or(content, \"ISO8859_7\", 9)\n .or(content, \"ISO8859_8\", 10)\n .or(content, \"ISO8859_9\", 11)\n .or(content, \"ISO8859_10\", 12)\n .or(content, \"ISO8859_11\", 13)\n .or(content, \"ISO8859_13\", 15)\n .or(content, \"ISO8859_14\", 16)\n .or(content, \"ISO8859_15\", 17)\n .or(content, \"ISO8859_16\", 18)\n .or(content, \"Windows_1250\", 21)\n .or(content, \"Windows_1251\", 22)\n .or(content, \"Windows_1252\", 23)\n .or(content, \"Windows_1256\", 24)\n .or(content, \"SJIS\", 20)\n .or(content, \"UTF8\", 26);\n\n if (EciMode.NONE.equals(eci)) {\n throw new OkapiException(\"Unable to determine ECI mode.\");\n }\n\n eciMode = eci.mode;\n inputData = toBytes(content, eci.charset);\n\n encodeInfo += \"ECI Mode: \" + eci.mode + \"\\n\";\n encodeInfo += \"ECI Charset: \" + eci.charset.name() + \"\\n\";\n }",
"protected String getUniqueString(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n ResultSetAndStatement rsStmt = null;\r\n String returnValue = null;\r\n try\r\n {\r\n rsStmt = getBrokerForClass().serviceJdbcAccess().executeSQL(\r\n \"select newid()\", field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n if (rsStmt.m_rs.next())\r\n {\r\n returnValue = rsStmt.m_rs.getString(1);\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass()\r\n + \": Can't lookup new oid for field \" + field);\r\n }\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n\r\n finally\r\n {\r\n // close the used resources\r\n if (rsStmt != null) rsStmt.close();\r\n }\r\n return returnValue;\r\n }",
"@PostConstruct\n\tprotected void postConstruct() {\n\t\tif (null == authenticationServices) {\n\t\t\tauthenticationServices = new ArrayList<AuthenticationService>();\n\t\t}\n\t\tif (!excludeDefault) {\n\t\t\tauthenticationServices.add(staticAuthenticationService);\n\t\t}\n\t}",
"private void sendAnnouncement(InetAddress broadcastAddress) {\n try {\n DatagramPacket announcement = new DatagramPacket(announcementBytes, announcementBytes.length,\n broadcastAddress, DeviceFinder.ANNOUNCEMENT_PORT);\n socket.get().send(announcement);\n Thread.sleep(getAnnounceInterval());\n } catch (Throwable t) {\n logger.warn(\"Unable to send announcement packet, shutting down\", t);\n stop();\n }\n }",
"private static void mergeBlocks(List< Block > blocks) {\r\n for (int i = 1; i < blocks.size(); i++) {\r\n Block b1 = blocks.get(i - 1);\r\n Block b2 = blocks.get(i);\r\n if ((b1.mode == b2.mode) &&\r\n (b1.mode != EncodingMode.NUM || b1.length + b2.length <= MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n b1.length += b2.length;\r\n blocks.remove(i);\r\n i--;\r\n }\r\n }\r\n }",
"public void setValue(FieldContainer container, byte[] data)\n {\n if (data != null)\n {\n container.set(m_type, ((MPPUtility.getInt(data, m_offset) & m_mask) == 0) ? m_zeroValue : m_nonZeroValue);\n }\n }"
] |
Apply content type to response with result provided.
If `result` is an error then it might not apply content type as requested:
* If request is not ajax request, then use `text/html`
* If request is ajax request then apply requested content type only when `json` or `xml` is requested
* otherwise use `text/html`
@param result
the result used to check if it is error result
@return this `ActionContext`. | [
"public ActionContext applyContentType(Result result) {\n if (!result.status().isError()) {\n return applyContentType();\n }\n return applyContentType(contentTypeForErrorResult(req()));\n }"
] | [
"public static nsrpcnode[] get(nitro_service service) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tnsrpcnode[] response = (nsrpcnode[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Photo getListPhoto(String photoId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_PHOTO);\n\n parameters.put(\"photo_id\", photoId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element photoElement = response.getPayload();\n Photo photo = new Photo();\n photo.setId(photoElement.getAttribute(\"id\"));\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) photoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setId(tagElement.getAttribute(\"id\"));\n tag.setAuthor(tagElement.getAttribute(\"author\"));\n tag.setAuthorName(tagElement.getAttribute(\"authorname\"));\n tag.setRaw(tagElement.getAttribute(\"raw\"));\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n photo.setTags(tags);\n return photo;\n }",
"public static String truncate(int n, int smallestDigit, int biggestDigit) {\r\n int numDigits = biggestDigit - smallestDigit + 1;\r\n char[] result = new char[numDigits];\r\n for (int j = 1; j < smallestDigit; j++) {\r\n n = n / 10;\r\n }\r\n for (int j = numDigits - 1; j >= 0; j--) {\r\n result[j] = Character.forDigit(n % 10, 10);\r\n n = n / 10;\r\n }\r\n return new String(result);\r\n }",
"private void setRequestSitefilter(WbGetEntitiesActionData properties) {\n\t\tif (this.filter.excludeAllSiteLinks()\n\t\t\t\t|| this.filter.getSiteLinkFilter() == null) {\n\t\t\treturn;\n\t\t}\n\t\tproperties.sitefilter = ApiConnection.implodeObjects(this.filter\n\t\t\t\t.getSiteLinkFilter());\n\t}",
"public void setDefault() {\n try {\n TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);\n String phone = telephonyManager.getLine1Number();\n if (phone != null && !phone.isEmpty()) {\n this.setNumber(phone);\n } else {\n String iso = telephonyManager.getNetworkCountryIso();\n setEmptyDefault(iso);\n }\n } catch (SecurityException e) {\n setEmptyDefault();\n }\n }",
"public void refresh(String[] configLocations) throws GeomajasException {\n\t\ttry {\n\t\t\tsetConfigLocations(configLocations);\n\t\t\trefresh();\n\t\t} catch (Exception e) {\n\t\t\tthrow new GeomajasException(e, ExceptionCode.REFRESH_CONFIGURATION_FAILED);\n\t\t}\n\t}",
"private int read() {\n int curByte = 0;\n try {\n curByte = rawData.get() & 0xFF;\n } catch (Exception e) {\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n return curByte;\n }",
"public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs);\n recordAsyncOpTimeNs(null, opTimeNs);\n } else {\n this.asynOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }",
"private void printSuggestion( String arg, List<ConfigOption> co ) {\n List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co );\n Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) );\n System.err.println( \"Parse error for argument \\\"\" + arg + \"\\\", did you mean \" + sortedList.get( 0 ).getCommandLineOption()\n .showFlagInfo() + \"? Ignoring for now.\" );\n\n }"
] |
This method returns the actual raw class associated with the specified
type. | [
"public static Class<?> getRawType(Type type) {\n\t\tif (type instanceof Class) {\n\t\t\treturn (Class<?>) type;\n\t\t} else if (type instanceof ParameterizedType) {\n\t\t\tParameterizedType actualType = (ParameterizedType) type;\n\t\t\treturn getRawType(actualType.getRawType());\n\t\t} else if (type instanceof GenericArrayType) {\n\t\t\tGenericArrayType genericArrayType = (GenericArrayType) type;\n\t\t\tObject rawArrayType = Array.newInstance(getRawType(genericArrayType\n\t\t\t\t\t.getGenericComponentType()), 0);\n\t\t\treturn rawArrayType.getClass();\n\t\t} else if (type instanceof WildcardType) {\n\t\t\tWildcardType castedType = (WildcardType) type;\n\t\t\treturn getRawType(castedType.getUpperBounds()[0]);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Type \\'\"\n\t\t\t\t\t\t\t+ type\n\t\t\t\t\t\t\t+ \"\\' is not a Class, \"\n\t\t\t\t\t\t\t+ \"ParameterizedType, or GenericArrayType. Can't extract class.\");\n\t\t}\n\t}"
] | [
"public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deployment = entities.stream()\n .filter(hm -> hm instanceof Deployment)\n .map(hm -> (Deployment) hm)\n .map(rc -> rc.getMetadata().getName()).findFirst();\n\n deployment.ifPresent(name -> this.applicationName = name);\n }\n }",
"private void addWSAddressingInterceptors(InterceptorProvider provider) {\n MAPAggregator mapAggregator = new MAPAggregator();\n MAPCodec mapCodec = new MAPCodec();\n\n provider.getInInterceptors().add(mapAggregator);\n provider.getInInterceptors().add(mapCodec);\n\n provider.getOutInterceptors().add(mapAggregator);\n provider.getOutInterceptors().add(mapCodec);\n\n provider.getInFaultInterceptors().add(mapAggregator);\n provider.getInFaultInterceptors().add(mapCodec);\n\n provider.getOutFaultInterceptors().add(mapAggregator);\n provider.getOutFaultInterceptors().add(mapCodec);\n }",
"public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }",
"@Override\n public FileModel resolvePayload(GraphRewrite event, EvaluationContext context, WindupVertexFrame payload)\n {\n checkVariableName(event, context);\n if (payload instanceof FileReferenceModel)\n {\n return ((FileReferenceModel) payload).getFile();\n }\n if (payload instanceof FileModel)\n {\n return (FileModel) payload;\n }\n return null;\n }",
"@Override\n public final String getString(final String key) {\n String result = optString(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"public final void updateLastCheckTime(final String id, final long lastCheckTime) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.equal(root.get(\"referenceId\"), id));\n update.set(root.get(\"lastCheckTime\"), lastCheckTime);\n getSession().createQuery(update).executeUpdate();\n }",
"public int checkIn() {\n\n try {\n synchronized (STATIC_LOCK) {\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, false));\n CmsObject cms = getCmsObject();\n if (cms != null) {\n return checkInInternal();\n } else {\n m_logStream.println(\"No CmsObject given. Did you call init() first?\");\n return -1;\n }\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return -2;\n }\n }",
"public void resetResendCount() {\n\t\tthis.resendCount = 0;\n\t\tif (this.initializationComplete)\n\t\t\tthis.nodeStage = NodeStage.NODEBUILDINFO_DONE;\n\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t}",
"public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\n }"
] |
Scans the jar file and returns the paths that match the includes and excludes.
@return A List of paths
@throws An IllegalStateException when an I/O error occurs in reading the jar file. | [
"public List<String> scan() {\n try {\n JarFile jar = new JarFile(jarURL.getFile());\n try {\n List<String> result = new ArrayList<>();\n Enumeration<JarEntry> en = jar.entries();\n while (en.hasMoreElements()) {\n JarEntry entry = en.nextElement();\n String path = entry.getName();\n boolean match = includes.size() == 0;\n if (!match) {\n for (String pattern : includes) {\n if ( patternMatches(pattern, path)) {\n match = true;\n break;\n }\n }\n }\n if (match) {\n for (String pattern : excludes) {\n if ( patternMatches(pattern, path)) {\n match = false;\n break;\n }\n }\n }\n if (match) {\n result.add(path);\n }\n }\n return result;\n } finally {\n jar.close();\n }\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }"
] | [
"protected void loadEntries(final StorageAwareResource resource, final ZipInputStream zipIn) throws IOException {\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream = new BufferedInputStream(zipIn);\n this.readContents(resource, _bufferedInputStream);\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream_1 = new BufferedInputStream(zipIn);\n this.readResourceDescription(resource, _bufferedInputStream_1);\n if (this.storeNodeModel) {\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream_2 = new BufferedInputStream(zipIn);\n this.readNodeModel(resource, _bufferedInputStream_2);\n }\n }",
"private void fillQueue(QueueItem item, Integer minStartPosition,\n Integer maxStartPosition, Integer minEndPosition) throws IOException {\n int newStartPosition;\n int newEndPosition;\n Integer firstRetrievedPosition = null;\n // remove everything below minStartPosition\n if ((minStartPosition != null) && (item.lowestPosition != null)\n && (item.lowestPosition < minStartPosition)) {\n item.del((minStartPosition - 1));\n }\n // fill queue\n while (!item.noMorePositions) {\n boolean doNotCollectAnotherPosition;\n doNotCollectAnotherPosition = item.filledPosition\n && (minStartPosition == null) && (maxStartPosition == null);\n doNotCollectAnotherPosition |= item.filledPosition\n && (maxStartPosition != null) && (item.lastRetrievedPosition != null)\n && (maxStartPosition < item.lastRetrievedPosition);\n if (doNotCollectAnotherPosition) {\n return;\n } else {\n // collect another full position\n firstRetrievedPosition = null;\n while (!item.noMorePositions) {\n newStartPosition = item.sequenceSpans.spans.nextStartPosition();\n if (newStartPosition == NO_MORE_POSITIONS) {\n if (!item.queue.isEmpty()) {\n item.filledPosition = true;\n item.lastFilledPosition = item.lastRetrievedPosition;\n }\n item.noMorePositions = true;\n return;\n } else if ((minStartPosition != null)\n && (newStartPosition < minStartPosition)) {\n // do nothing\n } else {\n newEndPosition = item.sequenceSpans.spans.endPosition();\n if ((minEndPosition == null) || (newEndPosition >= minEndPosition\n - ignoreItem.getMinStartPosition(docId, newEndPosition))) {\n item.add(newStartPosition, newEndPosition);\n if (firstRetrievedPosition == null) {\n firstRetrievedPosition = newStartPosition;\n } else if (!firstRetrievedPosition.equals(newStartPosition)) {\n break;\n }\n }\n }\n }\n }\n }\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<PaxDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<PaxDate>) super.zonedDateTime(temporal);\n }",
"public static auditsyslogpolicy_aaauser_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_aaauser_binding obj = new auditsyslogpolicy_aaauser_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_aaauser_binding response[] = (auditsyslogpolicy_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static int numberAwareCompareTo(Comparable self, Comparable other) {\n NumberAwareComparator<Comparable> numberAwareComparator = new NumberAwareComparator<Comparable>();\n return numberAwareComparator.compare(self, other);\n }",
"@RequestMapping(value = \"/api/scripts\", method = RequestMethod.POST)\n public\n @ResponseBody\n Script addScript(Model model,\n @RequestParam(required = true) String name,\n @RequestParam(required = true) String script) throws Exception {\n\n return ScriptService.getInstance().addScript(name, script);\n }",
"private static DumpContentType guessDumpContentType(String fileName) {\n\t\tString lcDumpName = fileName.toLowerCase();\n\t\tif (lcDumpName.contains(\".json.gz\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".json.bz2\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".sql.gz\")) {\n\t\t\treturn DumpContentType.SITES;\n\t\t} else if (lcDumpName.contains(\".xml.bz2\")) {\n\t\t\tif (lcDumpName.contains(\"daily\")) {\n\t\t\t\treturn DumpContentType.DAILY;\n\t\t\t} else if (lcDumpName.contains(\"current\")) {\n\t\t\t\treturn DumpContentType.CURRENT;\n\t\t\t} else {\n\t\t\t\treturn DumpContentType.FULL;\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.warn(\"Could not guess type of the dump file \\\"\" + fileName\n\t\t\t\t\t+ \"\\\". Defaulting to json.gz.\");\n\t\t\treturn DumpContentType.JSON;\n\t\t}\n\t}",
"public void setAttributes(Object feature, Map<String, Attribute> attributes) throws LayerException {\n\t\tfor (Map.Entry<String, Attribute> entry : attributes.entrySet()) {\n\t\t\tString name = entry.getKey();\n\t\t\tif (!name.equals(getGeometryAttributeName())) {\n\t\t\t\tasFeature(feature).setAttribute(name, entry.getValue());\n\t\t\t}\n\t\t}\n\t}",
"public static List<Integer> checkKeyBelongsToPartition(byte[] key,\n Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples,\n Cluster cluster,\n StoreDefinition storeDef) {\n List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,\n cluster)\n .getPartitionList(key);\n List<Integer> nodesToPush = Lists.newArrayList();\n for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) {\n List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst())\n .getPartitionIds();\n if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions,\n nodePartitions,\n stealNodeToMap.getSecond())) {\n nodesToPush.add(stealNodeToMap.getFirst());\n }\n }\n return nodesToPush;\n }"
] |
Aggregate results to see the status code distribution with target hosts.
@return the aggregateResultMap | [
"public Map<String, SetAndCount> getAggregateResultFullSummary() {\n\n Map<String, SetAndCount> summaryMap = new ConcurrentHashMap<String, SetAndCount>();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n summaryMap.put(entry.getKey(), new SetAndCount(entry.getValue()));\n }\n\n return summaryMap;\n }"
] | [
"public static void toggleStyleName(final UIObject uiObject,\n final boolean toggleStyle,\n final String styleName) {\n if (toggleStyle) {\n uiObject.addStyleName(styleName);\n } else {\n uiObject.removeStyleName(styleName);\n }\n }",
"public int getModifiers() {\n MetaMethod getter = getGetter();\n MetaMethod setter = getSetter();\n if (setter != null && getter == null) return setter.getModifiers();\n if (getter != null && setter == null) return getter.getModifiers();\n int modifiers = getter.getModifiers() | setter.getModifiers();\n int visibility = 0;\n if (Modifier.isPublic(modifiers)) visibility = Modifier.PUBLIC;\n if (Modifier.isProtected(modifiers)) visibility = Modifier.PROTECTED;\n if (Modifier.isPrivate(modifiers)) visibility = Modifier.PRIVATE;\n int states = getter.getModifiers() & setter.getModifiers();\n states &= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE);\n states |= visibility;\n return states;\n }",
"private void writeWorkWeeks(Project.Calendars.Calendar xmlCalendar, ProjectCalendar mpxjCalendar)\n {\n List<ProjectCalendarWeek> weeks = mpxjCalendar.getWorkWeeks();\n if (!weeks.isEmpty())\n {\n WorkWeeks xmlWorkWeeks = m_factory.createProjectCalendarsCalendarWorkWeeks();\n xmlCalendar.setWorkWeeks(xmlWorkWeeks);\n List<WorkWeek> xmlWorkWeekList = xmlWorkWeeks.getWorkWeek();\n\n for (ProjectCalendarWeek week : weeks)\n {\n WorkWeek xmlWeek = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeek();\n xmlWorkWeekList.add(xmlWeek);\n\n xmlWeek.setName(week.getName());\n TimePeriod xmlTimePeriod = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekTimePeriod();\n xmlWeek.setTimePeriod(xmlTimePeriod);\n xmlTimePeriod.setFromDate(week.getDateRange().getStart());\n xmlTimePeriod.setToDate(week.getDateRange().getEnd());\n\n WeekDays xmlWeekDays = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDays();\n xmlWeek.setWeekDays(xmlWeekDays);\n\n List<Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay> dayList = xmlWeekDays.getWeekDay();\n\n for (int loop = 1; loop < 8; loop++)\n {\n DayType workingFlag = week.getWorkingDay(Day.getInstance(loop));\n\n if (workingFlag != DayType.DEFAULT)\n {\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDaysWeekDay();\n dayList.add(day);\n day.setDayType(BigInteger.valueOf(loop));\n day.setDayWorking(Boolean.valueOf(workingFlag == DayType.WORKING));\n\n if (workingFlag == DayType.WORKING)\n {\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDaysWeekDayWorkingTimes();\n day.setWorkingTimes(times);\n List<Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n ProjectCalendarHours bch = week.getCalendarHours(Day.getInstance(loop));\n if (bch != null)\n {\n for (DateRange range : bch)\n {\n if (range != null)\n {\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDaysWeekDayWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }\n }\n }\n }\n }\n }",
"protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n \r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n \r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading schemas for catalog \" \r\n + this.getAttribute(ATT_CATALOG_NAME));\r\n rs = getDbMeta().getSchemas();\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n int count = 0;\r\n while (rs.next())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Creating schema \" + getCatalogName() + \".\" + rs.getString(\"TABLE_SCHEM\"));\r\n alNew.add(new DBMetaSchemaNode(getDbMeta(),\r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, \r\n rs.getString(\"TABLE_SCHEM\")));\r\n count++;\r\n }\r\n if (count == 0) \r\n alNew.add(new DBMetaSchemaNode(getDbMeta(), \r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, null));\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaCatalogNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx2);\r\n } \r\n return false;\r\n }\r\n return true;\r\n }",
"public static <K, V> Map<K, V> of(K key, V value) {\n return new ImmutableMapEntry<K, V>(key, value);\n }",
"public void setClassOfObject(Class c)\r\n {\r\n m_Class = c;\r\n isAbstract = Modifier.isAbstract(m_Class.getModifiers());\r\n // TODO : Shouldn't the HashMap in DescriptorRepository be updated as well?\r\n }",
"public String code(final String code) {\n if (this.theme == null) {\n throw new TemplateProcessingException(\"Theme cannot be resolved because RequestContext was not found. \"\n + \"Are you using a Context object without a RequestContext variable?\");\n }\n return this.theme.getMessageSource().getMessage(code, null, \"\", this.locale);\n }",
"public static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) {\n return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(List<InnerT> inners) {\n return Observable.from(inners);\n }\n });\n }",
"public static String resolveSvnMigratedRevision(final Revision revision, final String branch) {\n if (revision == null) {\n return null;\n }\n final Pattern pattern = Pattern.compile(\"^git-svn-id: .*\" + branch + \"@([0-9]+) \", Pattern.MULTILINE);\n final Matcher matcher = pattern.matcher(revision.getMessage());\n if (matcher.find()) {\n return matcher.group(1);\n } else {\n return revision.getRevision();\n }\n }"
] |
Use this API to fetch all the dospolicy resources that are configured on netscaler. | [
"public static dospolicy[] get(nitro_service service) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tdospolicy[] response = (dospolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"@Override\n public EthiopicDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"@Override\n public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n EnvVars env = build.getEnvironment(listener);\n FilePath workDir = build.getModuleRoot();\n FilePath ws = build.getWorkspace();\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.error(\"Couldn't find Maven home: \" + mavenHome.getRemote());\n throw new Run.RunnerAbortedException();\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, ws, ws);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }",
"@Override\n public HandlerRegistration addChangeHandler(final ChangeHandler handler) {\n return getRangeInputElement().addDomHandler(handler, ChangeEvent.getType());\n }",
"static int[] toIntArray(List<Integer> integers) {\n\t\tint[] ints = new int[integers.size()];\n\t\tint i = 0;\n\t\tfor (Integer n : integers) {\n\t\t\tints[i++] = n;\n\t\t}\n\t\treturn ints;\n\t}",
"private static Map<Integer, LinkedList<MetadataCache>> gatherCandidateAttachmentGroups() {\n Map<Integer,LinkedList<MetadataCache>> candidateGroups = new TreeMap<Integer, LinkedList<MetadataCache>>();\n final Iterator<File> iterator = MetadataFinder.getInstance().getAutoAttachCacheFiles().iterator();\n while (iterator.hasNext()) {\n final File file = iterator.next();\n try {\n final MetadataCache candidate = new MetadataCache(file);\n if (candidateGroups.get(candidate.sourcePlaylist) == null) {\n candidateGroups.put(candidate.sourcePlaylist, new LinkedList<MetadataCache>());\n }\n candidateGroups.get(candidate.sourcePlaylist).add(candidate);\n } catch (Exception e) {\n logger.error(\"Unable to open metadata cache file \" + file + \", discarding\", e);\n iterator.remove();\n }\n }\n return candidateGroups;\n }",
"private static Class<?> extractTypeFromClass(Class<?> clazz, Class<?> source, int typeIndex,\n\t\t\tMap<TypeVariable, Type> typeVariableMap, Map<Integer, Integer> typeIndexesPerLevel,\n\t\t\tint nestingLevel, int currentLevel) {\n\n\t\tif (clazz.getName().startsWith(\"java.util.\")) {\n\t\t\treturn null;\n\t\t}\n\t\tif (clazz.getSuperclass() != null && isIntrospectionCandidate(clazz.getSuperclass())) {\n\t\t\ttry {\n\t\t\t\treturn extractType(clazz.getGenericSuperclass(), source, typeIndex, typeVariableMap,\n\t\t\t\t\t\ttypeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t}\n\t\t\tcatch (MalformedParameterizedTypeException ex) {\n\t\t\t\t// from getGenericSuperclass() - ignore and continue with interface introspection\n\t\t\t}\n\t\t}\n\t\tType[] ifcs = clazz.getGenericInterfaces();\n\t\tif (ifcs != null) {\n\t\t\tfor (Type ifc : ifcs) {\n\t\t\t\tType rawType = ifc;\n\t\t\t\tif (ifc instanceof ParameterizedType) {\n\t\t\t\t\trawType = ((ParameterizedType) ifc).getRawType();\n\t\t\t\t}\n\t\t\t\tif (rawType instanceof Class && isIntrospectionCandidate((Class) rawType)) {\n\t\t\t\t\treturn extractType(ifc, source, typeIndex, typeVariableMap, typeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"private ClassTypeSignature getClassTypeSignature(\r\n\t\t\tParameterizedType parameterizedType) {\r\n\t\tClass<?> rawType = (Class<?>) parameterizedType.getRawType();\r\n\t\tType[] typeArguments = parameterizedType.getActualTypeArguments();\r\n\t\tTypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArguments.length];\r\n\t\tfor (int i = 0; i < typeArguments.length; i++) {\r\n\t\t\ttypeArgSignatures[i] = getTypeArgSignature(typeArguments[i]);\r\n\t\t}\r\n\r\n\t\tString binaryName = rawType.isMemberClass() ? rawType.getSimpleName()\r\n\t\t\t\t: rawType.getName();\r\n\t\tClassTypeSignature ownerTypeSignature = parameterizedType\r\n\t\t\t\t.getOwnerType() == null ? null\r\n\t\t\t\t: (ClassTypeSignature) getFullTypeSignature(parameterizedType\r\n\t\t\t\t\t\t.getOwnerType());\r\n\t\tClassTypeSignature classTypeSignature = new ClassTypeSignature(\r\n\t\t\t\tbinaryName, typeArgSignatures, ownerTypeSignature);\r\n\t\treturn classTypeSignature;\r\n\t}",
"@JmxGetter(name = \"getChunkIdToNumChunks\", description = \"Returns a string representation of the map of chunk id to number of chunks\")\n public String getChunkIdToNumChunks() {\n StringBuilder builder = new StringBuilder();\n for(Entry<Object, Integer> entry: fileSet.getChunkIdToNumChunks().entrySet()) {\n builder.append(entry.getKey().toString() + \" - \" + entry.getValue().toString() + \", \");\n }\n return builder.toString();\n }",
"private void adjustOptionsColumn(\n CmsMessageBundleEditorTypes.EditMode oldMode,\n CmsMessageBundleEditorTypes.EditMode newMode) {\n\n if (m_model.isShowOptionsColumn(oldMode) != m_model.isShowOptionsColumn(newMode)) {\n m_table.removeGeneratedColumn(TableProperty.OPTIONS);\n if (m_model.isShowOptionsColumn(newMode)) {\n // Don't know why exactly setting the filter field invisible is necessary here,\n // it should be already set invisible - but apparently not setting it invisible again\n // will result in the field being visible.\n m_table.setFilterFieldVisible(TableProperty.OPTIONS, false);\n m_table.addGeneratedColumn(TableProperty.OPTIONS, m_optionsColumn);\n }\n }\n }"
] |
Stops the background data synchronization thread. | [
"public void stop() {\n syncLock.lock();\n try {\n if (syncThread == null) {\n return;\n }\n instanceChangeStreamListener.stop();\n syncThread.interrupt();\n try {\n syncThread.join();\n } catch (final InterruptedException e) {\n return;\n }\n syncThread = null;\n isRunning = false;\n } finally {\n syncLock.unlock();\n }\n }"
] | [
"private float[] calculatePointerPosition(float angle) {\n\t\tfloat x = (float) (mColorWheelRadius * Math.cos(angle));\n\t\tfloat y = (float) (mColorWheelRadius * Math.sin(angle));\n\n\t\treturn new float[] { x, y };\n\t}",
"public void start() {\n instanceLock.writeLock().lock();\n try {\n for (final Map.Entry<MongoNamespace, NamespaceChangeStreamListener> streamerEntry :\n nsStreamers.entrySet()) {\n streamerEntry.getValue().start();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }",
"public static CmsSolrSpellchecker getInstance(CoreContainer container) {\n\n if (null == instance) {\n synchronized (CmsSolrSpellchecker.class) {\n if (null == instance) {\n @SuppressWarnings(\"resource\")\n SolrCore spellcheckCore = container.getCore(CmsSolrSpellchecker.SPELLCHECKER_INDEX_CORE);\n if (spellcheckCore == null) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_SPELLCHECK_CORE_NOT_AVAILABLE_1,\n CmsSolrSpellchecker.SPELLCHECKER_INDEX_CORE));\n return null;\n }\n instance = new CmsSolrSpellchecker(container, spellcheckCore);\n }\n }\n }\n\n return instance;\n }",
"public void setActiveView(View v, int position) {\n final View oldView = mActiveView;\n mActiveView = v;\n mActivePosition = position;\n\n if (mAllowIndicatorAnimation && oldView != null) {\n startAnimatingIndicator();\n }\n\n invalidate();\n }",
"private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars, HashMap<Integer, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null && baseCal.getName() != null)\n {\n cal.setParent(baseCal);\n }\n else\n {\n // Remove invalid calendar to avoid serious problems later.\n m_file.removeCalendar(cal);\n }\n }\n }",
"public CmsJspDateSeriesBean getToDateSeries() {\n\n if (m_dateSeries == null) {\n m_dateSeries = new CmsJspDateSeriesBean(this, m_cms.getRequestContext().getLocale());\n }\n return m_dateSeries;\n }",
"public static <OutT, InT> PagedList<OutT> toPagedList(List<InT> list, final Func1<InT, OutT> mapper) {\n PageImpl<InT> page = new PageImpl<>();\n page.setItems(list);\n page.setNextPageLink(null);\n PagedList<InT> pagedList = new PagedList<InT>(page) {\n @Override\n public Page<InT> nextPage(String nextPageLink) {\n return null;\n }\n };\n PagedListConverter<InT, OutT> converter = new PagedListConverter<InT, OutT>() {\n @Override\n public Observable<OutT> typeConvertAsync(InT inner) {\n return Observable.just(mapper.call(inner));\n }\n };\n return converter.convert(pagedList);\n }",
"private void writeIntegerField(String fieldName, Object value) throws IOException\n {\n int val = ((Number) value).intValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"static byte[] hmacSha1(StringBuilder message, String key) {\n try {\n Mac mac = Mac.getInstance(\"HmacSHA1\");\n mac.init(new SecretKeySpec(key.getBytes(), \"HmacSHA1\"));\n return mac.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }"
] |
Reads characters until any 'end' character is encountered, ignoring
escape sequences.
@param out
The StringBuilder to write to.
@param in
The Input String.
@param start
Starting position.
@param end
End characters.
@return The new position or -1 if no 'end' char was found. | [
"public final static int readXMLUntil(final StringBuilder out, final String in, final int start, final char... end)\n {\n int pos = start;\n boolean inString = false;\n char stringChar = 0;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (inString)\n {\n if (ch == '\\\\')\n {\n out.append(ch);\n pos++;\n if (pos < in.length())\n {\n out.append(ch);\n pos++;\n }\n continue;\n }\n if (ch == stringChar)\n {\n inString = false;\n out.append(ch);\n pos++;\n continue;\n }\n }\n switch (ch)\n {\n case '\"':\n case '\\'':\n inString = true;\n stringChar = ch;\n break;\n }\n if (!inString)\n {\n boolean endReached = false;\n for (int n = 0; n < end.length; n++)\n {\n if (ch == end[n])\n {\n endReached = true;\n break;\n }\n }\n if (endReached)\n {\n break;\n }\n }\n out.append(ch);\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }"
] | [
"@PostConstruct\n public final void init() throws URISyntaxException {\n final String address = getConfig(ADDRESS, null);\n if (address != null) {\n final URI uri = new URI(\"udp://\" + address);\n final String prefix = getConfig(PREFIX, \"mapfish-print\").replace(\"%h\", getHostname());\n final int period = Integer.parseInt(getConfig(PERIOD, \"10\"));\n LOGGER.info(\"Starting a StatsD reporter targeting {} with prefix {} and period {}s\",\n uri, prefix, period);\n this.reporter = StatsDReporter.forRegistry(this.metricRegistry)\n .prefixedWith(prefix)\n .build(uri.getHost(), uri.getPort());\n this.reporter.start(period, TimeUnit.SECONDS);\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 void setRefreshFrequency(IntervalFrequency frequency) {\n if (NONE_REFRESH_INTERVAL == mRefreshInterval && IntervalFrequency.NONE != frequency) {\n // Install draw-frame listener if frequency is no longer NONE\n getGVRContext().unregisterDrawFrameListener(mFrameListener);\n getGVRContext().registerDrawFrameListener(mFrameListener);\n }\n switch (frequency) {\n case REALTIME:\n mRefreshInterval = REALTIME_REFRESH_INTERVAL;\n break;\n case HIGH:\n mRefreshInterval = HIGH_REFRESH_INTERVAL;\n break;\n case MEDIUM:\n mRefreshInterval = MEDIUM_REFRESH_INTERVAL;\n break;\n case LOW:\n mRefreshInterval = LOW_REFRESH_INTERVAL;\n break;\n case NONE:\n mRefreshInterval = NONE_REFRESH_INTERVAL;\n break;\n default:\n break;\n }\n }",
"void onEndTypeChange() {\n\n EndType endType = m_model.getEndType();\n m_groupDuration.selectButton(getDurationButtonForType(endType));\n switch (endType) {\n case DATE:\n case TIMES:\n m_durationPanel.setVisible(true);\n m_seriesEndDate.setValue(m_model.getSeriesEndDate());\n int occurrences = m_model.getOccurrences();\n if (!m_occurrences.isFocused()) {\n m_occurrences.setFormValueAsString(occurrences > 0 ? \"\" + occurrences : \"\");\n }\n break;\n default:\n m_durationPanel.setVisible(false);\n break;\n }\n updateExceptions();\n }",
"private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n\n m_project.getProjectProperties().setFileApplication(\"Merlin\");\n m_project.getProjectProperties().setFileType(\"SQLITE\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n populateEntityMap();\n processProject();\n processCalendars();\n processResources();\n processTasks();\n processAssignments();\n processDependencies();\n\n return m_project;\n }",
"public static void addService(final ServiceTarget serviceTarget, final Bootstrap.Configuration configuration,\n final ControlledProcessState processState, final BootstrapListener bootstrapListener,\n final RunningModeControl runningModeControl, final AbstractVaultReader vaultReader, final ManagedAuditLogger auditLogger,\n final DelegatingConfigurableAuthorizer authorizer, final ManagementSecurityIdentitySupplier securityIdentitySupplier,\n final SuspendController suspendController) {\n\n // Install Executor services\n final ThreadGroup threadGroup = new ThreadGroup(\"ServerService ThreadGroup\");\n final String namePattern = \"ServerService Thread Pool -- %t\";\n final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<ThreadFactory>() {\n public ThreadFactory run() {\n return new JBossThreadFactory(threadGroup, Boolean.FALSE, null, namePattern, null, null);\n }\n });\n\n // TODO determine why QueuelessThreadPoolService makes boot take > 35 secs\n// final QueuelessThreadPoolService serverExecutorService = new QueuelessThreadPoolService(Integer.MAX_VALUE, false, new TimeSpec(TimeUnit.SECONDS, 5));\n// serverExecutorService.getThreadFactoryInjector().inject(threadFactory);\n final boolean forDomain = ProcessType.DOMAIN_SERVER == getProcessType(configuration.getServerEnvironment());\n final ServerExecutorService serverExecutorService = new ServerExecutorService(threadFactory, forDomain);\n serviceTarget.addService(MANAGEMENT_EXECUTOR, serverExecutorService)\n .addAliases(Services.JBOSS_SERVER_EXECUTOR, ManagementRemotingServices.SHUTDOWN_EXECUTOR_NAME) // Use this executor for mgmt shutdown for now\n .install();\n final ServerScheduledExecutorService serverScheduledExecutorService = new ServerScheduledExecutorService(threadFactory);\n serviceTarget.addService(JBOSS_SERVER_SCHEDULED_EXECUTOR, serverScheduledExecutorService)\n .addAliases(JBOSS_SERVER_SCHEDULED_EXECUTOR)\n .addDependency(MANAGEMENT_EXECUTOR, ExecutorService.class, serverScheduledExecutorService.executorInjector)\n .install();\n\n final CapabilityRegistry capabilityRegistry = configuration.getCapabilityRegistry();\n ServerService service = new ServerService(configuration, processState, null, bootstrapListener, new ServerDelegatingResourceDefinition(),\n runningModeControl, vaultReader, auditLogger, authorizer, securityIdentitySupplier, capabilityRegistry, suspendController);\n\n ExternalManagementRequestExecutor.install(serviceTarget, threadGroup, EXECUTOR_CAPABILITY.getCapabilityServiceName(), service.getStabilityMonitor());\n\n ServiceBuilder<?> serviceBuilder = serviceTarget.addService(Services.JBOSS_SERVER_CONTROLLER, service);\n serviceBuilder.addDependency(DeploymentMountProvider.SERVICE_NAME,DeploymentMountProvider.class, service.injectedDeploymentRepository);\n serviceBuilder.addDependency(ContentRepository.SERVICE_NAME, ContentRepository.class, service.injectedContentRepository);\n serviceBuilder.addDependency(Services.JBOSS_SERVICE_MODULE_LOADER, ServiceModuleLoader.class, service.injectedModuleLoader);\n serviceBuilder.addDependency(Services.JBOSS_EXTERNAL_MODULE_SERVICE, ExternalModuleService.class,\n service.injectedExternalModuleService);\n serviceBuilder.addDependency(PATH_MANAGER_CAPABILITY.getCapabilityServiceName(), PathManager.class, service.injectedPathManagerService);\n if (configuration.getServerEnvironment().isAllowModelControllerExecutor()) {\n serviceBuilder.addDependency(MANAGEMENT_EXECUTOR, ExecutorService.class, service.getExecutorServiceInjector());\n }\n if (configuration.getServerEnvironment().getLaunchType() == ServerEnvironment.LaunchType.DOMAIN) {\n serviceBuilder.addDependency(HostControllerConnectionService.SERVICE_NAME, ControllerInstabilityListener.class,\n service.getContainerInstabilityInjector());\n }\n\n serviceBuilder.install();\n }",
"protected void solveL(double[] vv) {\n\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sumReal = vv[ip*2];\n double sumImg = vv[ip*2+1];\n\n vv[ip*2] = vv[i*2];\n vv[ip*2+1] = vv[i*2+1];\n\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*stride + (ii-1)*2;\n for( int j = ii-1; j < i; j++ ){\n double luReal = dataLU[index++];\n double luImg = dataLU[index++];\n\n double vvReal = vv[j*2];\n double vvImg = vv[j*2+1];\n\n sumReal -= luReal*vvReal - luImg*vvImg;\n sumImg -= luReal*vvImg + luImg*vvReal;\n }\n } else if( sumReal*sumReal + sumImg*sumImg != 0.0 ) {\n ii=i+1;\n }\n vv[i*2] = sumReal;\n vv[i*2+1] = sumImg;\n }\n }",
"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 static CallSite bootstrapCurrent(Lookup caller, String name, MethodType type) {\n return realBootstrap(caller, name, CALL_TYPES.METHOD.ordinal(), type, false, true, false);\n }"
] |
Sets the transformations to be applied to the shape before indexing it.
@param transformations the sequence of transformations
@return this with the specified sequence of transformations | [
"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 static servicegroup_lbmonitor_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroup_lbmonitor_binding obj = new servicegroup_lbmonitor_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroup_lbmonitor_binding response[] = (servicegroup_lbmonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public List<Method> getMethodsFromGroupIds(int[] groupIds, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n\n for (int groupId : groupIds) {\n methods.addAll(getMethodsFromGroupId(groupId, filters));\n }\n\n return methods;\n }",
"public static base_response restart(nitro_service client) throws Exception {\n\t\tdbsmonitors restartresource = new dbsmonitors();\n\t\treturn restartresource.perform_operation(client,\"restart\");\n\t}",
"protected void init(EnhancedAnnotation<T> annotatedAnnotation) {\n initType(annotatedAnnotation);\n initValid(annotatedAnnotation);\n check(annotatedAnnotation);\n }",
"private void ensureReferencedFKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException\r\n {\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = modelDef.getClass(elementClassName);\r\n String fkFieldNames = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);\r\n ArrayList missingFields = new ArrayList();\r\n SequencedHashMap fkFields = new SequencedHashMap();\r\n\r\n // first we gather all field names\r\n for (CommaListIterator it = new CommaListIterator(fkFieldNames); it.hasNext();)\r\n {\r\n String fieldName = (String)it.next();\r\n FieldDescriptorDef fieldDef = elementClassDef.getField(fieldName);\r\n\r\n if (fieldDef == null)\r\n {\r\n missingFields.add(fieldName);\r\n }\r\n fkFields.put(fieldName, fieldDef);\r\n }\r\n\r\n // next we traverse all sub types and gather fields as we go\r\n for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext() && !missingFields.isEmpty();)\r\n {\r\n ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n for (int idx = 0; idx < missingFields.size();)\r\n {\r\n FieldDescriptorDef fieldDef = subTypeDef.getField((String)missingFields.get(idx));\r\n\r\n if (fieldDef != null)\r\n {\r\n fkFields.put(fieldDef.getName(), fieldDef);\r\n missingFields.remove(idx);\r\n }\r\n else\r\n {\r\n idx++;\r\n }\r\n }\r\n }\r\n if (!missingFields.isEmpty())\r\n {\r\n throw new ConstraintException(\"Cannot find field \"+missingFields.get(0).toString()+\" in the hierarchy with root type \"+\r\n elementClassDef.getName()+\" which is used as foreignkey in collection \"+\r\n collDef.getName()+\" in \"+collDef.getOwner().getName());\r\n }\r\n\r\n // copy the found fields into the element class\r\n ensureFields(elementClassDef, fkFields.values());\r\n }",
"public synchronized void stop() {\n if (isRunning()) {\n try {\n setSendingStatus(false);\n } catch (Throwable t) {\n logger.error(\"Problem stopping sending status during shutdown\", t);\n }\n DeviceFinder.getInstance().removeIgnoredAddress(socket.get().getLocalAddress());\n socket.get().close();\n socket.set(null);\n broadcastAddress.set(null);\n updates.clear();\n setTempoMaster(null);\n setDeviceNumber((byte)0); // Set up for self-assignment if restarted.\n deliverLifecycleAnnouncement(logger, false);\n }\n }",
"protected static <R extends AddressSection, S extends AddressSegment> R fastIncrement(\n\t\t\tR section,\n\t\t\tlong increment,\n\t\t\tAddressCreator<?, R, ?, S> addrCreator, \n\t\t\tSupplier<R> lowerProducer,\n\t\t\tSupplier<R> upperProducer,\n\t\t\tInteger prefixLength) {\n\t\tif(increment >= 0) {\n\t\t\tBigInteger count = section.getCount();\n\t\t\tif(count.compareTo(LONG_MAX) <= 0) {\n\t\t\t\tlong longCount = count.longValue();\n\t\t\t\tif(longCount > increment) {\n\t\t\t\t\tif(longCount == increment + 1) {\n\t\t\t\t\t\treturn upperProducer.get();\n\t\t\t\t\t}\n\t\t\t\t\treturn incrementRange(section, increment, addrCreator, lowerProducer, prefixLength);\n\t\t\t\t}\n\t\t\t\tBigInteger value = section.getValue();\n\t\t\t\tBigInteger upperValue;\n\t\t\t\tif(value.compareTo(LONG_MAX) <= 0 && (upperValue = section.getUpperValue()).compareTo(LONG_MAX) <= 0) {\n\t\t\t\t\treturn increment(\n\t\t\t\t\t\t\tsection,\n\t\t\t\t\t\t\tincrement,\n\t\t\t\t\t\t\taddrCreator,\n\t\t\t\t\t\t\tcount.longValue(),\n\t\t\t\t\t\t\tvalue.longValue(),\n\t\t\t\t\t\t\tupperValue.longValue(),\n\t\t\t\t\t\t\tlowerProducer,\n\t\t\t\t\t\t\tupperProducer,\n\t\t\t\t\t\t\tprefixLength);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tBigInteger value = section.getValue();\n\t\t\tif(value.compareTo(LONG_MAX) <= 0) {\n\t\t\t\treturn add(lowerProducer.get(), value.longValue(), increment, addrCreator, prefixLength);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public final PJsonArray getJSONArray(final String key) {\n final JSONArray val = this.obj.optJSONArray(key);\n if (val == null) {\n throw new ObjectMissingException(this, key);\n }\n return new PJsonArray(this, val, key);\n }",
"private static BsonDocument withNewVersion(\n final BsonDocument document,\n final BsonDocument newVersion\n ) {\n final BsonDocument newDocument = BsonUtils.copyOfDocument(document);\n newDocument.put(DOCUMENT_VERSION_FIELD, newVersion);\n return newDocument;\n }"
] |
New SOAP client uses new SOAP service. | [
"public void useNewSOAPService(boolean direct) throws Exception {\n URL wsdlURL = getClass().getResource(\"/CustomerServiceNew.wsdl\");\n org.customer.service.CustomerServiceService service = \n new org.customer.service.CustomerServiceService(wsdlURL);\n \n org.customer.service.CustomerService customerService = \n direct ? service.getCustomerServicePort() : service.getCustomerServiceNewPort();\n\n System.out.println(\"Using new SOAP CustomerService with new client\");\n \n customer.v2.Customer customer = createNewCustomer(\"Barry New SOAP\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry New SOAP\");\n printNewCustomerDetails(customer);\n }"
] | [
"protected void handleINEvent(Exchange exchange, String reqFid) throws Fault {\n Message inMsg = exchange.getInMessage();\n\n EventProducerInterceptor epi = null;\n FlowIdHelper.setFlowId(inMsg, reqFid);\n\n ListIterator<Interceptor<? extends Message>> interceptors = inMsg\n .getInterceptorChain().getIterator();\n\n while (interceptors.hasNext() && epi == null) {\n Interceptor<? extends Message> interceptor = interceptors.next();\n\n if (interceptor instanceof EventProducerInterceptor) {\n epi = (EventProducerInterceptor) interceptor;\n epi.handleMessage(inMsg);\n }\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 static base_response delete(nitro_service client, String domain) throws Exception {\n\t\tdnstxtrec deleteresource = new dnstxtrec();\n\t\tdeleteresource.domain = domain;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static DMatrix2 extractColumn( DMatrix2x2 a , int column , DMatrix2 out ) {\n if( out == null) out = new DMatrix2();\n switch( column ) {\n case 0:\n out.a1 = a.a11;\n out.a2 = a.a21;\n break;\n case 1:\n out.a1 = a.a12;\n out.a2 = a.a22;\n break;\n default:\n throw new IllegalArgumentException(\"Out of bounds column. column = \"+column);\n }\n return out;\n }",
"public static List<String> getCommaSeparatedStringValues(String paramValue, String type) {\n List<String> commaSeparatedProps = Lists.newArrayList();\n for(String url: Utils.COMMA_SEP.split(paramValue.trim()))\n if(url.trim().length() > 0)\n commaSeparatedProps.add(url);\n\n if(commaSeparatedProps.size() == 0) {\n throw new RuntimeException(\"Number of \" + type + \" should be greater than zero\");\n }\n return commaSeparatedProps;\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 static <T> void finish(T query, long correlationId, EventBus bus, String... labels) {\n for (String type : labels) {\n RemoveLabelledQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }",
"protected void parseRequest(HttpServletRequest request,\n HttpServletResponse response) {\n requestParams = new HashMap<String, Object>();\n listFiles = new ArrayList<FileItemStream>();\n listFileStreams = new ArrayList<ByteArrayOutputStream>();\n\n // Parse the request\n if (ServletFileUpload.isMultipartContent(request)) {\n // multipart request\n try {\n ServletFileUpload upload = new ServletFileUpload();\n FileItemIterator iter = upload.getItemIterator(request);\n while (iter.hasNext()) {\n FileItemStream item = iter.next();\n String name = item.getFieldName();\n InputStream stream = item.openStream();\n if (item.isFormField()) {\n requestParams.put(name,\n Streams.asString(stream));\n } else {\n String fileName = item.getName();\n if (fileName != null && !\"\".equals(fileName.trim())) {\n listFiles.add(item);\n\n ByteArrayOutputStream os = new ByteArrayOutputStream();\n IOUtils.copy(stream,\n os);\n listFileStreams.add(os);\n }\n }\n }\n } catch (Exception e) {\n logger.error(\"Unexpected error parsing multipart content\",\n e);\n }\n } else {\n // not a multipart\n for (Object mapKey : request.getParameterMap().keySet()) {\n String mapKeyString = (String) mapKey;\n\n if (mapKeyString.endsWith(\"[]\")) {\n // multiple values\n String values[] = request.getParameterValues(mapKeyString);\n List<String> listeValues = new ArrayList<String>();\n for (String value : values) {\n listeValues.add(value);\n }\n requestParams.put(mapKeyString,\n listeValues);\n } else {\n // single value\n String value = request.getParameter(mapKeyString);\n requestParams.put(mapKeyString,\n value);\n }\n }\n }\n }",
"public void deleteIndex(String indexName, String designDocId, String type) {\n assertNotEmpty(indexName, \"indexName\");\n assertNotEmpty(designDocId, \"designDocId\");\n assertNotNull(type, \"type\");\n if (!designDocId.startsWith(\"_design\")) {\n designDocId = \"_design/\" + designDocId;\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").path(designDocId)\n .path(type).path(indexName).build();\n InputStream response = null;\n try {\n HttpConnection connection = Http.DELETE(uri);\n response = client.couchDbClient.executeToInputStream(connection);\n getResponse(response, Response.class, client.getGson());\n } finally {\n close(response);\n }\n }"
] |
Alternate version of autoGeneratedKeys.
@param sql
@param autoGeneratedKeys
@return cache key to use. | [
"public String calculateCacheKey(String sql, int autoGeneratedKeys) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\ttmp.append(autoGeneratedKeys);\r\n\t\treturn tmp.toString();\r\n\t}"
] | [
"public void classifyAndWriteViterbiSearchGraph(String testFile, String searchGraphPrefix, DocumentReaderAndWriter<IN> readerAndWriter) throws IOException {\r\n Timing timer = new Timing();\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromFile(testFile, readerAndWriter);\r\n int numWords = 0;\r\n int numSentences = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n DFSA<String, Integer> tagLattice = getViterbiSearchGraph(doc, AnswerAnnotation.class);\r\n numWords += doc.size();\r\n PrintWriter latticeWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences\r\n + \".wlattice\"));\r\n PrintWriter vsgWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences + \".lattice\"));\r\n if (readerAndWriter instanceof LatticeWriter)\r\n ((LatticeWriter) readerAndWriter).printLattice(tagLattice, doc, latticeWriter);\r\n tagLattice.printAttFsmFormat(vsgWriter);\r\n latticeWriter.close();\r\n vsgWriter.close();\r\n numSentences++;\r\n }\r\n\r\n long millis = timer.stop();\r\n double wordspersec = numWords / (((double) millis) / 1000);\r\n NumberFormat nf = new DecimalFormat(\"0.00\"); // easier way!\r\n System.err.println(this.getClass().getName() + \" tagged \" + numWords + \" words in \" + numSentences\r\n + \" documents at \" + nf.format(wordspersec) + \" words per second.\");\r\n }",
"@Nullable\n\tpublic Import find(@Nonnull final String typeName) {\n\t\tCheck.notEmpty(typeName, \"typeName\");\n\t\tImport ret = null;\n\t\tfinal Type type = new Type(typeName);\n\t\tfor (final Import imp : imports) {\n\t\t\tif (imp.getType().getName().equals(type.getName())) {\n\t\t\t\tret = imp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (ret == null) {\n\t\t\tfinal Type javaLangType = Type.evaluateJavaLangType(typeName);\n\t\t\tif (javaLangType != null) {\n\t\t\t\tret = Import.of(javaLangType);\n\t\t\t}\n\t\t}\n\t\treturn ret;\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 }",
"private void applyAliases(Map<FieldType, String> aliases)\n {\n CustomFieldContainer fields = m_project.getCustomFields();\n for (Map.Entry<FieldType, String> entry : aliases.entrySet())\n {\n fields.getCustomField(entry.getKey()).setAlias(entry.getValue());\n }\n }",
"String getRangeUri(PropertyIdValue propertyIdValue) {\n\t\tString datatype = this.propertyRegister\n\t\t\t\t.getPropertyType(propertyIdValue);\n\n\t\tif (datatype == null)\n\t\t\treturn null;\n\n\t\tswitch (datatype) {\n\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.RDF_LANG_STRING;\n\t\tcase DatatypeIdValue.DT_STRING:\n\t\tcase DatatypeIdValue.DT_EXTERNAL_ID:\n\t\tcase DatatypeIdValue.DT_MATH:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.XSD_STRING;\n\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\tcase DatatypeIdValue.DT_ITEM:\n\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\tcase DatatypeIdValue.DT_LEXEME:\n\t\tcase DatatypeIdValue.DT_FORM:\n\t\tcase DatatypeIdValue.DT_SENSE:\n\t\tcase DatatypeIdValue.DT_TIME:\n\t\tcase DatatypeIdValue.DT_URL:\n\t\tcase DatatypeIdValue.DT_GEO_SHAPE:\n\t\tcase DatatypeIdValue.DT_TABULAR_DATA:\n\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\tthis.rdfConversionBuffer.addObjectProperty(propertyIdValue);\n\t\t\treturn Vocabulary.OWL_THING;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}",
"private static DumpContentType guessDumpContentType(String fileName) {\n\t\tString lcDumpName = fileName.toLowerCase();\n\t\tif (lcDumpName.contains(\".json.gz\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".json.bz2\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".sql.gz\")) {\n\t\t\treturn DumpContentType.SITES;\n\t\t} else if (lcDumpName.contains(\".xml.bz2\")) {\n\t\t\tif (lcDumpName.contains(\"daily\")) {\n\t\t\t\treturn DumpContentType.DAILY;\n\t\t\t} else if (lcDumpName.contains(\"current\")) {\n\t\t\t\treturn DumpContentType.CURRENT;\n\t\t\t} else {\n\t\t\t\treturn DumpContentType.FULL;\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.warn(\"Could not guess type of the dump file \\\"\" + fileName\n\t\t\t\t\t+ \"\\\". Defaulting to json.gz.\");\n\t\t\treturn DumpContentType.JSON;\n\t\t}\n\t}",
"private Long fetchServiceId(ServiceReference serviceReference) {\n return (Long) serviceReference.getProperty(org.osgi.framework.Constants.SERVICE_ID);\n }",
"@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n List<String> storeNames = null;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET_RO);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET_RO);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE);\n\n // execute command\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {\n metaKeys = Lists.newArrayList();\n metaKeys.add(KEY_MAX_VERSION);\n metaKeys.add(KEY_CURRENT_VERSION);\n metaKeys.add(KEY_STORAGE_FORMAT);\n }\n\n doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys);\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}"
] |
Given the current and final cluster dumps it into the output directory
@param currentCluster Initial cluster metadata
@param finalCluster Final cluster metadata
@param outputDirName Output directory where to dump this file
@throws IOException | [
"public static void dumpClusters(Cluster currentCluster,\n Cluster finalCluster,\n String outputDirName) {\n dumpClusters(currentCluster, finalCluster, outputDirName, \"\");\n }"
] | [
"public static server_service_binding[] get(nitro_service service, String name) throws Exception{\n\t\tserver_service_binding obj = new server_service_binding();\n\t\tobj.set_name(name);\n\t\tserver_service_binding response[] = (server_service_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void processResourceAssignment(Task task, MapRow row)\n {\n Resource resource = m_resourceMap.get(row.getUUID(\"RESOURCE_UUID\"));\n task.addResourceAssignment(resource);\n }",
"public void executeDelete(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeDelete: \" + obj);\r\n }\r\n\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n try\r\n {\r\n stmt = sm.getDeleteStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getDeleteStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"JdbcAccessImpl: getDeleteStatement returned a null statement\");\r\n }\r\n\r\n sm.bindDelete(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeDelete: \" + stmt);\r\n\r\n // @todo: clearify semantics\r\n // thma: the following check is not secure. The object could be deleted *or* changed.\r\n // if it was deleted it makes no sense to throw an OL exception.\r\n // does is make sense to throw an OL exception if the object was changed?\r\n if (stmt.executeUpdate() == 0 && cld.isLocking()) //BRJ\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tString objToString = \"\";\r\n \ttry {\r\n \t\tobjToString = obj.toString();\r\n \t} catch (Exception ex) {}\r\n throw new OptimisticLockException(\"Object has been modified or deleted by someone else: \" + objToString, obj);\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getDeleteProcedure(), obj, stmt);\r\n }\r\n catch (OptimisticLockException e)\r\n {\r\n // Don't log as error\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"OptimisticLockException during the execution of delete: \"\r\n + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of delete: \"\r\n + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedDeleteStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }",
"public static 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}",
"protected void modify(Transaction t) {\n try {\n this.lock.writeLock().lock();\n t.perform();\n } finally {\n this.lock.writeLock().unlock();\n }\n }",
"public int getBoneIndex(String bonename)\n {\n for (int i = 0; i < getNumBones(); ++i)\n\n if (mBoneNames[i].equals(bonename))\n return i;\n return -1;\n }",
"public boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n LockEntry writer = getWriter(obj);\r\n if (writer == null)\r\n return false;\r\n else if (writer.isOwnedBy(tx))\r\n return true;\r\n else\r\n return false;\r\n }",
"public ParallelTaskBuilder setTargetHostsFromJsonPath(String jsonPath,\n String sourcePath, HostsSourceType sourceType)\n throws TargetHostsLoadException {\n\n this.targetHosts = targetHostBuilder.setTargetHostsFromJsonPath(jsonPath, sourcePath,\n sourceType);\n return this;\n\n }",
"public synchronized void addListener(CollectionProxyListener listener)\r\n {\r\n if (_listeners == null)\r\n {\r\n _listeners = new ArrayList();\r\n }\r\n // to avoid multi-add of same listener, do check\r\n if(!_listeners.contains(listener))\r\n {\r\n _listeners.add(listener);\r\n }\r\n }"
] |
Performs a HTTP DELETE request.
@return {@link Response} | [
"Response delete(URI uri) {\n HttpConnection connection = Http.DELETE(uri);\n return executeToResponse(connection);\n }"
] | [
"public Conditionals ifModifiedSince(LocalDateTime time) {\n Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH));\n Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_UNMODIFIED_SINCE));\n time = time.withNano(0);\n return new Conditionals(empty(), noneMatch, Optional.of(time), Optional.empty());\n }",
"void markReferenceElements(PersistenceBroker broker)\r\n {\r\n // these cases will be handled by ObjectEnvelopeTable#cascadingDependents()\r\n // if(getModificationState().needsInsert() || getModificationState().needsDelete()) return;\r\n\r\n Map oldImage = getBeforeImage();\r\n Map newImage = getCurrentImage();\r\n\r\n Iterator iter = newImage.entrySet().iterator();\r\n while (iter.hasNext())\r\n {\r\n Map.Entry entry = (Map.Entry) iter.next();\r\n Object key = entry.getKey();\r\n // we only interested in references\r\n if(key instanceof ObjectReferenceDescriptor)\r\n {\r\n Image oldRefImage = (Image) oldImage.get(key);\r\n Image newRefImage = (Image) entry.getValue();\r\n newRefImage.performReferenceDetection(oldRefImage);\r\n }\r\n }\r\n }",
"public static appfwpolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_policybinding_binding obj = new appfwpolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_policybinding_binding response[] = (appfwpolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void addOrderedChildResourceTypes(PathAddress resourceAddress, Resource resource) {\n Set<String> orderedChildTypes = resource.getOrderedChildTypes();\n if (orderedChildTypes.size() > 0) {\n orderedChildren.put(resourceAddress, resource.getOrderedChildTypes());\n }\n }",
"public Record getChild(String key)\n {\n Record result = null;\n if (key != null)\n {\n for (Record record : m_records)\n {\n if (key.equals(record.getField()))\n {\n result = record;\n break;\n }\n }\n }\n return result;\n }",
"@Pure\n\tpublic static <T> List<T> reverseView(List<T> list) {\n\t\treturn Lists.reverse(list);\n\t}",
"private void batchStatusLog(int batchCount,\n int numBatches,\n int partitionStoreCount,\n int numPartitionStores,\n long totalTimeMs) {\n // Calculate the estimated end time and pretty print stats\n double rate = 1;\n long estimatedTimeMs = 0;\n if(numPartitionStores > 0) {\n rate = partitionStoreCount / numPartitionStores;\n estimatedTimeMs = (long) (totalTimeMs / rate) - totalTimeMs;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"Batch Complete!\")\n .append(Utils.NEWLINE)\n .append(\"\\tbatches moved: \")\n .append(batchCount)\n .append(\" out of \")\n .append(numBatches)\n .append(Utils.NEWLINE)\n .append(\"\\tPartition stores moved: \")\n .append(partitionStoreCount)\n .append(\" out of \")\n .append(numPartitionStores)\n .append(Utils.NEWLINE)\n .append(\"\\tPercent done: \")\n .append(decimalFormatter.format(rate * 100.0))\n .append(Utils.NEWLINE)\n .append(\"\\tEstimated time left: \")\n .append(estimatedTimeMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toHours(estimatedTimeMs))\n .append(\" hours)\");\n RebalanceUtils.printBatchLog(batchCount, logger, sb.toString());\n }",
"public ArrayList getPrimaryKeys()\r\n {\r\n ArrayList result = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = getFields(); it.hasNext();)\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n result.add(fieldDef);\r\n }\r\n }\r\n return result;\r\n }",
"public Jar setJarPrefix(String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (value != null && jarPrefixFile != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixFile + \")\");\n this.jarPrefixStr = value;\n return this;\n }"
] |
Send a failed operation response.
@param context the request context
@param errorCode the error code
@param message the operation message
@throws IOException for any error | [
"static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {\n final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());\n final FlushableDataOutput output = context.writeMessage(header);\n try {\n // This is an error\n output.writeByte(DomainControllerProtocol.PARAM_ERROR);\n // send error code\n output.writeByte(errorCode);\n // error message\n if (message == null) {\n output.writeUTF(\"unknown error\");\n } else {\n output.writeUTF(message);\n }\n // response end\n output.writeByte(ManagementProtocol.RESPONSE_END);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }"
] | [
"public static Connection connectSync(final ProtocolConnectionConfiguration configuration) throws IOException {\n long timeoutMillis = configuration.getConnectionTimeout();\n CallbackHandler handler = configuration.getCallbackHandler();\n final CallbackHandler actualHandler;\n ProtocolTimeoutHandler timeoutHandler = configuration.getTimeoutHandler();\n // Note: If a client supplies a ProtocolTimeoutHandler it is taking on full responsibility for timeout management.\n if (timeoutHandler == null) {\n GeneralTimeoutHandler defaultTimeoutHandler = new GeneralTimeoutHandler();\n // No point wrapping our AnonymousCallbackHandler.\n actualHandler = handler != null ? new WrapperCallbackHandler(defaultTimeoutHandler, handler) : null;\n timeoutHandler = defaultTimeoutHandler;\n } else {\n actualHandler = handler;\n }\n\n final IoFuture<Connection> future = connect(actualHandler, configuration);\n\n IoFuture.Status status = timeoutHandler.await(future, timeoutMillis);\n\n if (status == IoFuture.Status.DONE) {\n return future.get();\n }\n if (status == IoFuture.Status.FAILED) {\n throw ProtocolLogger.ROOT_LOGGER.failedToConnect(configuration.getUri(), future.getException());\n }\n throw ProtocolLogger.ROOT_LOGGER.couldNotConnect(configuration.getUri());\n }",
"private List<TransformEntry> readTransformEntries(File file) throws Exception {\n\n List<TransformEntry> result = new ArrayList<>();\n try (FileInputStream fis = new FileInputStream(file)) {\n byte[] data = CmsFileUtil.readFully(fis, false);\n Document doc = CmsXmlUtils.unmarshalHelper(data, null, false);\n for (Node node : doc.selectNodes(\"//transform\")) {\n Element elem = ((Element)node);\n String xslt = elem.attributeValue(\"xslt\");\n String conf = elem.attributeValue(\"config\");\n TransformEntry entry = new TransformEntry(conf, xslt);\n result.add(entry);\n }\n }\n return result;\n }",
"public static int lengthOfCodePoint(int codePoint)\n {\n if (codePoint < 0) {\n throw new InvalidCodePointException(codePoint);\n }\n if (codePoint < 0x80) {\n // normal ASCII\n // 0xxx_xxxx\n return 1;\n }\n if (codePoint < 0x800) {\n return 2;\n }\n if (codePoint < 0x1_0000) {\n return 3;\n }\n if (codePoint < 0x11_0000) {\n return 4;\n }\n // Per RFC3629, UTF-8 is limited to 4 bytes, so more bytes are illegal\n throw new InvalidCodePointException(codePoint);\n }",
"public int[][] argb() {\n return Arrays.stream(points()).map(p -> argb(p.x, p.y)).toArray(int[][]::new);\n }",
"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}",
"private boolean validate(CmsFavoriteEntry entry) {\n\n try {\n String siteRoot = entry.getSiteRoot();\n if (!m_okSiteRoots.contains(siteRoot)) {\n m_rootCms.readResource(siteRoot);\n m_okSiteRoots.add(siteRoot);\n }\n CmsUUID project = entry.getProjectId();\n if (!m_okProjects.contains(project)) {\n m_cms.readProject(project);\n m_okProjects.add(project);\n }\n for (CmsUUID id : Arrays.asList(entry.getDetailId(), entry.getStructureId())) {\n if ((id != null) && !m_okStructureIds.contains(id)) {\n m_cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n m_okStructureIds.add(id);\n }\n }\n return true;\n\n } catch (Exception e) {\n LOG.info(\"Favorite entry validation failed: \" + e.getLocalizedMessage(), e);\n return false;\n }\n\n }",
"public <Result, Param extends Resource> Result execWithoutCacheClear(Param resource, IUnitOfWork<Result, Param> transaction) throws WrappedException {\n\t\tCacheAdapter cacheAdapter = getOrCreate(resource);\n\t\ttry {\n\t\t\tcacheAdapter.ignoreNotifications();\n\t\t\treturn transaction.exec(resource);\n\t\t} catch (RuntimeException e) {\n\t\t\tthrow e;\n\t\t} catch (Exception e) {\n\t\t\tthrow new WrappedException(e);\n\t\t} finally {\n\t\t\tcacheAdapter.listenToNotifications();\n\t\t}\n\t}",
"public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) {\n return !searchForAnnotation(method, annotation).isEmpty();\n }",
"private static int getTrimmedHeight(BufferedImage img) {\n int width = img.getWidth();\n int height = img.getHeight();\n int trimmedHeight = 0;\n\n for (int i = 0; i < width; i++) {\n for (int j = height - 1; j >= 0; j--) {\n if (img.getRGB(i, j) != Color.WHITE.getRGB() && j > trimmedHeight) {\n trimmedHeight = j;\n break;\n }\n }\n }\n\n return trimmedHeight;\n }"
] |
Given an array of variable names, returns an Xml String
of values.
@param dataMap an map containing variable names and their corresponding values
names.
@param dataMap
@return values in Xml format | [
"public String getXmlFormatted(Map<String, String> dataMap) {\r\n StringBuilder sb = new StringBuilder();\r\n for (String var : outTemplate) {\r\n sb.append(appendXmlStartTag(var));\r\n sb.append(dataMap.get(var));\r\n sb.append(appendXmlEndingTag(var));\r\n }\r\n return sb.toString();\r\n }"
] | [
"protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n queue.add(event);\n }",
"private List<TimephasedCost> getTimephasedCostMultipleRates(List<TimephasedWork> standardWorkList, List<TimephasedWork> overtimeWorkList)\n {\n List<TimephasedWork> standardWorkResult = new LinkedList<TimephasedWork>();\n List<TimephasedWork> overtimeWorkResult = new LinkedList<TimephasedWork>();\n CostRateTable table = getCostRateTable();\n ProjectCalendar calendar = getCalendar();\n\n Iterator<TimephasedWork> iter = overtimeWorkList.iterator();\n for (TimephasedWork standardWork : standardWorkList)\n {\n TimephasedWork overtimeWork = iter.hasNext() ? iter.next() : null;\n\n int startIndex = getCostRateTableEntryIndex(standardWork.getStart());\n int finishIndex = getCostRateTableEntryIndex(standardWork.getFinish());\n\n if (startIndex == finishIndex)\n {\n standardWorkResult.add(standardWork);\n if (overtimeWork != null)\n {\n overtimeWorkResult.add(overtimeWork);\n }\n }\n else\n {\n standardWorkResult.addAll(splitWork(table, calendar, standardWork, startIndex));\n if (overtimeWork != null)\n {\n overtimeWorkResult.addAll(splitWork(table, calendar, overtimeWork, startIndex));\n }\n }\n }\n\n return getTimephasedCostSingleRate(standardWorkResult, overtimeWorkResult);\n }",
"public FailureDetectorConfig setCluster(Cluster cluster) {\n Utils.notNull(cluster);\n this.cluster = cluster;\n /*\n * FIXME: this is the hacky way to refresh the admin connection\n * verifier, but it'll just work. The clean way to do so is to have a\n * centralized metadata management, and all references of cluster object\n * point to that.\n */\n if(this.connectionVerifier instanceof AdminConnectionVerifier) {\n ((AdminConnectionVerifier) connectionVerifier).setCluster(cluster);\n }\n return this;\n }",
"public static String flatten(String left, String right) {\n\t\treturn left == null || left.isEmpty() ? right : left + \".\" + right;\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 }",
"@SuppressWarnings(\"deprecation\")\n @RequestMapping(value = \"/api/backup\", method = RequestMethod.GET)\n public\n @ResponseBody\n String getBackup(Model model, HttpServletResponse response) throws Exception {\n response.addHeader(\"Content-Disposition\", \"attachment; filename=backup.json\");\n response.setContentType(\"application/json\");\n\n Backup backup = BackupService.getInstance().getBackupData();\n ObjectMapper objectMapper = new ObjectMapper();\n ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();\n\n return writer.withView(ViewFilters.Default.class).writeValueAsString(backup);\n }",
"public static base_response Shutdown(nitro_service client, shutdown resource) throws Exception {\n\t\tshutdown Shutdownresource = new shutdown();\n\t\treturn Shutdownresource.perform_operation(client);\n\t}",
"public static void moveBandsElemnts(int yOffset, JRDesignBand band) {\n\t\tif (band == null)\n\t\t\treturn;\n\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\telem.setY(elem.getY() + yOffset);\n\t\t}\n\t}",
"public static lbvserver[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tlbvserver[] response = (lbvserver[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}"
] |
Goes through the token lists and adds all the variables which can be used to define a sub-matrix. If anything
else is found an excpetion is thrown | [
"private void addSubMatrixVariables(List<TokenList.Token> inputs, List<Variable> variables) {\n for (int i = 0; i < inputs.size(); i++) {\n TokenList.Token t = inputs.get(i);\n if( t.getType() != Type.VARIABLE )\n throw new ParseError(\"Expected variables only in sub-matrix input, not \"+t.getType());\n Variable v = t.getVariable();\n if( v.getType() == VariableType.INTEGER_SEQUENCE || isVariableInteger(t) ) {\n variables.add(v);\n } else {\n throw new ParseError(\"Expected an integer, integer sequence, or array range to define a submatrix\");\n }\n }\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n public T[] nextCombinationAsArray()\n {\n T[] combination = (T[]) Array.newInstance(elements.getClass().getComponentType(),\n combinationIndices.length);\n return nextCombinationAsArray(combination);\n }",
"public BoxFileUploadSession.Info createUploadSession(long fileSize) {\n URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.addHeader(\"Content-Type\", \"application/json\");\n\n JsonObject body = new JsonObject();\n body.add(\"file_size\", fileSize);\n request.setBody(body.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n String sessionId = jsonObject.get(\"id\").asString();\n BoxFileUploadSession session = new BoxFileUploadSession(this.getAPI(), sessionId);\n return session.new Info(jsonObject);\n }",
"public int getIndexMin() {\n int indexMin = 0;\n double min = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m < min ) {\n min = m;\n indexMin = i;\n }\n }\n\n return indexMin;\n }",
"private void verifyXopResponse(XopBean xopOriginal, XopBean xopResponse) {\n if (!Arrays.equals(xopResponse.getBytes(), xopOriginal.getBytes())) {\n throw new RuntimeException(\"Received XOP attachment is corrupted\");\n }\n System.out.println();\n System.out.println(\"XOP attachment has been successfully received\");\n }",
"private Duration getDuration(String value)\n {\n Duration result = null;\n\n if (value != null && value.length() != 0)\n {\n double seconds = getLong(value);\n double hours = seconds / (60 * 60);\n double days = hours / 8;\n\n if (days < 1)\n {\n result = Duration.getInstance(hours, TimeUnit.HOURS);\n }\n else\n {\n double durationDays = hours / 8;\n result = Duration.getInstance(durationDays, TimeUnit.DAYS);\n }\n }\n\n return (result);\n }",
"public static ModelControllerClient createAndAdd(final ManagementChannelHandler handler) {\n final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler);\n handler.addHandlerFactory(client);\n return client;\n }",
"public void setResourceCalendar(ProjectCalendar calendar)\n {\n set(ResourceField.CALENDAR, calendar);\n if (calendar == null)\n {\n setResourceCalendarUniqueID(null);\n }\n else\n {\n calendar.setResource(this);\n setResourceCalendarUniqueID(calendar.getUniqueID());\n }\n }",
"private void writeFields(String objectName, FieldContainer container, FieldType[] fields) throws IOException\n {\n m_writer.writeStartObject(objectName);\n for (FieldType field : fields)\n {\n Object value = container.getCurrentValue(field);\n if (value != null)\n {\n writeField(field, value);\n }\n }\n m_writer.writeEndObject();\n }",
"public DbConn getConn()\n {\n Connection cnx = null;\n try\n {\n Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.\n cnx = _ds.getConnection();\n if (cnx.getAutoCommit())\n {\n cnx.setAutoCommit(false);\n cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode\n }\n\n if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)\n {\n cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n }\n\n return new DbConn(this, cnx);\n }\n catch (SQLException e)\n {\n DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.\n throw new DatabaseException(e);\n }\n }"
] |
This method tokenizes a string by space characters,
but ignores spaces in quoted parts,that are parts in
'' or "". The method does allows the usage of "" in ''
and '' in "". The space character between tokens is not
returned.
@param s the string to tokenize
@return the tokens | [
"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 }"
] | [
"public void load(IAssetEvents handler)\n {\n GVRAssetLoader loader = getGVRContext().getAssetLoader();\n\n if (mReplaceScene)\n {\n loader.loadScene(getOwnerObject(), mVolume, mImportSettings, getGVRContext().getMainScene(), handler);\n }\n else\n {\n loader.loadModel(mVolume, getOwnerObject(), mImportSettings, true, handler);\n }\n }",
"private void deleteRecursive(final File file) {\n if (file.isDirectory()) {\n final String[] files = file.list();\n if (files != null) {\n for (String name : files) {\n deleteRecursive(new File(file, name));\n }\n }\n }\n\n if (!file.delete()) {\n ControllerLogger.ROOT_LOGGER.cannotDeleteFileOrDirectory(file);\n }\n }",
"public <T> T decodeSignedRequest(String signedRequest, Class<T> type) throws SignedRequestException {\n\t\tString[] split = signedRequest.split(\"\\\\.\");\n\t\tString encodedSignature = split[0];\n\t\tString payload = split[1];\t\t\n\t\tString decoded = base64DecodeToString(payload);\t\t\n\t\tbyte[] signature = base64DecodeToBytes(encodedSignature);\n\t\ttry {\n\t\t\tT data = objectMapper.readValue(decoded, type);\t\t\t\n\t\t\tString algorithm = objectMapper.readTree(decoded).get(\"algorithm\").textValue();\n\t\t\tif (algorithm == null || !algorithm.equals(\"HMAC-SHA256\")) {\n\t\t\t\tthrow new SignedRequestException(\"Unknown encryption algorithm: \" + algorithm);\n\t\t\t}\t\t\t\n\t\t\tbyte[] expectedSignature = encrypt(payload, secret);\n\t\t\tif (!Arrays.equals(expectedSignature, signature)) {\n\t\t\t\tthrow new SignedRequestException(\"Invalid signature.\");\n\t\t\t}\t\t\t\n\t\t\treturn data;\n\t\t} catch (IOException e) {\n\t\t\tthrow new SignedRequestException(\"Error parsing payload.\", e);\n\t\t}\n\t}",
"@Override\n protected void registerRequest(RestRequestValidator requestValidator,\n ChannelHandlerContext ctx,\n MessageEvent messageEvent) {\n // At this point we know the request is valid and we have a\n // error handler. So we construct the composite Voldemort\n // request object.\n CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject();\n if(requestObject != null) {\n\n // Dropping dead requests from going to next handler\n long now = System.currentTimeMillis();\n if(requestObject.getRequestOriginTimeInMs() + requestObject.getRoutingTimeoutInMs() <= now) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUEST_TIMEOUT,\n \"current time: \"\n + now\n + \"\\torigin time: \"\n + requestObject.getRequestOriginTimeInMs()\n + \"\\ttimeout in ms: \"\n + requestObject.getRoutingTimeoutInMs());\n return;\n } else {\n Store store = getStore(requestValidator.getStoreName(),\n requestValidator.getParsedRoutingType());\n if(store != null) {\n VoldemortStoreRequest voldemortStoreRequest = new VoldemortStoreRequest(requestObject,\n store,\n parseZoneId());\n Channels.fireMessageReceived(ctx, voldemortStoreRequest);\n } else {\n logger.error(\"Error when getting store. Non Existing store name.\");\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Non Existing store name. Critical error.\");\n return;\n\n }\n }\n }\n }",
"protected ManageableCollection createCollection(CollectionDescriptor desc, Class collectionClass)\r\n {\r\n Class fieldType = desc.getPersistentField().getType();\r\n ManageableCollection col;\r\n\r\n if (collectionClass == null)\r\n {\r\n if (ManageableCollection.class.isAssignableFrom(fieldType))\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)fieldType.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the default collection type \"+fieldType.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareCollection.class))\r\n {\r\n col = new RemovalAwareCollection();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareList.class))\r\n {\r\n col = new RemovalAwareList();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareSet.class))\r\n {\r\n col = new RemovalAwareSet();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Cannot determine a default collection type for collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the collection class \"+collectionClass.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n return col;\r\n }",
"private Storepoint getCurrentStorepoint(Project phoenixProject)\n {\n List<Storepoint> storepoints = phoenixProject.getStorepoints().getStorepoint();\n Collections.sort(storepoints, new Comparator<Storepoint>()\n {\n @Override public int compare(Storepoint o1, Storepoint o2)\n {\n return DateHelper.compare(o2.getCreationTime(), o1.getCreationTime());\n }\n });\n return storepoints.get(0);\n }",
"public void exceptionShift() {\n numExceptional++;\n double mag = 0.05 * numExceptional;\n if (mag > 1.0) mag = 1.0;\n\n double angle = 2.0 * UtilEjml.PI * (rand.nextDouble() - 0.5) * mag;\n performImplicitSingleStep(0, angle, true);\n\n // allow more convergence time\n nextExceptional = steps + exceptionalThresh; // (numExceptional+1)*\n }",
"@SuppressWarnings(\"rawtypes\") public static final Map getMap(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return ((Map) bundle.getObject(key));\n }",
"private void initWsClient(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n String serviceURL = (String)config.getProperties().get(\"service.url\");\n retryNum = Integer.parseInt((String)config.getProperties().get(\"service.retry.number\"));\n retryDelay = Long.parseLong((String)config.getProperties().get(\"service.retry.delay\"));\n\n JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();\n factory.setServiceClass(org.talend.esb.sam.monitoringservice.v1.MonitoringService.class);\n factory.setAddress(serviceURL);\n monitoringService = (MonitoringService)factory.create();\n }"
] |
Extract child task data.
@param task MPXJ task
@param row Synchro task data | [
"private void processChildTasks(Task task, MapRow row) throws IOException\n {\n List<MapRow> tasks = row.getRows(\"TASKS\");\n if (tasks != null)\n {\n for (MapRow childTask : tasks)\n {\n processTask(task, childTask);\n }\n }\n }"
] | [
"public static base_response unset(nitro_service client, gslbsite resource, String[] args) throws Exception{\n\t\tgslbsite unsetresource = new gslbsite();\n\t\tunsetresource.sitename = resource.sitename;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }",
"private void sort()\n {\n DefaultDirectedWeightedGraph<RuleProvider, DefaultEdge> graph = new DefaultDirectedWeightedGraph<>(\n DefaultEdge.class);\n\n for (RuleProvider provider : providers)\n {\n graph.addVertex(provider);\n }\n\n addProviderRelationships(graph);\n\n checkForCycles(graph);\n\n List<RuleProvider> result = new ArrayList<>(this.providers.size());\n TopologicalOrderIterator<RuleProvider, DefaultEdge> iterator = new TopologicalOrderIterator<>(graph);\n while (iterator.hasNext())\n {\n RuleProvider provider = iterator.next();\n result.add(provider);\n }\n\n this.providers = Collections.unmodifiableList(result);\n\n int index = 0;\n for (RuleProvider provider : this.providers)\n {\n if (provider instanceof AbstractRuleProvider)\n ((AbstractRuleProvider) provider).setExecutionIndex(index++);\n }\n }",
"public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException {\n return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType );\n }",
"public InsertIntoTable addRowsFrom(File file, FileParser fileParser) {\n builder.addRowsFrom(file, fileParser);\n return this;\n }",
"@Override\n public void destroy(SocketDestination dest, ClientRequestExecutor clientRequestExecutor)\n throws Exception {\n clientRequestExecutor.close();\n int numDestroyed = destroyed.incrementAndGet();\n if(stats != null) {\n stats.incrementCount(dest, ClientSocketStats.Tracked.CONNECTION_DESTROYED_EVENT);\n }\n\n if(logger.isDebugEnabled())\n logger.debug(\"Destroyed socket \" + numDestroyed + \" connection to \" + dest.getHost()\n + \":\" + dest.getPort());\n }",
"public void refreshConnection() throws SQLException{\r\n\t\tthis.connection.close(); // if it's still in use, close it.\r\n\t\ttry{\r\n\t\t\tthis.connection = this.pool.obtainRawInternalConnection();\r\n\t\t} catch(SQLException e){\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}",
"public void validate(final List<Throwable> validationErrors) {\n if (this.matchers == null) {\n validationErrors.add(new IllegalArgumentException(\n \"Matchers cannot be null. There should be at least a !acceptAll matcher\"));\n }\n if (this.matchers != null && this.matchers.isEmpty()) {\n validationErrors.add(new IllegalArgumentException(\n \"There are no url matchers defined. There should be at least a \" +\n \"!acceptAll matcher\"));\n }\n }",
"public static String confSetName() {\n String profile = SysProps.get(AppConfigKey.PROFILE.key());\n if (S.blank(profile)) {\n profile = Act.mode().name().toLowerCase();\n }\n return profile;\n }"
] |
Static method to convert a binary operator into a string.
@param oper is the binary comparison operator to be converted | [
"protected static String ConvertBinaryOperator(int oper)\r\n {\r\n // Convert the operator into the proper string\r\n String oper_string;\r\n switch (oper)\r\n {\r\n default:\r\n case EQUAL:\r\n oper_string = \"=\";\r\n break;\r\n case LIKE:\r\n oper_string = \"LIKE\";\r\n break;\r\n case NOT_EQUAL:\r\n oper_string = \"!=\";\r\n break;\r\n case LESS_THAN:\r\n oper_string = \"<\";\r\n break;\r\n case GREATER_THAN:\r\n oper_string = \">\";\r\n break;\r\n case GREATER_EQUAL:\r\n oper_string = \">=\";\r\n break;\r\n case LESS_EQUAL:\r\n oper_string = \"<=\";\r\n break;\r\n }\r\n return oper_string;\r\n }"
] | [
"public static final Object getObject(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return (bundle.getObject(key));\n }",
"private void copy(InputStream input, OutputStream output) throws IOException {\n try {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = input.read(buffer);\n while (bytesRead != -1) {\n output.write(buffer, 0, bytesRead);\n bytesRead = input.read(buffer);\n }\n } finally {\n input.close();\n output.close();\n }\n }",
"public static base_response update(nitro_service client, protocolhttpband resource) throws Exception {\n\t\tprotocolhttpband updateresource = new protocolhttpband();\n\t\tupdateresource.reqbandsize = resource.reqbandsize;\n\t\tupdateresource.respbandsize = resource.respbandsize;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private GeometryCoordinateSequenceTransformer getTransformer() {\n\t\tif (unitToPixel == null) {\n\t\t\tunitToPixel = new GeometryCoordinateSequenceTransformer();\n\t\t\tunitToPixel.setMathTransform(ProjectiveTransform.create(new AffineTransform(scale, 0, 0, -scale, -scale\n\t\t\t\t\t* panOrigin.x, scale * panOrigin.y)));\n\t\t}\n\t\treturn unitToPixel;\n\t}",
"public static int count(CharSequence self, CharSequence text) {\n int answer = 0;\n for (int idx = 0; true; idx++) {\n idx = self.toString().indexOf(text.toString(), idx);\n // break once idx goes to -1 or for case of empty string once\n // we get to the end to avoid JDK library bug (see GROOVY-5858)\n if (idx < answer) break;\n ++answer;\n }\n return answer;\n }",
"private static String guessPackaging(ProjectModel projectModel)\n {\n String projectType = projectModel.getProjectType();\n if (projectType != null)\n return projectType;\n\n LOG.warning(\"WINDUP-983 getProjectType() returned null for: \" + projectModel.getRootFileModel().getPrettyPath());\n\n String suffix = StringUtils.substringAfterLast(projectModel.getRootFileModel().getFileName(), \".\");\n if (\"jar war ear sar har \".contains(suffix+\" \")){\n projectModel.setProjectType(suffix); // FIXME: Remove when WINDUP-983 is fixed.\n return suffix;\n }\n\n // Should we try something more? Used APIs? What if it's a source?\n\n return \"unknown\";\n }",
"public void deleteArtifact(final String gavc, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactPath(gavc));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to DELETE artifact \" + gavc;\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"private void addModuleToTree(final DbModule module, final TreeNode tree) {\n final TreeNode subTree = new TreeNode();\n subTree.setName(module.getName());\n tree.addChild(subTree);\n\n // Add SubsubModules\n for (final DbModule subsubmodule : module.getSubmodules()) {\n addModuleToTree(subsubmodule, subTree);\n }\n }",
"private void initAdapter()\n {\n Connection tmp = null;\n DatabaseMetaData meta = null;\n try\n {\n tmp = _ds.getConnection();\n meta = tmp.getMetaData();\n product = meta.getDatabaseProductName().toLowerCase();\n }\n catch (SQLException e)\n {\n throw new DatabaseException(\"Cannot connect to the database\", e);\n }\n finally\n {\n try\n {\n if (tmp != null)\n {\n tmp.close();\n }\n }\n catch (SQLException e)\n {\n // Nothing to do.\n }\n }\n\n DbAdapter newAdpt = null;\n for (String s : ADAPTERS)\n {\n try\n {\n Class<? extends DbAdapter> clazz = Db.class.getClassLoader().loadClass(s).asSubclass(DbAdapter.class);\n newAdpt = clazz.newInstance();\n if (newAdpt.compatibleWith(meta))\n {\n adapter = newAdpt;\n break;\n }\n }\n catch (Exception e)\n {\n throw new DatabaseException(\"Issue when loading database adapter named: \" + s, e);\n }\n }\n\n if (adapter == null)\n {\n throw new DatabaseException(\"Unsupported database! There is no JQM database adapter compatible with product name \" + product);\n }\n else\n {\n jqmlogger.info(\"Using database adapter {}\", adapter.getClass().getCanonicalName());\n }\n }"
] |
This method extracts data for a single calendar from an MSPDI file.
@param calendar Calendar data
@param map Map of calendar UIDs to names
@param baseCalendars list of base calendars | [
"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 ItemRequest<CustomField> findById(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"GET\");\n }",
"private void handleApplicationCommandRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Application Command Request\");\n\t\tint nodeId = incomingMessage.getMessagePayloadByte(1);\n\t\tlogger.debug(\"Application Command Request from Node \" + nodeId);\n\t\tZWaveNode node = getNode(nodeId);\n\t\t\n\t\tif (node == null) {\n\t\t\tlogger.warn(\"Node {} not initialized yet, ignoring message.\", nodeId);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tnode.resetResendCount();\n\t\t\n\t\tint commandClassCode = incomingMessage.getMessagePayloadByte(3);\n\t\tZWaveCommandClass.CommandClass commandClass = ZWaveCommandClass.CommandClass.getCommandClass(commandClassCode);\n\n\t\tif (commandClass == null) {\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlogger.debug(String.format(\"Incoming command class %s (0x%02x)\", commandClass.getLabel(), commandClass.getKey()));\n\t\tZWaveCommandClass zwaveCommandClass = node.getCommandClass(commandClass);\n\t\t\n\t\t// We got an unsupported command class, return.\n\t\tif (zwaveCommandClass == null) {\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlogger.trace(\"Found Command Class {}, passing to handleApplicationCommandRequest\", zwaveCommandClass.getCommandClass().getLabel());\n\t\tzwaveCommandClass.handleApplicationCommandRequest(incomingMessage, 4, 1);\n\n\t\tif (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && nodeId == this.lastSentMessage.getMessageNode() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\ttransactionCompleted.release();\n\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t}\n\t}",
"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 static Boolean assertTrue(Boolean value, String message) {\n if (!Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }",
"private void batchStatusLog(int batchCount,\n int numBatches,\n int partitionStoreCount,\n int numPartitionStores,\n long totalTimeMs) {\n // Calculate the estimated end time and pretty print stats\n double rate = 1;\n long estimatedTimeMs = 0;\n if(numPartitionStores > 0) {\n rate = partitionStoreCount / numPartitionStores;\n estimatedTimeMs = (long) (totalTimeMs / rate) - totalTimeMs;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"Batch Complete!\")\n .append(Utils.NEWLINE)\n .append(\"\\tbatches moved: \")\n .append(batchCount)\n .append(\" out of \")\n .append(numBatches)\n .append(Utils.NEWLINE)\n .append(\"\\tPartition stores moved: \")\n .append(partitionStoreCount)\n .append(\" out of \")\n .append(numPartitionStores)\n .append(Utils.NEWLINE)\n .append(\"\\tPercent done: \")\n .append(decimalFormatter.format(rate * 100.0))\n .append(Utils.NEWLINE)\n .append(\"\\tEstimated time left: \")\n .append(estimatedTimeMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toHours(estimatedTimeMs))\n .append(\" hours)\");\n RebalanceUtils.printBatchLog(batchCount, logger, sb.toString());\n }",
"protected void updateModel(final ModelNode operation, final Resource resource) throws OperationFailedException {\n updateModel(operation, resource.getModel());\n }",
"public static String movePath( final String file,\n final String target ) {\n final String name = new File(file).getName();\n return target.endsWith(\"/\") ? target + name : target + '/' + name;\n }",
"public static <T extends Comparable<? super T>> List<T> sortInplace(List<T> list) {\n\t\tCollections.sort(list);\n\t\treturn list;\n\t}",
"public <C extends Contextual<I>, I> C getContextual(String id) {\n return this.<C, I>getContextual(new StringBeanIdentifier(id));\n }"
] |
Get the Exif data for the photo.
The calling user must have permission to view the photo.
This method does not require authentication.
@param photoId
The photo ID
@param secret
The secret
@return A collection of Exif objects
@throws FlickrException | [
"public Collection<Exif> getExif(String photoId, String secret) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_EXIF);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n if (secret != null) {\r\n parameters.put(\"secret\", secret);\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n List<Exif> exifs = new ArrayList<Exif>();\r\n Element photoElement = response.getPayload();\r\n NodeList exifElements = photoElement.getElementsByTagName(\"exif\");\r\n for (int i = 0; i < exifElements.getLength(); i++) {\r\n Element exifElement = (Element) exifElements.item(i);\r\n Exif exif = new Exif();\r\n exif.setTagspace(exifElement.getAttribute(\"tagspace\"));\r\n exif.setTagspaceId(exifElement.getAttribute(\"tagspaceid\"));\r\n exif.setTag(exifElement.getAttribute(\"tag\"));\r\n exif.setLabel(exifElement.getAttribute(\"label\"));\r\n exif.setRaw(XMLUtilities.getChildValue(exifElement, \"raw\"));\r\n exif.setClean(XMLUtilities.getChildValue(exifElement, \"clean\"));\r\n exifs.add(exif);\r\n }\r\n return exifs;\r\n }"
] | [
"public void writeNameValuePair(String name, String value) throws IOException\n {\n internalWriteNameValuePair(name, escapeString(value));\n }",
"public int getPathId(String pathName, int profileId) {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n // first get the pathId for the pathName/profileId\n int pathId = -1;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_PATH\n + \" WHERE \" + Constants.PATH_PROFILE_PATHNAME + \"= ? \"\n + \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n queryStatement.setString(1, pathName);\n queryStatement.setInt(2, profileId);\n results = queryStatement.executeQuery();\n if (results.next()) {\n pathId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return pathId;\n }",
"public void install(@Observes(precedence = 90) CubeDockerConfiguration configuration,\n ArquillianDescriptor arquillianDescriptor) {\n\n DockerCompositions cubes = configuration.getDockerContainersContent();\n\n final SeleniumContainers seleniumContainers =\n SeleniumContainers.create(getBrowser(arquillianDescriptor), cubeDroneConfigurationInstance.get());\n cubes.add(seleniumContainers.getSeleniumContainerName(), seleniumContainers.getSeleniumContainer());\n\n final boolean recording = cubeDroneConfigurationInstance.get().isRecording();\n if (recording) {\n cubes.add(seleniumContainers.getVncContainerName(), seleniumContainers.getVncContainer());\n cubes.add(seleniumContainers.getVideoConverterContainerName(),\n seleniumContainers.getVideoConverterContainer());\n }\n\n seleniumContainersInstanceProducer.set(seleniumContainers);\n\n System.out.println(\"SELENIUM INSTALLED\");\n System.out.println(ConfigUtil.dump(cubes));\n }",
"private void cascadeInsertFor(ObjectEnvelope mod, List alreadyPrepared)\r\n {\r\n // avoid endless recursion, so use List for registration\r\n if(alreadyPrepared.contains(mod.getIdentity())) return;\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 cascadeInsertSingleReferences(mod, refs, alreadyPrepared);\r\n\r\n List colls = cld.getCollectionDescriptors(true);\r\n cascadeInsertCollectionReferences(mod, colls, alreadyPrepared);\r\n }",
"public void convertToSparse() {\n switch ( mat.getType() ) {\n case DDRM: {\n DMatrixSparseCSC m = new DMatrixSparseCSC(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrixRMaj) mat, m,0);\n setMatrix(m);\n } break;\n case FDRM: {\n FMatrixSparseCSC m = new FMatrixSparseCSC(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrixRMaj) mat, m,0);\n setMatrix(m);\n } break;\n\n case DSCC:\n case FSCC:\n break;\n default:\n throw new RuntimeException(\"Conversion not supported!\");\n }\n }",
"public static void replaceBadXmlCharactersBySpace(char[] cbuf, int off, int len) {\n for (int i = off; i < off + len; i++) {\n if (isBadXmlCharacter(cbuf[i])) {\n cbuf[i] = '\\u0020';\n }\n }\n }",
"protected byte[] readByteArray(InputStream is, int size) throws IOException\n {\n byte[] buffer = new byte[size];\n if (is.read(buffer) != buffer.length)\n {\n throw new EOFException();\n }\n return (buffer);\n }",
"public static boolean isArrayOfUnboundedTypeVariablesOrObjects(Type[] types) {\n for (Type type : types) {\n if (Object.class.equals(type)) {\n continue;\n }\n if (type instanceof TypeVariable<?>) {\n Type[] bounds = ((TypeVariable<?>) type).getBounds();\n if (bounds == null || bounds.length == 0 || (bounds.length == 1 && Object.class.equals(bounds[0]))) {\n continue;\n }\n }\n return false;\n }\n return true;\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}"
] |
Finds the preferred provider for the given service. The preferred
provider is the last one added to the set of providers.
@param serviceName
The fully qualified name of the service interface.
@return
The last provider added for the service if any exists.
Otherwise, it returns <tt>null</tt>.
@throws IllegalArgumentException if serviceName is <tt>null</tt> | [
"public static synchronized Class< ? > locate(final String serviceName) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null && !l.isEmpty() ) {\n Callable<Class< ? >> c = l.get( l.size() - 1 );\n try {\n return c.call();\n } catch ( Exception e ) {\n }\n }\n }\n return null;\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n protected void addPostRunDependent(Executable<? extends Indexable> executable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) executable;\n this.addPostRunDependent(dependency);\n }",
"public int deleteTopic(String topic, String password) throws IOException {\n KV<Receive, ErrorMapping> response = send(new DeleterRequest(topic, password));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }",
"private void processActivityCodes(Storepoint storepoint)\n {\n for (Code code : storepoint.getActivityCodes().getCode())\n {\n int sequence = 0;\n for (Value value : code.getValue())\n {\n UUID uuid = getUUID(value.getUuid(), value.getName());\n m_activityCodeValues.put(uuid, value.getName());\n m_activityCodeSequence.put(uuid, Integer.valueOf(++sequence));\n }\n }\n }",
"protected Model createFlattenedPom( File pomFile )\n throws MojoExecutionException, MojoFailureException\n {\n\n ModelBuildingRequest buildingRequest = createModelBuildingRequest( pomFile );\n Model effectivePom = createEffectivePom( buildingRequest, isEmbedBuildProfileDependencies(), this.flattenMode );\n\n Model flattenedPom = new Model();\n\n // keep original encoding (we could also normalize to UTF-8 here)\n String modelEncoding = effectivePom.getModelEncoding();\n if ( StringUtils.isEmpty( modelEncoding ) )\n {\n modelEncoding = \"UTF-8\";\n }\n flattenedPom.setModelEncoding( modelEncoding );\n\n Model cleanPom = createCleanPom( effectivePom );\n\n FlattenDescriptor descriptor = getFlattenDescriptor();\n Model originalPom = this.project.getOriginalModel();\n Model resolvedPom = this.project.getModel();\n Model interpolatedPom = createResolvedPom( buildingRequest );\n\n // copy the configured additional POM elements...\n\n for ( PomProperty<?> property : PomProperty.getPomProperties() )\n {\n if ( property.isElement() )\n {\n Model sourceModel = getSourceModel( descriptor, property, effectivePom, originalPom, resolvedPom,\n interpolatedPom, cleanPom );\n if ( sourceModel == null )\n {\n if ( property.isRequired() )\n {\n throw new MojoFailureException( \"Property \" + property.getName()\n + \" is required and can not be removed!\" );\n }\n }\n else\n {\n property.copy( sourceModel, flattenedPom );\n }\n }\n }\n\n return flattenedPom;\n }",
"public List<MapRow> readBlocks(Class<? extends BlockReader> readerClass) throws IOException\n {\n BlockReader reader;\n\n try\n {\n reader = readerClass.getConstructor(StreamReader.class).newInstance(this);\n }\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n return reader.read();\n }",
"public Bundler put(String key, Serializable value) {\n delegate.putSerializable(key, value);\n return this;\n }",
"public int getIndex(T value) {\n int count = getItemCount();\n for (int i = 0; i < count; i++) {\n if (Objects.equals(getValue(i), value)) {\n return i;\n }\n }\n return -1;\n }",
"public 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 }",
"public static String getGetterName(String propertyName, Class type) {\n String prefix = type == boolean.class || type == Boolean.class ? \"is\" : \"get\";\n return prefix + MetaClassHelper.capitalize(propertyName);\n }"
] |
Set the menu view from a layout resource.
@param layoutResId Resource ID to be inflated. | [
"public void setMenuView(int layoutResId) {\n mMenuContainer.removeAllViews();\n mMenuView = LayoutInflater.from(getContext()).inflate(layoutResId, mMenuContainer, false);\n mMenuContainer.addView(mMenuView);\n }"
] | [
"public void setBackgroundColor(int color) {\n setBackgroundColorR(Colors.byteToGl(Color.red(color)));\n setBackgroundColorG(Colors.byteToGl(Color.green(color)));\n setBackgroundColorB(Colors.byteToGl(Color.blue(color)));\n setBackgroundColorA(Colors.byteToGl(Color.alpha(color)));\n }",
"private String getDynamicAttributeValue(\n CmsFile file,\n I_CmsXmlContentValue value,\n String attributeName,\n CmsEntity editedLocalEntity) {\n\n if ((null != editedLocalEntity) && (editedLocalEntity.getAttribute(attributeName) != null)) {\n getSessionCache().setDynamicValue(\n attributeName,\n editedLocalEntity.getAttribute(attributeName).getSimpleValue());\n }\n String currentValue = getSessionCache().getDynamicValue(attributeName);\n if (null != currentValue) {\n return currentValue;\n }\n if (null != file) {\n if (value.getTypeName().equals(CmsXmlDynamicCategoryValue.TYPE_NAME)) {\n List<CmsCategory> categories = new ArrayList<CmsCategory>(0);\n try {\n categories = CmsCategoryService.getInstance().readResourceCategories(getCmsObject(), file);\n } catch (CmsException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERROR_FAILED_READING_CATEGORIES_1), e);\n }\n I_CmsWidget widget = null;\n widget = CmsWidgetUtil.collectWidgetInfo(value).getWidget();\n if ((null != widget) && (widget instanceof CmsCategoryWidget)) {\n String mainCategoryPath = ((CmsCategoryWidget)widget).getStartingCategory(\n getCmsObject(),\n getCmsObject().getSitePath(file));\n StringBuffer pathes = new StringBuffer();\n for (CmsCategory category : categories) {\n if (category.getPath().startsWith(mainCategoryPath)) {\n String path = category.getBasePath() + category.getPath();\n path = getCmsObject().getRequestContext().removeSiteRoot(path);\n pathes.append(path).append(',');\n }\n }\n String dynamicConfigString = pathes.length() > 0 ? pathes.substring(0, pathes.length() - 1) : \"\";\n getSessionCache().setDynamicValue(attributeName, dynamicConfigString);\n return dynamicConfigString;\n }\n }\n }\n return \"\";\n\n }",
"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 }",
"private boolean tryCustomErrorPage(CmsObject cms, HttpServletRequest req, HttpServletResponse res, int errorCode) {\n\n String siteRoot = OpenCms.getSiteManager().matchRequest(req).getSiteRoot();\n CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);\n if (site != null) {\n // store current site root and URI\n String currentSiteRoot = cms.getRequestContext().getSiteRoot();\n String currentUri = cms.getRequestContext().getUri();\n try {\n if (site.getErrorPage() != null) {\n String rootPath = site.getErrorPage();\n if (loadCustomErrorPage(cms, req, res, rootPath)) {\n return true;\n }\n }\n String rootPath = CmsStringUtil.joinPaths(siteRoot, \"/.errorpages/handle\" + errorCode + \".html\");\n if (loadCustomErrorPage(cms, req, res, rootPath)) {\n return true;\n }\n } finally {\n cms.getRequestContext().setSiteRoot(currentSiteRoot);\n cms.getRequestContext().setUri(currentUri);\n }\n }\n return false;\n }",
"public void addFile(InputStream inputStream) {\n String name = \"file\";\n fileStreams.put(normalizeDuplicateName(name), inputStream);\n }",
"public void add(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n parameters.put(\"photo_id\", photoId);\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 }",
"@Override\n public Map<String, Set<String>> cleanObsoleteContent() {\n if(!readWrite) {\n return Collections.emptyMap();\n }\n Map<String, Set<String>> cleanedContents = new HashMap<>(2);\n cleanedContents.put(MARKED_CONTENT, new HashSet<>());\n cleanedContents.put(DELETED_CONTENT, new HashSet<>());\n synchronized (contentHashReferences) {\n for (ContentReference fsContent : listLocalContents()) {\n if (!readWrite) {\n return Collections.emptyMap();\n }\n if (!contentHashReferences.containsKey(fsContent.getHexHash())) { //We have no reference to this content\n if (markAsObsolete(fsContent)) {\n cleanedContents.get(DELETED_CONTENT).add(fsContent.getContentIdentifier());\n } else {\n cleanedContents.get(MARKED_CONTENT).add(fsContent.getContentIdentifier());\n }\n } else {\n obsoleteContents.remove(fsContent.getHexHash()); //Remove existing references from obsoleteContents\n }\n }\n }\n return cleanedContents;\n }",
"public static tmglobal_binding get(nitro_service service) throws Exception{\n\t\ttmglobal_binding obj = new tmglobal_binding();\n\t\ttmglobal_binding response = (tmglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"void update(Object feature) throws LayerException {\n\t\tSimpleFeatureSource source = getFeatureSource();\n\t\tif (source instanceof SimpleFeatureStore) {\n\t\t\tSimpleFeatureStore store = (SimpleFeatureStore) source;\n\t\t\tString featureId = getFeatureModel().getId(feature);\n\t\t\tFilter filter = filterService.createFidFilter(new String[] { featureId });\n\t\t\ttransactionSynchronization.synchTransaction(store);\n\t\t\tList<Name> names = new ArrayList<Name>();\n\t\t\tMap<String, Attribute> attrMap = getFeatureModel().getAttributes(feature);\n\t\t\tList<Object> values = new ArrayList<Object>();\n\t\t\tfor (Map.Entry<String, Attribute> entry : attrMap.entrySet()) {\n\t\t\t\tString name = entry.getKey();\n\t\t\t\tnames.add(store.getSchema().getDescriptor(name).getName());\n\t\t\t\tvalues.add(entry.getValue().getValue());\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tstore.modifyFeatures(names.toArray(new Name[names.size()]), values.toArray(), filter);\n\t\t\t\tstore.modifyFeatures(store.getSchema().getGeometryDescriptor().getName(), getFeatureModel()\n\t\t\t\t\t\t.getGeometry(feature), filter);\n\t\t\t\tlog.debug(\"Updated feature {} in {}\", featureId, getFeatureSourceName());\n\t\t\t} catch (IOException ioe) {\n\t\t\t\tfeatureModelUsable = false;\n\t\t\t\tthrow new LayerException(ioe, ExceptionCode.LAYER_MODEL_IO_EXCEPTION);\n\t\t\t}\n\t\t} else {\n\t\t\tlog.error(\"Don't know how to create or update \" + getFeatureSourceName() + \", class \"\n\t\t\t\t\t+ source.getClass().getName() + \" does not implement SimpleFeatureStore\");\n\t\t\tthrow new LayerException(ExceptionCode.CREATE_OR_UPDATE_NOT_IMPLEMENTED, getFeatureSourceName(), source\n\t\t\t\t\t.getClass().getName());\n\t\t}\n\t}"
] |
Returns all base types.
@return An iterator of the base types | [
"public Iterator getAllBaseTypes()\r\n {\r\n ArrayList baseTypes = new ArrayList();\r\n\r\n baseTypes.addAll(_directBaseTypes.values());\r\n\r\n for (int idx = baseTypes.size() - 1; idx >= 0; idx--)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)baseTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getDirectBaseTypes(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curBaseTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!baseTypes.contains(curBaseTypeDef))\r\n {\r\n baseTypes.add(0, curBaseTypeDef);\r\n idx++;\r\n }\r\n }\r\n }\r\n return baseTypes.iterator();\r\n }"
] | [
"private TestClassResults getResultsForClass(Map<IClass, TestClassResults> flattenedResults,\n ITestResult testResult)\n {\n TestClassResults resultsForClass = flattenedResults.get(testResult.getTestClass());\n if (resultsForClass == null)\n {\n resultsForClass = new TestClassResults(testResult.getTestClass());\n flattenedResults.put(testResult.getTestClass(), resultsForClass);\n }\n return resultsForClass;\n }",
"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 }",
"private double convertMaturity(int maturityInMonths) {\r\n\t\tSchedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, 12);\r\n\t\treturn schedule.getFixing(0);\r\n\t}",
"public static boolean isMethodNamed(MethodCallExpression methodCall, String methodNamePattern, Integer numArguments) {\r\n Expression method = methodCall.getMethod();\r\n\r\n // !important: performance enhancement\r\n boolean IS_NAME_MATCH = false;\r\n if (method instanceof ConstantExpression) {\r\n if (((ConstantExpression) method).getValue() instanceof String) {\r\n IS_NAME_MATCH = ((String)((ConstantExpression) method).getValue()).matches(methodNamePattern);\r\n }\r\n }\r\n\r\n if (IS_NAME_MATCH && numArguments != null) {\r\n return AstUtil.getMethodArguments(methodCall).size() == numArguments;\r\n }\r\n return IS_NAME_MATCH;\r\n }",
"public static base_response add(nitro_service client, transformpolicy resource) throws Exception {\n\t\ttransformpolicy addresource = new transformpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static void main(String[] args) {\r\n try {\r\n TreeFactory tf = new LabeledScoredTreeFactory();\r\n Reader r = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), \"UTF-8\"));\r\n TreeReader tr = new PennTreeReader(r, tf);\r\n Tree t = tr.readTree();\r\n while (t != null) {\r\n System.out.println(t);\r\n System.out.println();\r\n t = tr.readTree();\r\n }\r\n r.close();\r\n } catch (IOException ioe) {\r\n ioe.printStackTrace();\r\n }\r\n }",
"private int runCommitScript() {\n\n if (m_checkout && !m_fetchAndResetBeforeImport) {\n m_logStream.println(\"Skipping script....\");\n return 0;\n }\n try {\n m_logStream.flush();\n String commandParam;\n if (m_resetRemoteHead) {\n commandParam = resetRemoteHeadScriptCommand();\n } else if (m_resetHead) {\n commandParam = resetHeadScriptCommand();\n } else if (m_checkout) {\n commandParam = checkoutScriptCommand();\n } else {\n commandParam = checkinScriptCommand();\n }\n String[] cmd = {\"bash\", \"-c\", commandParam};\n m_logStream.println(\"Calling the script as follows:\");\n m_logStream.println();\n m_logStream.println(cmd[0] + \" \" + cmd[1] + \" \" + cmd[2]);\n ProcessBuilder builder = new ProcessBuilder(cmd);\n m_logStream.close();\n m_logStream = null;\n Redirect redirect = Redirect.appendTo(new File(DEFAULT_LOGFILE_PATH));\n builder.redirectOutput(redirect);\n builder.redirectError(redirect);\n Process scriptProcess = builder.start();\n int exitCode = scriptProcess.waitFor();\n scriptProcess.getOutputStream().close();\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, true));\n return exitCode;\n } catch (InterruptedException | IOException e) {\n e.printStackTrace(m_logStream);\n return -1;\n }\n\n }",
"static void addDeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) {\n final String name = deployment.getName();\n\n final Set<String> serverGroups = deployment.getServerGroups();\n // If the server groups are empty this is a standalone deployment\n if (serverGroups.isEmpty()) {\n final ModelNode address = createAddress(DEPLOYMENT, name);\n builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address));\n } else {\n for (String serverGroup : serverGroups) {\n final ModelNode address = createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, name);\n builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address));\n }\n }\n }",
"private long validateMessage(FileChannel channel, long start, long len, ByteBuffer buffer) throws IOException {\n buffer.rewind();\n int read = channel.read(buffer, start);\n if (read < 4) return -1;\n\n // check that we have sufficient bytes left in the file\n int size = buffer.getInt(0);\n if (size < Message.MinHeaderSize) return -1;\n\n long next = start + 4 + size;\n if (next > len) return -1;\n\n // read the message\n ByteBuffer messageBuffer = ByteBuffer.allocate(size);\n long curr = start + 4;\n while (messageBuffer.hasRemaining()) {\n read = channel.read(messageBuffer, curr);\n if (read < 0) throw new IllegalStateException(\"File size changed during recovery!\");\n else curr += read;\n }\n messageBuffer.rewind();\n Message message = new Message(messageBuffer);\n if (!message.isValid()) return -1;\n else return next;\n }"
] |
This method writes resource data to a Planner file. | [
"private void writeResources()\n {\n Resources resources = m_factory.createResources();\n m_plannerProject.setResources(resources);\n List<net.sf.mpxj.planner.schema.Resource> resourceList = resources.getResource();\n for (Resource mpxjResource : m_projectFile.getResources())\n {\n net.sf.mpxj.planner.schema.Resource plannerResource = m_factory.createResource();\n resourceList.add(plannerResource);\n writeResource(mpxjResource, plannerResource);\n }\n }"
] | [
"public static Collection<String> getFormatProviderNames() {\n Collection<String> providers = Optional.ofNullable(getMonetaryFormatsSpi()).orElseThrow(\n () -> new MonetaryException(\n \"No MonetaryFormatsSingletonSpi loaded, query functionality is not available.\"))\n .getProviderNames();\n if (Objects.isNull(providers)) {\n Logger.getLogger(MonetaryFormats.class.getName()).warning(\n \"No supported rate/conversion providers returned by SPI: \" +\n getMonetaryFormatsSpi().getClass().getName());\n return Collections.emptySet();\n }\n return providers;\n }",
"@Deprecated\r\n public Location resolvePlaceId(String placeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_ID);\r\n\r\n parameters.put(\"place_id\", placeId);\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 locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }",
"public Set<String> rangeByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (lexRange.hasLimit()) {\n return jedis.zrangeByLex(getKey(), lexRange.from(), lexRange.to(), lexRange.offset(), lexRange.count());\n } else {\n return jedis.zrangeByLex(getKey(), lexRange.from(), lexRange.to());\n }\n }\n });\n }",
"protected void addProcessedData(List<List<CRFDatum<Collection<String>, String>>> processedData, int[][][][] data,\r\n int[][] labels, int offset) {\r\n for (int i = 0, pdSize = processedData.size(); i < pdSize; i++) {\r\n int dataIndex = i + offset;\r\n List<CRFDatum<Collection<String>, String>> document = processedData.get(i);\r\n int dsize = document.size();\r\n labels[dataIndex] = new int[dsize];\r\n data[dataIndex] = new int[dsize][][];\r\n for (int j = 0; j < dsize; j++) {\r\n CRFDatum<Collection<String>, String> crfDatum = document.get(j);\r\n // add label, they are offset by extra context\r\n labels[dataIndex][j] = classIndex.indexOf(crfDatum.label());\r\n // add features\r\n List<Collection<String>> cliques = crfDatum.asFeatures();\r\n int csize = cliques.size();\r\n data[dataIndex][j] = new int[csize][];\r\n for (int k = 0; k < csize; k++) {\r\n Collection<String> features = cliques.get(k);\r\n\r\n // Debug only: Remove\r\n // if (j < windowSize) {\r\n // System.err.println(\"addProcessedData: Features Size: \" +\r\n // features.size());\r\n // }\r\n\r\n data[dataIndex][j][k] = new int[features.size()];\r\n\r\n int m = 0;\r\n try {\r\n for (String feature : features) {\r\n // System.err.println(\"feature \" + feature);\r\n // if (featureIndex.indexOf(feature)) ;\r\n if (featureIndex == null) {\r\n System.out.println(\"Feature is NULL!\");\r\n }\r\n data[dataIndex][j][k][m] = featureIndex.indexOf(feature);\r\n m++;\r\n }\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n System.err.printf(\"[index=%d, j=%d, k=%d, m=%d]\\n\", dataIndex, j, k, m);\r\n System.err.println(\"data.length \" + data.length);\r\n System.err.println(\"data[dataIndex].length \" + data[dataIndex].length);\r\n System.err.println(\"data[dataIndex][j].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k][m] \" + data[dataIndex][j][k][m]);\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n }",
"public static double computeHouseholder(double []x , int xStart , int xEnd , double max , DScalar gamma ) {\n double tau = 0;\n for (int i = xStart; i < xEnd ; i++) {\n double val = x[i] /= max;\n tau += val*val;\n }\n tau = Math.sqrt(tau);\n if( x[xStart] < 0 ) {\n tau = -tau;\n }\n double u_0 = x[xStart] + tau;\n gamma.value = u_0/tau;\n x[xStart] = 1;\n for (int i = xStart+1; i < xEnd ; i++) {\n x[i] /= u_0;\n }\n\n return -tau*max;\n }",
"public static DMatrixRMaj copyTriangle(DMatrixRMaj src , DMatrixRMaj dst , boolean upper ) {\n if( dst == null ) {\n dst = new DMatrixRMaj(src.numRows,src.numCols);\n } else if( src.numRows != dst.numRows || src.numCols != dst.numCols ) {\n throw new IllegalArgumentException(\"src and dst must have the same dimensions.\");\n }\n\n if( upper ) {\n int N = Math.min(src.numRows,src.numCols);\n for( int i = 0; i < N; i++ ) {\n int index = i*src.numCols+i;\n System.arraycopy(src.data,index,dst.data,index,src.numCols-i);\n }\n } else {\n for( int i = 0; i < src.numRows; i++ ) {\n int length = Math.min(i+1,src.numCols);\n int index = i*src.numCols;\n System.arraycopy(src.data,index,dst.data,index,length);\n }\n }\n\n return dst;\n }",
"public void setValueSelected(T value, boolean selected) {\n int idx = getIndex(value);\n if (idx >= 0) {\n setItemSelectedInternal(idx, selected);\n }\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, BeatGrid> getLoadedBeatGrids() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, BeatGrid>(hotCache));\n }",
"public static String generateQuery(final Map<String,Object> params){\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tboolean newEntry = false;\n\t\t\n\t\tsb.append(\"{\");\n\t\tfor(final Entry<String,Object> param: params.entrySet()){\n\t\t\tif(newEntry){\n\t\t\t\tsb.append(\", \");\n\t\t\t}\n\n\t\t\tsb.append(param.getKey());\n\t\t\tsb.append(\": \");\n\t\t\tsb.append(getParam(param.getValue()));\n\t\t\tnewEntry = true;\n\t\t}\n\t\tsb.append(\"}\");\n\t\t\n\t\treturn sb.toString();\n\t}"
] |
if you want to convert some string to an object, you have an argument to parse | [
"public ConfigOptionBuilder setStringConverter( StringConverter converter ) {\n co.setConverter( converter );\n co.setHasArgument( true );\n return this;\n }"
] | [
"private int getFlagResource(Country country) {\n return getContext().getResources().getIdentifier(\"country_\" + country.getIso().toLowerCase(), \"drawable\", getContext().getPackageName());\n }",
"public void assignField(ConnectionSource connectionSource, Object data, Object val, boolean parentObject,\n\t\t\tObjectCache objectCache) throws SQLException {\n\n\t\tif (logger.isLevelEnabled(Level.TRACE)) {\n\t\t\tlogger.trace(\"assiging from data {}, val {}: {}\", (data == null ? \"null\" : data.getClass()),\n\t\t\t\t\t(val == null ? \"null\" : val.getClass()), val);\n\t\t}\n\t\t// if this is a foreign object then val is the foreign object's id val\n\t\tif (foreignRefField != null && val != null) {\n\t\t\t// get the current field value which is the foreign-id\n\t\t\tObject foreignRef = extractJavaFieldValue(data);\n\t\t\t/*\n\t\t\t * See if we don't need to create a new foreign object. If we are refreshing and the id field has not\n\t\t\t * changed then there is no need to create a new foreign object and maybe lose previously refreshed field\n\t\t\t * information.\n\t\t\t */\n\t\t\tif (foreignRef != null && foreignRef.equals(val)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// awhitlock: raised as OrmLite issue: bug #122\n\t\t\tObject cachedVal;\n\t\t\tObjectCache foreignCache = foreignDao.getObjectCache();\n\t\t\tif (foreignCache == null) {\n\t\t\t\tcachedVal = null;\n\t\t\t} else {\n\t\t\t\tcachedVal = foreignCache.get(getType(), val);\n\t\t\t}\n\t\t\tif (cachedVal != null) {\n\t\t\t\tval = cachedVal;\n\t\t\t} else if (!parentObject) {\n\t\t\t\t// the value we are to assign to our field is now the foreign object itself\n\t\t\t\tval = createForeignObject(connectionSource, val, objectCache);\n\t\t\t}\n\t\t}\n\n\t\tif (fieldSetMethod == null) {\n\t\t\ttry {\n\t\t\t\tfield.set(data, val);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tif (val == null) {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\"Could not assign object '\" + val + \"' to field \" + this, e);\n\t\t\t\t} else {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \" to field \" + this, e);\n\t\t\t\t}\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \"' to field \" + this, e);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tfieldSetMethod.invoke(data, val);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow SqlExceptionUtil\n\t\t\t\t\t\t.create(\"Could not call \" + fieldSetMethod + \" on object with '\" + val + \"' for \" + this, e);\n\t\t\t}\n\t\t}\n\t}",
"public boolean isAlive(Connection conn)\r\n {\r\n try\r\n {\r\n return con != null ? !con.isClosed() : false;\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"IsAlive check failed, running connection was invalid!!\", e);\r\n return false;\r\n }\r\n }",
"public Object getJavaDefaultValueDefault() {\n\t\tif (field.getType() == boolean.class) {\n\t\t\treturn DEFAULT_VALUE_BOOLEAN;\n\t\t} else if (field.getType() == byte.class || field.getType() == Byte.class) {\n\t\t\treturn DEFAULT_VALUE_BYTE;\n\t\t} else if (field.getType() == char.class || field.getType() == Character.class) {\n\t\t\treturn DEFAULT_VALUE_CHAR;\n\t\t} else if (field.getType() == short.class || field.getType() == Short.class) {\n\t\t\treturn DEFAULT_VALUE_SHORT;\n\t\t} else if (field.getType() == int.class || field.getType() == Integer.class) {\n\t\t\treturn DEFAULT_VALUE_INT;\n\t\t} else if (field.getType() == long.class || field.getType() == Long.class) {\n\t\t\treturn DEFAULT_VALUE_LONG;\n\t\t} else if (field.getType() == float.class || field.getType() == Float.class) {\n\t\t\treturn DEFAULT_VALUE_FLOAT;\n\t\t} else if (field.getType() == double.class || field.getType() == Double.class) {\n\t\t\treturn DEFAULT_VALUE_DOUBLE;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}",
"public static PackageNameMappingWithPackagePattern fromPackage(String packagePattern)\n {\n PackageNameMapping packageNameMapping = new PackageNameMapping();\n packageNameMapping.setPackagePattern(packagePattern);\n return packageNameMapping;\n }",
"public static boolean isAvroSchema(String serializerName) {\n if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerName.equals(AVRO_GENERIC_TYPE_NAME)\n || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME)\n || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) {\n return true;\n } else {\n return false;\n }\n }",
"public static String buildDynamicCapabilityName(String baseName, String dynamicNameElement) {\n return buildDynamicCapabilityName(baseName, new String[]{dynamicNameElement});\n }",
"public void applyTo(Context ctx, GradientDrawable drawable) {\n if (mColorInt != 0) {\n drawable.setColor(mColorInt);\n } else if (mColorRes != -1) {\n drawable.setColor(ContextCompat.getColor(ctx, mColorRes));\n }\n }",
"@Override public void process(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException\n {\n try\n {\n populateMemberData(reader, file, root);\n processProjectProperties();\n\n if (!reader.getReadPropertiesOnly())\n {\n processCalendarData();\n processResourceData();\n processTaskData();\n processConstraintData();\n processAssignmentData();\n\n if (reader.getReadPresentationData())\n {\n processViewPropertyData();\n processViewData();\n processTableData();\n }\n }\n }\n\n finally\n {\n clearMemberData();\n }\n }"
] |
Displays text which shows the valid command line parameters, and then exits. | [
"private void wrongUsage() {\n\n String usage = \"Usage: java -cp $PATH_TO_OPENCMS_JAR org.opencms.rmi.CmsRemoteShellClient\\n\"\n + \" -script=[path to script] (optional) \\n\"\n + \" -registryPort=[port of RMI registry] (optional, default is \"\n + CmsRemoteShellConstants.DEFAULT_PORT\n + \")\\n\"\n + \" -additional=[additional commands class name] (optional)\";\n System.out.println(usage);\n System.exit(1);\n }"
] | [
"public static void rebuild(final MODE newMode) {\n if (mode != newMode) {\n mode = newMode;\n TYPE type;\n switch (mode) {\n case DEBUG:\n type = TYPE.ANDROID;\n Log.startFullLog();\n break;\n case DEVELOPER:\n type = TYPE.PERSISTENT;\n Log.stopFullLog();\n break;\n case USER:\n type = TYPE.ANDROID;\n break;\n default:\n type = DEFAULT_TYPE;\n Log.stopFullLog();\n break;\n }\n currentLog = getLog(type);\n }\n }",
"public void addForeignkey(String relationName, String remoteTable, List localColumns, List remoteColumns)\r\n {\r\n ForeignkeyDef foreignkeyDef = new ForeignkeyDef(relationName, remoteTable);\r\n\r\n // the field arrays have the same length if we already checked the constraints\r\n for (int idx = 0; idx < localColumns.size(); idx++)\r\n {\r\n foreignkeyDef.addColumnPair((String)localColumns.get(idx),\r\n (String)remoteColumns.get(idx));\r\n }\r\n\r\n // we got to determine whether this foreignkey is already present \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 (foreignkeyDef.equals(def))\r\n {\r\n return;\r\n }\r\n }\r\n foreignkeyDef.setOwner(this);\r\n _foreignkeys.add(foreignkeyDef);\r\n }",
"private void processCalendarHours(ProjectCalendar calendar, Row row, int dayIndex)\n {\n Day day = Day.getInstance(dayIndex);\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n calendar.setWorkingDay(day, working);\n if (working == true)\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Date start = row.getDate(\"CD_FROM_TIME1\");\n Date end = row.getDate(\"CD_TO_TIME1\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME2\");\n end = row.getDate(\"CD_TO_TIME2\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME3\");\n end = row.getDate(\"CD_TO_TIME3\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME4\");\n end = row.getDate(\"CD_TO_TIME4\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME5\");\n end = row.getDate(\"CD_TO_TIME5\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n }\n }",
"public final int deleteOld(final long checkTimeThreshold) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaDelete<PrintJobStatusExtImpl> delete =\n builder.createCriteriaDelete(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = delete.from(PrintJobStatusExtImpl.class);\n delete.where(builder.and(builder.isNotNull(root.get(\"lastCheckTime\")),\n builder.lessThan(root.get(\"lastCheckTime\"), checkTimeThreshold)));\n return getSession().createQuery(delete).executeUpdate();\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 static Map<Double, Double> doQuantization(double max,\n double min,\n double[] values)\n {\n double range = max - min;\n int noIntervals = 20;\n double intervalSize = range / noIntervals;\n int[] intervals = new int[noIntervals];\n for (double value : values)\n {\n int interval = Math.min(noIntervals - 1,\n (int) Math.floor((value - min) / intervalSize));\n assert interval >= 0 && interval < noIntervals : \"Invalid interval: \" + interval;\n ++intervals[interval];\n }\n Map<Double, Double> discretisedValues = new HashMap<Double, Double>();\n for (int i = 0; i < intervals.length; i++)\n {\n // Correct the value to take into account the size of the interval.\n double value = (1 / intervalSize) * (double) intervals[i];\n discretisedValues.put(min + ((i + 0.5) * intervalSize), value);\n }\n return discretisedValues;\n }",
"public boolean attachComponent(GVRComponent component) {\n if (component.getNative() != 0) {\n NativeSceneObject.attachComponent(getNative(), component.getNative());\n }\n synchronized (mComponents) {\n long type = component.getType();\n if (!mComponents.containsKey(type)) {\n mComponents.put(type, component);\n component.setOwnerObject(this);\n return true;\n }\n }\n return false;\n }",
"private void readUnread(CommitData cd, Consumer<Entry<Key, Value>> locksSeen) {\n // TODO make async\n // TODO need to keep track of ranges read (not ranges passed in, but actual data read... user\n // may not iterate over entire range\n Map<Bytes, Set<Column>> columnsToRead = new HashMap<>();\n\n for (Entry<Bytes, Set<Column>> entry : cd.getRejected().entrySet()) {\n Set<Column> rowColsRead = columnsRead.get(entry.getKey());\n if (rowColsRead == null) {\n columnsToRead.put(entry.getKey(), entry.getValue());\n } else {\n HashSet<Column> colsToRead = new HashSet<>(entry.getValue());\n colsToRead.removeAll(rowColsRead);\n if (!colsToRead.isEmpty()) {\n columnsToRead.put(entry.getKey(), colsToRead);\n }\n }\n }\n\n for (Entry<Bytes, Set<Column>> entry : columnsToRead.entrySet()) {\n getImpl(entry.getKey(), entry.getValue(), locksSeen);\n }\n }",
"public void onLayoutApplied(final WidgetContainer container, final Vector3Axis viewPortSize) {\n mContainer = container;\n mViewPort.setSize(viewPortSize);\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }"
] |
Updates the information about the user status for this terms of service with any info fields that have
been modified locally.
@param info the updated info. | [
"public void updateInfo(BoxTermsOfServiceUserStatus.Info info) {\n URL url = TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n info.update(responseJSON);\n }"
] | [
"public boolean isWorkingDay(Day day)\n {\n DayType value = getWorkingDay(day);\n boolean result;\n\n if (value == DayType.DEFAULT)\n {\n ProjectCalendar cal = getParent();\n if (cal != null)\n {\n result = cal.isWorkingDay(day);\n }\n else\n {\n result = (day != Day.SATURDAY && day != Day.SUNDAY);\n }\n }\n else\n {\n result = (value == DayType.WORKING);\n }\n\n return (result);\n }",
"private List<PermissionFactory> retrievePermissionSet(final OperationContext context, final ModelNode node) throws OperationFailedException {\n\n final List<PermissionFactory> permissions = new ArrayList<>();\n\n if (node != null && node.isDefined()) {\n for (ModelNode permissionNode : node.asList()) {\n String permissionClass = CLASS.resolveModelAttribute(context, permissionNode).asString();\n String permissionName = null;\n if (permissionNode.hasDefined(PERMISSION_NAME))\n permissionName = NAME.resolveModelAttribute(context, permissionNode).asString();\n String permissionActions = null;\n if (permissionNode.hasDefined(PERMISSION_ACTIONS))\n permissionActions = ACTIONS.resolveModelAttribute(context, permissionNode).asString();\n String moduleName = null;\n if(permissionNode.hasDefined(PERMISSION_MODULE)) {\n moduleName = MODULE.resolveModelAttribute(context, permissionNode).asString();\n }\n ClassLoader cl = WildFlySecurityManager.getClassLoaderPrivileged(this.getClass());\n if(moduleName != null) {\n try {\n cl = Module.getBootModuleLoader().loadModule(ModuleIdentifier.fromString(moduleName)).getClassLoader();\n } catch (ModuleLoadException e) {\n throw new OperationFailedException(e);\n }\n }\n\n permissions.add(new LoadedPermissionFactory(cl,\n permissionClass, permissionName, permissionActions));\n }\n }\n return permissions;\n }",
"public GVRShaderId getShaderType(Class<? extends GVRShader> shaderClass)\n {\n GVRShaderId shaderId = mShaderTemplates.get(shaderClass);\n\n if (shaderId == null)\n {\n GVRContext ctx = getGVRContext();\n shaderId = new GVRShaderId(shaderClass);\n mShaderTemplates.put(shaderClass, shaderId);\n shaderId.getTemplate(ctx);\n }\n return shaderId;\n }",
"public AsciiTable setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public int getPropertyId(@NotNull final PersistentStoreTransaction txn, @NotNull final String propertyName, final boolean allowCreate) {\n return allowCreate ? propertyIds.getOrAllocateId(txn, propertyName) : propertyIds.getId(txn, propertyName);\n }",
"public static String rset(String input, int width)\n {\n String result; // result to return\n StringBuilder pad = new StringBuilder();\n if (input == null)\n {\n for (int i = 0; i < width - 1; i++)\n {\n pad.append(' '); // put blanks into buffer\n }\n result = \" \" + pad; // one short to use + overload\n }\n else\n {\n if (input.length() >= width)\n {\n result = input.substring(0, width); // when input is too long, truncate\n }\n else\n {\n int padLength = width - input.length(); // number of blanks to add\n for (int i = 0; i < padLength; i++)\n {\n pad.append(' '); // actually put blanks into buffer\n }\n result = pad + input; // concatenate\n }\n }\n return result;\n }",
"public static sslservice[] get(nitro_service service, sslservice_args args) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsslservice[] response = (sslservice[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"public final void setValue(String value) {\n\n if ((null == value) || value.isEmpty()) {\n setDefaultValue();\n } else {\n try {\n tryToSetParsedValue(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n CmsDebugLog.consoleLog(\"Could not set invalid serial date value: \" + value);\n setDefaultValue();\n }\n }\n notifyOnValueChange();\n }",
"protected String statusMsg(final String queue, final Job job) throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setQueue(queue);\n status.setPayload(job);\n return ObjectMapperFactory.get().writeValueAsString(status);\n }"
] |
Returns an array of normalized strings for this host name instance.
If this represents an IP address, the address segments are separated into the returned array.
If this represents a host name string, the domain name segments are separated into the returned array,
with the top-level domain name (right-most segment) as the last array element.
The individual segment strings are normalized in the same way as {@link #toNormalizedString()}
Ports, service name strings, prefix lengths, and masks are all omitted from the returned array.
@return | [
"public String[] getNormalizedLabels() {\n\t\tif(isValid()) {\n\t\t\treturn parsedHost.getNormalizedLabels();\n\t\t}\n\t\tif(host.length() == 0) {\n\t\t\treturn new String[0];\n\t\t}\n\t\treturn new String[] {host};\n\t}"
] | [
"void flushLogQueue() {\n Set<String> problems = new LinkedHashSet<String>();\n synchronized (messageQueue) {\n Iterator<LogEntry> i = messageQueue.iterator();\n while (i.hasNext()) {\n problems.add(\"\\t\\t\" + i.next().getMessage() + \"\\n\");\n i.remove();\n }\n }\n if (!problems.isEmpty()) {\n logger.transformationWarnings(target.getHostName(), problems);\n }\n }",
"protected String getIsolationLevelAsString()\r\n {\r\n if (defaultIsolationLevel == IL_READ_UNCOMMITTED)\r\n {\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_READ_COMMITTED)\r\n {\r\n return LITERAL_IL_READ_COMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_REPEATABLE_READ)\r\n {\r\n return LITERAL_IL_REPEATABLE_READ;\r\n }\r\n else if (defaultIsolationLevel == IL_SERIALIZABLE)\r\n {\r\n return LITERAL_IL_SERIALIZABLE;\r\n }\r\n else if (defaultIsolationLevel == IL_OPTIMISTIC)\r\n {\r\n return LITERAL_IL_OPTIMISTIC;\r\n }\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\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 }",
"public ItemRequest<Story> delete(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"DELETE\");\n }",
"public static base_responses add(nitro_service client, onlinkipv6prefix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tonlinkipv6prefix addresources[] = new onlinkipv6prefix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new onlinkipv6prefix();\n\t\t\t\taddresources[i].ipv6prefix = resources[i].ipv6prefix;\n\t\t\t\taddresources[i].onlinkprefix = resources[i].onlinkprefix;\n\t\t\t\taddresources[i].autonomusprefix = resources[i].autonomusprefix;\n\t\t\t\taddresources[i].depricateprefix = resources[i].depricateprefix;\n\t\t\t\taddresources[i].decrementprefixlifetimes = resources[i].decrementprefixlifetimes;\n\t\t\t\taddresources[i].prefixvalidelifetime = resources[i].prefixvalidelifetime;\n\t\t\t\taddresources[i].prefixpreferredlifetime = resources[i].prefixpreferredlifetime;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private BigInteger printExtendedAttributeDurationFormat(Object value)\n {\n BigInteger result = null;\n if (value instanceof Duration)\n {\n result = DatatypeConverter.printDurationTimeUnits(((Duration) value).getUnits(), false);\n }\n return (result);\n }",
"protected void addPropertiesStart(String type) {\n putProperty(PropertyKey.Host.name(), IpUtils.getHostName());\n putProperty(PropertyKey.Type.name(), type);\n putProperty(PropertyKey.Status.name(), Status.Start.name());\n }",
"public static boolean intArrayContains(int[] array, int numToCheck) {\n for (int i = 0; i < array.length; i++) {\n if (array[i] == numToCheck) {\n return true;\n }\n }\n return false;\n }",
"protected boolean isFiltered(Param param) {\n\t\tAbstractElement elementToParse = param.elementToParse;\n\t\twhile (elementToParse != null) {\n\t\t\tif (isFiltered(elementToParse, param)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telementToParse = getEnclosingSingleElementGroup(elementToParse);\n\t\t}\n\t\treturn false;\n\t}"
] |
Calculates the local translation and rotation for a bone.
Assumes WorldRot and WorldPos have been calculated for the bone. | [
"protected void\t\tcalcLocal(Bone bone, int parentId)\n {\n if (parentId < 0)\n {\n bone.LocalMatrix.set(bone.WorldMatrix);\n return;\n }\n\t/*\n\t * WorldMatrix = WorldMatrix(parent) * LocalMatrix\n\t * LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix\n\t */\n getWorldMatrix(parentId, mTempMtxA);\t// WorldMatrix(par)\n mTempMtxA.invert();\t\t\t\t\t // INVERSE[ WorldMatrix(parent) ]\n mTempMtxA.mul(bone.WorldMatrix, bone.LocalMatrix); // LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix\n }"
] | [
"private void setHex() {\r\n\r\n String hRed = Integer.toHexString(getRed());\r\n String hGreen = Integer.toHexString(getGreen());\r\n String hBlue = Integer.toHexString(getBlue());\r\n\r\n if (hRed.length() == 0) {\r\n hRed = \"00\";\r\n }\r\n if (hRed.length() == 1) {\r\n hRed = \"0\" + hRed;\r\n }\r\n if (hGreen.length() == 0) {\r\n hGreen = \"00\";\r\n }\r\n if (hGreen.length() == 1) {\r\n hGreen = \"0\" + hGreen;\r\n }\r\n if (hBlue.length() == 0) {\r\n hBlue = \"00\";\r\n }\r\n if (hBlue.length() == 1) {\r\n hBlue = \"0\" + hBlue;\r\n }\r\n\r\n m_hex = hRed + hGreen + hBlue;\r\n }",
"protected void appendHavingClause(StringBuffer having, Criteria crit, StringBuffer stmt)\r\n {\r\n if (having.length() == 0)\r\n {\r\n having = null;\r\n }\r\n\r\n if (having != null || crit != null)\r\n {\r\n stmt.append(\" HAVING \");\r\n appendClause(having, crit, stmt);\r\n }\r\n }",
"public void stop() {\n if (accelerometer != null) {\n queue.clear();\n sensorManager.unregisterListener(this, accelerometer);\n sensorManager = null;\n accelerometer = null;\n }\n }",
"public static String writeSingleClientConfigAvro(Properties props) {\n // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json...\n String avroConfig = \"\";\n Boolean firstProp = true;\n for(String key: props.stringPropertyNames()) {\n if(firstProp) {\n firstProp = false;\n } else {\n avroConfig = avroConfig + \",\\n\";\n }\n avroConfig = avroConfig + \"\\t\\t\\\"\" + key + \"\\\": \\\"\" + props.getProperty(key) + \"\\\"\";\n }\n if(avroConfig.isEmpty()) {\n return \"{}\";\n } else {\n return \"{\\n\" + avroConfig + \"\\n\\t}\";\n }\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 static String join(final Collection<?> collection, final String separator) {\n StringBuffer buffer = new StringBuffer();\n boolean first = true;\n Iterator<?> iter = collection.iterator();\n while (iter.hasNext()) {\n Object next = iter.next();\n if (first) {\n first = false;\n } else {\n buffer.append(separator);\n }\n buffer.append(next);\n }\n return buffer.toString();\n }",
"public static void setTime(Calendar cal, Date time)\n {\n if (time != null)\n {\n Calendar startCalendar = popCalendar(time);\n cal.set(Calendar.HOUR_OF_DAY, startCalendar.get(Calendar.HOUR_OF_DAY));\n cal.set(Calendar.MINUTE, startCalendar.get(Calendar.MINUTE));\n cal.set(Calendar.SECOND, startCalendar.get(Calendar.SECOND));\n pushCalendar(startCalendar);\n }\n }",
"void release() {\n\t\tif (mCurrentRequests != null) {\n\t\t\tsynchronized (mCurrentRequests) {\n\t\t\t\tmCurrentRequests.clear();\n\t\t\t\tmCurrentRequests = null;\n\t\t\t}\n\t\t}\n\n\t\tif (mDownloadQueue != null) {\n\t\t\tmDownloadQueue = null;\n\t\t}\n\n\t\tif (mDownloadDispatchers != null) {\n\t\t\tstop();\n\n\t\t\tfor (int i = 0; i < mDownloadDispatchers.length; i++) {\n\t\t\t\tmDownloadDispatchers[i] = null;\n\t\t\t}\n\t\t\tmDownloadDispatchers = null;\n\t\t}\n\n\t}",
"@Override\n\tpublic void writeValue(TimeValue value, Resource resource)\n\t\t\tthrows RDFHandlerException {\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.WB_TIME_VALUE);\n\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.WB_TIME,\n\t\t\t\tTimeValueConverter.getTimeLiteral(value, this.rdfWriter));\n\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_PRECISION, value.getPrecision());\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_TIMEZONE,\n\t\t\t\tvalue.getTimezoneOffset());\n\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_CALENDAR_MODEL,\n\t\t\t\tvalue.getPreferredCalendarModel());\n\t}"
] |
Handle unbind service event.
@param service Service instance
@param props Service reference properties | [
"public void unbind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.remove(ServiceUtil.getComparableForServiceRanking(props));\n updateSortedServices();\n }\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}",
"private int getCacheKey(InputDevice device, GVRControllerType controllerType) {\n if (controllerType != GVRControllerType.UNKNOWN &&\n controllerType != GVRControllerType.EXTERNAL) {\n // Sometimes a device shows up using two device ids\n // here we try to show both devices as one using the\n // product and vendor id\n\n int key = device.getVendorId();\n key = 31 * key + device.getProductId();\n key = 31 * key + controllerType.hashCode();\n\n return key;\n }\n return -1; // invalid key\n }",
"public static base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}",
"public ProjectCalendarHours getHours(Day day)\n {\n ProjectCalendarHours result = getCalendarHours(day);\n if (result == null)\n {\n //\n // If this is a base calendar and we have no hours, then we\n // have a problem - so we add the default hours and try again\n //\n if (m_parent == null)\n {\n // Only add default hours for the day that is 'missing' to avoid overwriting real calendar hours\n addDefaultCalendarHours(day);\n result = getCalendarHours(day);\n }\n else\n {\n result = m_parent.getHours(day);\n }\n }\n return result;\n }",
"public static responderpolicy get(nitro_service service, String name) throws Exception{\n\t\tresponderpolicy obj = new responderpolicy();\n\t\tobj.set_name(name);\n\t\tresponderpolicy response = (responderpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static base_response update(nitro_service client, nsdiameter resource) throws Exception {\n\t\tnsdiameter updateresource = new nsdiameter();\n\t\tupdateresource.identity = resource.identity;\n\t\tupdateresource.realm = resource.realm;\n\t\tupdateresource.serverclosepropagation = resource.serverclosepropagation;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private int read() {\n int curByte = 0;\n try {\n curByte = rawData.get() & 0xFF;\n } catch (Exception e) {\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n return curByte;\n }",
"private Task findChildTaskByUUID(ChildTaskContainer parent, UUID uuid)\n {\n Task result = null;\n\n for (Task task : parent.getChildTasks())\n {\n if (uuid.equals(task.getGUID()))\n {\n result = task;\n break;\n }\n }\n\n return result;\n }",
"public ProjectCalendarHours getHours(Day day)\n {\n ProjectCalendarHours result = getCalendarHours(day);\n if (result == null)\n {\n //\n // If this is a base calendar and we have no hours, then we\n // have a problem - so we add the default hours and try again\n //\n if (m_parent == null)\n {\n // Only add default hours for the day that is 'missing' to avoid overwriting real calendar hours\n addDefaultCalendarHours(day);\n result = getCalendarHours(day);\n }\n else\n {\n result = m_parent.getHours(day);\n }\n }\n return result;\n }"
] |
get the key name to use in log from the logging keys map | [
"public String getKeyValue(String key){\n String keyName = keysMap.get(key);\n if (keyName != null){\n return keyName;\n }\n return \"\"; //key wasn't defined in keys properties file\n }"
] | [
"public static void addToListIfNotExists(List<String> list, String value) {\n boolean found = false;\n for (String item : list) {\n if (item.equalsIgnoreCase(value)) {\n found = true;\n break;\n }\n }\n if (!found) {\n list.add(value);\n }\n }",
"protected void buildSuperJoinTree(TableAlias left, ClassDescriptor cld, String name, boolean useOuterJoin)\r\n {\r\n ClassDescriptor superCld = cld.getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n SuperReferenceDescriptor superRef = cld.getSuperReference();\r\n FieldDescriptor[] leftFields = superRef.getForeignKeyFieldDescriptors(cld);\r\n TableAlias base_alias = getTableAliasForPath(name, null, null);\r\n String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++;\r\n TableAlias right = new TableAlias(superCld, aliasName, useOuterJoin, null);\r\n\r\n Join join1to1 = new Join(left, leftFields, right, superCld.getPkFields(), useOuterJoin, \"superClass\");\r\n base_alias.addJoin(join1to1);\r\n\r\n buildSuperJoinTree(right, superCld, name, useOuterJoin);\r\n }\r\n }",
"static List<List<String>> handleNewLines( List<List<String>> tableModel ) {\n List<List<String>> result = Lists.newArrayListWithExpectedSize( tableModel.size() );\n\n for( List<String> row : tableModel ) {\n if( hasNewline( row ) ) {\n result.addAll( splitRow( row ) );\n } else {\n result.add( row );\n }\n }\n\n return result;\n }",
"private static boolean isEqual(Method m, Method a) {\n if (m.getName().equals(a.getName()) && m.getParameterTypes().length == a.getParameterTypes().length && m.getReturnType().isAssignableFrom(a.getReturnType())) {\n for (int i = 0; i < m.getParameterTypes().length; i++) {\n if (!(m.getParameterTypes()[i].isAssignableFrom(a.getParameterTypes()[i]))) {\n return false;\n }\n }\n return true;\n }\n return false;\n }",
"protected Collection loadData() throws PersistenceBrokerException\r\n {\r\n PersistenceBroker broker = getBroker();\r\n try\r\n {\r\n Collection result;\r\n\r\n if (_data != null) // could be set by listener\r\n {\r\n result = _data;\r\n }\r\n else if (_size != 0)\r\n {\r\n // TODO: returned ManageableCollection should extend Collection to avoid\r\n // this cast\r\n result = (Collection) broker.getCollectionByQuery(getCollectionClass(), getQuery());\r\n }\r\n else\r\n {\r\n result = (Collection)getCollectionClass().newInstance();\r\n }\r\n return result;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n finally\r\n {\r\n releaseBroker(broker);\r\n }\r\n }",
"@Override\n protected <T> CompletableFuture<T> doExecute(Command<T> command) throws Exception {\n final CompletableFuture<T> future = new CompletableFuture<>();\n executor.execute(() -> {\n try {\n future.complete(blockingExecute(command));\n } catch (Throwable t) {\n future.completeExceptionally(t);\n }\n });\n return future;\n }",
"public static int wavelengthToRGB(float wavelength) {\n\t\tfloat gamma = 0.80f;\n\t\tfloat r, g, b, factor;\n\n\t\tint w = (int)wavelength;\n\t\tif (w < 380) {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 440) {\n\t\t\tr = -(wavelength - 440) / (440 - 380);\n\t\t\tg = 0.0f;\n\t\t\tb = 1.0f;\n\t\t} else if (w < 490) {\n\t\t\tr = 0.0f;\n\t\t\tg = (wavelength - 440) / (490 - 440);\n\t\t\tb = 1.0f;\n\t\t} else if (w < 510) {\n\t\t\tr = 0.0f;\n\t\t\tg = 1.0f;\n\t\t\tb = -(wavelength - 510) / (510 - 490);\n\t\t} else if (w < 580) {\n\t\t\tr = (wavelength - 510) / (580 - 510);\n\t\t\tg = 1.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 645) {\n\t\t\tr = 1.0f;\n\t\t\tg = -(wavelength - 645) / (645 - 580);\n\t\t\tb = 0.0f;\n\t\t} else if (w <= 780) {\n\t\t\tr = 1.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t}\n\n\t\t// Let the intensity fall off near the vision limits\n\t\tif (380 <= w && w <= 419)\n\t\t\tfactor = 0.3f + 0.7f*(wavelength - 380) / (420 - 380);\n\t\telse if (420 <= w && w <= 700)\n\t\t\tfactor = 1.0f;\n\t\telse if (701 <= w && w <= 780)\n\t\t\tfactor = 0.3f + 0.7f*(780 - wavelength) / (780 - 700);\n\t\telse\n\t\t\tfactor = 0.0f;\n\n\t\tint ir = adjust(r, factor, gamma);\n\t\tint ig = adjust(g, factor, gamma);\n\t\tint ib = adjust(b, factor, gamma);\n\n\t\treturn 0xff000000 | (ir << 16) | (ig << 8) | ib;\n\t}",
"public void setRegistrationConfig(RegistrationConfig registrationConfig) {\n this.registrationConfig = registrationConfig;\n\n if (registrationConfig.getDefaultConfig()!=null) {\n for (String key : registrationConfig.getDefaultConfig().keySet()) {\n dynamicConfig.put(key, registrationConfig.getDefaultConfig().get(key));\n }\n }\n }",
"public void saveFavorites(List<CmsFavoriteEntry> favorites) throws CmsException {\n\n try {\n JSONObject json = new JSONObject();\n JSONArray array = new JSONArray();\n for (CmsFavoriteEntry entry : favorites) {\n array.put(entry.toJson());\n }\n json.put(BASE_KEY, array);\n String data = json.toString();\n CmsUser user = readUser();\n user.setAdditionalInfo(ADDINFO_KEY, data);\n m_cms.writeUser(user);\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n\n }"
] |
Gets a first data set value.
@param dataSet
IIM record and dataset code (See constants in {@link IIM})
@return data set value
@throws SerializationException
if value can't be deserialized from binary representation | [
"public Object get(int dataSet) throws SerializationException {\r\n\t\tObject result = null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult = getData(ds);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}"
] | [
"void createDirectory(Path path) throws IOException {\n\t\tif (Files.exists(path) && Files.isDirectory(path)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.readOnly) {\n\t\t\tthrow new FileNotFoundException(\n\t\t\t\t\t\"The requested directory \\\"\"\n\t\t\t\t\t\t\t+ path.toString()\n\t\t\t\t\t\t\t+ \"\\\" does not exist and we are in read-only mode, so it cannot be created.\");\n\t\t}\n\n\t\tFiles.createDirectory(path);\n\t}",
"public String code(final String code) {\n if (this.theme == null) {\n throw new TemplateProcessingException(\"Theme cannot be resolved because RequestContext was not found. \"\n + \"Are you using a Context object without a RequestContext variable?\");\n }\n return this.theme.getMessageSource().getMessage(code, null, \"\", this.locale);\n }",
"private void addProgressInterceptor() {\n httpClient.networkInterceptors().add(new Interceptor() {\n @Override\n public Response intercept(Interceptor.Chain chain) throws IOException {\n final Request request = chain.request();\n final Response originalResponse = chain.proceed(request);\n if (request.tag() instanceof ApiCallback) {\n final ApiCallback callback = (ApiCallback) request.tag();\n return originalResponse.newBuilder()\n .body(new ProgressResponseBody(originalResponse.body(), callback)).build();\n }\n return originalResponse;\n }\n });\n }",
"public AT_Row setTextAlignment(TextAlignment textAlignment){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static void dumpMaterialProperty(AiMaterial.Property property) {\n System.out.print(property.getKey() + \" \" + property.getSemantic() + \n \" \" + property.getIndex() + \": \");\n Object data = property.getData();\n \n if (data instanceof ByteBuffer) {\n ByteBuffer buf = (ByteBuffer) data;\n for (int i = 0; i < buf.capacity(); i++) {\n System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + \" \");\n }\n \n System.out.println();\n }\n else {\n System.out.println(data.toString());\n }\n }",
"public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {\n\t\tinit(t1, t2);\n\t\tSTR = new int[size1][size2];\n\t\tcomputeOptimalStrategy();\n\t\treturn computeDistUsingStrArray(it1, it2);\n\t}",
"public Integer getIdFromName(String profileName) {\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.PROFILE_PROFILE_NAME + \" = ?\");\n query.setString(1, profileName);\n results = query.executeQuery();\n if (results.next()) {\n Object toReturn = results.getObject(Constants.GENERIC_ID);\n query.close();\n return (Integer) toReturn;\n }\n query.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }",
"boolean lockInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireNanos(permit, unit.toNanos(timeout));\n }",
"public void updateIntegerBelief(String name, int value) {\n introspector.storeBeliefValue(this, name, getIntegerBelief(name) + value);\n }"
] |
Read relationship data from a PEP file. | [
"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 }"
] | [
"static synchronized void clearLogContext() {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n // Remove the configurator and clear the log context\n final Configurator configurator = embeddedLogContext.getLogger(\"\").detach(Configurator.ATTACHMENT_KEY);\n // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext\n if (configurator instanceof PropertyConfigurator) {\n final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();\n clearLogContext(logContextConfiguration);\n } else if (configurator instanceof LogContextConfiguration) {\n clearLogContext((LogContextConfiguration) configurator);\n } else {\n // Remove all the handlers and close them as well as reset the loggers\n final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());\n for (String name : loggerNames) {\n final Logger logger = embeddedLogContext.getLoggerIfExists(name);\n if (logger != null) {\n final Handler[] handlers = logger.clearHandlers();\n if (handlers != null) {\n for (Handler handler : handlers) {\n handler.close();\n }\n }\n logger.setFilter(null);\n logger.setUseParentFilters(false);\n logger.setUseParentHandlers(true);\n logger.setLevel(Level.INFO);\n }\n }\n }\n }",
"private void deleteDir(File dir)\r\n {\r\n if (dir.exists() && dir.isDirectory())\r\n {\r\n File[] files = dir.listFiles();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (!files[idx].exists())\r\n {\r\n continue;\r\n }\r\n if (files[idx].isDirectory())\r\n {\r\n deleteDir(files[idx]);\r\n }\r\n else\r\n {\r\n files[idx].delete();\r\n }\r\n }\r\n dir.delete();\r\n }\r\n }",
"public void transformPose(Matrix4f trans)\n {\n Bone bone = mBones[0];\n\n bone.LocalMatrix.set(trans);\n bone.WorldMatrix.set(trans);\n bone.Changed = WORLD_POS | WORLD_ROT;\n mNeedSync = true;\n sync();\n }",
"final public void addPositionRange(int start, int end) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(start, end);\n } else {\n int[] positions = new int[end - start + 1];\n for (int i = start; i <= end; i++) {\n positions[i - start] = i;\n }\n tokenPosition.add(positions);\n }\n }",
"public PhotoContext getContext(String photoId, String userId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Collection<Element> payload = response.getPayloadCollection();\r\n PhotoContext photoContext = new PhotoContext();\r\n for (Element element : payload) {\r\n String elementName = element.getTagName();\r\n if (elementName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (elementName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setNextPhoto(photo);\r\n } else {\r\n if (logger.isInfoEnabled()) {\r\n logger.info(\"unsupported element name: \" + elementName);\r\n }\r\n }\r\n }\r\n return photoContext;\r\n }",
"private void readAvailabilityTable(Resource resource, AvailabilityPeriods periods)\n {\n if (periods != null)\n {\n AvailabilityTable table = resource.getAvailability();\n List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();\n for (AvailabilityPeriod period : list)\n {\n Date start = period.getAvailableFrom();\n Date end = period.getAvailableTo();\n Number units = DatatypeConverter.parseUnits(period.getAvailableUnits());\n Availability availability = new Availability(start, end, units);\n table.add(availability);\n }\n Collections.sort(table);\n }\n }",
"public static void printResults(Counter<String> entityTP, Counter<String> entityFP,\r\n Counter<String> entityFN) {\r\n Set<String> entities = new TreeSet<String>();\r\n entities.addAll(entityTP.keySet());\r\n entities.addAll(entityFP.keySet());\r\n entities.addAll(entityFN.keySet());\r\n boolean printedHeader = false;\r\n for (String entity : entities) {\r\n double tp = entityTP.getCount(entity);\r\n double fp = entityFP.getCount(entity);\r\n double fn = entityFN.getCount(entity);\r\n printedHeader = printPRLine(entity, tp, fp, fn, printedHeader);\r\n }\r\n double tp = entityTP.totalCount();\r\n double fp = entityFP.totalCount();\r\n double fn = entityFN.totalCount();\r\n printedHeader = printPRLine(\"Totals\", tp, fp, fn, printedHeader);\r\n }",
"private void setPlaying(boolean playing) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.playing != playing) {\n setPlaybackState(oldState.player, oldState.position, playing);\n }\n }",
"private static void checkPreconditions(final List<String> forbiddenSubStrings) {\n\t\tif( forbiddenSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"forbiddenSubStrings list should not be null\");\n\t\t} else if( forbiddenSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"forbiddenSubStrings list should not be empty\");\n\t\t}\n\t}"
] |
Calculate start dates for a yearly recurrence.
@param calendar current date
@param dates array of start dates | [
"private void getYearlyDates(Calendar calendar, List<Date> dates)\n {\n if (m_relative)\n {\n getYearlyRelativeDates(calendar, dates);\n }\n else\n {\n getYearlyAbsoluteDates(calendar, dates);\n }\n }"
] | [
"private void fillQueue(QueueItem item, Integer minStartPosition,\n Integer maxStartPosition, Integer minEndPosition) throws IOException {\n int newStartPosition;\n int newEndPosition;\n Integer firstRetrievedPosition = null;\n // remove everything below minStartPosition\n if ((minStartPosition != null) && (item.lowestPosition != null)\n && (item.lowestPosition < minStartPosition)) {\n item.del((minStartPosition - 1));\n }\n // fill queue\n while (!item.noMorePositions) {\n boolean doNotCollectAnotherPosition;\n doNotCollectAnotherPosition = item.filledPosition\n && (minStartPosition == null) && (maxStartPosition == null);\n doNotCollectAnotherPosition |= item.filledPosition\n && (maxStartPosition != null) && (item.lastRetrievedPosition != null)\n && (maxStartPosition < item.lastRetrievedPosition);\n if (doNotCollectAnotherPosition) {\n return;\n } else {\n // collect another full position\n firstRetrievedPosition = null;\n while (!item.noMorePositions) {\n newStartPosition = item.sequenceSpans.spans.nextStartPosition();\n if (newStartPosition == NO_MORE_POSITIONS) {\n if (!item.queue.isEmpty()) {\n item.filledPosition = true;\n item.lastFilledPosition = item.lastRetrievedPosition;\n }\n item.noMorePositions = true;\n return;\n } else if ((minStartPosition != null)\n && (newStartPosition < minStartPosition)) {\n // do nothing\n } else {\n newEndPosition = item.sequenceSpans.spans.endPosition();\n if ((minEndPosition == null) || (newEndPosition >= minEndPosition\n - ignoreItem.getMinStartPosition(docId, newEndPosition))) {\n item.add(newStartPosition, newEndPosition);\n if (firstRetrievedPosition == null) {\n firstRetrievedPosition = newStartPosition;\n } else if (!firstRetrievedPosition.equals(newStartPosition)) {\n break;\n }\n }\n }\n }\n }\n }\n }",
"public static appfwpolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_stats obj = new appfwpolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_stats response = (appfwpolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public GroovyConstructorDoc[] constructors() {\n Collections.sort(constructors);\n return constructors.toArray(new GroovyConstructorDoc[constructors.size()]);\n }",
"public void setFullscreen(boolean fullscreen) {\n if (mBuilder.mScrimInsetsLayout != null) {\n mBuilder.mScrimInsetsLayout.setTintStatusBar(!fullscreen);\n mBuilder.mScrimInsetsLayout.setTintNavigationBar(!fullscreen);\n }\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerFilters(List<AlgoliaFilter> filters) {\n for (final AlgoliaFilter filter : filters) {\n searcher.addFacet(filter.getAttribute());\n }\n }",
"public static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) {\n return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(List<InnerT> inners) {\n return Observable.from(inners);\n }\n });\n }",
"@Deprecated\n public static TraceContextHolder wrap(TraceContext traceContext) {\n return (traceContext != null) ? new TraceContextHolder(traceContext) : TraceContextHolder.EMPTY;\n }",
"@Override\n public Scenario<GIVEN, WHEN, THEN> startScenario( String description ) {\n super.startScenario( description );\n return this;\n\n }",
"private TableAlias getTableAliasForPath(String aPath, String aUserAlias, List hintClasses)\r\n {\r\n if (aUserAlias == null)\r\n {\r\n return getTableAliasForPath(aPath, hintClasses);\r\n }\r\n else\r\n {\r\n\t\t\treturn getTableAliasForPath(aUserAlias + ALIAS_SEPARATOR + aPath, hintClasses);\r\n }\r\n }"
] |
Return the map bounds rotated with the set rotation. The bounds are adapted to rounding changes of the
size of the paint area.
@param paintAreaPrecise The exact size of the paint area.
@param paintArea The rounded size of the paint area.
@return Rotated bounds. | [
"public MapBounds getRotatedBounds(final Rectangle2D.Double paintAreaPrecise, final Rectangle paintArea) {\n final MapBounds rotatedBounds = this.getRotatedBounds();\n\n if (rotatedBounds instanceof CenterScaleMapBounds) {\n return rotatedBounds;\n }\n\n final ReferencedEnvelope envelope = ((BBoxMapBounds) rotatedBounds).toReferencedEnvelope(null);\n // the paint area size and the map bounds are rotated independently. because\n // the paint area size is rounded to integers, the map bounds have to be adjusted\n // to these rounding changes.\n final double widthRatio = paintArea.getWidth() / paintAreaPrecise.getWidth();\n final double heightRatio = paintArea.getHeight() / paintAreaPrecise.getHeight();\n\n final double adaptedWidth = envelope.getWidth() * widthRatio;\n final double adaptedHeight = envelope.getHeight() * heightRatio;\n\n final double widthDiff = adaptedWidth - envelope.getWidth();\n final double heigthDiff = adaptedHeight - envelope.getHeight();\n envelope.expandBy(widthDiff / 2.0, heigthDiff / 2.0);\n\n return new BBoxMapBounds(envelope);\n }"
] | [
"public static String copyToString(InputStream in, Charset charset) throws IOException {\n\t\tAssert.notNull(in, \"No InputStream specified\");\n\t\tStringBuilder out = new StringBuilder();\n\t\tInputStreamReader reader = new InputStreamReader(in, charset);\n\t\tchar[] buffer = new char[BUFFER_SIZE];\n\t\tint bytesRead = -1;\n\t\twhile ((bytesRead = reader.read(buffer)) != -1) {\n\t\t\tout.append(buffer, 0, bytesRead);\n\t\t}\n\t\treturn out.toString();\n\t}",
"private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(ClientConfig.ENABLE_JMX_PROPERTY)) {\n this.setEnableJmx(props.getBoolean(ClientConfig.ENABLE_JMX_PROPERTY));\n }\n\n if(props.containsKey(ClientConfig.BOOTSTRAP_URLS_PROPERTY)) {\n List<String> urls = props.getList(ClientConfig.BOOTSTRAP_URLS_PROPERTY);\n if(urls.size() > 0) {\n setHttpBootstrapURL(urls.get(0));\n }\n }\n\n if(props.containsKey(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY)) {\n setMaxR2ConnectionPoolSize(props.getInt(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY,\n maxR2ConnectionPoolSize));\n }\n\n if(props.containsKey(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY))\n this.setTimeoutMs(props.getLong(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY, timeoutMs),\n TimeUnit.MILLISECONDS);\n\n // By default, make all the timeouts equal to routing timeout\n timeoutConfig = new TimeoutConfig(timeoutMs, false);\n\n if(props.containsKey(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_ALL_OP_CODE,\n props.getInt(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_OP_CODE,\n props.getInt(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY)) {\n long putTimeoutMs = props.getInt(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY);\n timeoutConfig.setOperationTimeout(VoldemortOpCode.PUT_OP_CODE, putTimeoutMs);\n // By default, use the same thing for getVersions() also\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE, putTimeoutMs);\n }\n\n // of course, if someone overrides it, we will respect that\n if(props.containsKey(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE,\n props.getInt(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY))\n timeoutConfig.setOperationTimeout(VoldemortOpCode.DELETE_OP_CODE,\n props.getInt(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY));\n\n if(props.containsKey(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY))\n timeoutConfig.setPartialGetAllAllowed(props.getBoolean(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY));\n\n }",
"public void visitParameter(String name, int access) {\n if (mv != null) {\n mv.visitParameter(name, access);\n }\n }",
"private void instanceAlreadyLoaded(\n\t\tfinal Tuple resultset,\n\t\tfinal int i,\n\t\t\t//TODO create an interface for this usage\n\t\tfinal OgmEntityPersister persister,\n\t\tfinal org.hibernate.engine.spi.EntityKey key,\n\t\tfinal Object object,\n\t\tfinal LockMode lockMode,\n\t\tfinal SharedSessionContractImplementor session)\n\tthrows HibernateException {\n\t\tif ( !persister.isInstance( object ) ) {\n\t\t\tthrow new WrongClassException(\n\t\t\t\t\t\"loaded object was of wrong class \" + object.getClass(),\n\t\t\t\t\tkey.getIdentifier(),\n\t\t\t\t\tpersister.getEntityName()\n\t\t\t\t);\n\t\t}\n\n\t\tif ( LockMode.NONE != lockMode && upgradeLocks() ) { // no point doing this if NONE was requested\n\n\t\t\tfinal boolean isVersionCheckNeeded = persister.isVersioned() &&\n\t\t\t\t\tsession.getPersistenceContext().getEntry( object )\n\t\t\t\t\t\t\t.getLockMode().lessThan( lockMode );\n\t\t\t// we don't need to worry about existing version being uninitialized\n\t\t\t// because this block isn't called by a re-entrant load (re-entrant\n\t\t\t// loads _always_ have lock mode NONE)\n\t\t\tif ( isVersionCheckNeeded ) {\n\t\t\t\t//we only check the version when _upgrading_ lock modes\n\t\t\t\tObject oldVersion = session.getPersistenceContext().getEntry( object ).getVersion();\n\t\t\t\tpersister.checkVersionAndRaiseSOSE( key.getIdentifier(), oldVersion, session, resultset );\n\t\t\t\t//we need to upgrade the lock mode to the mode requested\n\t\t\t\tsession.getPersistenceContext().getEntry( object )\n\t\t\t\t\t\t.setLockMode( lockMode );\n\t\t\t}\n\t\t}\n\t}",
"public <T> T eval(ELVars vars, String el, Class<T> returnType) throws ELEvalException {\n Utils.checkNotNull(vars, \"vars\");\n Utils.checkNotNull(el, \"expression\");\n Utils.checkNotNull(returnType, \"returnType\");\n VARIABLES_IN_SCOPE_TL.set(vars);\n try {\n return evaluate(vars, el, returnType);\n } finally {\n VARIABLES_IN_SCOPE_TL.set(null);\n }\n }",
"public static authenticationradiusaction[] get(nitro_service service) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tauthenticationradiusaction[] response = (authenticationradiusaction[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void logShort(CharSequence message, boolean trim) throws IOException {\n int length = message.length();\n if (trim) {\n while (length > 0 && Character.isWhitespace(message.charAt(length - 1))) {\n length--;\n }\n }\n\n char [] chars = new char [length + 1];\n for (int i = 0; i < length; i++) {\n chars[i] = message.charAt(i);\n }\n chars[length] = '\\n';\n\n output.write(chars);\n }",
"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 void assertGLThread() {\n if (Thread.currentThread().getId() != mGLThreadID) {\n RuntimeException e = new RuntimeException(\n \"Should not run GL functions from a non-GL thread!\");\n e.printStackTrace();\n throw e;\n }\n }"
] |
Gets the attributes provided by the processor.
@return the attributes | [
"public Map<String, Attribute> getAttributes() {\n Map<String, Attribute> result = new HashMap<>();\n DataSourceAttribute datasourceAttribute = new DataSourceAttribute();\n Map<String, Attribute> dsResult = new HashMap<>();\n dsResult.put(MAP_KEY, this.mapAttribute);\n datasourceAttribute.setAttributes(dsResult);\n result.put(\"datasource\", datasourceAttribute);\n return result;\n }"
] | [
"public static List<KoreanPhraseExtractor.KoreanPhrase> extractPhrases(Seq<KoreanToken> tokens, boolean filterSpam, boolean includeHashtags) {\n return JavaConversions.seqAsJavaList(\n TwitterKoreanProcessor.extractPhrases(tokens, filterSpam, includeHashtags)\n );\n }",
"private void addProperties(final PropertyDescriptor[] _properties) throws ColumnBuilderException, ClassNotFoundException {\n for (final PropertyDescriptor property : _properties) {\n if (isValidProperty(property)) {\n addColumn(getColumnTitle(property), property.getName(), property.getPropertyType().getName(), getColumnWidth(property));\n }\n }\n setUseFullPageWidth(true);\n }",
"public void setPlaying(boolean playing) {\n\n if (this.playing.get() == playing) {\n return;\n }\n\n this.playing.set(playing);\n\n if (playing) {\n metronome.jumpToBeat(whereStopped.get().getBeat());\n if (isSendingStatus()) { // Need to also start the beat sender.\n beatSender.set(new BeatSender(metronome));\n }\n } else {\n final BeatSender activeSender = beatSender.get();\n if (activeSender != null) { // We have a beat sender we need to stop.\n activeSender.shutDown();\n beatSender.set(null);\n }\n whereStopped.set(metronome.getSnapshot());\n }\n }",
"private Observable<Indexable> invokeReadyTasksAsync(final InvocationContext context) {\n TaskGroupEntry<TaskItem> readyTaskEntry = super.getNext();\n final List<Observable<Indexable>> observables = new ArrayList<>();\n // Enumerate the ready tasks (those with dependencies resolved) and kickoff them concurrently\n //\n while (readyTaskEntry != null) {\n final TaskGroupEntry<TaskItem> currentEntry = readyTaskEntry;\n final TaskItem currentTaskItem = currentEntry.data();\n if (currentTaskItem instanceof ProxyTaskItem) {\n observables.add(invokeAfterPostRunAsync(currentEntry, context));\n } else {\n observables.add(invokeTaskAsync(currentEntry, context));\n }\n readyTaskEntry = super.getNext();\n }\n return Observable.mergeDelayError(observables);\n }",
"@Inline(value = \"$1.remove($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> boolean operator_remove(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\t//TODO use the JRE 1.8 API: map.remove(entry.getKey(), entry.getValue());\n\t\tfinal K key = entry.getKey();\n\t\tfinal V storedValue = map.get(entry.getKey());\n\t if (!Objects.equal(storedValue, entry.getValue())\n\t\t\t|| (storedValue == null && !map.containsKey(key))) {\n\t return false;\n \t}\n \tmap.remove(key);\n\t return true;\n\t}",
"protected List<String> splitLinesAndNewLines(String text) {\n\t\tif (text == null)\n\t\t\treturn Collections.emptyList();\n\t\tint idx = initialSegmentSize(text);\n\t\tif (idx == text.length()) {\n\t\t\treturn Collections.singletonList(text);\n\t\t}\n\n\t\treturn continueSplitting(text, idx);\n\t}",
"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 }",
"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 }",
"private ClassDescriptor discoverDescriptor(Class clazz)\r\n {\r\n ClassDescriptor result = (ClassDescriptor) descriptorTable.get(clazz.getName());\r\n\r\n if (result == null)\r\n {\r\n Class superClass = clazz.getSuperclass();\r\n // only recurse if the superClass is not java.lang.Object\r\n if (superClass != null)\r\n {\r\n result = discoverDescriptor(superClass);\r\n }\r\n if (result == null)\r\n {\r\n // we're also checking the interfaces as there could be normal\r\n // mappings for them in the repository (using factory-class,\r\n // factory-method, and the property field accessor)\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n if ((interfaces != null) && (interfaces.length > 0))\r\n {\r\n for (int idx = 0; (idx < interfaces.length) && (result == null); idx++)\r\n {\r\n result = discoverDescriptor(interfaces[idx]);\r\n }\r\n }\r\n }\r\n\r\n if (result != null)\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tsynchronized (descriptorTable) {\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n \t\tdescriptorTable.put(clazz.getName(), result);\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \t}\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n }\r\n return result;\r\n }"
] |
Append the given char as a decimal HTML entity.
@param out
The StringBuilder to write to.
@param value
The character. | [
"public final static void appendDecEntity(final StringBuilder out, final char value)\n {\n out.append(\"&#\");\n out.append((int)value);\n out.append(';');\n }"
] | [
"public final void notifyContentItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= contentItemCount || toPosition >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \"\n + toPosition + \" is not within the position bounds for content items [0 - \" + (contentItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition + headerItemCount, toPosition + headerItemCount);\n }",
"public static int getStatusBarHeight(Context context, boolean force) {\n int result = 0;\n int resourceId = context.getResources().getIdentifier(\"status_bar_height\", \"dimen\", \"android\");\n if (resourceId > 0) {\n result = context.getResources().getDimensionPixelSize(resourceId);\n }\n\n int dimenResult = context.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding);\n //if our dimension is 0 return 0 because on those devices we don't need the height\n if (dimenResult == 0 && !force) {\n return 0;\n } else {\n //if our dimens is > 0 && the result == 0 use the dimenResult else the result;\n return result == 0 ? dimenResult : result;\n }\n }",
"public Photoset getInfo(String photosetId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photosetElement.getAttribute(\"owner\"));\r\n photoset.setOwner(owner);\r\n\r\n Photo primaryPhoto = new Photo();\r\n primaryPhoto.setId(photosetElement.getAttribute(\"primary\"));\r\n primaryPhoto.setSecret(photosetElement.getAttribute(\"secret\")); // TODO verify that this is the secret for the photo\r\n primaryPhoto.setServer(photosetElement.getAttribute(\"server\")); // TODO verify that this is the server for the photo\r\n primaryPhoto.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n // TODO remove secret/server/farm from photoset?\r\n // It's rather related to the primaryPhoto, then to the photoset itself.\r\n photoset.setSecret(photosetElement.getAttribute(\"secret\"));\r\n photoset.setServer(photosetElement.getAttribute(\"server\"));\r\n photoset.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPhotoCount(photosetElement.getAttribute(\"count_photos\"));\r\n photoset.setVideoCount(Integer.parseInt(photosetElement.getAttribute(\"count_videos\")));\r\n photoset.setViewCount(Integer.parseInt(photosetElement.getAttribute(\"count_views\")));\r\n photoset.setCommentCount(Integer.parseInt(photosetElement.getAttribute(\"count_comments\")));\r\n photoset.setDateCreate(photosetElement.getAttribute(\"date_create\"));\r\n photoset.setDateUpdate(photosetElement.getAttribute(\"date_update\"));\r\n\r\n photoset.setIsCanComment(\"1\".equals(photosetElement.getAttribute(\"can_comment\")));\r\n\r\n photoset.setTitle(XMLUtilities.getChildValue(photosetElement, \"title\"));\r\n photoset.setDescription(XMLUtilities.getChildValue(photosetElement, \"description\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n return photoset;\r\n }",
"public CmsResource buildResource() {\n\n return new CmsResource(\n m_structureId,\n m_resourceId,\n m_rootPath,\n m_type,\n m_flags,\n m_projectLastModified,\n m_state,\n m_dateCreated,\n m_userCreated,\n m_dateLastModified,\n m_userLastModified,\n m_dateReleased,\n m_dateExpired,\n m_length,\n m_flags,\n m_dateContent,\n m_version);\n }",
"private void cleanupLogs() throws IOException {\n logger.trace(\"Beginning log cleanup...\");\n int total = 0;\n Iterator<Log> iter = getLogIterator();\n long startMs = System.currentTimeMillis();\n while (iter.hasNext()) {\n Log log = iter.next();\n total += cleanupExpiredSegments(log) + cleanupSegmentsToMaintainSize(log);\n }\n if (total > 0) {\n logger.warn(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n } else {\n logger.trace(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n }\n }",
"private void writeExceptions(List<ProjectCalendar> records) throws IOException\n {\n for (ProjectCalendar record : records)\n {\n if (!record.getCalendarExceptions().isEmpty())\n {\n // Need to move HOLI up here and get 15 exceptions per line as per USACE spec.\n // for now, we'll write one line for each calendar exception, hope there aren't too many\n //\n // changing this would be a serious upgrade, too much coding to do today....\n for (ProjectCalendarException ex : record.getCalendarExceptions())\n {\n writeCalendarException(record, ex);\n }\n }\n m_eventManager.fireCalendarWrittenEvent(record); // left here from MPX template, maybe not needed???\n }\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 }",
"GVRShader makeTemplate(Class<? extends GVRShader> id, GVRContext ctx)\n {\n try\n {\n Constructor<? extends GVRShader> maker = id.getDeclaredConstructor(GVRContext.class);\n return maker.newInstance(ctx);\n }\n catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex)\n {\n try\n {\n Constructor<? extends GVRShader> maker = id.getDeclaredConstructor();\n return maker.newInstance();\n }\n catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex2)\n {\n ctx.getEventManager().sendEvent(ctx, IErrorEvents.class, \"onError\", new Object[] {ex2.getMessage(), this});\n return null;\n }\n }\n }",
"public double d(double x){\n\t\tint intervalNumber =getIntervalNumber(x);\n\t\tif (intervalNumber==0 || intervalNumber==points.length) {\n\t\t\treturn x;\n\t\t}\n\t\treturn getIntervalReferencePoint(intervalNumber-1);\n\t}"
] |
This method allows us to peek into the OLE compound document to extract the file format.
This allows the UniversalProjectReader to determine if this is an MPP file, or if
it is another type of OLE compound document.
@param fs POIFSFileSystem instance
@return file format name
@throws IOException | [
"public static String getFileFormat(POIFSFileSystem fs) throws IOException\n {\n String fileFormat = \"\";\n DirectoryEntry root = fs.getRoot();\n if (root.getEntryNames().contains(\"\\1CompObj\"))\n {\n CompObj compObj = new CompObj(new DocumentInputStream((DocumentEntry) root.getEntry(\"\\1CompObj\")));\n fileFormat = compObj.getFileFormat();\n }\n return fileFormat;\n }"
] | [
"public void executeInsert(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeInsert: \" + obj);\r\n }\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n try\r\n {\r\n stmt = sm.getInsertStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getInsertStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getInsertStatement returned a null statement\");\r\n }\r\n // before bind values perform autoincrement sequence columns\r\n assignAutoincrementSequences(cld, obj);\r\n sm.bindInsert(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeInsert: \" + stmt);\r\n stmt.executeUpdate();\r\n // after insert read and assign identity columns\r\n assignAutoincrementIdentityColumns(cld, obj);\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getInsertProcedure(), obj, stmt);\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of the insert: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch(SequenceManagerException e)\r\n {\r\n throw new PersistenceBrokerException(\"Error while try to assign identity value\", e);\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }",
"public List<BoxAPIResponse> execute(List<BoxAPIRequest> requests) {\n this.prepareRequest(requests);\n BoxJSONResponse batchResponse = (BoxJSONResponse) send();\n return this.parseResponse(batchResponse);\n }",
"private static void logVersionWarnings(String label1, String version1, String label2, String version2) {\n\t\tif (version1 == null) {\n\t\t\tif (version2 != null) {\n\t\t\t\twarning(null, \"Unknown version\", \" for {}, version for {} is '{}'\", new Object[] { label1, label2,\n\t\t\t\t\t\tversion2 });\n\t\t\t}\n\t\t} else {\n\t\t\tif (version2 == null) {\n\t\t\t\twarning(null, \"Unknown version\", \" for {}, version for {} is '{}'\", new Object[] { label2, label1,\n\t\t\t\t\t\tversion1 });\n\t\t\t} else if (!version1.equals(version2)) {\n\t\t\t\twarning(null, \"Mismatched versions\", \": {} is '{}', while {} is '{}'\", new Object[] { label1, version1,\n\t\t\t\t\t\tlabel2, version2 });\n\t\t\t}\n\t\t}\n\t}",
"protected void updateTables()\n {\n byte[] data = m_model.getData();\n int columns = m_model.getColumns();\n int rows = (data.length / columns) + 1;\n int offset = m_model.getOffset();\n\n String[][] hexData = new String[rows][columns];\n String[][] asciiData = new String[rows][columns];\n\n int row = 0;\n int column = 0;\n StringBuilder hexValue = new StringBuilder();\n for (int index = offset; index < data.length; index++)\n {\n int value = data[index];\n hexValue.setLength(0);\n hexValue.append(HEX_DIGITS[(value & 0xF0) >> 4]);\n hexValue.append(HEX_DIGITS[value & 0x0F]);\n\n char c = (char) value;\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n hexData[row][column] = hexValue.toString();\n asciiData[row][column] = Character.toString(c);\n\n ++column;\n if (column == columns)\n {\n column = 0;\n ++row;\n }\n }\n\n String[] columnHeadings = new String[columns];\n TableModel hexTableModel = new DefaultTableModel(hexData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n TableModel asciiTableModel = new DefaultTableModel(asciiData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n m_model.setSizeValueLabel(Integer.toString(data.length));\n m_model.setHexTableModel(hexTableModel);\n m_model.setAsciiTableModel(asciiTableModel);\n m_model.setCurrentSelectionIndex(0);\n m_model.setPreviousSelectionIndex(0);\n }",
"private String generateAbbreviatedExceptionMessage(final Throwable throwable) {\n\n\t\tfinal StringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\": \");\n\t\tbuilder.append(throwable.getClass().getCanonicalName());\n\t\tbuilder.append(\": \");\n\t\tbuilder.append(throwable.getMessage());\n\n\t\tThrowable cause = throwable.getCause();\n\t\twhile (cause != null) {\n\t\t\tbuilder.append('\\n');\n\t\t\tbuilder.append(\"Caused by: \");\n\t\t\tbuilder.append(cause.getClass().getCanonicalName());\n\t\t\tbuilder.append(\": \");\n\t\t\tbuilder.append(cause.getMessage());\n\t\t\t// make sure the exception cause is not itself to prevent infinite\n\t\t\t// looping\n\t\t\tassert (cause != cause.getCause());\n\t\t\tcause = (cause == cause.getCause() ? null : cause.getCause());\n\t\t}\n\t\treturn builder.toString();\n\t}",
"public ChangesResult getChanges() {\n final URI uri = this.databaseHelper.changesUri(\"feed\", \"normal\");\n return client.get(uri, ChangesResult.class);\n }",
"public double[] getBasisVector( int which ) {\n if( which < 0 || which >= numComponents )\n throw new IllegalArgumentException(\"Invalid component\");\n\n DMatrixRMaj v = new DMatrixRMaj(1,A.numCols);\n CommonOps_DDRM.extract(V_t,which,which+1,0,A.numCols,v,0,0);\n\n return v.data;\n }",
"public boolean process( DMatrixSparseCSC A ) {\n init(A);\n\n TriangularSolver_DSCC.eliminationTree(A,true,parent,gwork);\n\n countNonZeroInR(parent);\n countNonZeroInV(parent);\n\n // if more columns than rows it's possible that Q*R != A. That's because a householder\n // would need to be created that's outside the m by m Q matrix. In reality it has\n // a partial solution. Column pivot are needed.\n if( m < n ) {\n for (int row = 0; row <m; row++) {\n if( gwork.data[head+row] < 0 ) {\n return false;\n }\n }\n }\n return true;\n }",
"public static final Boolean parseBoolean(String value)\n {\n return (value == null || value.charAt(0) != '1' ? Boolean.FALSE : Boolean.TRUE);\n }"
] |
Returns the precedence of the specified operator. Non-operator's will
receive -1 or a GroovyBugError, depending on your preference. | [
"public static int getPrecedence( int type, boolean throwIfInvalid ) {\n\n switch( type ) {\n\n case LEFT_PARENTHESIS:\n return 0;\n\n case EQUAL:\n case PLUS_EQUAL:\n case MINUS_EQUAL:\n case MULTIPLY_EQUAL:\n case DIVIDE_EQUAL:\n case INTDIV_EQUAL:\n case MOD_EQUAL:\n case POWER_EQUAL:\n case LOGICAL_OR_EQUAL:\n case LOGICAL_AND_EQUAL:\n case LEFT_SHIFT_EQUAL:\n case RIGHT_SHIFT_EQUAL:\n case RIGHT_SHIFT_UNSIGNED_EQUAL:\n case BITWISE_OR_EQUAL:\n case BITWISE_AND_EQUAL:\n case BITWISE_XOR_EQUAL:\n return 5;\n\n case QUESTION:\n return 10;\n\n case LOGICAL_OR:\n return 15;\n\n case LOGICAL_AND:\n return 20;\n\n case BITWISE_OR:\n case BITWISE_AND:\n case BITWISE_XOR:\n return 22;\n\n case COMPARE_IDENTICAL:\n case COMPARE_NOT_IDENTICAL:\n return 24;\n\n case COMPARE_NOT_EQUAL:\n case COMPARE_EQUAL:\n case COMPARE_LESS_THAN:\n case COMPARE_LESS_THAN_EQUAL:\n case COMPARE_GREATER_THAN:\n case COMPARE_GREATER_THAN_EQUAL:\n case COMPARE_TO:\n case FIND_REGEX:\n case MATCH_REGEX:\n case KEYWORD_INSTANCEOF:\n return 25;\n\n case DOT_DOT:\n case DOT_DOT_DOT:\n return 30;\n\n case LEFT_SHIFT:\n case RIGHT_SHIFT:\n case RIGHT_SHIFT_UNSIGNED:\n return 35;\n\n case PLUS:\n case MINUS:\n return 40;\n\n case MULTIPLY:\n case DIVIDE:\n case INTDIV:\n case MOD:\n return 45;\n\n case NOT:\n case REGEX_PATTERN:\n return 50;\n\n case SYNTH_CAST:\n return 55;\n\n case PLUS_PLUS:\n case MINUS_MINUS:\n case PREFIX_PLUS_PLUS:\n case PREFIX_MINUS_MINUS:\n case POSTFIX_PLUS_PLUS:\n case POSTFIX_MINUS_MINUS:\n return 65;\n\n case PREFIX_PLUS:\n case PREFIX_MINUS:\n return 70;\n\n case POWER:\n return 72;\n\n case SYNTH_METHOD:\n case LEFT_SQUARE_BRACKET:\n return 75;\n\n case DOT:\n case NAVIGATE:\n return 80;\n\n case KEYWORD_NEW:\n return 85;\n }\n\n if( throwIfInvalid ) {\n throw new GroovyBugError( \"precedence requested for non-operator\" );\n }\n\n return -1;\n }"
] | [
"public static appfwpolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_policybinding_binding obj = new appfwpolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_policybinding_binding response[] = (appfwpolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public ChangesResult getChanges() {\n final URI uri = this.databaseHelper.changesUri(\"feed\", \"normal\");\n return client.get(uri, ChangesResult.class);\n }",
"public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }",
"private List<TaskField> getAllTaskExtendedAttributes()\n {\n ArrayList<TaskField> result = new ArrayList<TaskField>();\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_TEXT));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(TaskFieldLists.CUSTOM_OUTLINE_CODE));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(TaskFieldLists.ENTERPRISE_TEXT));\n return result;\n }",
"public void setEmptyDefault(String iso) {\n if (iso == null || iso.isEmpty()) {\n iso = DEFAULT_COUNTRY;\n }\n int defaultIdx = mCountries.indexOfIso(iso);\n mSelectedCountry = mCountries.get(defaultIdx);\n mCountrySpinner.setSelection(defaultIdx);\n }",
"@SafeVarargs\n public static void registerFilterTypes(final Class<? extends DynamicFilter>... types) {\n FILTER_TYPES.addAll(Arrays.asList(types));\n }",
"@Nullable\n public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {\n return this.first.get(txn, first);\n }",
"@Override\n public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deploymentConfig = entities.stream()\n .filter(hm -> hm instanceof DeploymentConfig)\n .map(hm -> (DeploymentConfig) hm)\n .map(dc -> dc.getMetadata().getName()).findFirst();\n\n deploymentConfig.ifPresent(name -> this.applicationName = name);\n }\n }",
"public static base_response add(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager addresource = new snmpmanager();\n\t\taddresource.ipaddress = resource.ipaddress;\n\t\taddresource.netmask = resource.netmask;\n\t\taddresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Sets the access token to use when authenticating a client. | [
"public final B accessToken(String accessToken) {\n requireNonNull(accessToken, \"accessToken\");\n checkArgument(!accessToken.isEmpty(), \"accessToken is empty.\");\n this.accessToken = accessToken;\n return self();\n }"
] | [
"public boolean matches(PathElement pe) {\n return pe.key.equals(key) && (isWildcard() || pe.value.equals(value));\n }",
"protected final void _onConnect(WebSocketContext context) {\n if (null != connectionListener) {\n connectionListener.onConnect(context);\n }\n connectionListenerManager.notifyFreeListeners(context, false);\n Act.eventBus().emit(new WebSocketConnectEvent(context));\n }",
"public static base_response delete(nitro_service client, String servicename) throws Exception {\n\t\tgslbservice deleteresource = new gslbservice();\n\t\tdeleteresource.servicename = servicename;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"synchronized long storeUserProfile(String id, JSONObject obj) {\n\n if (id == null) return DB_UPDATE_ERROR;\n\n if (!this.belowMemThreshold()) {\n getConfigLogger().verbose(\"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.USER_PROFILES.getName();\n\n long ret = DB_UPDATE_ERROR;\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(\"_id\", id);\n ret = db.insertWithOnConflict(tableName, null, cv, SQLiteDatabase.CONFLICT_REPLACE);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n return ret;\n }",
"private String formatDuration(Object value)\n {\n String result = null;\n if (value instanceof Duration)\n {\n Duration duration = (Duration) value;\n result = m_formats.getDurationDecimalFormat().format(duration.getDuration()) + formatTimeUnit(duration.getUnits());\n }\n return result;\n }",
"public static lbmonitor_binding[] get(nitro_service service, String monitorname[]) throws Exception{\n\t\tif (monitorname !=null && monitorname.length>0) {\n\t\t\tlbmonitor_binding response[] = new lbmonitor_binding[monitorname.length];\n\t\t\tlbmonitor_binding obj[] = new lbmonitor_binding[monitorname.length];\n\t\t\tfor (int i=0;i<monitorname.length;i++) {\n\t\t\t\tobj[i] = new lbmonitor_binding();\n\t\t\t\tobj[i].set_monitorname(monitorname[i]);\n\t\t\t\tresponse[i] = (lbmonitor_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"private boolean verify(String key, BoxSignatureAlgorithm actualAlgorithm, String actualSignature,\n String webHookPayload, String deliveryTimestamp) {\n if (actualSignature == null) {\n return false;\n }\n\n byte[] actual = Base64.decode(actualSignature);\n byte[] expected = this.signRaw(actualAlgorithm, key, webHookPayload, deliveryTimestamp);\n\n return Arrays.equals(expected, actual);\n }",
"private String formatRelation(Relation relation)\n {\n String result = null;\n\n if (relation != null)\n {\n StringBuilder sb = new StringBuilder(relation.getTargetTask().getID().toString());\n\n Duration duration = relation.getLag();\n RelationType type = relation.getType();\n double durationValue = duration.getDuration();\n\n if ((durationValue != 0) || (type != RelationType.FINISH_START))\n {\n String[] typeNames = LocaleData.getStringArray(m_locale, LocaleData.RELATION_TYPES);\n sb.append(typeNames[type.getValue()]);\n }\n\n if (durationValue != 0)\n {\n if (durationValue > 0)\n {\n sb.append('+');\n }\n\n sb.append(formatDuration(duration));\n }\n\n result = sb.toString();\n }\n\n m_eventManager.fireRelationWrittenEvent(relation);\n return (result);\n }",
"public NodeList getAt(String name) {\n NodeList answer = new NodeList();\n for (Object child : this) {\n if (child instanceof Node) {\n Node childNode = (Node) child;\n Object temp = childNode.get(name);\n if (temp instanceof Collection) {\n answer.addAll((Collection) temp);\n } else {\n answer.add(temp);\n }\n }\n }\n return answer;\n }"
] |
Get info about the shards in the database.
@return List of shards
@see <a
href="https://console.bluemix.net/docs/services/Cloudant/api/advanced.html#-get-database-_shards-"
target="_blank">_shards</a> | [
"public List<Shard> getShards() {\n InputStream response = null;\n try {\n response = client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path(\"_shards\")\n .build());\n return getResponseList(response, client.getGson(), DeserializationTypes.SHARDS);\n } finally {\n close(response);\n }\n }"
] | [
"public static void printResults(Counter<String> entityTP, Counter<String> entityFP,\r\n Counter<String> entityFN) {\r\n Set<String> entities = new TreeSet<String>();\r\n entities.addAll(entityTP.keySet());\r\n entities.addAll(entityFP.keySet());\r\n entities.addAll(entityFN.keySet());\r\n boolean printedHeader = false;\r\n for (String entity : entities) {\r\n double tp = entityTP.getCount(entity);\r\n double fp = entityFP.getCount(entity);\r\n double fn = entityFN.getCount(entity);\r\n printedHeader = printPRLine(entity, tp, fp, fn, printedHeader);\r\n }\r\n double tp = entityTP.totalCount();\r\n double fp = entityFP.totalCount();\r\n double fn = entityFN.totalCount();\r\n printedHeader = printPRLine(\"Totals\", tp, fp, fn, printedHeader);\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 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 }",
"@JsonProperty(\"aliases\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, List<TermImpl>> getAliasUpdates() {\n \t\n \tMap<String, List<TermImpl>> updatedValues = new HashMap<>();\n \tfor(Map.Entry<String,AliasesWithUpdate> entry : newAliases.entrySet()) {\n \t\tAliasesWithUpdate update = entry.getValue();\n \t\tif (!update.write) {\n \t\t\tcontinue;\n \t\t}\n \t\tList<TermImpl> convertedAliases = new ArrayList<>();\n \t\tfor(MonolingualTextValue alias : update.aliases) {\n \t\t\tconvertedAliases.add(monolingualToJackson(alias));\n \t\t}\n \t\tupdatedValues.put(entry.getKey(), convertedAliases);\n \t}\n \treturn updatedValues;\n }",
"private static void parseBounds(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"bounds\")) {\n JSONObject boundsObject = modelJSON.getJSONObject(\"bounds\");\n current.setBounds(new Bounds(new Point(boundsObject.getJSONObject(\"lowerRight\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"lowerRight\").getDouble(\n \"y\")),\n new Point(boundsObject.getJSONObject(\"upperLeft\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"upperLeft\").getDouble(\"y\"))));\n }\n }",
"public InputStream getStream(String url, RasterLayer layer) throws IOException {\n\t\tif (layer instanceof ProxyLayerSupport) {\n\t\t\tProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;\n\t\t\tif (proxyLayer.isUseCache() && null != cacheManagerService) {\n\t\t\t\tObject cachedObject = cacheManagerService.get(proxyLayer, CacheCategory.RASTER, url);\n\t\t\t\tif (null != cachedObject) {\n\t\t\t\t\ttestRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_GET_FROM_CACHE);\n\t\t\t\t\treturn new ByteArrayInputStream((byte[]) cachedObject);\n\t\t\t\t} else {\n\t\t\t\t\ttestRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_PUT_IN_CACHE);\n\t\t\t\t\tInputStream stream = super.getStream(url, proxyLayer);\n\t\t\t\t\tByteArrayOutputStream os = new ByteArrayOutputStream();\n\t\t\t\t\tint b;\n\t\t\t\t\twhile ((b = stream.read()) >= 0) {\n\t\t\t\t\t\tos.write(b);\n\t\t\t\t\t}\n\t\t\t\t\tcacheManagerService.put(proxyLayer, CacheCategory.RASTER, url, os.toByteArray(),\n\t\t\t\t\t\t\tgetLayerEnvelope(proxyLayer));\n\t\t\t\t\treturn new ByteArrayInputStream((byte[]) os.toByteArray());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn super.getStream(url, layer);\n\t}",
"public static base_responses unset(nitro_service client, bridgetable resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable unsetresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new bridgetable();\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public double dot(Vector3d v1) {\n return x * v1.x + y * v1.y + z * v1.z;\n }",
"public static DocumentBuilder getXmlParser() {\r\n DocumentBuilder db = null;\r\n try {\r\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n dbf.setValidating(false);\r\n\r\n //Disable DTD loading and validation\r\n //See http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\r\n\r\n db = dbf.newDocumentBuilder();\r\n db.setErrorHandler(new SAXErrorHandler());\r\n\r\n } catch (ParserConfigurationException e) {\r\n System.err.printf(\"%s: Unable to create XML parser\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n\r\n } catch(UnsupportedOperationException e) {\r\n System.err.printf(\"%s: API error while setting up XML parser. Check your JAXP version\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n }\r\n\r\n return db;\r\n }"
] |
Generates timephased costs from the assignment's cost value. Used for Cost type Resources.
@return timephased cost | [
"private List<TimephasedCost> getTimephasedCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n ProjectCalendar cal = getCalendar();\n\n double remainingCost = getRemainingCost().doubleValue();\n\n if (remainingCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(cal, remainingCost, getStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(cal, remainingCost, getFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently depending on whether or not\n //any actual has been entered, since we want to mimic the other timephased data\n //where planned and actual values do not overlap\n double numWorkingDays = cal.getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n if (getActualCost().intValue() > 0)\n {\n //need to get three possible blocks of data: one for the possible partial amount\n //overlap with timephased actual cost; one with all the standard amount days\n //that happen after the actual cost stops; and one with any remaining\n //partial day cost amount\n\n int numActualDaysUsed = (int) Math.ceil(getActualCost().doubleValue() / standardAmountPerDay);\n Date actualWorkFinish = cal.getDate(getStart(), Duration.getInstance(numActualDaysUsed, TimeUnit.DAYS), false);\n\n double partialDayActualAmount = getActualCost().doubleValue() % standardAmountPerDay;\n\n if (partialDayActualAmount > 0)\n {\n double dayAmount = standardAmountPerDay < remainingCost ? standardAmountPerDay - partialDayActualAmount : remainingCost;\n\n result.add(splitCostEnd(cal, dayAmount, actualWorkFinish));\n\n remainingCost -= dayAmount;\n }\n\n //see if there's anything left to work with\n if (remainingCost > 0)\n {\n //have to split up the amount into standard prorated amount days and whatever is left\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, cal.getNextWorkStart(actualWorkFinish)));\n }\n\n }\n else\n {\n //no actual cost to worry about, so just a standard split from the beginning of the assignment\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, getStart()));\n }\n }\n }\n\n return result;\n }"
] | [
"@SuppressWarnings({ \"unchecked\" })\n public static <T> T[] readArrayAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n final List<T> list = readListAttributeElement(reader, attributeName, type);\n return list.toArray((T[]) Array.newInstance(type, list.size()));\n }",
"public 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 }",
"public CustomHeadersInterceptor addHeaderMultimap(Map<String, List<String>> headers) {\n this.headers.putAll(headers);\n return this;\n }",
"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 static <T> void notNull(final String name, final T value) {\n if (value == null) {\n throw new IllegalArgumentException(name + \" can not be null\");\n }\n }",
"public void deleteById(Object id) {\n\n int count = beginDelete().whereEquals(idColumn.getColumnName(), id).delete();\n\n if (count == 0) {\n throw new RowNotFoundException(table, id);\n }\n }",
"public static Range toRange(Span span) {\n return new Range(toKey(span.getStart()), span.isStartInclusive(), toKey(span.getEnd()),\n span.isEndInclusive());\n }",
"private static Set<String> imageOrientationsOf(ImageMetadata metadata) {\n\n String exifIFD0DirName = new ExifIFD0Directory().getName();\n\n Tag[] tags = Arrays.stream(metadata.getDirectories())\n .filter(dir -> dir.getName().equals(exifIFD0DirName))\n .findFirst()\n .map(Directory::getTags)\n .orElseGet(() -> new Tag[0]);\n\n return Arrays.stream(tags)\n .filter(tag -> tag.getType() == 274)\n .map(Tag::getRawValue)\n .collect(Collectors.toSet());\n }",
"Map<String, String> packageNameMap() {\n if (packageNames == null) {\n return emptyMap();\n }\n\n Map<String, String> names = new LinkedHashMap<String, String>();\n for (PackageName name : packageNames) {\n names.put(name.getUri(), name.getPackage());\n }\n return names;\n }"
] |
this method will be invoked after methodToBeInvoked is invoked | [
"protected Object doInvoke(Object proxy, Method methodToBeInvoked, Object[] args)\r\n\t\tthrows Throwable\r\n\t{\r\n\t\tMethod m =\r\n\t\t\tgetRealSubject().getClass().getMethod(\r\n\t\t\t\tmethodToBeInvoked.getName(),\r\n\t\t\t\tmethodToBeInvoked.getParameterTypes());\r\n\t\treturn m.invoke(getRealSubject(), args);\r\n\t}"
] | [
"protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }",
"public int rank() {\n if( is64 ) {\n return SingularOps_DDRM.rank((SingularValueDecomposition_F64)svd, tol);\n } else {\n return SingularOps_FDRM.rank((SingularValueDecomposition_F32)svd, (float)tol);\n }\n }",
"public boolean shouldCompress(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkSuffixes(uri, zipSuffixes);\n\t}",
"private void validateArguments() throws BuildException {\n Path tempDir = getTempDir();\n\n if (tempDir == null) {\n throw new BuildException(\"Temporary directory cannot be null.\");\n }\n \n if (Files.exists(tempDir)) {\n if (!Files.isDirectory(tempDir)) {\n throw new BuildException(\"Temporary directory is not a folder: \" + tempDir.toAbsolutePath());\n }\n } else {\n try {\n Files.createDirectories(tempDir);\n } catch (IOException e) {\n throw new BuildException(\"Failed to create temporary folder: \" + tempDir, e);\n }\n }\n }",
"public static CuratorFramework newAppCurator(FluoConfiguration config) {\n return newCurator(config.getAppZookeepers(), config.getZookeeperTimeout(),\n config.getZookeeperSecret());\n }",
"public static callhome get(nitro_service service) throws Exception{\n\t\tcallhome obj = new callhome();\n\t\tcallhome[] response = (callhome[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"private void removeMount(SlotReference slot) {\n mediaDetails.remove(slot);\n if (mediaMounts.remove(slot)) {\n deliverMountUpdate(slot, false);\n }\n }",
"private TableModel createTableModel(Object object, Set<String> excludedMethods)\n {\n List<Method> methods = new ArrayList<Method>();\n for (Method method : object.getClass().getMethods())\n {\n if ((method.getParameterTypes().length == 0) || (method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == int.class))\n {\n String name = method.getName();\n if (!excludedMethods.contains(name) && (name.startsWith(\"get\") || name.startsWith(\"is\")))\n {\n methods.add(method);\n }\n }\n }\n\n Map<String, String> map = new TreeMap<String, String>();\n for (Method method : methods)\n {\n if (method.getParameterTypes().length == 0)\n {\n getSingleValue(method, object, map);\n }\n else\n {\n getMultipleValues(method, object, map);\n }\n }\n\n String[] headings = new String[]\n {\n \"Property\",\n \"Value\"\n };\n\n String[][] data = new String[map.size()][2];\n int rowIndex = 0;\n for (Entry<String, String> entry : map.entrySet())\n {\n data[rowIndex][0] = entry.getKey();\n data[rowIndex][1] = entry.getValue();\n ++rowIndex;\n }\n\n TableModel tableModel = new DefaultTableModel(data, headings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n return tableModel;\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}"
] |
Parses and adds dictionaries to the Solr index.
@param cms the OpenCms object.
@throws CmsRoleViolationException in case the user does not have the required role ROOT_ADMIN | [
"public void parseAndAddDictionaries(CmsObject cms) throws CmsRoleViolationException {\n\n OpenCms.getRoleManager().checkRole(cms, CmsRole.ROOT_ADMIN);\n CmsSpellcheckDictionaryIndexer.parseAndAddZippedDictionaries(m_solrClient, cms);\n CmsSpellcheckDictionaryIndexer.parseAndAddDictionaries(m_solrClient, cms);\n }"
] | [
"public static int cudnnActivationBackward(\n cudnnHandle handle, \n cudnnActivationDescriptor activationDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnActivationBackwardNative(handle, activationDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }",
"private void process(String input, String output) throws MPXJException, IOException\n {\n //\n // Extract the project data\n //\n MPPReader reader = new MPPReader();\n m_project = reader.read(input);\n\n String varDataFileName;\n String projectDirName;\n int mppFileType = NumberHelper.getInt(m_project.getProjectProperties().getMppFileType());\n switch (mppFileType)\n {\n case 8:\n {\n projectDirName = \" 1\";\n varDataFileName = \"FixDeferFix 0\";\n break;\n }\n\n case 9:\n {\n projectDirName = \" 19\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n case 12:\n {\n projectDirName = \" 112\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n case 14:\n {\n projectDirName = \" 114\";\n varDataFileName = \"Var2Data\";\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported file type \" + mppFileType);\n }\n }\n\n //\n // Load the raw file\n //\n FileInputStream is = new FileInputStream(input);\n POIFSFileSystem fs = new POIFSFileSystem(is);\n is.close();\n\n //\n // Locate the root of the project file system\n //\n DirectoryEntry root = fs.getRoot();\n m_projectDir = (DirectoryEntry) root.getEntry(projectDirName);\n\n //\n // Process Tasks\n //\n Map<String, String> replacements = new HashMap<String, String>();\n for (Task task : m_project.getTasks())\n {\n mapText(task.getName(), replacements);\n }\n processReplacements(((DirectoryEntry) m_projectDir.getEntry(\"TBkndTask\")), varDataFileName, replacements, true);\n\n //\n // Process Resources\n //\n replacements.clear();\n for (Resource resource : m_project.getResources())\n {\n mapText(resource.getName(), replacements);\n mapText(resource.getInitials(), replacements);\n }\n processReplacements((DirectoryEntry) m_projectDir.getEntry(\"TBkndRsc\"), varDataFileName, replacements, true);\n\n //\n // Process project properties\n //\n replacements.clear();\n ProjectProperties properties = m_project.getProjectProperties();\n mapText(properties.getProjectTitle(), replacements);\n processReplacements(m_projectDir, \"Props\", replacements, true);\n\n replacements.clear();\n mapText(properties.getProjectTitle(), replacements);\n mapText(properties.getSubject(), replacements);\n mapText(properties.getAuthor(), replacements);\n mapText(properties.getKeywords(), replacements);\n mapText(properties.getComments(), replacements);\n processReplacements(root, \"\\005SummaryInformation\", replacements, false);\n\n replacements.clear();\n mapText(properties.getManager(), replacements);\n mapText(properties.getCompany(), replacements);\n mapText(properties.getCategory(), replacements);\n processReplacements(root, \"\\005DocumentSummaryInformation\", replacements, false);\n\n //\n // Write the replacement raw file\n //\n FileOutputStream os = new FileOutputStream(output);\n fs.writeFilesystem(os);\n os.flush();\n os.close();\n fs.close();\n }",
"protected boolean showMoreEntries(Calendar nextDate, int previousOccurrences) {\n\n switch (getSerialEndType()) {\n case DATE:\n boolean moreByDate = nextDate.getTimeInMillis() < m_endMillis;\n boolean moreByOccurrences = previousOccurrences < CmsSerialDateUtil.getMaxEvents();\n if (moreByDate && !moreByOccurrences) {\n m_hasTooManyOccurrences = Boolean.TRUE;\n }\n return moreByDate && moreByOccurrences;\n case TIMES:\n case SINGLE:\n return previousOccurrences < getOccurrences();\n default:\n throw new IllegalArgumentException();\n }\n }",
"public void checkpoint(ObjectEnvelope mod)\r\n throws org.apache.ojb.broker.PersistenceBrokerException\r\n {\r\n mod.doUpdate();\r\n }",
"public void unlock() {\n\n for (Locale l : m_lockedBundleFiles.keySet()) {\n LockedFile f = m_lockedBundleFiles.get(l);\n f.tryUnlock();\n }\n if (null != m_descFile) {\n m_descFile.tryUnlock();\n }\n }",
"public static String getCorrelationId(Message message) {\n String correlationId = (String) message.get(CORRELATION_ID_KEY);\n if(null == correlationId) {\n correlationId = readCorrelationId(message);\n }\n if(null == correlationId) {\n correlationId = readCorrelationIdSoap(message);\n }\n return correlationId;\n }",
"public static String multiply(CharSequence self, Number factor) {\n String s = self.toString();\n int size = factor.intValue();\n if (size == 0)\n return \"\";\n else if (size < 0) {\n throw new IllegalArgumentException(\"multiply() should be called with a number of 0 or greater not: \" + size);\n }\n StringBuilder answer = new StringBuilder(s);\n for (int i = 1; i < size; i++) {\n answer.append(s);\n }\n return answer.toString();\n }",
"private String joinElements(int length)\n {\n StringBuilder sb = new StringBuilder();\n for (int index = 0; index < length; index++)\n {\n sb.append(m_elements.get(index));\n }\n return sb.toString();\n }",
"public void setControllerModel(GVRSceneObject controllerModel)\n {\n if (mControllerModel != null)\n {\n mControllerGroup.removeChildObject(mControllerModel);\n }\n mControllerModel = controllerModel;\n mControllerGroup.addChildObject(mControllerModel);\n mControllerModel.setEnable(mShowControllerModel);\n }"
] |
Gets the path used for the results of XSLT Transforms. | [
"public Path getTransformedXSLTPath(FileModel payload)\n {\n ReportService reportService = new ReportService(getGraphContext());\n Path outputPath = reportService.getReportDirectory();\n outputPath = outputPath.resolve(this.getRelativeTransformedXSLTPath(payload));\n if (!Files.isDirectory(outputPath))\n {\n try\n {\n Files.createDirectories(outputPath);\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to create output directory at: \" + outputPath + \" due to: \"\n + e.getMessage(), e);\n }\n }\n return outputPath;\n }"
] | [
"private ReferenceDescriptorDef usedByReference(ModelDef modelDef, FieldDescriptorDef fieldDef)\r\n {\r\n String ownerClassName = ((ClassDescriptorDef)fieldDef.getOwner()).getQualifiedName();\r\n ClassDescriptorDef classDef;\r\n ReferenceDescriptorDef refDef;\r\n String targetClassName;\r\n\r\n // only relevant for primarykey fields\r\n if (PropertyHelper.toBoolean(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY), false))\r\n {\r\n for (Iterator classIt = modelDef.getClasses(); classIt.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)classIt.next();\r\n for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)\r\n {\r\n refDef = (ReferenceDescriptorDef)refIt.next();\r\n targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF).replace('$', '.');\r\n if (ownerClassName.equals(targetClassName))\r\n {\r\n // the field is a primary key of the class referenced by this reference descriptor\r\n return refDef;\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n }",
"ValidationResult isRestrictedEventName(String name) {\n ValidationResult error = new ValidationResult();\n if (name == null) {\n error.setErrorCode(510);\n error.setErrorDesc(\"Event Name is null\");\n return error;\n }\n for (String x : restrictedNames)\n if (name.equalsIgnoreCase(x)) {\n // The event name is restricted\n\n error.setErrorCode(513);\n error.setErrorDesc(name + \" is a restricted event name. Last event aborted.\");\n Logger.v(name + \" is a restricted system event name. Last event aborted.\");\n return error;\n }\n return error;\n }",
"public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CRFClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CRFClassifier<CoreLabel> crf = new CRFClassifier<CoreLabel>(props);\r\n String testFile = crf.flags.testFile;\r\n String textFile = crf.flags.textFile;\r\n String loadPath = crf.flags.loadClassifier;\r\n String loadTextPath = crf.flags.loadTextClassifier;\r\n String serializeTo = crf.flags.serializeTo;\r\n String serializeToText = crf.flags.serializeToText;\r\n\r\n if (loadPath != null) {\r\n crf.loadClassifierNoExceptions(loadPath, props);\r\n } else if (loadTextPath != null) {\r\n System.err.println(\"Warning: this is now only tested for Chinese Segmenter\");\r\n System.err.println(\"(Sun Dec 23 00:59:39 2007) (pichuan)\");\r\n try {\r\n crf.loadTextClassifier(loadTextPath, props);\r\n // System.err.println(\"DEBUG: out from crf.loadTextClassifier\");\r\n } catch (Exception e) {\r\n throw new RuntimeException(\"error loading \" + loadTextPath, e);\r\n }\r\n } else if (crf.flags.loadJarClassifier != null) {\r\n crf.loadJarClassifier(crf.flags.loadJarClassifier, props);\r\n } else if (crf.flags.trainFile != null || crf.flags.trainFileList != null) {\r\n crf.train();\r\n } else {\r\n crf.loadDefaultClassifier();\r\n }\r\n\r\n // System.err.println(\"Using \" + crf.flags.featureFactory);\r\n // System.err.println(\"Using \" +\r\n // StringUtils.getShortClassName(crf.readerAndWriter));\r\n\r\n if (serializeTo != null) {\r\n crf.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (serializeToText != null) {\r\n crf.serializeTextClassifier(serializeToText);\r\n }\r\n\r\n if (testFile != null) {\r\n DocumentReaderAndWriter<CoreLabel> readerAndWriter = crf.makeReaderAndWriter();\r\n if (crf.flags.searchGraphPrefix != null) {\r\n crf.classifyAndWriteViterbiSearchGraph(testFile, crf.flags.searchGraphPrefix, crf.makeReaderAndWriter());\r\n } else if (crf.flags.printFirstOrderProbs) {\r\n crf.printFirstOrderProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.printProbs) {\r\n crf.printProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.useKBest) {\r\n int k = crf.flags.kBest;\r\n crf.classifyAndWriteAnswersKBest(testFile, k, readerAndWriter);\r\n } else if (crf.flags.printLabelValue) {\r\n crf.printLabelInformation(testFile, readerAndWriter);\r\n } else {\r\n crf.classifyAndWriteAnswers(testFile, readerAndWriter);\r\n }\r\n }\r\n\r\n if (textFile != null) {\r\n crf.classifyAndWriteAnswers(textFile);\r\n }\r\n\r\n if (crf.flags.readStdin) {\r\n crf.classifyStdin();\r\n }\r\n }",
"private static void validatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager) {\n if (bean.getInjectionPoints().isEmpty()) {\n // Skip validation if there are no injection points (e.g. for classes which are not intended to be used as beans)\n return;\n }\n reallyValidatePseudoScopedBean(bean, beanManager, new LinkedHashSet<Object>(), new HashSet<Bean<?>>());\n }",
"public void addNode(NodeT node) {\n node.setOwner(this);\n nodeTable.put(node.key(), node);\n }",
"@Programmatic\n public <T> List<T> fromExcel(\n final Blob excelBlob,\n final Class<T> cls,\n final String sheetName) throws ExcelService.Exception {\n return fromExcel(excelBlob, new WorksheetSpec(cls, sheetName));\n }",
"private boolean contentEqualsUnchecked(byte[] bytes, int offset, int len) {\n if (length != len) {\n return false;\n }\n\n return compareToUnchecked(bytes, offset, len) == 0;\n }",
"public static Date getYearlyAbsoluteAsDate(RecurringData data)\n {\n Date result;\n Integer yearlyAbsoluteDay = data.getDayNumber();\n Integer yearlyAbsoluteMonth = data.getMonthNumber();\n Date startDate = data.getStartDate();\n\n if (yearlyAbsoluteDay == null || yearlyAbsoluteMonth == null || startDate == null)\n {\n result = null;\n }\n else\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n cal.set(Calendar.MONTH, yearlyAbsoluteMonth.intValue() - 1);\n cal.set(Calendar.DAY_OF_MONTH, yearlyAbsoluteDay.intValue());\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n return result;\n }",
"public static String getAt(GString text, int index) {\n return (String) getAt(text.toString(), index);\n }"
] |
Return tabular data
@param labels Labels array
@param data Data bidimensional array
@param padding Total space between fields
@return String | [
"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 static String getPunctClass(String punc) {\r\n if(punc.equals(\"%\") || punc.equals(\"-PLUS-\"))//-PLUS- is an escape for \"+\" in the ATB\r\n return \"perc\";\r\n else if(punc.startsWith(\"*\"))\r\n return \"bullet\";\r\n else if(sfClass.contains(punc))\r\n return \"sf\";\r\n else if(colonClass.contains(punc) || pEllipsis.matcher(punc).matches())\r\n return \"colon\";\r\n else if(commaClass.contains(punc))\r\n return \"comma\";\r\n else if(currencyClass.contains(punc))\r\n return \"curr\";\r\n else if(slashClass.contains(punc))\r\n return \"slash\";\r\n else if(lBracketClass.contains(punc))\r\n return \"lrb\";\r\n else if(rBracketClass.contains(punc))\r\n return \"rrb\";\r\n else if(quoteClass.contains(punc))\r\n return \"quote\";\r\n \r\n return \"\";\r\n }",
"public void localRollback()\r\n {\r\n log.info(\"Rollback was called, do rollback on current connection \" + con);\r\n if (!this.isInLocalTransaction)\r\n {\r\n throw new PersistenceBrokerException(\"Not in transaction, cannot abort\");\r\n }\r\n try\r\n {\r\n //truncate the local transaction\r\n this.isInLocalTransaction = false;\r\n if(!broker.isManaged())\r\n {\r\n if (batchCon != null)\r\n {\r\n batchCon.rollback();\r\n }\r\n else if (con != null && !con.isClosed())\r\n {\r\n con.rollback();\r\n }\r\n }\r\n else\r\n {\r\n if(log.isEnabledFor(Logger.INFO)) log.info(\r\n \"Found managed environment setting in PB, will ignore rollback call on connection, this should be done by JTA\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"Rollback on the underlying connection failed\", e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n \trestoreAutoCommitState();\r\n\t\t }\r\n catch(OJBRuntimeException ignore)\r\n {\r\n\t\t\t // Ignore or log exception\r\n\t\t }\r\n releaseConnection();\r\n }\r\n }",
"public void setOffset(float offset, final Axis axis) {\n if (!equal(mOffset.get(axis), offset)) {\n mOffset.set(offset, axis);\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }",
"private ProjectCalendarDateRanges getRanges(Date date, Calendar cal, Day day)\n {\n ProjectCalendarDateRanges ranges = getException(date);\n if (ranges == null)\n {\n ProjectCalendarWeek week = getWorkWeek(date);\n if (week == null)\n {\n week = this;\n }\n\n if (day == null)\n {\n if (cal == null)\n {\n cal = Calendar.getInstance();\n cal.setTime(date);\n }\n day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n }\n\n ranges = week.getHours(day);\n }\n return ranges;\n }",
"public static csvserver_cspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cspolicy_binding obj = new csvserver_cspolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cspolicy_binding response[] = (csvserver_cspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void revisitMessages(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<ItemDefinition> toAddDefinitions = new ArrayList<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Message) {\n if (!existsMessageItemDefinition(rootElements,\n root.getId())) {\n ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();\n itemdef.setId(root.getId() + \"Type\");\n toAddDefinitions.add(itemdef);\n ((Message) root).setItemRef(itemdef);\n }\n }\n }\n for (ItemDefinition id : toAddDefinitions) {\n def.getRootElements().add(id);\n }\n }",
"public boolean getBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n return (data[word] & (1 << offset)) != 0;\n }",
"public static String readTextFile(Context context, String asset) {\n try {\n InputStream inputStream = context.getAssets().open(asset);\n return org.gearvrf.utility.TextFile.readTextFile(inputStream);\n } catch (FileNotFoundException f) {\n Log.w(TAG, \"readTextFile(): asset file '%s' doesn't exist\", asset);\n } catch (IOException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"readTextFile()\");\n }\n return null;\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 }"
] |
Gets the parameter names of a method node.
@param node
the node to search parameter names on
@return
argument names, never null | [
"public static List<String> getParameterNames(MethodNode node) {\r\n ArrayList<String> result = new ArrayList<String>();\r\n\r\n if (node.getParameters() != null) {\r\n for (Parameter parameter : node.getParameters()) {\r\n result.add(parameter.getName());\r\n }\r\n }\r\n return result;\r\n }"
] | [
"public NodeInfo getNode(String name) {\n final URI uri = uriWithPath(\"./nodes/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, NodeInfo.class);\n }",
"public Token add( String word ) {\n Token t = new Token(word);\n push( t );\n return t;\n }",
"public static double SquaredEuclidean(double[] x, double[] y) {\n double d = 0.0, u;\n\n for (int i = 0; i < x.length; i++) {\n u = x[i] - y[i];\n d += u * u;\n }\n\n return d;\n }",
"public Collection<BoxFileVersion> getVersions() {\n URL url = VERSIONS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n JsonArray entries = jsonObject.get(\"entries\").asArray();\n Collection<BoxFileVersion> versions = new ArrayList<BoxFileVersion>();\n for (JsonValue entry : entries) {\n versions.add(new BoxFileVersion(this.getAPI(), entry.asObject(), this.getID()));\n }\n\n return versions;\n }",
"public <T> T decodeSignedRequest(String signedRequest, Class<T> type) throws SignedRequestException {\n\t\tString[] split = signedRequest.split(\"\\\\.\");\n\t\tString encodedSignature = split[0];\n\t\tString payload = split[1];\t\t\n\t\tString decoded = base64DecodeToString(payload);\t\t\n\t\tbyte[] signature = base64DecodeToBytes(encodedSignature);\n\t\ttry {\n\t\t\tT data = objectMapper.readValue(decoded, type);\t\t\t\n\t\t\tString algorithm = objectMapper.readTree(decoded).get(\"algorithm\").textValue();\n\t\t\tif (algorithm == null || !algorithm.equals(\"HMAC-SHA256\")) {\n\t\t\t\tthrow new SignedRequestException(\"Unknown encryption algorithm: \" + algorithm);\n\t\t\t}\t\t\t\n\t\t\tbyte[] expectedSignature = encrypt(payload, secret);\n\t\t\tif (!Arrays.equals(expectedSignature, signature)) {\n\t\t\t\tthrow new SignedRequestException(\"Invalid signature.\");\n\t\t\t}\t\t\t\n\t\t\treturn data;\n\t\t} catch (IOException e) {\n\t\t\tthrow new SignedRequestException(\"Error parsing payload.\", e);\n\t\t}\n\t}",
"private void initUpperLeftComponent() {\n\n m_upperLeftComponent = new HorizontalLayout();\n m_upperLeftComponent.setHeight(\"100%\");\n m_upperLeftComponent.setSpacing(true);\n m_upperLeftComponent.setDefaultComponentAlignment(Alignment.MIDDLE_RIGHT);\n m_upperLeftComponent.addComponent(m_languageSwitch);\n m_upperLeftComponent.addComponent(m_filePathLabel);\n\n }",
"private void createAndLockDescriptorFile() throws CmsException {\n\n String sitePath = m_sitepath + m_basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX;\n m_desc = m_cms.createResource(\n sitePath,\n OpenCms.getResourceManager().getResourceType(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString()));\n m_descFile = LockedFile.lockResource(m_cms, m_desc);\n m_descFile.setCreated(true);\n }",
"public boolean isValid() {\n\t\tif(parsedHost != null) {\n\t\t\treturn true;\n\t\t}\n\t\tif(validationException != null) {\n\t\t\treturn false;\n\t\t}\n\t\ttry {\n\t\t\tvalidate();\n\t\t\treturn true;\n\t\t} catch(HostNameException e) {\n\t\t\treturn false;\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 }"
] |
Sends a text message using given server setup for SMTP.
@param to the to address.
@param from the from address.
@param subject the subject.
@param msg the test message.
@param setup the SMTP setup. | [
"public static void sendTextEmail(String to, String from, String subject, String msg, final ServerSetup setup) {\r\n sendMimeMessage(createTextEmail(to, from, subject, msg, setup));\r\n }"
] | [
"private static ModelNode createOperation(ServerIdentity identity) {\n // The server address\n final ModelNode address = new ModelNode();\n address.add(ModelDescriptionConstants.HOST, identity.getHostName());\n address.add(ModelDescriptionConstants.RUNNING_SERVER, identity.getServerName());\n //\n final ModelNode operation = OPERATION.clone();\n operation.get(ModelDescriptionConstants.OP_ADDR).set(address);\n return operation;\n }",
"protected void checkJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n if (jobTypes == null) {\n throw new IllegalArgumentException(\"jobTypes must not be null\");\n }\n for (final Entry<String, ? extends Class<?>> entry : jobTypes.entrySet()) {\n try {\n checkJobType(entry.getKey(), entry.getValue());\n } catch (IllegalArgumentException iae) {\n throw new IllegalArgumentException(\"jobTypes contained invalid value\", iae);\n }\n }\n }",
"public static String getPrefix(String column) {\n\t\treturn column.contains( \".\" ) ? DOT_SEPARATOR_PATTERN.split( column )[0] : null;\n\t}",
"public static void checkStringNotNullOrEmpty(String parameterName,\n String value) {\n if (TextUtils.isEmpty(value)) {\n throw Exceptions.IllegalArgument(\"Current input string %s is %s.\",\n parameterName, value == null ? \"null\" : \"empty\");\n }\n }",
"public static Info neg(final Variable A, ManagerTempVariables manager) {\n Info ret = new Info();\n\n if( A instanceof VariableInteger ) {\n final VariableInteger output = manager.createInteger();\n ret.output = output;\n ret.op = new Operation(\"neg-i\") {\n @Override\n public void process() {\n output.value = -((VariableInteger)A).value;\n }\n };\n } else if( A instanceof VariableScalar ) {\n final VariableDouble output = manager.createDouble();\n ret.output = output;\n ret.op = new Operation(\"neg-s\") {\n @Override\n public void process() {\n output.value = -((VariableScalar)A).getDouble();\n }\n };\n } else if( A instanceof VariableMatrix ) {\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"neg-m\") {\n @Override\n public void process() {\n DMatrixRMaj a = ((VariableMatrix)A).matrix;\n output.matrix.reshape(a.numRows, a.numCols);\n CommonOps_DDRM.changeSign(a, output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable \"+A);\n }\n\n return ret;\n }",
"private void createPropertyVfsBundleFiles() throws CmsIllegalArgumentException, CmsLoaderException, CmsException {\n\n String bundleFileBasePath = m_sitepath + m_basename + \"_\";\n for (Locale l : m_localizations.keySet()) {\n CmsResource res = m_cms.createResource(\n bundleFileBasePath + l.toString(),\n OpenCms.getResourceManager().getResourceType(\n CmsMessageBundleEditorTypes.BundleType.PROPERTY.toString()));\n m_bundleFiles.put(l, res);\n LockedFile file = LockedFile.lockResource(m_cms, res);\n file.setCreated(true);\n m_lockedBundleFiles.put(l, file);\n m_changedTranslations.add(l);\n }\n\n }",
"public boolean isMaintenanceModeEnabled(String appName) {\n App app = connection.execute(new AppInfo(appName), apiKey);\n return app.isMaintenance();\n }",
"public QueryBuilder<T, ID> groupBy(String columnName) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't groupBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddGroupBy(ColumnNameOrRawSql.withColumnName(columnName));\n\t\treturn this;\n\t}",
"public 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 }"
] |
Sets a property on this Javascript object for which the value is a
JavascriptEnum
The value is set to what is returned by the getEnumValue() method on the JavascriptEnum
@param propertyName The name of the property.
@param propertyValue The value of the property. | [
"protected void setProperty(String propertyName, JavascriptEnum propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getEnumValue());\n }"
] | [
"public String interpolate( String input, RecursionInterceptor recursionInterceptor )\n\t throws InterpolationException\n\t {\n\t try\n\t {\n\t return interpolate( input, recursionInterceptor, new HashSet<String>() );\n\t }\n\t finally\n\t {\n\t if ( !cacheAnswers )\n\t {\n\t existingAnswers.clear();\n\t }\n\t }\n\t }",
"public Response deleteTemplate(String id)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.delete(\"/templates/\" + id, new HashMap<String, Object>()));\n }",
"synchronized ArrayList<CTMessageDAO> getMessages(String userId){\n final String tName = Table.INBOX_MESSAGES.getName();\n Cursor cursor;\n ArrayList<CTMessageDAO> messageDAOArrayList = new ArrayList<>();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n cursor= db.rawQuery(\"SELECT * FROM \"+tName+\" WHERE \" + USER_ID + \" = ? ORDER BY \" + KEY_CREATED_AT+ \" DESC\", new String[]{userId});\n if(cursor != null) {\n while(cursor.moveToNext()){\n CTMessageDAO ctMessageDAO = new CTMessageDAO();\n ctMessageDAO.setId(cursor.getString(cursor.getColumnIndex(_ID)));\n ctMessageDAO.setJsonData(new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA))));\n ctMessageDAO.setWzrkParams(new JSONObject(cursor.getString(cursor.getColumnIndex(WZRKPARAMS))));\n ctMessageDAO.setDate(cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT)));\n ctMessageDAO.setExpires(cursor.getLong(cursor.getColumnIndex(EXPIRES)));\n ctMessageDAO.setRead(cursor.getInt(cursor.getColumnIndex(IS_READ)));\n ctMessageDAO.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));\n ctMessageDAO.setTags(cursor.getString(cursor.getColumnIndex(TAGS)));\n ctMessageDAO.setCampaignId(cursor.getString(cursor.getColumnIndex(CAMPAIGN)));\n messageDAOArrayList.add(ctMessageDAO);\n }\n cursor.close();\n }\n return messageDAOArrayList;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e);\n return null;\n } catch (JSONException e) {\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e.getMessage());\n return null;\n } finally {\n dbHelper.close();\n }\n }",
"private 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 }",
"public void fireResourceReadEvent(Resource resource)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.resourceRead(resource);\n }\n }\n }",
"public static base_responses change(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey updateresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslcertkey();\n\t\t\t\tupdateresources[i].certkey = resources[i].certkey;\n\t\t\t\tupdateresources[i].cert = resources[i].cert;\n\t\t\t\tupdateresources[i].key = resources[i].key;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].fipskey = resources[i].fipskey;\n\t\t\t\tupdateresources[i].inform = resources[i].inform;\n\t\t\t\tupdateresources[i].passplain = resources[i].passplain;\n\t\t\t\tupdateresources[i].nodomaincheck = resources[i].nodomaincheck;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, updateresources,\"update\");\n\t\t}\n\t\treturn result;\n\t}",
"public DateTimeZone getZone(String id) {\n if (id == null) {\n return null;\n }\n\n Object obj = iZoneInfoMap.get(id);\n if (obj == null) {\n return null;\n }\n\n if (id.equals(obj)) {\n // Load zone data for the first time.\n return loadZoneData(id);\n }\n\n if (obj instanceof SoftReference<?>) {\n @SuppressWarnings(\"unchecked\")\n SoftReference<DateTimeZone> ref = (SoftReference<DateTimeZone>) obj;\n DateTimeZone tz = ref.get();\n if (tz != null) {\n return tz;\n }\n // Reference cleared; load data again.\n return loadZoneData(id);\n }\n\n // If this point is reached, mapping must link to another.\n return getZone((String) obj);\n }",
"public static void setTime(Calendar cal, Date time)\n {\n if (time != null)\n {\n Calendar startCalendar = popCalendar(time);\n cal.set(Calendar.HOUR_OF_DAY, startCalendar.get(Calendar.HOUR_OF_DAY));\n cal.set(Calendar.MINUTE, startCalendar.get(Calendar.MINUTE));\n cal.set(Calendar.SECOND, startCalendar.get(Calendar.SECOND));\n pushCalendar(startCalendar);\n }\n }",
"public TopicList<Topic> getTopicsList(String groupId, int perPage, int page) throws FlickrException {\r\n TopicList<Topic> topicList = new TopicList<Topic>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_TOPICS_GET_LIST);\r\n\r\n parameters.put(\"group_id\", groupId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element topicElements = response.getPayload();\r\n topicList.setPage(topicElements.getAttribute(\"page\"));\r\n topicList.setPages(topicElements.getAttribute(\"pages\"));\r\n topicList.setPerPage(topicElements.getAttribute(\"perpage\"));\r\n topicList.setTotal(topicElements.getAttribute(\"total\"));\r\n topicList.setGroupId(topicElements.getAttribute(\"group_id\"));\r\n topicList.setIconServer(Integer.parseInt(topicElements.getAttribute(\"iconserver\")));\r\n topicList.setIconFarm(Integer.parseInt(topicElements.getAttribute(\"iconfarm\")));\r\n topicList.setName(topicElements.getAttribute(\"name\"));\r\n topicList.setMembers(Integer.parseInt(topicElements.getAttribute(\"members\")));\r\n topicList.setPrivacy(Integer.parseInt(topicElements.getAttribute(\"privacy\")));\r\n topicList.setLanguage(topicElements.getAttribute(\"lang\"));\r\n topicList.setIsPoolModerated(\"1\".equals(topicElements.getAttribute(\"ispoolmoderated\")));\r\n\r\n NodeList topicNodes = topicElements.getElementsByTagName(\"topic\");\r\n for (int i = 0; i < topicNodes.getLength(); i++) {\r\n Element element = (Element) topicNodes.item(i);\r\n topicList.add(parseTopic(element));\r\n }\r\n return topicList;\r\n }"
] |
Applies the given filter to each of the given elems, and returns the
list of elems that were accepted. The runtime type of the returned
array is the same as the passed in array. | [
"@SuppressWarnings(\"unchecked\")\r\n public static <E> E[] filter(E[] elems, Filter<E> filter) {\r\n List<E> filtered = new ArrayList<E>();\r\n for (E elem: elems) {\r\n if (filter.accept(elem)) {\r\n filtered.add(elem);\r\n }\r\n }\r\n return (filtered.toArray((E[]) Array.newInstance(elems.getClass().getComponentType(), filtered.size())));\r\n }"
] | [
"private String filterTag(String tag) {\r\n\t AttributeValues answerAV = TagSet.getTagSet().fromTag(tag);\r\n\t answerAV.removeNonlexicalAttributes();\r\n\t return TagSet.getTagSet().toTag(answerAV);\r\n }",
"public void setSchema(String schema)\n {\n if (schema == null)\n {\n schema = \"\";\n }\n else\n {\n if (!schema.isEmpty() && !schema.endsWith(\".\"))\n {\n schema = schema + '.';\n }\n }\n m_schema = schema;\n }",
"private void reorder()\r\n {\r\n if(getTransaction().isOrdering() && needsCommit && mhtObjectEnvelopes.size() > 1)\r\n {\r\n ObjectEnvelopeOrdering ordering = new ObjectEnvelopeOrdering(mvOrderOfIds, mhtObjectEnvelopes);\r\n ordering.reorder();\r\n Identity[] newOrder = ordering.getOrdering();\r\n\r\n mvOrderOfIds.clear();\r\n for(int i = 0; i < newOrder.length; i++)\r\n {\r\n mvOrderOfIds.add(newOrder[i]);\r\n }\r\n }\r\n }",
"public static int Hamming(String first, String second) {\n\n if (first.length() != second.length())\n throw new IllegalArgumentException(\"The size of string must be the same.\");\n\n int diff = 0;\n for (int i = 0; i < first.length(); i++)\n if (first.charAt(i) != second.charAt(i))\n diff++;\n return diff;\n }",
"public void startTask(int id, String taskName) {\n if (isActivated) {\n durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));\n }\n }",
"private void destroyRequestQueue(Queue<AsyncResourceRequest<V>> requestQueue) {\n if(requestQueue != null) {\n AsyncResourceRequest<V> resourceRequest = requestQueue.poll();\n while(resourceRequest != null) {\n destroyRequest(resourceRequest);\n resourceRequest = requestQueue.poll();\n }\n }\n }",
"public void removePathnameFromProfile(int path_id, int profileId) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"private void cleanUpAction() {\n\n try {\n m_model.deleteDescriptorIfNecessary();\n } catch (CmsException e) {\n LOG.error(m_messages.key(Messages.ERR_DELETING_DESCRIPTOR_0), e);\n }\n // unlock resource\n m_model.unlock();\n }",
"public static TagModel getSingleParent(TagModel tag)\n {\n final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator();\n if (!parents.hasNext())\n throw new WindupException(\"Tag is not designated by any tags: \" + tag);\n\n final TagModel maybeOnlyParent = parents.next();\n\n if (parents.hasNext()) {\n StringBuilder sb = new StringBuilder();\n tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(\", \"));\n throw new WindupException(String.format(\"Tag %s is designated by multiple tags: %s\", tag, sb.toString()));\n }\n\n return maybeOnlyParent;\n }"
] |
Fill the attributes in the processor.
@param processors The processors
@param initialAttributes The attributes
@see RequireAttributes
@see ProvideAttributes | [
"public static void fillProcessorAttributes(\n final List<Processor> processors,\n final Map<String, Attribute> initialAttributes) {\n Map<String, Attribute> currentAttributes = new HashMap<>(initialAttributes);\n for (Processor processor: processors) {\n if (processor instanceof RequireAttributes) {\n for (ProcessorDependencyGraphFactory.InputValue inputValue:\n ProcessorDependencyGraphFactory.getInputs(processor)) {\n if (inputValue.type == Values.class) {\n if (processor instanceof CustomDependencies) {\n for (String attributeName: ((CustomDependencies) processor).getDependencies()) {\n Attribute attribute = currentAttributes.get(attributeName);\n if (attribute != null) {\n ((RequireAttributes) processor).setAttribute(\n attributeName, currentAttributes.get(attributeName));\n }\n }\n\n } else {\n for (Map.Entry<String, Attribute> attribute: currentAttributes.entrySet()) {\n ((RequireAttributes) processor).setAttribute(\n attribute.getKey(), attribute.getValue());\n }\n }\n } else {\n try {\n ((RequireAttributes) processor).setAttribute(\n inputValue.internalName,\n currentAttributes.get(inputValue.name));\n } catch (ClassCastException e) {\n throw new IllegalArgumentException(String.format(\"The processor '%s' requires \" +\n \"the attribute '%s' \" +\n \"(%s) but he has the \" +\n \"wrong type:\\n%s\",\n processor, inputValue.name,\n inputValue.internalName,\n e.getMessage()), e);\n }\n }\n }\n }\n if (processor instanceof ProvideAttributes) {\n Map<String, Attribute> newAttributes = ((ProvideAttributes) processor).getAttributes();\n for (ProcessorDependencyGraphFactory.OutputValue ouputValue:\n ProcessorDependencyGraphFactory.getOutputValues(processor)) {\n currentAttributes.put(\n ouputValue.name, newAttributes.get(ouputValue.internalName));\n }\n }\n }\n }"
] | [
"public static pqbinding[] get(nitro_service service, pqbinding_args args) throws Exception{\n\t\tpqbinding obj = new pqbinding();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tpqbinding[] response = (pqbinding[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {\n WeldBeanDeploymentArchive additionalBda = new WeldBeanDeploymentArchive(ADDITIONAL_BDA_ID, Collections.synchronizedSet(new HashSet<String>()), null);\n additionalBda.getServices().addAll(getServices().entrySet());\n beanDeploymentArchives.add(additionalBda);\n setBeanDeploymentArchivesAccessibility();\n return additionalBda;\n }",
"private static void bodyWithBuilder(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename,\n Predicate<PropertyCodeGenerator> isOptional) {\n Variable result = new Variable(\"result\");\n\n code.add(\" %1$s %2$s = new %1$s(\\\"%3$s{\", StringBuilder.class, result, typename);\n boolean midStringLiteral = true;\n boolean midAppends = true;\n boolean prependCommas = false;\n\n PropertyCodeGenerator lastOptionalGenerator = generatorsByProperty.values()\n .stream()\n .filter(isOptional)\n .reduce((first, second) -> second)\n .get();\n\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n if (isOptional.test(generator)) {\n if (midStringLiteral) {\n code.add(\"\\\")\");\n }\n if (midAppends) {\n code.add(\";%n \");\n }\n code.add(\"if (\");\n if (generator.initialState() == Initially.OPTIONAL) {\n generator.addToStringCondition(code);\n } else {\n code.add(\"!%s.contains(%s.%s)\",\n UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName());\n }\n code.add(\") {%n %s.append(\\\"\", result);\n if (prependCommas) {\n code.add(\", \");\n }\n code.add(\"%s=\\\").append(%s)\", property.getName(), property.getField());\n if (!prependCommas) {\n code.add(\".append(\\\", \\\")\");\n }\n code.add(\";%n }%n \");\n if (generator.equals(lastOptionalGenerator)) {\n code.add(\"return %s.append(\\\"\", result);\n midStringLiteral = true;\n midAppends = true;\n } else {\n midStringLiteral = false;\n midAppends = false;\n }\n } else {\n if (!midAppends) {\n code.add(\"%s\", result);\n }\n if (!midStringLiteral) {\n code.add(\".append(\\\"\");\n }\n if (prependCommas) {\n code.add(\", \");\n }\n code.add(\"%s=\\\").append(%s)\", property.getName(), (Excerpt) generator::addToStringValue);\n midStringLiteral = false;\n midAppends = true;\n prependCommas = true;\n }\n }\n\n checkState(prependCommas, \"Unexpected state at end of toString method\");\n checkState(midAppends, \"Unexpected state at end of toString method\");\n if (!midStringLiteral) {\n code.add(\".append(\\\"\");\n }\n code.add(\"}\\\").toString();%n\", result);\n }",
"public String getPermalink(CmsObject cms, String resourceName, CmsUUID detailContentId) {\n\n String permalink = \"\";\n try {\n permalink = substituteLink(cms, CmsPermalinkResourceHandler.PERMALINK_HANDLER);\n String id = cms.readResource(resourceName, CmsResourceFilter.ALL).getStructureId().toString();\n permalink += id;\n if (detailContentId != null) {\n permalink += \":\" + detailContentId;\n }\n String ext = CmsFileUtil.getExtension(resourceName);\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(ext)) {\n permalink += ext;\n }\n CmsSite currentSite = OpenCms.getSiteManager().getCurrentSite(cms);\n String serverPrefix = null;\n if (currentSite == OpenCms.getSiteManager().getDefaultSite()) {\n Optional<CmsSite> siteForDefaultUri = OpenCms.getSiteManager().getSiteForDefaultUri();\n if (siteForDefaultUri.isPresent()) {\n serverPrefix = siteForDefaultUri.get().getServerPrefix(cms, resourceName);\n } else {\n serverPrefix = OpenCms.getSiteManager().getWorkplaceServer();\n }\n } else {\n serverPrefix = currentSite.getServerPrefix(cms, resourceName);\n }\n\n if (!permalink.startsWith(serverPrefix)) {\n permalink = serverPrefix + permalink;\n }\n } catch (CmsException e) {\n // if something wrong\n permalink = e.getLocalizedMessage();\n if (LOG.isErrorEnabled()) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return permalink;\n }",
"@Deprecated\n public ClientConfig setThreadIdleTime(long threadIdleTime, TimeUnit unit) {\n this.threadIdleMs = unit.toMillis(threadIdleTime);\n return this;\n }",
"public static void block(DMatrix1Row A , DMatrix1Row A_tran ,\n final int blockLength )\n {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int blockHeight = Math.min( blockLength , A.numRows - i);\n\n int indexSrc = i*A.numCols;\n int indexDst = i;\n\n for( int j = 0; j < A.numCols; j += blockLength ) {\n int blockWidth = Math.min( blockLength , A.numCols - j);\n\n// int indexSrc = i*A.numCols + j;\n// int indexDst = j*A_tran.numCols + i;\n\n int indexSrcEnd = indexSrc + blockWidth;\n// for( int l = 0; l < blockWidth; l++ , indexSrc++ ) {\n for( ; indexSrc < indexSrcEnd; indexSrc++ ) {\n int rowSrc = indexSrc;\n int rowDst = indexDst;\n int end = rowDst + blockHeight;\n// for( int k = 0; k < blockHeight; k++ , rowSrc += A.numCols ) {\n for( ; rowDst < end; rowSrc += A.numCols ) {\n // faster to write in sequence than to read in sequence\n A_tran.data[ rowDst++ ] = A.data[ rowSrc ];\n }\n indexDst += A_tran.numCols;\n }\n }\n }\n }",
"protected void appendList(StringBuilder sql, List<?> list, String init, String sep) {\n\n boolean first = true;\n\n for (Object s : list) {\n if (first) {\n sql.append(init);\n } else {\n sql.append(sep);\n }\n sql.append(s);\n first = false;\n }\n }",
"public static MBeanParameterInfo[] extractParameterInfo(Method m) {\n Class<?>[] types = m.getParameterTypes();\n Annotation[][] annotations = m.getParameterAnnotations();\n MBeanParameterInfo[] params = new MBeanParameterInfo[types.length];\n for(int i = 0; i < params.length; i++) {\n boolean hasAnnotation = false;\n for(int j = 0; j < annotations[i].length; j++) {\n if(annotations[i][j] instanceof JmxParam) {\n JmxParam param = (JmxParam) annotations[i][j];\n params[i] = new MBeanParameterInfo(param.name(),\n types[i].getName(),\n param.description());\n hasAnnotation = true;\n break;\n }\n }\n if(!hasAnnotation) {\n params[i] = new MBeanParameterInfo(\"\", types[i].getName(), \"\");\n }\n }\n\n return params;\n }",
"public static void validateUserStoreNamesOnNode(AdminClient adminClient,\n Integer nodeId,\n List<String> storeNames) {\n List<StoreDefinition> storeDefList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n Map<String, Boolean> existingStoreNames = new HashMap<String, Boolean>();\n for(StoreDefinition storeDef: storeDefList) {\n existingStoreNames.put(storeDef.getName(), true);\n }\n for(String storeName: storeNames) {\n if(!Boolean.TRUE.equals(existingStoreNames.get(storeName))) {\n Utils.croak(\"Store \" + storeName + \" does not exist!\");\n }\n }\n }"
] |
Read correlation id from message.
@param message the message
@return the CorrelationId as string | [
"public static String readCorrelationId(Message message) {\n String correlationId = null;\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n List<String> correlationIds = headers.get(CORRELATION_ID_KEY);\n if (correlationIds != null && correlationIds.size() > 0) {\n correlationId = correlationIds.get(0);\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + CORRELATION_ID_KEY + \"' found: \" + correlationId);\n }\n } else {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No HTTP header '\" + CORRELATION_ID_KEY + \"' found\");\n }\n }\n\n return correlationId;\n }"
] | [
"protected boolean showMoreEntries(Calendar nextDate, int previousOccurrences) {\n\n switch (getSerialEndType()) {\n case DATE:\n boolean moreByDate = nextDate.getTimeInMillis() < m_endMillis;\n boolean moreByOccurrences = previousOccurrences < CmsSerialDateUtil.getMaxEvents();\n if (moreByDate && !moreByOccurrences) {\n m_hasTooManyOccurrences = Boolean.TRUE;\n }\n return moreByDate && moreByOccurrences;\n case TIMES:\n case SINGLE:\n return previousOccurrences < getOccurrences();\n default:\n throw new IllegalArgumentException();\n }\n }",
"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 }",
"public float DistanceTo(IntPoint anotherPoint) {\r\n float dx = this.x - anotherPoint.x;\r\n float dy = this.y - anotherPoint.y;\r\n\r\n return (float) Math.sqrt(dx * dx + dy * dy);\r\n }",
"public Script[] getScripts(Integer type) {\n ArrayList<Script> returnData = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" ORDER BY \" + Constants.GENERIC_ID);\n if (type != null) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.SCRIPT_TYPE + \"= ?\" +\n \" ORDER BY \" + Constants.GENERIC_ID);\n statement.setInt(1, type);\n }\n\n logger.info(\"Query: {}\", statement);\n\n results = statement.executeQuery();\n while (results.next()) {\n returnData.add(scriptFromSQLResult(results));\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnData.toArray(new Script[0]);\n }",
"protected void handleExceptions(MessageEvent messageEvent, Exception exception) {\n logger.error(\"Unknown exception. Internal Server Error.\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Internal Server Error\");\n }",
"public void postConstruct() {\n parseGeometry();\n\n Assert.isTrue(this.polygon != null, \"Polygon is null. 'area' string is: '\" + this.area + \"'\");\n Assert.isTrue(this.display != null, \"'display' is null\");\n\n Assert.isTrue(this.style == null || this.display == AoiDisplay.RENDER,\n \"'style' does not make sense unless 'display' == RENDER. In this case 'display' == \" +\n this.display);\n }",
"public static int getIbanLength(final CountryCode countryCode) {\n final BbanStructure structure = getBbanStructure(countryCode);\n return COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH + structure.getBbanLength();\n }",
"public static appfwprofile_crosssitescripting_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_crosssitescripting_binding obj = new appfwprofile_crosssitescripting_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_crosssitescripting_binding response[] = (appfwprofile_crosssitescripting_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static List<Dependency> getAllDependencies(final Module module) {\n final Set<Dependency> dependencies = new HashSet<Dependency>();\n final List<String> producedArtifacts = new ArrayList<String>();\n for(final Artifact artifact: getAllArtifacts(module)){\n producedArtifacts.add(artifact.getGavc());\n }\n\n dependencies.addAll(getAllDependencies(module, producedArtifacts));\n\n return new ArrayList<Dependency>(dependencies);\n }"
] |
Processes the original class rather than the current class definition.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"public void originalClass(String template, Properties attributes) throws XDocletException\r\n {\r\n pushCurrentClass(_curClassDef.getOriginalClass());\r\n generate(template);\r\n popCurrentClass();\r\n }"
] | [
"public static String getGetterName(String propertyName, Class type) {\n String prefix = type == boolean.class || type == Boolean.class ? \"is\" : \"get\";\n return prefix + MetaClassHelper.capitalize(propertyName);\n }",
"public Iterator select(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return this.query(predicate).iterator();\r\n }",
"private NodeList getNodeList(String document, XPathExpression expression) throws Exception\n {\n Document doc = m_documentBuilder.parse(new InputSource(new StringReader(document)));\n return (NodeList) expression.evaluate(doc, XPathConstants.NODESET);\n }",
"public void updateBuildpackInstallations(String appName, List<String> buildpacks) {\n connection.execute(new BuildpackInstallationUpdate(appName, buildpacks), apiKey);\n }",
"public static EventLog getEnterpriseEvents(BoxAPIConnection api, Date after, Date before, BoxEvent.Type... types) {\n return getEnterpriseEvents(api, null, after, before, ENTERPRISE_LIMIT, types);\n }",
"private void fireTreeStructureChanged()\n {\n // Guaranteed to return a non-null array\n Object[] listeners = m_listenerList.getListenerList();\n TreeModelEvent e = null;\n // Process the listeners last to first, notifying\n // those that are interested in this event\n for (int i = listeners.length - 2; i >= 0; i -= 2)\n {\n if (listeners[i] == TreeModelListener.class)\n {\n // Lazily create the event:\n if (e == null)\n {\n e = new TreeModelEvent(getRoot(), new Object[]\n {\n getRoot()\n }, null, null);\n }\n ((TreeModelListener) listeners[i + 1]).treeStructureChanged(e);\n }\n }\n }",
"private void setAnimationProgress(float progress) {\n if (isAlphaUsedForScale()) {\n setColorViewAlpha((int) (progress * MAX_ALPHA));\n } else {\n ViewCompat.setScaleX(mCircleView, progress);\n ViewCompat.setScaleY(mCircleView, progress);\n }\n }",
"public void setFrustum(float fovy, float aspect, float znear, float zfar)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.perspective((float) Math.toRadians(fovy), aspect, znear, zfar);\n setFrustum(projMatrix);\n }",
"public boolean isHoliday(String dateString) {\n boolean isHoliday = false;\n for (Holiday date : EquivalenceClassTransformer.HOLIDAYS) {\n if (convertToReadableDate(date.forYear(Integer.parseInt(dateString.substring(0, 4)))).equals(dateString)) {\n isHoliday = true;\n }\n }\n return isHoliday;\n }"
] |
Retrieves a ProjectReader instance which can read a file of the
type specified by the supplied file name.
@param name file name
@return ProjectReader instance | [
"public static ProjectReader getProjectReader(String name) throws MPXJException\n {\n int index = name.lastIndexOf('.');\n if (index == -1)\n {\n throw new IllegalArgumentException(\"Filename has no extension: \" + name);\n }\n\n String extension = name.substring(index + 1).toUpperCase();\n\n Class<? extends ProjectReader> fileClass = READER_MAP.get(extension);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot read files of type: \" + extension);\n }\n\n try\n {\n ProjectReader file = fileClass.newInstance();\n return (file);\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to load project reader\", ex);\n }\n }"
] | [
"public boolean isPrivate() {\n\t\t// refer to RFC 1918\n // 10/8 prefix\n // 172.16/12 prefix (172.16.0.0 – 172.31.255.255)\n // 192.168/16 prefix\n\t\tIPv4AddressSegment seg0 = getSegment(0);\n\t\tIPv4AddressSegment seg1 = getSegment(1);\n\t\treturn seg0.matches(10)\n\t\t\t|| seg0.matches(172) && seg1.matchesWithPrefixMask(16, 4)\n\t\t\t|| seg0.matches(192) && seg1.matches(168);\n\t}",
"public static String createFirstLowCaseName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return changeFirstLetterToLowerCase(name);\n }",
"public static base_responses update(nitro_service client, dbdbprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdbdbprofile updateresources[] = new dbdbprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new dbdbprofile();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].interpretquery = resources[i].interpretquery;\n\t\t\t\tupdateresources[i].stickiness = resources[i].stickiness;\n\t\t\t\tupdateresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\tupdateresources[i].conmultiplex = resources[i].conmultiplex;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withTag(String key, String value) {\n if (this.inner().getTags() == null) {\n this.inner().withTags(new HashMap<String, String>());\n }\n this.inner().getTags().put(key, value);\n return (FluentModelImplT) this;\n }",
"public String getNextDay(String dateString, boolean onlyBusinessDays) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime date = parser.parseDateTime(dateString).plusDays(1);\n Calendar cal = Calendar.getInstance();\n cal.setTime(date.toDate());\n\n if (onlyBusinessDays) {\n if (cal.get(Calendar.DAY_OF_WEEK) == 1 || cal.get(Calendar.DAY_OF_WEEK) == 7\n || isHoliday(date.toString().substring(0, 10))) {\n return getNextDay(date.toString().substring(0, 10), true);\n } else {\n return parser.print(date);\n }\n } else {\n return parser.print(date);\n }\n }",
"public final void setVolumeByIncrement(float level) throws IOException {\n Volume volume = this.getStatus().volume;\n float total = volume.level;\n\n if (volume.increment <= 0f) {\n throw new ChromeCastException(\"Volume.increment is <= 0\");\n }\n\n // With floating points we always have minor decimal variations, using the Math.min/max\n // works around this issue\n // Increase volume\n if (level > total) {\n while (total < level) {\n total = Math.min(total + volume.increment, level);\n setVolume(total);\n }\n // Decrease Volume\n } else if (level < total) {\n while (total > level) {\n total = Math.max(total - volume.increment, level);\n setVolume(total);\n }\n }\n }",
"public static <T> ConflictHandler<T> localWins() {\n return new ConflictHandler<T>() {\n @Override\n public T resolveConflict(\n final BsonValue documentId,\n final ChangeEvent<T> localEvent,\n final ChangeEvent<T> remoteEvent\n ) {\n return localEvent.getFullDocument();\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 synchronized void shutdown(){\r\n\r\n\t\tif (!this.poolShuttingDown){\r\n\t\t\tlogger.info(\"Shutting down connection pool...\");\r\n\t\t\tthis.poolShuttingDown = true;\r\n\t\t\tthis.shutdownStackTrace = captureStackTrace(SHUTDOWN_LOCATION_TRACE);\r\n\t\t\tthis.keepAliveScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.maxAliveScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.connectionsScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.asyncExecutor.shutdownNow();\r\n\r\n\t\t\ttry {\r\n\t\t\t\tthis.connectionsScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\r\n\t\t\t\tthis.maxAliveScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\tthis.keepAliveScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\tthis.asyncExecutor.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\t\r\n\t\t\t\tif (this.closeConnectionExecutor != null){\r\n\t\t\t\t\tthis.closeConnectionExecutor.shutdownNow();\r\n\t\t\t\t\tthis.closeConnectionExecutor.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} catch (InterruptedException e) {\r\n\t\t\t\t// do nothing\r\n\t\t\t}\r\n\t\t\tthis.connectionStrategy.terminateAllConnections();\r\n\t\t\tunregisterDriver();\r\n\t\t\tregisterUnregisterJMX(false);\r\n\t\t\tif (finalizableRefQueue != null) {\r\n\t\t\t\tfinalizableRefQueue.close();\r\n\t\t\t}\r\n\t\t\t logger.info(\"Connection pool has been shutdown.\");\r\n\t\t}\r\n\t}"
] |
Serialize a map of objects to a JSON String.
@param map The map of objects to serialize.
@param jsonObjectClass The @JsonObject class of the list elements | [
"public static <E> String serialize(Map<String, E> map, Class<E> jsonObjectClass) throws IOException {\n return mapperFor(jsonObjectClass).serialize(map);\n }"
] | [
"public void splitSpan(int n) {\n\t\tint x = (xKnots[n] + xKnots[n+1])/2;\n\t\taddKnot(x, getColor(x/256.0f), knotTypes[n]);\n\t\trebuildGradient();\n\t}",
"private void addChildrenForRolesNode(String ouItem) {\n\n try {\n List<CmsRole> roles = OpenCms.getRoleManager().getRoles(m_cms, ouItem.substring(1), false);\n CmsRole.applySystemRoleOrder(roles);\n for (CmsRole role : roles) {\n String roleId = ouItem + \"/\" + role.getId();\n Item roleItem = m_treeContainer.addItem(roleId);\n if (roleItem == null) {\n roleItem = getItem(roleId);\n }\n roleItem.getItemProperty(PROP_NAME).setValue(getIconCaptionHTML(role, CmsOuTreeType.ROLE));\n roleItem.getItemProperty(PROP_TYPE).setValue(CmsOuTreeType.ROLE);\n setChildrenAllowed(roleId, false);\n m_treeContainer.setParent(roleId, ouItem);\n }\n } catch (CmsException e) {\n LOG.error(\"Can not read group\", e);\n }\n }",
"static void restoreFromHistory(final InstallationManager.MutablePatchingTarget target, final String rollbackPatchId,\n final Patch.PatchType patchType, final PatchableTarget.TargetInfo history) throws PatchingException {\n if (patchType == Patch.PatchType.CUMULATIVE) {\n assert history.getCumulativePatchID().equals(rollbackPatchId);\n target.apply(rollbackPatchId, patchType);\n // Restore one off state\n final List<String> oneOffs = new ArrayList<String>(history.getPatchIDs());\n Collections.reverse(oneOffs);\n for (final String oneOff : oneOffs) {\n target.apply(oneOff, Patch.PatchType.ONE_OFF);\n }\n }\n checkState(history, history); // Just check for tests, that rollback should restore the old state\n }",
"private void releaseConnection()\n {\n if (m_rs != null)\n {\n try\n {\n m_rs.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_rs = null;\n }\n\n if (m_ps != null)\n {\n try\n {\n m_ps.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_ps = null;\n }\n }",
"private void solveInternalL() {\n // This takes advantage of the diagonal elements always being real numbers\n\n // solve L*y=b storing y in x\n TriangularSolver_ZDRM.solveL_diagReal(t, vv, n);\n\n // solve L^T*x=y\n TriangularSolver_ZDRM.solveConjTranL_diagReal(t, vv, n);\n }",
"public Bundler put(String key, String value) {\n delegate.putString(key, value);\n return this;\n }",
"public void value2x2( double a11 , double a12, double a21 , double a22 )\n {\n // apply a rotators such that th a11 and a22 elements are the same\n double c,s;\n\n if( a12 + a21 == 0 ) { // is this pointless since\n c = s = 1.0 / Math.sqrt(2);\n } else {\n double aa = (a11-a22);\n double bb = (a12+a21);\n\n double t_hat = aa/bb;\n double t = t_hat/(1.0 + Math.sqrt(1.0+t_hat*t_hat));\n\n c = 1.0/ Math.sqrt(1.0+t*t);\n s = c*t;\n }\n\n double c2 = c*c;\n double s2 = s*s;\n double cs = c*s;\n\n double b11 = c2*a11 + s2*a22 - cs*(a12+a21);\n double b12 = c2*a12 - s2*a21 + cs*(a11-a22);\n double b21 = c2*a21 - s2*a12 + cs*(a11-a22);\n// double b22 = c2*a22 + s2*a11 + cs*(a12+a21);\n\n // apply second rotator to make A upper triangular if real eigenvalues\n if( b21*b12 >= 0 ) {\n if( b12 == 0 ) {\n c = 0;\n s = 1;\n } else {\n s = Math.sqrt(b21/(b12+b21));\n c = Math.sqrt(b12/(b12+b21));\n }\n\n// c2 = b12;//c*c;\n// s2 = b21;//s*s;\n cs = c*s;\n\n a11 = b11 - cs*(b12 + b21);\n// a12 = c2*b12 - s2*b21;\n// a21 = c2*b21 - s2*b12;\n a22 = b11 + cs*(b12 + b21);\n\n value0.real = a11;\n value1.real = a22;\n\n value0.imaginary = value1.imaginary = 0;\n\n } else {\n value0.real = value1.real = b11;\n value0.imaginary = Math.sqrt(-b21*b12);\n value1.imaginary = -value0.imaginary;\n }\n }",
"public void setDefaults(Annotation[] defaultAnnotations) {\n if (defaultAnnotations == null) {\n return;\n }\n for (Annotation each : defaultAnnotations) {\n Class<? extends Annotation> key = each.annotationType();\n if (Title.class.equals(key) || Description.class.equals(key)) {\n continue;\n }\n if (!annotations.containsKey(key)) {\n annotations.put(key, each);\n }\n }\n }",
"public static clusternodegroup_binding get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup_binding obj = new clusternodegroup_binding();\n\t\tobj.set_name(name);\n\t\tclusternodegroup_binding response = (clusternodegroup_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Unloads the sound file for this source, if any. | [
"public void unload()\n {\n if (mAudioListener != null)\n {\n Log.d(\"SOUND\", \"unloading audio source %d %s\", getSourceId(), getSoundFile());\n mAudioListener.getAudioEngine().unloadSoundFile(getSoundFile());\n }\n mSoundFile = null;\n mSourceId = GvrAudioEngine.INVALID_ID;\n }"
] | [
"private static JSONArray parseChildShapesRecursive(ArrayList<Shape> childShapes) throws JSONException {\n if (childShapes != null) {\n JSONArray childShapesArray = new JSONArray();\n\n for (Shape childShape : childShapes) {\n JSONObject childShapeObject = new JSONObject();\n\n childShapeObject.put(\"resourceId\",\n childShape.getResourceId().toString());\n childShapeObject.put(\"properties\",\n parseProperties(childShape.getProperties()));\n childShapeObject.put(\"stencil\",\n parseStencil(childShape.getStencilId()));\n childShapeObject.put(\"childShapes\",\n parseChildShapesRecursive(childShape.getChildShapes()));\n childShapeObject.put(\"outgoing\",\n parseOutgoings(childShape.getOutgoings()));\n childShapeObject.put(\"bounds\",\n parseBounds(childShape.getBounds()));\n childShapeObject.put(\"dockers\",\n parseDockers(childShape.getDockers()));\n\n if (childShape.getTarget() != null) {\n childShapeObject.put(\"target\",\n parseTarget(childShape.getTarget()));\n }\n\n childShapesArray.put(childShapeObject);\n }\n\n return childShapesArray;\n }\n\n return new JSONArray();\n }",
"private DBHandling createDBHandling() throws BuildException\r\n {\r\n if ((_handling == null) || (_handling.length() == 0))\r\n {\r\n throw new BuildException(\"No handling specified\");\r\n }\r\n try\r\n {\r\n String className = \"org.apache.ojb.broker.platforms.\"+\r\n \t\t\t\t\t Character.toTitleCase(_handling.charAt(0))+_handling.substring(1)+\r\n \t\t\t\t\t \"DBHandling\";\r\n Class handlingClass = ClassHelper.getClass(className);\r\n\r\n return (DBHandling)handlingClass.newInstance();\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new BuildException(\"Invalid handling '\"+_handling+\"' specified\");\r\n }\r\n }",
"private static JSONObject parseBounds(Bounds bounds) throws JSONException {\n if (bounds != null) {\n JSONObject boundsObject = new JSONObject();\n JSONObject lowerRight = new JSONObject();\n JSONObject upperLeft = new JSONObject();\n\n lowerRight.put(\"x\",\n bounds.getLowerRight().getX().doubleValue());\n lowerRight.put(\"y\",\n bounds.getLowerRight().getY().doubleValue());\n\n upperLeft.put(\"x\",\n bounds.getUpperLeft().getX().doubleValue());\n upperLeft.put(\"y\",\n bounds.getUpperLeft().getY().doubleValue());\n\n boundsObject.put(\"lowerRight\",\n lowerRight);\n boundsObject.put(\"upperLeft\",\n upperLeft);\n\n return boundsObject;\n }\n\n return new JSONObject();\n }",
"@Deprecated\n\tpublic void setResolutions(List<Double> resolutions) {\n\t\tgetZoomLevels().clear();\n\t\tfor (Double resolution : resolutions) {\n\t\t\tgetZoomLevels().add(new ScaleInfo(1. / resolution));\n\t\t}\n\t}",
"public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs);\n recordCheckoutTimeUs(null, checkoutTimeUs);\n } else {\n this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US);\n }\n }",
"@Override\r\n public <VALUEBASE, VALUE extends VALUEBASE, KEY extends Key<CoreMap, VALUEBASE>>\r\n VALUE set(Class<KEY> key, VALUE value) {\r\n \r\n if (immutableKeys.contains(key)) {\r\n throw new HashableCoreMapException(\"Attempt to change value \" +\r\n \t\t\"of immutable field \"+key.getSimpleName());\r\n }\r\n \r\n return super.set(key, value);\r\n }",
"private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded());\n }\n\n return flatItemList;\n }",
"public double getYield(double bondPrice, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenYield(0.0,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\n\t}",
"private Map<Integer, List<Row>> createWorkPatternAssignmentMap(List<Row> rows) throws ParseException\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"ID\");\n String workPatterns = row.getString(\"WORK_PATTERNS\");\n map.put(calendarID, createWorkPatternAssignmentRowList(workPatterns));\n }\n return map;\n }"
] |
Sets reference to the graph owning this node.
@param ownerGraph the owning graph | [
"public void setOwner(Graph<DataT, NodeT> ownerGraph) {\n if (this.ownerGraph != null) {\n throw new RuntimeException(\"Changing owner graph is not allowed\");\n }\n this.ownerGraph = ownerGraph;\n }"
] | [
"public static final String printTimestamp(Date value)\n {\n return (value == null ? null : TIMESTAMP_FORMAT.get().format(value));\n }",
"public static String readDesignerVersion(ServletContext context) {\n String retStr = \"\";\n BufferedReader br = null;\n try {\n InputStream inputStream = context.getResourceAsStream(\"/META-INF/MANIFEST.MF\");\n br = new BufferedReader(new InputStreamReader(inputStream,\n \"UTF-8\"));\n String line;\n while ((line = br.readLine()) != null) {\n if (line.startsWith(BUNDLE_VERSION)) {\n retStr = line.substring(BUNDLE_VERSION.length() + 1);\n retStr = retStr.trim();\n }\n }\n inputStream.close();\n } catch (Exception e) {\n logger.error(e.getMessage(),\n e);\n } finally {\n if (br != null) {\n IOUtils.closeQuietly(br);\n }\n }\n return retStr;\n }",
"private void setBandFinalHeight(JRDesignBand band, int currHeigth, boolean fitToContent) {\n if (band != null) {\n int finalHeight = LayoutUtils.findVerticalOffset(band);\n //noinspection StatementWithEmptyBody\n if (finalHeight < currHeigth && !fitToContent) {\n //nothing\n } else {\n band.setHeight(finalHeight);\n }\n }\n\n }",
"public static String stripHtml(String html) {\n\n if (html == null) {\n return null;\n }\n Element el = DOM.createDiv();\n el.setInnerHTML(html);\n return el.getInnerText();\n }",
"public int getModifiers() {\n MetaMethod getter = getGetter();\n MetaMethod setter = getSetter();\n if (setter != null && getter == null) return setter.getModifiers();\n if (getter != null && setter == null) return getter.getModifiers();\n int modifiers = getter.getModifiers() | setter.getModifiers();\n int visibility = 0;\n if (Modifier.isPublic(modifiers)) visibility = Modifier.PUBLIC;\n if (Modifier.isProtected(modifiers)) visibility = Modifier.PROTECTED;\n if (Modifier.isPrivate(modifiers)) visibility = Modifier.PRIVATE;\n int states = getter.getModifiers() & setter.getModifiers();\n states &= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE);\n states |= visibility;\n return states;\n }",
"public void forAllIndexColumns(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curIndexDef.getColumns(); it.hasNext(); )\r\n {\r\n _curColumnDef = _curTableDef.getColumn((String)it.next());\r\n generate(template);\r\n }\r\n _curColumnDef = null;\r\n }",
"public void prepare(Properties p, Connection cnx)\n {\n this.tablePrefix = p.getProperty(\"com.enioka.jqm.jdbc.tablePrefix\", \"\");\n queries.putAll(DbImplBase.queries);\n for (Map.Entry<String, String> entry : DbImplBase.queries.entrySet())\n {\n queries.put(entry.getKey(), this.adaptSql(entry.getValue()));\n }\n }",
"private List<String> getCommandLines(File file) {\n List<String> lines = new ArrayList<>();\n try (BufferedReader reader = new BufferedReader(new FileReader(file))) {\n String line = reader.readLine();\n while (line != null) {\n lines.add(line);\n line = reader.readLine();\n }\n } catch (Throwable e) {\n throw new IllegalStateException(\"Failed to process file \" + file.getAbsolutePath(), e);\n }\n return lines;\n }",
"public ContentAssistContext.Builder copy() {\n\t\tBuilder result = builderProvider.get();\n\t\tresult.copyFrom(this);\n\t\treturn result;\n\t}"
] |
Computes the determinant for the specified matrix. It must be square and have
the same width and height as what was specified in the constructor.
@param mat The matrix whose determinant is to be computed.
@return The determinant. | [
"public double compute( DMatrix1Row mat ) {\n if( width != mat.numCols || width != mat.numRows ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n\n // make sure everything is in the proper state before it starts\n initStructures();\n\n// System.arraycopy(mat.data,0,minorMatrix[0],0,mat.data.length);\n\n int level = 0;\n while( true ) {\n int levelWidth = width-level;\n int levelIndex = levelIndexes[level];\n\n if( levelIndex == levelWidth ) {\n if( level == 0 ) {\n return levelResults[0];\n }\n int prevLevelIndex = levelIndexes[level-1]++;\n\n double val = mat.get((level-1)*width+levelRemoved[level-1]);\n if( prevLevelIndex % 2 == 0 ) {\n levelResults[level-1] += val * levelResults[level];\n } else {\n levelResults[level-1] -= val * levelResults[level];\n }\n\n putIntoOpen(level-1);\n\n levelResults[level] = 0;\n levelIndexes[level] = 0;\n level--;\n } else {\n int excluded = openRemove( levelIndex );\n\n levelRemoved[level] = excluded;\n\n if( levelWidth == minWidth ) {\n createMinor(mat);\n double subresult = mat.get(level*width+levelRemoved[level]);\n\n subresult *= UnrolledDeterminantFromMinor_DDRM.det(tempMat);\n\n if( levelIndex % 2 == 0 ) {\n levelResults[level] += subresult;\n } else {\n levelResults[level] -= subresult;\n }\n\n // put it back into the list\n putIntoOpen(level);\n levelIndexes[level]++;\n } else {\n level++;\n }\n }\n }\n }"
] | [
"public double getAccruedInterest(double time, AnalyticModel model) {\n\t\tLocalDate date= FloatingpointDate.getDateFromFloatingPointDate(schedule.getReferenceDate(), time);\n\t\treturn getAccruedInterest(date, model);\n\t}",
"private void initAdapter()\n {\n Connection tmp = null;\n DatabaseMetaData meta = null;\n try\n {\n tmp = _ds.getConnection();\n meta = tmp.getMetaData();\n product = meta.getDatabaseProductName().toLowerCase();\n }\n catch (SQLException e)\n {\n throw new DatabaseException(\"Cannot connect to the database\", e);\n }\n finally\n {\n try\n {\n if (tmp != null)\n {\n tmp.close();\n }\n }\n catch (SQLException e)\n {\n // Nothing to do.\n }\n }\n\n DbAdapter newAdpt = null;\n for (String s : ADAPTERS)\n {\n try\n {\n Class<? extends DbAdapter> clazz = Db.class.getClassLoader().loadClass(s).asSubclass(DbAdapter.class);\n newAdpt = clazz.newInstance();\n if (newAdpt.compatibleWith(meta))\n {\n adapter = newAdpt;\n break;\n }\n }\n catch (Exception e)\n {\n throw new DatabaseException(\"Issue when loading database adapter named: \" + s, e);\n }\n }\n\n if (adapter == null)\n {\n throw new DatabaseException(\"Unsupported database! There is no JQM database adapter compatible with product name \" + product);\n }\n else\n {\n jqmlogger.info(\"Using database adapter {}\", adapter.getClass().getCanonicalName());\n }\n }",
"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 void histogramToStructure(int histogram[] ) {\n col_idx[0] = 0;\n int index = 0;\n for (int i = 1; i <= numCols; i++) {\n col_idx[i] = index += histogram[i-1];\n }\n nz_length = index;\n growMaxLength( nz_length , false);\n if( col_idx[numCols] != nz_length )\n throw new RuntimeException(\"Egads\");\n }",
"public String getAuthorizationUri(final String redirectUri, final Set<String> scopes, final String state) {\n if (account == null)\n throw new IllegalArgumentException(\"Auth is not set\");\n if (account.getClientId() == null)\n throw new IllegalArgumentException(\"client_id is not set\");\n StringBuilder builder = new StringBuilder();\n builder.append(URI_AUTHENTICATION);\n builder.append(\"?\");\n builder.append(\"response_type=\");\n builder.append(encode(\"code\"));\n builder.append(\"&redirect_uri=\");\n builder.append(encode(redirectUri));\n builder.append(\"&client_id=\");\n builder.append(encode(account.getClientId()));\n builder.append(\"&scope=\");\n builder.append(encode(getScopesString(scopes)));\n builder.append(\"&state=\");\n builder.append(encode(state));\n builder.append(\"&code_challenge\");\n builder.append(getCodeChallenge()); // Already url encoded\n builder.append(\"&code_challenge_method=\");\n builder.append(encode(\"S256\"));\n return builder.toString();\n }",
"public static Class<?> resolveTypeArgument(Class<?> clazz, Class<?> genericIfc) {\n\t\tClass<?>[] typeArgs = resolveTypeArguments(clazz, genericIfc);\n\t\tif (typeArgs == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (typeArgs.length != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Expected 1 type argument on generic interface [\" +\n\t\t\t\t\tgenericIfc.getName() + \"] but found \" + typeArgs.length);\n\t\t}\n\t\treturn typeArgs[0];\n\t}",
"@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 Object getRealSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tif (_realSubject == null)\r\n\t\t{\r\n\t\t\tbeforeMaterialization();\r\n\t\t\t_realSubject = materializeSubject();\r\n\t\t\tafterMaterialization();\r\n\t\t}\r\n\t\treturn _realSubject;\r\n\t}",
"public 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 }"
] |
Adds a directory to the collection of module paths.
@param moduleDir the module directory to add
@throws java.lang.IllegalArgumentException if the path is {@code null} | [
"public void addModuleDir(final String moduleDir) {\n if (moduleDir == null) {\n throw LauncherMessages.MESSAGES.nullParam(\"moduleDir\");\n }\n // Validate the path\n final Path path = Paths.get(moduleDir).normalize();\n modulesDirs.add(path.toString());\n }"
] | [
"private ValidationResult _mergeListInternalForKey(String key, JSONArray left,\n JSONArray right, boolean remove, ValidationResult vr) {\n\n if (left == null) {\n vr.setObject(null);\n return vr;\n }\n\n if (right == null) {\n vr.setObject(left);\n return vr;\n }\n\n int maxValNum = Constants.MAX_MULTI_VALUE_ARRAY_LENGTH;\n\n JSONArray mergedList = new JSONArray();\n\n HashSet<String> set = new HashSet<>();\n\n int lsize = left.length(), rsize = right.length();\n\n BitSet dupSetForAdd = null;\n\n if (!remove)\n dupSetForAdd = new BitSet(lsize + rsize);\n\n int lidx = 0;\n\n int ridx = scan(right, set, dupSetForAdd, lsize);\n\n if (!remove && set.size() < maxValNum) {\n lidx = scan(left, set, dupSetForAdd, 0);\n }\n\n for (int i = lidx; i < lsize; i++) {\n try {\n if (remove) {\n String _j = (String) left.get(i);\n\n if (!set.contains(_j)) {\n mergedList.put(_j);\n }\n } else if (!dupSetForAdd.get(i)) {\n mergedList.put(left.get(i));\n }\n\n } catch (Throwable t) {\n //no-op\n }\n }\n\n if (!remove && mergedList.length() < maxValNum) {\n\n for (int i = ridx; i < rsize; i++) {\n\n try {\n if (!dupSetForAdd.get(i + lsize)) {\n mergedList.put(right.get(i));\n }\n } catch (Throwable t) {\n //no-op\n }\n }\n }\n\n // check to see if the list got trimmed in the merge\n if (ridx > 0 || lidx > 0) {\n vr.setErrorDesc(\"Multi value property for key \" + key + \" exceeds the limit of \" + maxValNum + \" items. Trimmed\");\n vr.setErrorCode(521);\n }\n\n vr.setObject(mergedList);\n\n return vr;\n }",
"@SuppressWarnings(\"deprecation\")\n public ResponseFromManager sendTaskToExecutionManager(ParallelTask task) {\n\n ResponseFromManager commandResponseFromManager = null;\n ActorRef executionManager = null;\n try {\n // Start new job\n logger.info(\"!!STARTED sendAgentCommandToManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr());\n\n executionManager = ActorConfig.createAndGetActorSystem().actorOf(\n Props.create(ExecutionManager.class, task),\n \"ExecutionManager-\" + task.getTaskId());\n\n final FiniteDuration duration = Duration.create(task.getConfig()\n .getTimeoutAskManagerSec(), TimeUnit.SECONDS);\n // Timeout timeout = new\n // Timeout(FiniteDuration.parse(\"300 seconds\"));\n Future<Object> future = Patterns.ask(executionManager,\n new InitialRequestToManager(task), new Timeout(duration));\n\n // set ref\n task.executionManager = executionManager;\n\n commandResponseFromManager = (ResponseFromManager) Await.result(\n future, duration);\n\n logger.info(\"!!COMPLETED sendTaskToExecutionManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr()\n + \" \\t\\t GenericResponseMap in future size: \"\n + commandResponseFromManager.getResponseCount());\n\n } catch (Exception ex) {\n logger.error(\"Exception in sendTaskToExecutionManager {} details {}: \",\n ex, ex);\n\n } finally {\n // stop the manager\n if (executionManager != null && !executionManager.isTerminated()) {\n ActorConfig.createAndGetActorSystem().stop(executionManager);\n }\n\n if (task.getConfig().isAutoSaveLogToLocal()) {\n task.saveLogToLocal();\n }\n\n }\n\n return commandResponseFromManager;\n\n }",
"public final void notifyContentItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n if (position < 0 || position >= newContentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position + \" is not within the position bounds for content items [0 - \" + (newContentItemCount - 1) + \"].\");\n }\n notifyItemInserted(position + newHeaderItemCount);\n }",
"public static AbstractReportGenerator generateHtml5Report() {\n AbstractReportGenerator report;\n try {\n Class<?> aClass = new ReportGenerator().getClass().getClassLoader()\n .loadClass( \"com.tngtech.jgiven.report.html5.Html5ReportGenerator\" );\n report = (AbstractReportGenerator) aClass.newInstance();\n } catch( ClassNotFoundException e ) {\n throw new JGivenInstallationException( \"The JGiven HTML5 Report Generator seems not to be on the classpath.\\n\"\n + \"Ensure that you have a dependency to jgiven-html5-report.\" );\n } catch( Exception e ) {\n throw new JGivenInternalDefectException( \"The HTML5 Report Generator could not be instantiated.\", e );\n }\n return report;\n }",
"public void store(Object obj) throws PersistenceBrokerException\n {\n obj = extractObjectToStore(obj);\n // only do something if obj != null\n if(obj == null) return;\n\n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n /*\n if one of the PK fields was null, we assume the objects\n was new and needs insert\n */\n boolean insert = serviceBrokerHelper().hasNullPKField(cld, obj);\n Identity oid = serviceIdentity().buildIdentity(cld, obj);\n /*\n if PK values are set, lookup cache or db to see whether object\n needs insert or update\n */\n if (!insert)\n {\n insert = objectCache.lookup(oid) == null\n && !serviceBrokerHelper().doesExist(cld, oid, obj);\n }\n store(obj, oid, cld, insert);\n }",
"@SuppressWarnings(\"boxing\")\r\n public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) {\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n\r\n // Flickr seems to return invalid token sometimes so retry a few times.\r\n // See http://www.flickr.com/groups/api/discuss/72157628028927244/\r\n OAuth1Token accessToken = null;\r\n boolean success = false;\r\n for (int i = 0; i < maxGetTokenRetries && !success; i++) {\r\n try {\r\n accessToken = service.getAccessToken(oAuthRequestToken, verifier);\r\n success = true;\r\n } catch (OAuthException | IOException | InterruptedException | ExecutionException e) {\r\n if (i == maxGetTokenRetries - 1) {\r\n logger.error(String.format(\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\", i), e);\r\n throw new FlickrRuntimeException(e);\r\n } else {\r\n logger.warn(String.format(\"OAuthService.getAccessToken failed, try number %d: %s\", i, e.getMessage()));\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n }\r\n\r\n return accessToken;\r\n }",
"final public void setRealOffset(Integer start, Integer end) {\n if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\n \"Start real offset after end real offset\");\n } else {\n tokenRealOffset = new MtasOffset(start, end);\n }\n }",
"private void getMultipleValues(Method method, Object object, Map<String, String> map)\n {\n try\n {\n int index = 1;\n while (true)\n {\n Object value = filterValue(method.invoke(object, Integer.valueOf(index)));\n if (value != null)\n {\n map.put(getPropertyName(method, index), String.valueOf(value));\n }\n ++index;\n }\n }\n catch (Exception ex)\n {\n // Reached the end of the valid indexes\n }\n }",
"public void addDefaultCalendarHours(Day day)\n {\n ProjectCalendarHours hours = addCalendarHours(day);\n\n if (day != Day.SATURDAY && day != Day.SUNDAY)\n {\n hours.addRange(DEFAULT_WORKING_MORNING);\n hours.addRange(DEFAULT_WORKING_AFTERNOON);\n }\n }"
] |
Return true if the expression is a constructor call on a class that matches the supplied.
@param expression - the expression
@param classNamePattern - the possible List of class names
@return as described | [
"public static boolean isConstructorCall(Expression expression, String classNamePattern) {\r\n return expression instanceof ConstructorCallExpression && expression.getType().getName().matches(classNamePattern);\r\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}",
"protected void recordContentLoader(final String patchID, final PatchContentLoader contentLoader) {\n if (contentLoaders.containsKey(patchID)) {\n throw new IllegalStateException(\"Content loader already registered for patch \" + patchID); // internal wrong usage, no i18n\n }\n contentLoaders.put(patchID, contentLoader);\n }",
"private static String createImageStreamRequest(String name, String version, String image, boolean insecure) {\n JSONObject imageStream = new JSONObject();\n JSONObject metadata = new JSONObject();\n JSONObject annotations = new JSONObject();\n\n metadata.put(\"name\", name);\n annotations.put(\"openshift.io/image.insecureRepository\", insecure);\n metadata.put(\"annotations\", annotations);\n\n // Definition of the image\n JSONObject from = new JSONObject();\n from.put(\"kind\", \"DockerImage\");\n from.put(\"name\", image);\n\n JSONObject importPolicy = new JSONObject();\n importPolicy.put(\"insecure\", insecure);\n\n JSONObject tag = new JSONObject();\n tag.put(\"name\", version);\n tag.put(\"from\", from);\n tag.put(\"importPolicy\", importPolicy);\n\n JSONObject tagAnnotations = new JSONObject();\n tagAnnotations.put(\"version\", version);\n tag.put(\"annotations\", tagAnnotations);\n\n JSONArray tags = new JSONArray();\n tags.add(tag);\n\n // Add image definition to image stream\n JSONObject spec = new JSONObject();\n spec.put(\"tags\", tags);\n\n imageStream.put(\"kind\", \"ImageStream\");\n imageStream.put(\"apiVersion\", \"v1\");\n imageStream.put(\"metadata\", metadata);\n imageStream.put(\"spec\", spec);\n\n return imageStream.toJSONString();\n }",
"public void promoteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.promoteModulePath(name, version));\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"promote module\", name, version);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"void addOption(final String value) {\n Assert.checkNotNullParam(\"value\", value);\n synchronized (options) {\n options.add(value);\n }\n }",
"public void addPieSlice(PieModel _Slice) {\n highlightSlice(_Slice);\n mPieData.add(_Slice);\n mTotalValue += _Slice.getValue();\n onDataChanged();\n }",
"public static Document readDocumentFromString(String s) throws Exception {\r\n InputSource in = new InputSource(new StringReader(s));\r\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n factory.setNamespaceAware(false);\r\n return factory.newDocumentBuilder().parse(in);\r\n }",
"public boolean isValid() {\n\t\tif(parsedHost != null) {\n\t\t\treturn true;\n\t\t}\n\t\tif(validationException != null) {\n\t\t\treturn false;\n\t\t}\n\t\ttry {\n\t\t\tvalidate();\n\t\t\treturn true;\n\t\t} catch(HostNameException e) {\n\t\t\treturn false;\n\t\t}\n\t}",
"private void addStatement(RecordImpl record,\n String subject,\n String property,\n String object) {\n Collection<Column> cols = columns.get(property);\n if (cols == null) {\n if (property.equals(RDF_TYPE) && !types.isEmpty())\n addValue(record, subject, property, object);\n return;\n }\n \n for (Column col : cols) {\n String cleaned = object;\n if (col.getCleaner() != null)\n cleaned = col.getCleaner().clean(object);\n if (cleaned != null && !cleaned.equals(\"\"))\n addValue(record, subject, col.getProperty(), cleaned);\n }\n }"
] |
Add key value pair to extra info
@param key Key of new item
@param value New value to add | [
"public void addExtraInfo(String key, Object value) {\n // Turn extraInfo into map\n Map<String, Object> infoMap = (HashMap<String, Object>)getMapFromJSON(extraInfo);\n // Add value\n infoMap.put(key, value);\n\n // Turn back into string\n extraInfo = getJSONFromMap(infoMap);\n }"
] | [
"@SuppressWarnings(\"unchecked\")\n\tpublic Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException {\n\t\treturn decodeSignedRequest(signedRequest, Map.class);\n\t}",
"static void checkUpgradeConditions(final UpgradeCondition condition, final InstallationManager.MutablePatchingTarget target) throws PatchingException {\n // See if the prerequisites are met\n for (final String required : condition.getRequires()) {\n if (!target.isApplied(required)) {\n throw PatchLogger.ROOT_LOGGER.requiresPatch(required);\n }\n }\n // Check for incompatibilities\n for (final String incompatible : condition.getIncompatibleWith()) {\n if (target.isApplied(incompatible)) {\n throw PatchLogger.ROOT_LOGGER.incompatiblePatch(incompatible);\n }\n }\n }",
"public Collection<V> put(K key, Collection<V> collection) {\r\n return map.put(key, collection);\r\n }",
"static GVROrthogonalCamera makeOrthoShadowCamera(GVRPerspectiveCamera centerCam)\n {\n GVROrthogonalCamera shadowCam = new GVROrthogonalCamera(centerCam.getGVRContext());\n float near = centerCam.getNearClippingDistance();\n float far = centerCam.getFarClippingDistance();\n float fovy = (float) Math.toRadians(centerCam.getFovY());\n float h = (float) (Math.atan(fovy / 2.0f) * far) / 2.0f;\n\n shadowCam.setLeftClippingDistance(-h);\n shadowCam.setRightClippingDistance(h);\n shadowCam.setTopClippingDistance(h);\n shadowCam.setBottomClippingDistance(-h);\n shadowCam.setNearClippingDistance(near);\n shadowCam.setFarClippingDistance(far);\n return shadowCam;\n }",
"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}",
"@Inline(value = \"$1.remove($2)\", statementExpression = true)\n\tpublic static <K, V> V operator_remove(Map<K, V> map, K key) {\n\t\treturn map.remove(key);\n\t}",
"public static long randomLongBetween(long min, long max) {\n Random rand = new Random();\n return min + (long) (rand.nextDouble() * (max - min));\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 }",
"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 }"
] |
Determine whether all references are available locally.
@param domain the domain model
@param hostElement the host path element
@return whether to a sync with the master is required | [
"private static boolean syncWithMaster(final Resource domain, final PathElement hostElement) {\n final Resource host = domain.getChild(hostElement);\n assert host != null;\n\n final Set<String> profiles = new HashSet<>();\n final Set<String> serverGroups = new HashSet<>();\n final Set<String> socketBindings = new HashSet<>();\n\n for (final Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {\n final ModelNode model = serverConfig.getModel();\n final String group = model.require(GROUP).asString();\n if (!serverGroups.contains(group)) {\n serverGroups.add(group);\n }\n if (model.hasDefined(SOCKET_BINDING_GROUP)) {\n processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings);\n }\n\n }\n\n // process referenced server-groups\n for (final Resource.ResourceEntry serverGroup : domain.getChildren(SERVER_GROUP)) {\n // If we have an unreferenced server-group\n if (!serverGroups.remove(serverGroup.getName())) {\n return true;\n }\n final ModelNode model = serverGroup.getModel();\n\n final String profile = model.require(PROFILE).asString();\n // Process the profile\n processProfile(domain, profile, profiles);\n // Process the socket-binding-group\n processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings);\n }\n // If we are missing a server group\n if (!serverGroups.isEmpty()) {\n return true;\n }\n // Process profiles\n for (final Resource.ResourceEntry profile : domain.getChildren(PROFILE)) {\n // We have an unreferenced profile\n if (!profiles.remove(profile.getName())) {\n return true;\n }\n }\n // We are missing a profile\n if (!profiles.isEmpty()) {\n return true;\n }\n // Process socket-binding groups\n for (final Resource.ResourceEntry socketBindingGroup : domain.getChildren(SOCKET_BINDING_GROUP)) {\n // We have an unreferenced socket-binding group\n if (!socketBindings.remove(socketBindingGroup.getName())) {\n return true;\n }\n }\n // We are missing a socket-binding group\n if (!socketBindings.isEmpty()) {\n return true;\n }\n // Looks good!\n return false;\n }"
] | [
"public static boolean isPrimitiveArray(Class<?> clazz) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\treturn (clazz.isArray() && clazz.getComponentType().isPrimitive());\n\t}",
"private void handleContentLength(Event event) {\n if (event.getContent() == null) {\n return;\n }\n\n if (maxContentLength == -1 || event.getContent().length() <= maxContentLength) {\n return;\n }\n\n if (maxContentLength < CUT_START_TAG.length() + CUT_END_TAG.length()) {\n event.setContent(\"\");\n event.setContentCut(true);\n return;\n }\n\n int contentLength = maxContentLength - CUT_START_TAG.length() - CUT_END_TAG.length();\n event.setContent(CUT_START_TAG + event.getContent().substring(0, contentLength) + CUT_END_TAG);\n event.setContentCut(true);\n }",
"public static void addToListIfNotExists(List<String> list, String value) {\n boolean found = false;\n for (String item : list) {\n if (item.equalsIgnoreCase(value)) {\n found = true;\n break;\n }\n }\n if (!found) {\n list.add(value);\n }\n }",
"public PayloadBuilder customField(final String key, final Object value) {\n root.put(key, value);\n return this;\n }",
"public String generateInitScript(EnvVars env) throws IOException, InterruptedException {\n StringBuilder initScript = new StringBuilder();\n InputStream templateStream = getClass().getResourceAsStream(\"/initscripttemplate.gradle\");\n String templateAsString = IOUtils.toString(templateStream, Charsets.UTF_8.name());\n File extractorJar = PluginDependencyHelper.getExtractorJar(env);\n FilePath dependencyDir = PluginDependencyHelper.getActualDependencyDirectory(extractorJar, rootPath);\n String absoluteDependencyDirPath = dependencyDir.getRemote();\n absoluteDependencyDirPath = absoluteDependencyDirPath.replace(\"\\\\\", \"/\");\n String str = templateAsString.replace(\"${pluginLibDir}\", absoluteDependencyDirPath);\n initScript.append(str);\n return initScript.toString();\n }",
"public static String getExtensionByMimeType(String type) {\n MimeTypes types = getDefaultMimeTypes();\n try {\n return types.forName(type).getExtension();\n } catch (Exception e) {\n LOGGER.warn(\"Can't detect extension for MIME-type \" + type, e);\n return \"\";\n }\n }",
"public void start() {\n syncLock.lock();\n try {\n if (!this.isConfigured) {\n return;\n }\n instanceChangeStreamListener.stop();\n if (listenersEnabled) {\n instanceChangeStreamListener.start();\n }\n\n if (syncThread == null) {\n syncThread = new Thread(\n new DataSynchronizerRunner(\n new WeakReference<>(this),\n networkMonitor,\n logger\n ),\n \"dataSynchronizerRunnerThread\"\n );\n }\n if (syncThreadEnabled && !isRunning) {\n syncThread.start();\n isRunning = true;\n }\n } finally {\n syncLock.unlock();\n }\n }",
"protected void switchTab() {\n\n Component tab = m_tab.getSelectedTab();\n int pos = m_tab.getTabPosition(m_tab.getTab(tab));\n if (m_isWebOU) {\n if (pos == 0) {\n pos = 1;\n }\n }\n m_tab.setSelectedTab(pos + 1);\n }",
"public static appflowpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tappflowpolicylabel response = (appflowpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Determines the accessor method name based on a field name.
@param fieldName
a field name
@return the resulting method name | [
"public static String determineAccessorName(@Nonnull final AccessorPrefix prefix, @Nonnull final String fieldName) {\n\t\tCheck.notNull(prefix, \"prefix\");\n\t\tCheck.notEmpty(fieldName, \"fieldName\");\n\t\tfinal Matcher m = PATTERN.matcher(fieldName);\n\t\tCheck.stateIsTrue(m.find(), \"passed field name '%s' is not applicable\", fieldName);\n\t\tfinal String name = m.group();\n\t\treturn prefix.getPrefix() + name.substring(0, 1).toUpperCase() + name.substring(1);\n\t}"
] | [
"private EditorState getMasterState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(4);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.DESCRIPTION);\n cols.add(TableProperty.DEFAULT);\n cols.add(TableProperty.TRANSLATION);\n return new EditorState(cols, true);\n }",
"public static nslimitidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tnslimitidentifier_stats obj = new nslimitidentifier_stats();\n\t\tobj.set_name(name);\n\t\tnslimitidentifier_stats response = (nslimitidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) {\n String separator = launcher.isUnix() ? \"/\" : \"\\\\\";\n String java_home = extendedEnv.get(\"JAVA_HOME\");\n if (StringUtils.isNotEmpty(java_home)) {\n if (!StringUtils.endsWith(java_home, separator)) {\n java_home += separator;\n }\n extendedEnv.put(\"PATH+JDK\", java_home + \"bin\");\n }\n }",
"private void cleanupLogs() throws IOException {\n logger.trace(\"Beginning log cleanup...\");\n int total = 0;\n Iterator<Log> iter = getLogIterator();\n long startMs = System.currentTimeMillis();\n while (iter.hasNext()) {\n Log log = iter.next();\n total += cleanupExpiredSegments(log) + cleanupSegmentsToMaintainSize(log);\n }\n if (total > 0) {\n logger.warn(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n } else {\n logger.trace(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n }\n }",
"private void readRecord(Tokenizer tk, List<String> record) throws IOException\n {\n record.clear();\n while (tk.nextToken() == Tokenizer.TT_WORD)\n {\n record.add(tk.getToken());\n }\n }",
"public static base_responses update(nitro_service client, snmpuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpuser updateresources[] = new snmpuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpuser();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].group = resources[i].group;\n\t\t\t\tupdateresources[i].authtype = resources[i].authtype;\n\t\t\t\tupdateresources[i].authpasswd = resources[i].authpasswd;\n\t\t\t\tupdateresources[i].privtype = resources[i].privtype;\n\t\t\t\tupdateresources[i].privpasswd = resources[i].privpasswd;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public String lookupUser(String url) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_USER);\r\n\r\n parameters.put(\"url\", url);\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\r\n Element payload = response.getPayload();\r\n Element groupnameElement = (Element) payload.getElementsByTagName(\"username\").item(0);\r\n return ((Text) groupnameElement.getFirstChild()).getData();\r\n }",
"private int findAvailablePortNumber( Integer portNumberStartingPoint, List<Integer> reservedPorts )\n {\n assert portNumberStartingPoint != null;\n int candidate = portNumberStartingPoint;\n while ( reservedPorts.contains( candidate ) )\n {\n candidate++;\n }\n return candidate;\n }",
"private void readRelationships()\n {\n for (MapRow row : m_tables.get(\"REL\"))\n {\n Task predecessor = m_activityMap.get(row.getString(\"PREDECESSOR_ACTIVITY_ID\"));\n Task successor = m_activityMap.get(row.getString(\"SUCCESSOR_ACTIVITY_ID\"));\n if (predecessor != null && successor != null)\n {\n Duration lag = row.getDuration(\"LAG_VALUE\");\n RelationType type = row.getRelationType(\"LAG_TYPE\");\n\n successor.addPredecessor(predecessor, type, lag);\n }\n }\n }"
] |
Method is called by spring and verifies that there is only one plugin per URI scheme. | [
"@PostConstruct\n public void checkUniqueSchemes() {\n Multimap<String, ConfigFileLoaderPlugin> schemeToPluginMap = HashMultimap.create();\n\n for (ConfigFileLoaderPlugin plugin: getLoaderPlugins()) {\n schemeToPluginMap.put(plugin.getUriScheme(), plugin);\n }\n\n StringBuilder violations = new StringBuilder();\n for (String scheme: schemeToPluginMap.keySet()) {\n final Collection<ConfigFileLoaderPlugin> plugins = schemeToPluginMap.get(scheme);\n if (plugins.size() > 1) {\n violations.append(\"\\n\\n* \").append(\"There are has multiple \")\n .append(ConfigFileLoaderPlugin.class.getSimpleName())\n .append(\" plugins that support the scheme: '\").append(scheme).append('\\'')\n .append(\":\\n\\t\").append(plugins);\n }\n }\n\n if (violations.length() > 0) {\n throw new IllegalStateException(violations.toString());\n }\n }"
] | [
"public ItemRequest<Task> dependencies(String task) {\n \n String path = String.format(\"/tasks/%s/dependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public static vpnglobal_authenticationsamlpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_authenticationsamlpolicy_binding obj = new vpnglobal_authenticationsamlpolicy_binding();\n\t\tvpnglobal_authenticationsamlpolicy_binding response[] = (vpnglobal_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void value2x2_fast( double a11 , double a12, double a21 , double a22 )\n {\n double left = (a11+a22)/2.0;\n double inside = 4.0*a12*a21 + (a11-a22)*(a11-a22);\n\n if( inside < 0 ) {\n value0.real = value1.real = left;\n value0.imaginary = Math.sqrt(-inside)/2.0;\n value1.imaginary = -value0.imaginary;\n } else {\n double right = Math.sqrt(inside)/2.0;\n value0.real = (left+right);\n value1.real = (left-right);\n value0.imaginary = value1.imaginary = 0.0;\n }\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 }",
"@UiHandler(\"m_currentTillEndCheckBox\")\n void onCurrentTillEndChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setCurrentTillEnd(event.getValue());\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 static void doMetaUpdateVersionsOnStores(AdminClient adminClient,\n List<StoreDefinition> oldStoreDefs,\n List<StoreDefinition> newStoreDefs) {\n Set<String> storeNamesUnion = new HashSet<String>();\n Map<String, StoreDefinition> oldStoreDefinitionMap = new HashMap<String, StoreDefinition>();\n Map<String, StoreDefinition> newStoreDefinitionMap = new HashMap<String, StoreDefinition>();\n List<String> storesChanged = new ArrayList<String>();\n for(StoreDefinition storeDef: oldStoreDefs) {\n String storeName = storeDef.getName();\n storeNamesUnion.add(storeName);\n oldStoreDefinitionMap.put(storeName, storeDef);\n }\n for(StoreDefinition storeDef: newStoreDefs) {\n String storeName = storeDef.getName();\n storeNamesUnion.add(storeName);\n newStoreDefinitionMap.put(storeName, storeDef);\n }\n for(String storeName: storeNamesUnion) {\n StoreDefinition oldStoreDef = oldStoreDefinitionMap.get(storeName);\n StoreDefinition newStoreDef = newStoreDefinitionMap.get(storeName);\n if(oldStoreDef == null && newStoreDef != null || oldStoreDef != null\n && newStoreDef == null || oldStoreDef != null && newStoreDef != null\n && !oldStoreDef.equals(newStoreDef)) {\n storesChanged.add(storeName);\n }\n }\n System.out.println(\"Updating metadata version for the following stores: \"\n + storesChanged);\n try {\n adminClient.metadataMgmtOps.updateMetadataversion(adminClient.getAdminClientCluster()\n .getNodeIds(),\n storesChanged);\n } catch(Exception e) {\n System.err.println(\"Error while updating metadata version for the specified store.\");\n }\n }",
"public static base_response delete(nitro_service client, String serverip) throws Exception {\n\t\tntpserver deleteresource = new ntpserver();\n\t\tdeleteresource.serverip = serverip;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private static BindingType map2BindingType(String bindingId) {\n BindingType type;\n if (SOAP11_BINDING_ID.equals(bindingId)) {\n type = BindingType.SOAP11;\n } else if (SOAP12_BINDING_ID.equals(bindingId)) {\n type = BindingType.SOAP12;\n } else if (JAXRS_BINDING_ID.equals(bindingId)) {\n type = BindingType.JAXRS;\n } else {\n type = BindingType.OTHER;\n }\n return type;\n }"
] |
Returns true if the activity is a milestone.
@param activity Phoenix activity
@return true if the activity is a milestone | [
"private boolean activityIsMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"Milestone\") != -1;\n }"
] | [
"public void handleChange(Object propertyId) {\n\n try {\n lockOnChange(propertyId);\n } catch (CmsException e) {\n LOG.debug(e);\n }\n if (isDescriptorProperty(propertyId)) {\n m_descriptorHasChanges = true;\n }\n if (isBundleProperty(propertyId)) {\n m_changedTranslations.add(getLocale());\n }\n\n }",
"public final void addRule(TableRowStyle style){\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN, \"cannot add a rule of unknown style\");\r\n\t\tthis.rows.add(AT_Row.createRule(TableRowType.RULE, style));\r\n\t}",
"private Envelope getBoundsLocal(Filter filter) throws LayerException {\n\t\ttry {\n\t\t\tSession session = getSessionFactory().getCurrentSession();\n\t\t\tCriteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());\n\t\t\tCriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);\n\t\t\tCriterion c = (Criterion) filter.accept(visitor, criteria);\n\t\t\tif (c != null) {\n\t\t\t\tcriteria.add(c);\n\t\t\t}\n\t\t\tcriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\t\t\tList<?> features = criteria.list();\n\t\t\tEnvelope bounds = new Envelope();\n\t\t\tfor (Object f : features) {\n\t\t\t\tEnvelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();\n\t\t\t\tif (!geomBounds.isNull()) {\n\t\t\t\t\tbounds.expandToInclude(geomBounds);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bounds;\n\t\t} catch (HibernateException he) {\n\t\t\tthrow new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()\n\t\t\t\t\t.getDataSourceName(), filter.toString());\n\t\t}\n\t}",
"private void checkRowReader(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String rowReaderName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_ROW_READER);\r\n\r\n if (rowReaderName == null)\r\n {\r\n return;\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(rowReaderName, ROW_READER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+rowReaderName+\" specified as row-reader of class \"+classDef.getName()+\" does not implement the interface \"+ROW_READER_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the row-reader class \"+rowReaderName+\" of class \"+classDef.getName());\r\n }\r\n }",
"public static Dimension rectangleDoubleToDimension(final Rectangle2D.Double rectangle) {\n return new Dimension(\n (int) Math.round(rectangle.width),\n (int) Math.round(rectangle.height));\n }",
"public final boolean roll(final LoggingEvent loggingEvent) {\n for (int i = 0; i < this.fileRollables.length; i++) {\n if (this.fileRollables[i].roll(loggingEvent)) {\n return true;\n }\n }\n return false;\n }",
"protected Connection newConnectionFromDriverManager(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JDBC DriverManager\r\n final String driver = jcd.getDriver();\r\n final String url = getDbURL(jcd);\r\n try\r\n {\r\n // loads the driver - NB call to newInstance() added to force initialisation\r\n ClassHelper.getClass(driver, true);\r\n final String user = jcd.getUserName();\r\n final String password = jcd.getPassWord();\r\n final Properties properties = getJdbcProperties(jcd, user, password);\r\n if (properties.isEmpty())\r\n {\r\n if (user == null)\r\n {\r\n retval = DriverManager.getConnection(url);\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, user, password);\r\n }\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, properties);\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n throw new LookupException(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n }\r\n catch (ClassNotFoundException cnfEx)\r\n {\r\n log.error(cnfEx);\r\n throw new LookupException(\"A class was not found\", cnfEx);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Instantiation of jdbc driver failed\", e);\r\n throw new LookupException(\"Instantiation of jdbc driver failed\", e);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DriverManager: \"+retval);\r\n return retval;\r\n }",
"public Map<String, ClientWidgetInfo> securityClone(Map<String, ClientWidgetInfo> widgetInfo) {\n\t\tMap<String, ClientWidgetInfo> res = new HashMap<String, ClientWidgetInfo>();\n\t\tfor (Map.Entry<String, ClientWidgetInfo> entry : widgetInfo.entrySet()) {\n\t\t\tClientWidgetInfo value = entry.getValue();\n\t\t\tif (!(value instanceof ServerSideOnlyInfo)) {\n\t\t\t\tres.put(entry.getKey(), value);\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}",
"public void refresh() {\n this.getRefreshLock().writeLock().lock();\n\n try {\n this.authenticate();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n this.getRefreshLock().writeLock().unlock();\n throw e;\n }\n\n this.notifyRefresh();\n this.getRefreshLock().writeLock().unlock();\n }"
] |
Computes either the vector p-norm or the induced matrix p-norm depending on A
being a vector or a matrix respectively.
@param A Vector or matrix whose norm is to be computed.
@param p The p value of the p-norm.
@return The computed norm. | [
"public static double normP(DMatrixRMaj A , double p ) {\n if( p == 1 ) {\n return normP1(A);\n } else if( p == 2 ) {\n return normP2(A);\n } else if( Double.isInfinite(p)) {\n return normPInf(A);\n }\n if( MatrixFeatures_DDRM.isVector(A) ) {\n return elementP(A,p);\n } else {\n throw new IllegalArgumentException(\"Doesn't support induced norms yet.\");\n }\n }"
] | [
"private void processFileType(String token) throws MPXJException\n {\n String version = token.substring(2).split(\" \")[0];\n //System.out.println(version);\n Class<? extends AbstractFileFormat> fileFormatClass = FILE_VERSION_MAP.get(Integer.valueOf(version));\n if (fileFormatClass == null)\n {\n throw new MPXJException(\"Unsupported PP file format version \" + version);\n }\n\n try\n {\n AbstractFileFormat format = fileFormatClass.newInstance();\n m_tableDefinitions = format.tableDefinitions();\n m_epochDateFormat = format.epochDateFormat();\n }\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to configure file format\", ex);\n }\n }",
"private float newRandomIndividualParticleRadius(@NonNull final SceneConfiguration scene) {\n return scene.getParticleRadiusMin() == scene.getParticleRadiusMax() ?\n scene.getParticleRadiusMin() : scene.getParticleRadiusMin() + (random.nextInt(\n (int) ((scene.getParticleRadiusMax() - scene.getParticleRadiusMin()) * 100f)))\n / 100f;\n }",
"public static float noise2(float x, float y) {\n int bx0, bx1, by0, by1, b00, b10, b01, b11;\n float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v;\n int i, j;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n t = y + N;\n by0 = ((int)t) & BM;\n by1 = (by0+1) & BM;\n ry0 = t - (int)t;\n ry1 = ry0 - 1.0f;\n\n i = p[bx0];\n j = p[bx1];\n\n b00 = p[i + by0];\n b10 = p[j + by0];\n b01 = p[i + by1];\n b11 = p[j + by1];\n\n sx = sCurve(rx0);\n sy = sCurve(ry0);\n\n q = g2[b00]; u = rx0 * q[0] + ry0 * q[1];\n q = g2[b10]; v = rx1 * q[0] + ry0 * q[1];\n a = lerp(sx, u, v);\n\n q = g2[b01]; u = rx0 * q[0] + ry1 * q[1];\n q = g2[b11]; v = rx1 * q[0] + ry1 * q[1];\n b = lerp(sx, u, v);\n\n return 1.5f*lerp(sy, a, b);\n }",
"public ProjectCalendar addResourceCalendar() throws MPXJException\n {\n if (getResourceCalendar() != null)\n {\n throw new MPXJException(MPXJException.MAXIMUM_RECORDS);\n }\n\n ProjectCalendar calendar = new ProjectCalendar(getParentFile());\n setResourceCalendar(calendar);\n return calendar;\n }",
"public static void resize(GVRMesh mesh, float size) {\n float dim[] = getBoundingSize(mesh);\n float maxsize = 0.0f;\n\n if (dim[0] > maxsize) maxsize = dim[0];\n if (dim[1] > maxsize) maxsize = dim[1];\n if (dim[2] > maxsize) maxsize = dim[2];\n\n scale(mesh, size / maxsize);\n }",
"@Override\n\tpublic void format(final StringBuffer sbuf, final LoggingEvent event) {\n\t\tfor (int i = 0; i < patternConverters.length; i++) {\n\t\t\tfinal int startField = sbuf.length();\n\t\t\tpatternConverters[i].format(event, sbuf);\n\t\t\tpatternFields[i].format(startField, sbuf);\n\t\t}\n\t}",
"public void work(RepositoryHandler repoHandler, DbProduct product) {\n if (!product.getDeliveries().isEmpty()) {\n\n product.getDeliveries().forEach(delivery -> {\n\n final Set<Artifact> artifacts = new HashSet<>();\n\n final DataFetchingUtils utils = new DataFetchingUtils();\n final DependencyHandler depHandler = new DependencyHandler(repoHandler);\n final Set<String> deliveryDependencies = utils.getDeliveryDependencies(repoHandler, depHandler, delivery);\n\n final Set<String> fullGAVCSet = deliveryDependencies.stream().filter(DataUtils::isFullGAVC).collect(Collectors.toSet());\n final Set<String> shortIdentiferSet = deliveryDependencies.stream().filter(entry -> !DataUtils.isFullGAVC(entry)).collect(Collectors.toSet());\n\n\n processDependencySet(repoHandler,\n shortIdentiferSet,\n batch -> String.format(BATCH_TEMPLATE_REGEX, StringUtils.join(batch, '|')),\n 1,\n artifacts::add\n );\n\n processDependencySet(repoHandler,\n fullGAVCSet,\n batch -> QueryUtils.quoteIds(batch, BATCH_TEMPLATE),\n 10,\n artifacts::add\n );\n\n if (!artifacts.isEmpty()) {\n delivery.setAllArtifactDependencies(new ArrayList<>(artifacts));\n }\n });\n\n repoHandler.store(product);\n }\n }",
"public String addExtent(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n\r\n if (!_model.hasClass(name))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_FIND_TYPE,\r\n new String[]{name}));\r\n }\r\n _curClassDef.addExtentClass(_model.getClass(name));\r\n return \"\";\r\n }",
"public OperationTransformerEntry resolveOperationTransformer(final PathAddress address, final String operationName, PlaceholderResolver placeholderResolver) {\n final Iterator<PathElement> iterator = address.iterator();\n final OperationTransformerEntry entry = resolveOperationTransformer(iterator, operationName, placeholderResolver);\n if(entry != null) {\n return entry;\n }\n // Default is forward unchanged\n return FORWARD;\n }"
] |
Sets selected page implicitly
@param page new selected page
@return true if the page has been selected successfully | [
"public boolean setCurrentPage(final int page) {\n Log.d(TAG, \"setPageId pageId = %d\", page);\n return (page >= 0 && page < getCheckableCount()) && check(page);\n }"
] | [
"public static Map<String, StoreDefinition> getUserStoreDefMapOnNode(AdminClient adminClient,\n Integer nodeId) {\n List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n Map<String, StoreDefinition> storeDefinitionMap = Maps.newHashMap();\n for(StoreDefinition storeDefinition: storeDefinitionList) {\n storeDefinitionMap.put(storeDefinition.getName(), storeDefinition);\n }\n return storeDefinitionMap;\n }",
"public RedwoodConfiguration captureStdout(){\r\n tasks.add(new Runnable() { public void run() { Redwood.captureSystemStreams(true, false); } });\r\n return this;\r\n }",
"public com.squareup.okhttp.Call getCharactersCharacterIdShipCall(Integer characterId, String datasource,\n String ifNoneMatch, String token, final ApiCallback callback) throws ApiException {\n Object localVarPostBody = new Object();\n\n // create path and map variables\n String localVarPath = \"/v1/characters/{character_id}/ship/\".replaceAll(\"\\\\{\" + \"character_id\" + \"\\\\}\",\n apiClient.escapeString(characterId.toString()));\n\n List<Pair> localVarQueryParams = new ArrayList<Pair>();\n List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();\n if (datasource != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"datasource\", datasource));\n }\n\n if (token != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"token\", token));\n }\n\n Map<String, String> localVarHeaderParams = new HashMap<String, String>();\n if (ifNoneMatch != null) {\n localVarHeaderParams.put(\"If-None-Match\", apiClient.parameterToString(ifNoneMatch));\n }\n\n Map<String, Object> localVarFormParams = new HashMap<String, Object>();\n final String[] localVarAccepts = { \"application/json\" };\n final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);\n if (localVarAccept != null) {\n localVarHeaderParams.put(\"Accept\", localVarAccept);\n }\n\n final String[] localVarContentTypes = {\n\n };\n final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);\n localVarHeaderParams.put(\"Content-Type\", localVarContentType);\n\n String[] localVarAuthNames = new String[] { \"evesso\" };\n return apiClient.buildCall(localVarPath, \"GET\", localVarQueryParams, localVarCollectionQueryParams,\n localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);\n }",
"private void populateDefaultData(FieldItem[] defaultData)\n {\n for (FieldItem item : defaultData)\n {\n m_map.put(item.getType(), item);\n }\n }",
"private GraphicalIndicatorCriteria processCriteria(FieldType type)\n {\n GraphicalIndicatorCriteria criteria = new GraphicalIndicatorCriteria(m_properties);\n criteria.setLeftValue(type);\n\n int indicatorType = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n criteria.setIndicator(indicatorType);\n\n if (m_dataOffset + 4 < m_data.length)\n {\n int operatorValue = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n TestOperator operator = (operatorValue == 0 ? TestOperator.IS_ANY_VALUE : TestOperator.getInstance(operatorValue - 0x3E7));\n criteria.setOperator(operator);\n\n if (operator != TestOperator.IS_ANY_VALUE)\n {\n processOperandValue(0, type, criteria);\n\n if (operator == TestOperator.IS_WITHIN || operator == TestOperator.IS_NOT_WITHIN)\n {\n processOperandValue(1, type, criteria);\n }\n }\n }\n\n return (criteria);\n }",
"private FilePath copyClassWorldsFile(FilePath ws, URL resource) {\n try {\n FilePath remoteClassworlds =\n ws.createTextTempFile(\"classworlds\", \"conf\", \"\");\n remoteClassworlds.copyFrom(resource);\n return remoteClassworlds;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public Sequence compile( String equation , boolean assignment, boolean debug ) {\n\n functions.setManagerTemp(managerTemp);\n\n Sequence sequence = new Sequence();\n TokenList tokens = extractTokens(equation,managerTemp);\n\n if( tokens.size() < 3 )\n throw new RuntimeException(\"Too few tokens\");\n\n TokenList.Token t0 = tokens.getFirst();\n\n if( t0.word != null && t0.word.compareToIgnoreCase(\"macro\") == 0 ) {\n parseMacro(tokens,sequence);\n } else {\n insertFunctionsAndVariables(tokens);\n insertMacros(tokens);\n if (debug) {\n System.out.println(\"Parsed tokens:\\n------------\");\n tokens.print();\n System.out.println();\n }\n\n // Get the results variable\n if (t0.getType() != Type.VARIABLE && t0.getType() != Type.WORD) {\n compileTokens(sequence,tokens);\n // If there's no output then this is acceptable, otherwise it's assumed to be a bug\n // If there's no output then a configuration was changed\n Variable variable = tokens.getFirst().getVariable();\n if( variable != null ) {\n if( assignment )\n throw new IllegalArgumentException(\"No assignment to an output variable could be found. Found \" + t0);\n else {\n sequence.output = variable; // set this to be the output for print()\n }\n }\n\n } else {\n compileAssignment(sequence, tokens, t0);\n }\n\n if (debug) {\n System.out.println(\"Operations:\\n------------\");\n for (int i = 0; i < sequence.operations.size(); i++) {\n System.out.println(sequence.operations.get(i).name());\n }\n }\n }\n\n return sequence;\n }",
"@Programmatic\n public <T> Blob toExcelPivot(\n final List<T> domainObjects,\n final Class<T> cls,\n final String fileName) throws ExcelService.Exception {\n return toExcelPivot(domainObjects, cls, null, fileName);\n }",
"private Integer getIntegerPropertyOverrideValue(String name, String key) {\n if (properties != null) {\n String propertyName = getPropertyName(name, key);\n\n String propertyOverrideValue = properties.getProperty(propertyName);\n\n if (propertyOverrideValue != null) {\n try {\n return Integer.parseInt(propertyOverrideValue);\n }\n catch (NumberFormatException e) {\n logger.error(\"Could not parse property override key={}, value={}\",\n key, propertyOverrideValue);\n }\n }\n }\n return null;\n }"
] |
Add classes to the map file.
@param writer XML stream writer
@param jarFile jar file
@param mapClassMethods true if we want to produce .Net style class method names
@throws IOException
@throws ClassNotFoundException
@throws XMLStreamException
@throws IntrospectionException | [
"private void addClasses(XMLStreamWriter writer, File jarFile, boolean mapClassMethods) throws IOException, ClassNotFoundException, XMLStreamException, IntrospectionException\n {\n ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();\n\n URLClassLoader loader = new URLClassLoader(new URL[]\n {\n jarFile.toURI().toURL()\n }, currentThreadClassLoader);\n\n JarFile jar = new JarFile(jarFile);\n Enumeration<JarEntry> enumeration = jar.entries();\n while (enumeration.hasMoreElements())\n {\n JarEntry jarEntry = enumeration.nextElement();\n if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(\".class\"))\n {\n addClass(loader, jarEntry, writer, mapClassMethods);\n }\n }\n jar.close();\n }"
] | [
"protected void generateRoutes()\n {\n try {\n\n//\t\t\tOptional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\n//\t\t\ttypeLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t \n//\t\t\t\tio.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();\n//\n//\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\n//\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t{\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\n//\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\n//\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t}\n//\t\t\t\t\n//\t\t\t});\n//\t\t\t\n//\t\t\tfor(Method m : this.controllerClass.getDeclaredMethods())\n//\t\t\t{\n//\t\t\t\n//\t\t\t\tOptional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\t\n//\t\t\t\tmethodLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t\t \n//\t\t\t\t\tio.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();\n//\t\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\t\n//\t\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\t\n//\t\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\t\n//\t\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t});\n//\n//\t\t\t}\n//\t\t\t\n//\t\t\tlog.info(\"handlerWrapperMap: \" + handlerWrapperMap);\n\n TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)\n .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));\n\n ClassName extractorClass = ClassName.get(\"io.sinistral.proteus.server\", \"Extractors\");\n\n ClassName injectClass = ClassName.get(\"com.google.inject\", \"Inject\");\n\n\n MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);\n\n String className = this.controllerClass.getSimpleName().toLowerCase() + \"Controller\";\n\n typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);\n\n ClassName wrapperClass = ClassName.get(\"io.undertow.server\", \"HandlerWrapper\");\n ClassName stringClass = ClassName.get(\"java.lang\", \"String\");\n ClassName mapClass = ClassName.get(\"java.util\", \"Map\");\n\n TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);\n\n TypeName annotatedMapOfWrappers = mapOfWrappers\n .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember(\"value\", \"$S\", \"registeredHandlerWrappers\").build());\n\n typeBuilder.addField(mapOfWrappers, \"registeredHandlerWrappers\", Modifier.PROTECTED, Modifier.FINAL);\n\n\n constructor.addParameter(this.controllerClass, className);\n constructor.addParameter(annotatedMapOfWrappers, \"registeredHandlerWrappers\");\n\n constructor.addStatement(\"this.$N = $N\", className, className);\n constructor.addStatement(\"this.$N = $N\", \"registeredHandlerWrappers\", \"registeredHandlerWrappers\");\n\n addClassMethodHandlers(typeBuilder, this.controllerClass);\n\n typeBuilder.addMethod(constructor.build());\n\n JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, \"*\").build();\n\n StringBuilder sb = new StringBuilder();\n\n javaFile.writeTo(sb);\n\n this.sourceString = sb.toString();\n\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n }",
"public void unbind(String name) throws ObjectNameNotFoundException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call unbind.\r\n */\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open. Must have an open DB to call unbind\");\r\n }\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"Tx is not open. Must have an open TX to call lookup.\");\r\n }\r\n\r\n tx.getNamedRootsMap().unbind(name);\r\n }",
"public static void changeSign(DMatrixSparseCSC A , DMatrixSparseCSC B ) {\n if( A != B ) {\n B.copyStructure(A);\n }\n\n for (int i = 0; i < A.nz_length; i++) {\n B.nz_values[i] = -A.nz_values[i];\n }\n }",
"public Date getDate(String path) throws ParseException {\n return BoxDateFormat.parse(this.getValue(path).asString());\n }",
"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 Iterable<BoxRetentionPolicyAssignment.Info> getEnterpriseAssignments(int limit, String ... fields) {\r\n return this.getAssignments(BoxRetentionPolicyAssignment.TYPE_ENTERPRISE, limit, fields);\r\n }",
"public static vpath_stats get(nitro_service service) throws Exception{\n\t\tvpath_stats obj = new vpath_stats();\n\t\tvpath_stats[] response = (vpath_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"@Override\n\tpublic Inet6Address toInetAddress() {\n\t\tif(hasZone()) {\n\t\t\tInet6Address result;\n\t\t\tif(hasNoValueCache() || (result = valueCache.inetAddress) == null) {\n\t\t\t\tvalueCache.inetAddress = result = (Inet6Address) toInetAddressImpl(getBytes());\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\treturn (Inet6Address) super.toInetAddress();\n\t}",
"public T create(BeanInstance beanInstance) {\n final T proxy = (System.getSecurityManager() == null) ? run() : AccessController.doPrivileged(this);\n ((ProxyObject) proxy).weld_setHandler(new ProxyMethodHandler(contextId, beanInstance, bean));\n return proxy;\n }"
] |
Within a single zone, swaps one random partition on one random node with
another random partition on different random node.
@param nextCandidateCluster
@param zoneId Zone ID within which to shuffle partitions
@return updated cluster | [
"public static Cluster swapRandomPartitionsWithinZone(final Cluster nextCandidateCluster,\n final int zoneId) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n Random r = new Random();\n\n List<Integer> nodeIdsInZone = new ArrayList<Integer>(nextCandidateCluster.getNodeIdsInZone(zoneId));\n\n if(nodeIdsInZone.size() == 0) {\n return returnCluster;\n }\n\n // Select random stealer node\n int stealerNodeOffset = r.nextInt(nodeIdsInZone.size());\n Integer stealerNodeId = nodeIdsInZone.get(stealerNodeOffset);\n\n // Select random stealer partition\n List<Integer> stealerPartitions = returnCluster.getNodeById(stealerNodeId)\n .getPartitionIds();\n if(stealerPartitions.size() == 0) {\n return nextCandidateCluster;\n }\n int stealerPartitionOffset = r.nextInt(stealerPartitions.size());\n int stealerPartitionId = stealerPartitions.get(stealerPartitionOffset);\n\n // Select random donor node\n List<Integer> donorNodeIds = new ArrayList<Integer>();\n donorNodeIds.addAll(nodeIdsInZone);\n donorNodeIds.remove(stealerNodeId);\n\n if(donorNodeIds.isEmpty()) { // No donor nodes!\n return returnCluster;\n }\n int donorIdOffset = r.nextInt(donorNodeIds.size());\n Integer donorNodeId = donorNodeIds.get(donorIdOffset);\n\n // Select random donor partition\n List<Integer> donorPartitions = returnCluster.getNodeById(donorNodeId).getPartitionIds();\n int donorPartitionOffset = r.nextInt(donorPartitions.size());\n int donorPartitionId = donorPartitions.get(donorPartitionOffset);\n\n return swapPartitions(returnCluster,\n stealerNodeId,\n stealerPartitionId,\n donorNodeId,\n donorPartitionId);\n }"
] | [
"private void remove() {\n if (removing) {\n return;\n }\n if (deactiveNotifications.size() == 0) {\n return;\n }\n removing = true;\n final NotificationPopupView view = deactiveNotifications.get(0);\n final LinearFadeOutAnimation fadeOutAnimation = new LinearFadeOutAnimation(view) {\n\n @Override\n public void onUpdate(double progress) {\n super.onUpdate(progress);\n for (int i = 0; i < activeNotifications.size(); i++) {\n NotificationPopupView v = activeNotifications.get(i);\n final int left = v.getPopupLeft();\n final int top = (int) (((i + 1) * SPACING) - (progress * SPACING));\n v.setPopupPosition(left,\n top);\n }\n }\n\n @Override\n public void onComplete() {\n super.onComplete();\n view.hide();\n deactiveNotifications.remove(view);\n activeNotifications.remove(view);\n removing = false;\n remove();\n }\n };\n fadeOutAnimation.run(500);\n }",
"public static Enum<?> findMatchingEnumVal(Field field, String unknownEnumName) {\n\t\tif (unknownEnumName == null || unknownEnumName.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tfor (Enum<?> enumVal : (Enum<?>[]) field.getType().getEnumConstants()) {\n\t\t\tif (enumVal.name().equals(unknownEnumName)) {\n\t\t\t\treturn enumVal;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unknwown enum unknown name \" + unknownEnumName + \" for field \" + field);\n\t}",
"public ImageSource apply(ImageSource input) {\n ImageSource originalImage = input;\n\n int width = originalImage.getWidth();\n int height = originalImage.getHeight();\n\n boolean[][] matrix = new boolean[width][height]; // black n white boolean matrix; true = blck, false = white\n\n // Copy\n ImageSource filteredImage = new MatrixSource(input);\n\n int[] histogram = OtsuBinarize.imageHistogram(originalImage);\n\n int totalNumberOfpixels = height * width;\n\n int threshold = OtsuBinarize.threshold(histogram, totalNumberOfpixels);\n\n int black = 0;\n int white = 255;\n\n int gray;\n int alpha;\n int newColor;\n\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n gray = originalImage.getGray(i, j);\n\n if (gray > threshold) {\n matrix[i][j] = false;\n } else {\n matrix[i][j] = true;\n }\n\n }\n }\n\n int blackTreshold = letterThreshold(originalImage, matrix);\n\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n gray = originalImage.getGray(i, j);\n alpha = originalImage.getA(i, j);\n\n if (gray > blackTreshold) {\n newColor = white;\n } else {\n newColor = black;\n }\n\n newColor = ColorHelper.getARGB(newColor, newColor, newColor, alpha);\n filteredImage.setRGB(i, j, newColor);\n }\n }\n\n return filteredImage;\n }",
"protected String format(String key, String defaultPattern, Object... args) {\n String escape = escape(defaultPattern);\n String s = lookupPattern(key, escape);\n Object[] objects = escapeAll(args);\n return MessageFormat.format(s, objects);\n }",
"public BufferedImage getNewImageInstance() {\n BufferedImage buf = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());\n buf.setData(image.getData());\n return buf;\n }",
"public static base_response update(nitro_service client, inat resource) throws Exception {\n\t\tinat updateresource = new inat();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.privateip = resource.privateip;\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.tftp = resource.tftp;\n\t\tupdateresource.usip = resource.usip;\n\t\tupdateresource.usnip = resource.usnip;\n\t\tupdateresource.proxyip = resource.proxyip;\n\t\tupdateresource.mode = resource.mode;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public AssemblyResponse save(boolean isResumable)\n throws RequestException, LocalOperationException {\n Request request = new Request(getClient());\n options.put(\"steps\", steps.toMap());\n\n // only do tus uploads if files will be uploaded\n if (isResumable && getFilesCount() > 0) {\n Map<String, String> tusOptions = new HashMap<String, String>();\n tusOptions.put(\"tus_num_expected_upload_files\", Integer.toString(getFilesCount()));\n\n AssemblyResponse response = new AssemblyResponse(\n request.post(\"/assemblies\", options, tusOptions, null, null), true);\n\n // check if the assembly returned an error\n if (response.hasError()) {\n throw new RequestException(\"Request to Assembly failed: \" + response.json().getString(\"error\"));\n }\n\n try {\n handleTusUpload(response);\n } catch (IOException e) {\n throw new LocalOperationException(e);\n } catch (ProtocolException e) {\n throw new RequestException(e);\n }\n return response;\n } else {\n return new AssemblyResponse(request.post(\"/assemblies\", options, null, files, fileStreams));\n }\n }",
"public DbOrganization getOrganization(final String organizationId) {\n final DbOrganization dbOrganization = repositoryHandler.getOrganization(organizationId);\n\n if(dbOrganization == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Organization \" + organizationId + \" does not exist.\").build());\n }\n\n return dbOrganization;\n }",
"public ServerGroup updateServerGroupName(int serverGroupId, String name) {\n ServerGroup serverGroup = null;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", name),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP + \"/\" + serverGroupId, params));\n serverGroup = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return serverGroup;\n }"
] |
Unlink the specified reference from this object.
More info see OJB doc.
@param obj Object with reference
@param ord the ObjectReferenceDescriptor of the reference
@param insert flag signals insert operation | [
"public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)\r\n {\r\n linkOrUnlink(false, obj, ord, insert);\r\n }"
] | [
"public static boolean isConstantVal(DMatrixRMaj mat , double val , double tol )\n {\n // see if the result is an identity matrix\n int index = 0;\n for( int i = 0; i < mat.numRows; i++ ) {\n for( int j = 0; j < mat.numCols; j++ ) {\n if( !(Math.abs(mat.get(index++)-val) <= tol) )\n return false;\n\n }\n }\n\n return true;\n }",
"private void throwOrWarnAboutDescriptorProblem(String message) {\n if (validateDescriptions) {\n throw new IllegalArgumentException(message);\n }\n ControllerLogger.ROOT_LOGGER.warn(message);\n }",
"public static lbvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_cachepolicy_binding obj = new lbvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_cachepolicy_binding response[] = (lbvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static BMatrixRMaj elementLessThan(DMatrixRMaj A , double value , BMatrixRMaj output )\n {\n if( output == null ) {\n output = new BMatrixRMaj(A.numRows,A.numCols);\n }\n\n output.reshape(A.numRows, A.numCols);\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n output.data[i] = A.data[i] < value;\n }\n\n return output;\n }",
"private static QName convertString(String str) {\n if (str != null) {\n return QName.valueOf(str);\n } else {\n return null;\n }\n }",
"public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {\n\t\tif (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {\n\t\t\tGenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\tGenericBeanDefinition def = new GenericBeanDefinition();\n\t\t\tdef.setBeanClassName(genericInfo.getClassName());\n\t\t\tif (genericInfo.getPropertyValues() != null) {\n\t\t\t\tMutablePropertyValues propertyValues = new MutablePropertyValues();\n\t\t\t\tfor (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {\n\t\t\t\t\tBeanMetadataElementInfo info = entry.getValue();\n\t\t\t\t\tpropertyValues.add(entry.getKey(), toInternal(info));\n\t\t\t\t}\n\t\t\t\tdef.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {\n\t\t\tObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;\n\t\t\treturn createBeanDefinitionByIntrospection(objectInfo.getObject());\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to internal of \" + beanDefinitionInfo.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}",
"public UriComponentsBuilder queryParams(MultiValueMap<String, String> params) {\n\t\tAssert.notNull(params, \"'params' must not be null\");\n\t\tthis.queryParams.putAll(params);\n\t\treturn this;\n\t}",
"protected void resize( VariableMatrix mat , int numRows , int numCols ) {\n if( mat.isTemp() ) {\n mat.matrix.reshape(numRows,numCols);\n }\n }",
"public static String next(CharSequence self) {\n StringBuilder buffer = new StringBuilder(self);\n if (buffer.length() == 0) {\n buffer.append(Character.MIN_VALUE);\n } else {\n char last = buffer.charAt(buffer.length() - 1);\n if (last == Character.MAX_VALUE) {\n buffer.append(Character.MIN_VALUE);\n } else {\n char next = last;\n next++;\n buffer.setCharAt(buffer.length() - 1, next);\n }\n }\n return buffer.toString();\n }"
] |
Convert one project file format to another.
@param inputFile input file
@param outputFile output file
@throws Exception | [
"public void process(String inputFile, String outputFile) throws Exception\n {\n System.out.println(\"Reading input file started.\");\n long start = System.currentTimeMillis();\n ProjectFile projectFile = readFile(inputFile);\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading input file completed in \" + elapsed + \"ms.\");\n\n System.out.println(\"Writing output file started.\");\n start = System.currentTimeMillis();\n ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);\n writer.write(projectFile, outputFile);\n elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Writing output completed in \" + elapsed + \"ms.\");\n }"
] | [
"public IPv6AddressSection[] mergeToSequentialBlocks(IPv6AddressSection ...sections) throws SizeMismatchException {\n\t\tList<IPAddressSegmentSeries> blocks = getMergedSequentialBlocks(this, sections, true, createSeriesCreator(getAddressCreator(), getMaxSegmentValue()));\n\t\treturn blocks.toArray(new IPv6AddressSection[blocks.size()]);\n\t}",
"public int getIndexByDate(Date date)\n {\n int result = -1;\n int index = 0;\n\n for (CostRateTableEntry entry : this)\n {\n if (DateHelper.compare(date, entry.getEndDate()) < 0)\n {\n result = index;\n break;\n }\n ++index;\n }\n\n return result;\n }",
"public AT_Row setPaddingLeftRight(int padding){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public boolean switchToStateAndCheckIfClone(final Eventable event, StateVertex newState,\n\t\t\t\t\t\t\t\t\t\t\t\tCrawlerContext context) {\n\t\tStateVertex cloneState = this.addStateToCurrentState(newState, event);\n\n\t\trunOnInvariantViolationPlugins(context);\n\n\t\tif (cloneState == null) {\n\t\t\tchangeState(newState);\n\t\t\tplugins.runOnNewStatePlugins(context, newState);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tchangeState(cloneState);\n\t\t\treturn false;\n\t\t}\n\t}",
"public PhotoList<Photo> getRecent(Set<String> extras, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_RECENT);\r\n\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }",
"private void setSiteFilters(String filters) {\n\t\tthis.filterSites = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tCollections.addAll(this.filterSites, filters.split(\",\"));\n\t\t}\n\t}",
"public static String nameFromOffset(long offset) {\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMinimumIntegerDigits(20);\n nf.setMaximumFractionDigits(0);\n nf.setGroupingUsed(false);\n return nf.format(offset) + Log.FileSuffix;\n }",
"public int getGeoPerms() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GEO_PERMS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n int perm = -1;\r\n Element personElement = response.getPayload();\r\n String geoPerms = personElement.getAttribute(\"geoperms\");\r\n try {\r\n perm = Integer.parseInt(geoPerms);\r\n } catch (NumberFormatException e) {\r\n throw new FlickrException(\"0\", \"Unable to parse geoPermission\");\r\n }\r\n return perm;\r\n }",
"public static <T> T assertNotNull(T value, String message) {\n if (value == null)\n throw new IllegalStateException(message);\n return value;\n }"
] |
Returns all selected values of the list box, or empty array if none.
@return the selected values of the list box | [
"public String[] getItemsSelected() {\n List<String> selected = new LinkedList<>();\n for (int i = getIndexOffset(); i < listBox.getItemCount(); i++) {\n if (listBox.isItemSelected(i)) {\n selected.add(listBox.getValue(i));\n }\n }\n return selected.toArray(new String[selected.size()]);\n }"
] | [
"public static double Y0(double x) {\r\n if (x < 8.0) {\r\n double y = x * x;\r\n\r\n double ans1 = -2957821389.0 + y * (7062834065.0 + y * (-512359803.6\r\n + y * (10879881.29 + y * (-86327.92757 + y * 228.4622733))));\r\n double ans2 = 40076544269.0 + y * (745249964.8 + y * (7189466.438\r\n + y * (47447.26470 + y * (226.1030244 + y * 1.0))));\r\n\r\n return (ans1 / ans2) + 0.636619772 * J0(x) * Math.log(x);\r\n } else {\r\n double z = 8.0 / x;\r\n double y = z * z;\r\n double xx = x - 0.785398164;\r\n\r\n double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4\r\n + y * (-0.2073370639e-5 + y * 0.2093887211e-6)));\r\n double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3\r\n + y * (-0.6911147651e-5 + y * (0.7621095161e-6\r\n + y * (-0.934945152e-7))));\r\n return Math.sqrt(0.636619772 / x) *\r\n (Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2);\r\n }\r\n }",
"public static String encodeAuthority(String authority, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(authority, encoding, HierarchicalUriComponents.Type.AUTHORITY);\n\t}",
"public static Long getSize(final File file){\n if ( file!=null && file.exists() ){\n return file.length();\n }\n return null;\n }",
"public static String getAt(String text, int index) {\n index = normaliseIndex(index, text.length());\n return text.substring(index, index + 1);\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 }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public synchronized void pushInstallReferrer(String source, String medium, String campaign) {\n if (source == null && medium == null && campaign == null) return;\n try {\n // If already pushed, don't send it again\n int status = StorageHelper.getInt(context, \"app_install_status\", 0);\n if (status != 0) {\n Logger.d(\"Install referrer has already been set. Will not override it\");\n return;\n }\n StorageHelper.putInt(context, \"app_install_status\", 1);\n\n if (source != null) source = Uri.encode(source);\n if (medium != null) medium = Uri.encode(medium);\n if (campaign != null) campaign = Uri.encode(campaign);\n\n String uriStr = \"wzrk://track?install=true\";\n if (source != null) uriStr += \"&utm_source=\" + source;\n if (medium != null) uriStr += \"&utm_medium=\" + medium;\n if (campaign != null) uriStr += \"&utm_campaign=\" + campaign;\n\n Uri uri = Uri.parse(uriStr);\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n Logger.v(\"Failed to push install referrer\", t);\n }\n }",
"public static String toSafeFileName(String name) {\n int size = name.length();\n StringBuilder builder = new StringBuilder(size * 2);\n for (int i = 0; i < size; i++) {\n char c = name.charAt(i);\n boolean valid = c >= 'a' && c <= 'z';\n valid = valid || (c >= 'A' && c <= 'Z');\n valid = valid || (c >= '0' && c <= '9');\n valid = valid || (c == '_') || (c == '-') || (c == '.');\n\n if (valid) {\n builder.append(c);\n } else {\n // Encode the character using hex notation\n builder.append('x');\n builder.append(Integer.toHexString(i));\n }\n }\n return builder.toString();\n }",
"public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Document removeDocument(String key) throws PrintingException {\n\t\tif (documentMap.containsKey(key)) {\n\t\t\treturn documentMap.remove(key);\n\t\t} else {\n\t\t\tthrow new PrintingException(PrintingException.DOCUMENT_NOT_FOUND, key);\n\t\t}\n\t}"
] |
Return the index associated to the Renderer.
@param renderer used to search in the prototypes collection.
@return the prototype index associated to the renderer passed as argument. | [
"private int getPrototypeIndex(Renderer renderer) {\n int index = 0;\n for (Renderer prototype : prototypes) {\n if (prototype.getClass().equals(renderer.getClass())) {\n break;\n }\n index++;\n }\n return index;\n }"
] | [
"public ConnectionlessBootstrap bootStrapUdpClient()\n throws HttpRequestCreateException {\n\n ConnectionlessBootstrap udpClient = null;\n try {\n\n // Configure the client.\n udpClient = new ConnectionlessBootstrap(udpMeta.getChannelFactory());\n\n udpClient.setPipeline(new UdpPipelineFactory(\n TcpUdpSshPingResourceStore.getInstance().getTimer(), this)\n .getPipeline());\n\n } catch (Exception t) {\n throw new TcpUdpRequestCreateException(\n \"Error in creating request in udp worker. \"\n + \" If udpClient is null. Then fail to create.\", t);\n }\n\n return udpClient;\n\n }",
"public boolean hasRequiredMiniFluoProps() {\n boolean valid = true;\n if (getMiniStartAccumulo()) {\n // ensure that client properties are not set since we are using MiniAccumulo\n valid &= verifyStringPropNotSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropNotSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropNotSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n valid &= verifyStringPropNotSet(ACCUMULO_ZOOKEEPERS_PROP, CLIENT_ACCUMULO_ZOOKEEPERS_PROP);\n valid &= verifyStringPropNotSet(CONNECTION_ZOOKEEPERS_PROP, CLIENT_ZOOKEEPER_CONNECT_PROP);\n if (valid == false) {\n log.error(\"Client properties should not be set in your configuration if MiniFluo is \"\n + \"configured to start its own accumulo (indicated by fluo.mini.start.accumulo being \"\n + \"set to true)\");\n }\n } else {\n valid &= hasRequiredClientProps();\n valid &= hasRequiredAdminProps();\n valid &= hasRequiredOracleProps();\n valid &= hasRequiredWorkerProps();\n }\n return valid;\n }",
"protected void setupRegistration() {\n if (isServiceWorkerSupported()) {\n Navigator.serviceWorker.register(getResource()).then(object -> {\n logger.info(\"Service worker has been successfully registered\");\n registration = (ServiceWorkerRegistration) object;\n\n onRegistered(new ServiceEvent(), registration);\n\n // Observe service worker lifecycle\n observeLifecycle(registration);\n\n // Setup Service Worker events events\n setupOnControllerChangeEvent();\n setupOnMessageEvent();\n setupOnErrorEvent();\n return null;\n }, error -> {\n logger.info(\"ServiceWorker registration failed: \" + error);\n return null;\n });\n } else {\n logger.info(\"Service worker is not supported by this browser.\");\n }\n }",
"public void setOptions(Doc p) {\n\tif (p == null)\n\t return;\n\n\tfor (Tag tag : p.tags(\"opt\"))\n\t setOption(StringUtil.tokenize(tag.text()));\n }\n\n /**\n * Check if the supplied string matches an entity specified\n * with the -hide parameter.\n * @return true if the string matches.\n */\n public boolean matchesHideExpression(String s) {\n\tfor (Pattern hidePattern : hidePatterns) {\n\t // micro-optimization because the \"all pattern\" is heavily used in UmlGraphDoc\n\t if(hidePattern == allPattern)\n\t\treturn true;\n\t \n\t Matcher m = hidePattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n \n /**\n * Check if the supplied string matches an entity specified\n * with the -include parameter.\n * @return true if the string matches.\n */\n public boolean matchesIncludeExpression(String s) {\n\tfor (Pattern includePattern : includePatterns) {\n\t Matcher m = includePattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n\n /**\n * Check if the supplied string matches an entity specified\n * with the -collpackages parameter.\n * @return true if the string matches.\n */\n public boolean matchesCollPackageExpression(String s) {\n\tfor (Pattern collPattern : collPackages) {\n\t Matcher m = collPattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n \n // ---------------------------------------------------------------- \n // OptionProvider methods\n // ---------------------------------------------------------------- \n \n public Options getOptionsFor(ClassDoc cd) {\n\tOptions localOpt = getGlobalOptions();\n\tlocalOpt.setOptions(cd);\n\treturn localOpt;\n }\n\n public Options getOptionsFor(String name) {\n\treturn getGlobalOptions();\n }\n\n public Options getGlobalOptions() {\n\treturn (Options) clone();\n }\n\n public void overrideForClass(Options opt, ClassDoc cd) {\n\t// nothing to do\n }",
"public static ipset_nsip_binding[] get(nitro_service service, String name) throws Exception{\n\t\tipset_nsip_binding obj = new ipset_nsip_binding();\n\t\tobj.set_name(name);\n\t\tipset_nsip_binding response[] = (ipset_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void setOptions(Doc p) {\n\tif (p == null)\n\t return;\n\n\tfor (Tag tag : p.tags(\"opt\"))\n\t setOption(StringUtil.tokenize(tag.text()));\n }\n\n /**\n * Check if the supplied string matches an entity specified\n * with the -hide parameter.\n * @return true if the string matches.\n */\n public boolean matchesHideExpression(String s) {\n\tfor (Pattern hidePattern : hidePatterns) {\n\t // micro-optimization because the \"all pattern\" is heavily used in UmlGraphDoc\n\t if(hidePattern == allPattern)\n\t\treturn true;\n\t \n\t Matcher m = hidePattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n \n /**\n * Check if the supplied string matches an entity specified\n * with the -include parameter.\n * @return true if the string matches.\n */\n public boolean matchesIncludeExpression(String s) {\n\tfor (Pattern includePattern : includePatterns) {\n\t Matcher m = includePattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n\n /**\n * Check if the supplied string matches an entity specified\n * with the -collpackages parameter.\n * @return true if the string matches.\n */\n public boolean matchesCollPackageExpression(String s) {\n\tfor (Pattern collPattern : collPackages) {\n\t Matcher m = collPattern.matcher(s);\n\t if (strictMatching ? m.matches() : m.find())\n\t\treturn true;\n\t}\n\treturn false;\n }\n \n // ---------------------------------------------------------------- \n // OptionProvider methods\n // ---------------------------------------------------------------- \n \n public Options getOptionsFor(ClassDoc cd) {\n\tOptions localOpt = getGlobalOptions();\n\tlocalOpt.setOptions(cd);\n\treturn localOpt;\n }\n\n public Options getOptionsFor(String name) {\n\treturn getGlobalOptions();\n }\n\n public Options getGlobalOptions() {\n\treturn (Options) clone();\n }\n\n public void overrideForClass(Options opt, ClassDoc cd) {\n\t// nothing to do\n }",
"private int cleanupSegmentsToMaintainSize(final Log log) throws IOException {\n if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0;\n\n List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() {\n\n long diff = log.size() - logRetentionSize;\n\n public boolean filter(LogSegment segment) {\n diff -= segment.size();\n return diff >= 0;\n }\n });\n return deleteSegments(log, toBeDeleted);\n }",
"public ResultSetAndStatement executeQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeQuery: \" + query);\r\n }\r\n /*\r\n\t\t * MBAIRD: we should create a scrollable resultset if the start at\r\n\t\t * index or end at index is set\r\n\t\t */\r\n boolean scrollable = ((query.getStartAtIndex() > Query.NO_START_AT_INDEX) || (query.getEndAtIndex() > Query.NO_END_AT_INDEX));\r\n /*\r\n\t\t * OR if the prefetching of relationships is being used.\r\n\t\t */\r\n if (query != null && query.getPrefetchedRelationships() != null && !query.getPrefetchedRelationships().isEmpty())\r\n {\r\n scrollable = true;\r\n }\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n final int queryFetchSize = query.getFetchSize();\r\n final boolean isStoredProcedure = isStoredProcedure(sql.getStatement());\r\n stmt = sm.getPreparedStatement(cld, sql.getStatement() ,\r\n scrollable, queryFetchSize, isStoredProcedure);\r\n if (isStoredProcedure)\r\n {\r\n // Query implemented as a stored procedure, which must return a result set.\r\n // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}\r\n getPlatform().registerOutResultSet((CallableStatement) stmt, 1);\r\n sm.bindStatement(stmt, query, cld, 2);\r\n\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeQuery: \" + stmt);\r\n\r\n stmt.execute();\r\n rs = (ResultSet) ((CallableStatement) stmt).getObject(1);\r\n }\r\n else\r\n {\r\n sm.bindStatement(stmt, query, cld, 1);\r\n\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeQuery: \" + stmt);\r\n\r\n rs = stmt.executeQuery();\r\n }\r\n\r\n return new ResultSetAndStatement(sm, stmt, rs, sql);\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of the query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), null, logger, null);\r\n }\r\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<Symmetry454Date> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<Symmetry454Date>) super.zonedDateTime(temporal);\n }"
] |
Sets the name of the attribute group with which this attribute is associated.
@param attributeGroup the attribute group name. Cannot be an empty string but can be {@code null}
if the attribute is not associated with a group.
@return a builder that can be used to continue building the attribute definition | [
"public BUILDER setAttributeGroup(String attributeGroup) {\n assert attributeGroup == null || attributeGroup.length() > 0;\n //noinspection deprecation\n this.attributeGroup = attributeGroup;\n return (BUILDER) this;\n }"
] | [
"private String extractAndConvertTaskType(Task task)\n {\n String activityType = (String) task.getCachedValue(m_activityTypeField);\n if (activityType == null)\n {\n activityType = \"Resource Dependent\";\n }\n else\n {\n if (ACTIVITY_TYPE_MAP.containsKey(activityType))\n {\n activityType = ACTIVITY_TYPE_MAP.get(activityType);\n }\n }\n return activityType;\n }",
"public void setHighlightStrength(float _highlightStrength) {\n mHighlightStrength = _highlightStrength;\n for (PieModel model : mPieData) {\n highlightSlice(model);\n }\n invalidateGlobal();\n }",
"@Override\n public final Job queueIn(final Job job, final long millis) {\n return pushAt(job, System.currentTimeMillis() + millis);\n }",
"public static base_responses export(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 exportresources[] = new sslfipskey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texportresources[i] = new sslfipskey();\n\t\t\t\texportresources[i].fipskeyname = resources[i].fipskeyname;\n\t\t\t\texportresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, exportresources,\"export\");\n\t\t}\n\t\treturn result;\n\t}",
"protected EntityKey getEntityKey(Tuple tuple, AssociatedEntityKeyMetadata associatedEntityKeyMetadata) {\n\t\tObject[] columnValues = new Object[ associatedEntityKeyMetadata.getAssociationKeyColumns().length];\n\t\tint i = 0;\n\n\t\tfor ( String associationKeyColumn : associatedEntityKeyMetadata.getAssociationKeyColumns() ) {\n\t\t\tcolumnValues[i] = tuple.get( associationKeyColumn );\n\t\t\ti++;\n\t\t}\n\n\t\treturn new EntityKey( associatedEntityKeyMetadata.getEntityKeyMetadata(), columnValues );\n\t}",
"public void useOldRESTService() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using old RESTful CustomerService with old client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old REST\");\n printOldCustomerDetails(customer);\n }",
"public boolean computeDirect( DMatrixRMaj A ) {\n\n initPower(A);\n\n boolean converged = false;\n\n for( int i = 0; i < maxIterations && !converged; i++ ) {\n// q0.print();\n \n CommonOps_DDRM.mult(A,q0,q1);\n double s = NormOps_DDRM.normPInf(q1);\n CommonOps_DDRM.divide(q1,s,q2);\n\n converged = checkConverged(A);\n }\n\n return converged;\n }",
"public boolean containsIteratorForTable(String aTable)\r\n {\r\n boolean result = false;\r\n\r\n if (m_rsIterators != null)\r\n {\r\n for (int i = 0; i < m_rsIterators.size(); i++)\r\n {\r\n OJBIterator it = (OJBIterator) m_rsIterators.get(i);\r\n if (it instanceof RsIterator)\r\n {\r\n if (((RsIterator) it).getClassDescriptor().getFullTableName().equals(aTable))\r\n {\r\n result = true;\r\n break;\r\n }\r\n }\r\n else if (it instanceof ChainingIterator)\r\n {\r\n result = ((ChainingIterator) it).containsIteratorForTable(aTable);\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }",
"public static DoubleMatrix[] fullSVD(DoubleMatrix A) {\n int m = A.rows;\n int n = A.columns;\n\n DoubleMatrix U = new DoubleMatrix(m, m);\n DoubleMatrix S = new DoubleMatrix(min(m, n));\n DoubleMatrix V = new DoubleMatrix(n, n);\n\n int info = NativeBlas.dgesvd('A', 'A', m, n, A.dup().data, 0, m, S.data, 0, U.data, 0, m, V.data, 0, n);\n\n if (info > 0) {\n throw new LapackConvergenceException(\"GESVD\", info + \" superdiagonals of an intermediate bidiagonal form failed to converge.\");\n }\n\n return new DoubleMatrix[]{U, S, V.transpose()};\n }"
] |
Open the given url in default system browser. | [
"private void openBrowser(URI url) throws IOException {\n if (Desktop.isDesktopSupported()) {\n Desktop.getDesktop().browse(url);\n } else {\n LOGGER.error(\"Can not open browser because this capability is not supported on \" +\n \"your platform. You can use the link below to open the report manually.\");\n }\n }"
] | [
"private void calculateMenuItemPosition() {\n\n float itemRadius = (expandedRadius + collapsedRadius) / 2, f;\n RectF area = new RectF(\n center.x - itemRadius,\n center.y - itemRadius,\n center.x + itemRadius,\n center.y + itemRadius);\n Path path = new Path();\n path.addArc(area, (float) fromAngle, (float) (toAngle - fromAngle));\n PathMeasure measure = new PathMeasure(path, false);\n float len = measure.getLength();\n int divisor = getChildCount();\n float divider = len / divisor;\n\n for (int i = 0; i < getChildCount(); i++) {\n float[] coords = new float[2];\n measure.getPosTan(i * divider + divider * .5f, coords, null);\n FilterMenu.Item item = (FilterMenu.Item) getChildAt(i).getTag();\n item.setX((int) coords[0] - item.getView().getMeasuredWidth() / 2);\n item.setY((int) coords[1] - item.getView().getMeasuredHeight() / 2);\n }\n }",
"public Iterator getAllExtentClasses()\r\n {\r\n ArrayList subTypes = new ArrayList();\r\n\r\n subTypes.addAll(_extents);\r\n\r\n for (int idx = 0; idx < subTypes.size(); idx++)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)subTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curSubTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!subTypes.contains(curSubTypeDef))\r\n {\r\n subTypes.add(curSubTypeDef);\r\n }\r\n }\r\n }\r\n return subTypes.iterator();\r\n }",
"public UniqueEntityLoader buildLoader(\n\t\t\tOuterJoinLoadable persister,\n\t\t\tint batchSize,\n\t\t\tLockMode lockMode,\n\t\t\tSessionFactoryImplementor factory,\n\t\t\tLoadQueryInfluencers influencers,\n\t\t\tBatchableEntityLoaderBuilder innerEntityLoaderBuilder) {\n\t\tif ( batchSize <= 1 ) {\n\t\t\t// no batching\n\t\t\treturn buildNonBatchingLoader( persister, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t\t}\n\t\treturn buildBatchingLoader( persister, batchSize, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t}",
"protected void runImportScript(CmsObject cms, CmsModule module) {\n\n LOG.info(\"Executing import script for module \" + module.getName());\n m_report.println(\n org.opencms.module.Messages.get().container(org.opencms.module.Messages.RPT_IMPORT_SCRIPT_HEADER_0),\n I_CmsReport.FORMAT_HEADLINE);\n String importScript = \"echo on\\n\" + module.getImportScript();\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n PrintStream out = new PrintStream(buffer);\n CmsShell shell = new CmsShell(cms, \"${user}@${project}:${siteroot}|${uri}>\", null, out, out);\n shell.execute(importScript);\n String outputString = buffer.toString();\n LOG.info(\"Shell output for import script was: \\n\" + outputString);\n m_report.println(\n org.opencms.module.Messages.get().container(\n org.opencms.module.Messages.RPT_IMPORT_SCRIPT_OUTPUT_1,\n outputString));\n }",
"public double inverseCumulativeDistribution(double x) {\n\t\tdouble p = Math.exp(-lambda);\n\t\tdouble dp = p;\n\t\tint k = 0;\n\t\twhile(x > p) {\n\t\t\tk++;\n\t\t\tdp *= lambda / k;\n\t\t\tp += dp;\n\t\t}\n\t\treturn k;\n\t}",
"@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 }",
"private Pair<Double, String>\n summarizeBalance(final Map<Integer, Integer> nodeIdToPartitionCount, String title) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\n\" + title + \"\\n\");\n\n Map<Integer, ZoneBalanceStats> zoneToBalanceStats = new HashMap<Integer, ZoneBalanceStats>();\n for(Integer zoneId: cluster.getZoneIds()) {\n zoneToBalanceStats.put(zoneId, new ZoneBalanceStats());\n }\n\n for(Node node: cluster.getNodes()) {\n int curCount = nodeIdToPartitionCount.get(node.getId());\n builder.append(\"\\tNode ID: \" + node.getId() + \" : \" + curCount + \" (\" + node.getHost()\n + \")\\n\");\n zoneToBalanceStats.get(node.getZoneId()).addPartitions(curCount);\n }\n\n // double utilityToBeMinimized = Double.MIN_VALUE;\n double utilityToBeMinimized = 0;\n for(Integer zoneId: cluster.getZoneIds()) {\n builder.append(\"Zone \" + zoneId + \"\\n\");\n builder.append(zoneToBalanceStats.get(zoneId).dumpStats());\n utilityToBeMinimized += zoneToBalanceStats.get(zoneId).getUtility();\n /*- \n * Another utility function to consider \n if(zoneToBalanceStats.get(zoneId).getMaxMinRatio() > utilityToBeMinimized) {\n utilityToBeMinimized = zoneToBalanceStats.get(zoneId).getUtility();\n }\n */\n }\n\n return Pair.create(utilityToBeMinimized, builder.toString());\n }",
"public static ComplexNumber Add(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real + z2.real, z1.imaginary + z2.imaginary);\r\n }",
"public final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }"
] |
Create an error image should an error occur while fetching a WMS map.
@param width image width
@param height image height
@param e exception
@return error image
@throws java.io.IOException oops | [
"private byte[] createErrorImage(int width, int height, Exception e) throws IOException {\n\t\tString error = e.getMessage();\n\t\tif (null == error) {\n\t\t\tWriter result = new StringWriter();\n\t\t\tPrintWriter printWriter = new PrintWriter(result);\n\t\t\te.printStackTrace(printWriter);\n\t\t\terror = result.toString();\n\t\t}\n\n\t\tBufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);\n\t\tGraphics2D g = (Graphics2D) image.getGraphics();\n\n\t\tg.setColor(Color.RED);\n\t\tg.drawString(error, ERROR_MESSAGE_X, height / 2);\n\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\tImageIO.write(image, \"PNG\", out);\n\t\tout.flush();\n\t\tbyte[] result = out.toByteArray();\n\t\tout.close();\n\n\t\treturn result;\n\t}"
] | [
"private ProjectFile readTextFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaTextFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }",
"public void putEvents(List<Event> events) {\n Exception lastException;\n List<EventType> eventTypes = new ArrayList<EventType>();\n for (Event event : events) {\n EventType eventType = EventMapper.map(event);\n eventTypes.add(eventType);\n }\n\n int i = 0;\n lastException = null;\n while (i < numberOfRetries) {\n try {\n monitoringService.putEvents(eventTypes);\n break;\n } catch (Exception e) {\n lastException = e;\n i++;\n }\n if(i < numberOfRetries) {\n try {\n Thread.sleep(delayBetweenRetry);\n } catch (InterruptedException e) {\n break;\n }\n }\n }\n\n if (i == numberOfRetries) {\n throw new MonitoringException(\"1104\", \"Could not send events to monitoring service after \"\n + numberOfRetries + \" retries.\", lastException, events);\n }\n }",
"@Override\n public AccountingDate date(int prolepticYear, int month, int dayOfMonth) {\n return AccountingDate.of(this, prolepticYear, month, dayOfMonth);\n }",
"private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }",
"private void disableTalkBack() {\n GVRSceneObject[] sceneObjects = mGvrContext.getMainScene().getWholeSceneObjects();\n for (GVRSceneObject sceneObject : sceneObjects) {\n if (sceneObject instanceof GVRAccessiblityObject)\n if (((GVRAccessiblityObject) sceneObject).getTalkBack() != null)\n ((GVRAccessiblityObject) sceneObject).getTalkBack().setActive(false);\n\n }\n }",
"public void reportError(NodeT faulted, Throwable throwable) {\n faulted.setPreparer(true);\n String dependency = faulted.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onFaultedResolution(dependency, throwable);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }",
"private boolean renameKeyForAllLanguages(String oldKey, String newKey) {\n\n try {\n loadAllRemainingLocalizations();\n lockAllLocalizations(oldKey);\n if (hasDescriptor()) {\n lockDescriptor();\n }\n } catch (CmsException | IOException e) {\n LOG.error(e.getLocalizedMessage(), e);\n return false;\n }\n for (Entry<Locale, SortedProperties> entry : m_localizations.entrySet()) {\n SortedProperties localization = entry.getValue();\n if (localization.containsKey(oldKey)) {\n String value = localization.getProperty(oldKey);\n localization.remove(oldKey);\n localization.put(newKey, value);\n m_changedTranslations.add(entry.getKey());\n }\n }\n if (hasDescriptor()) {\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(\n Descriptor.N_MESSAGE,\n Descriptor.LOCALE);\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n if (key == oldKey) {\n m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(m_cms, newKey);\n break;\n }\n }\n m_descriptorHasChanges = true;\n }\n m_keyset.renameKey(oldKey, newKey);\n return true;\n }",
"public GVRTexture getSplashTexture(GVRContext gvrContext) {\n Bitmap bitmap = BitmapFactory.decodeResource( //\n gvrContext.getContext().getResources(), //\n R.drawable.__default_splash_screen__);\n GVRTexture tex = new GVRTexture(gvrContext);\n tex.setImage(new GVRBitmapImage(gvrContext, bitmap));\n return tex;\n }",
"public static ActorSystem createAndGetActorSystem() {\n if (actorSystem == null || actorSystem.isTerminated()) {\n actorSystem = ActorSystem.create(PcConstants.ACTOR_SYSTEM, conf);\n }\n return actorSystem;\n }"
] |
Utility function that fetches node ids.
@param adminClient An instance of AdminClient points to given cluster
@return Node ids in cluster | [
"public static List<Integer> getAllNodeIds(AdminClient adminClient) {\n List<Integer> nodeIds = Lists.newArrayList();\n for(Integer nodeId: adminClient.getAdminClientCluster().getNodeIds()) {\n nodeIds.add(nodeId);\n }\n return nodeIds;\n }"
] | [
"public static servicegroupbindings get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroupbindings obj = new servicegroupbindings();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroupbindings response = (servicegroupbindings) obj.get_resource(service);\n\t\treturn response;\n\t}",
"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 static void pushClassType(CodeAttribute b, String classType) {\n if (classType.length() != 1) {\n if (classType.startsWith(\"L\") && classType.endsWith(\";\")) {\n classType = classType.substring(1, classType.length() - 1);\n }\n b.loadClass(classType);\n } else {\n char type = classType.charAt(0);\n switch (type) {\n case 'I':\n b.getstatic(Integer.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'J':\n b.getstatic(Long.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'S':\n b.getstatic(Short.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'F':\n b.getstatic(Float.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'D':\n b.getstatic(Double.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'B':\n b.getstatic(Byte.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'C':\n b.getstatic(Character.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n case 'Z':\n b.getstatic(Boolean.class.getName(), TYPE, LJAVA_LANG_CLASS);\n break;\n default:\n throw new RuntimeException(\"Cannot handle primitive type: \" + type);\n }\n }\n }",
"private void writeIntegerField(String fieldName, Object value) throws IOException\n {\n int val = ((Number) value).intValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"@Nullable\n private static Converter<List<String>, Object> createPrimitiveTypeConverter(final Class<?> resultClass) {\n Object defaultValue = defaultValue(resultClass);\n\n if (defaultValue == null) {\n // For primitive type, the default value shouldn't be null\n return null;\n }\n\n return new BasicConverter(defaultValue) {\n @Override\n protected Object convert(String value) throws Exception {\n return valueOf(value, resultClass);\n }\n };\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 void set( T a ) {\n if( a.getType() == getType() )\n mat.set(a.getMatrix());\n else {\n setMatrix(a.mat.copy());\n }\n }",
"public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }",
"@Override public void setUniqueID(Integer uniqueID)\n {\n ProjectFile parent = getParentFile();\n\n if (m_uniqueID != null)\n {\n parent.getCalendars().unmapUniqueID(m_uniqueID);\n }\n\n parent.getCalendars().mapUniqueID(uniqueID, this);\n\n m_uniqueID = uniqueID;\n }"
] |
Get all sub-lists of the given list of the given sizes.
For example:
<pre>
List<String> items = Arrays.asList("a", "b", "c", "d");
System.out.println(CollectionUtils.getNGrams(items, 1, 2));
</pre>
would print out:
<pre>
[[a], [a, b], [b], [b, c], [c], [c, d], [d]]
</pre>
@param <T>
The type of items contained in the list.
@param items
The list of items.
@param minSize
The minimum size of an ngram.
@param maxSize
The maximum size of an ngram.
@return All sub-lists of the given sizes. | [
"public static <T> List<List<T>> getNGrams(List<T> items, int minSize, int maxSize) {\r\n List<List<T>> ngrams = new ArrayList<List<T>>();\r\n int listSize = items.size();\r\n for (int i = 0; i < listSize; ++i) {\r\n for (int ngramSize = minSize; ngramSize <= maxSize; ++ngramSize) {\r\n if (i + ngramSize <= listSize) {\r\n List<T> ngram = new ArrayList<T>();\r\n for (int j = i; j < i + ngramSize; ++j) {\r\n ngram.add(items.get(j));\r\n }\r\n ngrams.add(ngram);\r\n }\r\n }\r\n }\r\n return ngrams;\r\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}",
"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 }",
"@Override\n public void fire(StepStartedEvent event) {\n for (LifecycleListener listener : listeners) {\n try {\n listener.fire(event);\n } catch (Exception e) {\n logError(listener, e);\n }\n }\n }",
"public void genNodeDataMap(ParallelTask task) {\n\n TargetHostMeta targetHostMeta = task.getTargetHostMeta();\n HttpMeta httpMeta = task.getHttpMeta();\n\n String entityBody = httpMeta.getEntityBody();\n String requestContent = HttpMeta\n .replaceDefaultFullRequestContent(entityBody);\n\n Map<String, NodeReqResponse> parallelTaskResult = task\n .getParallelTaskResult();\n for (String fqdn : targetHostMeta.getHosts()) {\n NodeReqResponse nodeReqResponse = new NodeReqResponse(fqdn);\n nodeReqResponse.setDefaultReqestContent(requestContent);\n parallelTaskResult.put(fqdn, nodeReqResponse);\n }\n }",
"public static Mono<Void> waitForCompletion(CloudFoundryClient cloudFoundryClient, Duration completionTimeout, String jobId) {\n return requestJobV3(cloudFoundryClient, jobId)\n .filter(job -> JobState.PROCESSING != job.getState())\n .repeatWhenEmpty(exponentialBackOff(Duration.ofSeconds(1), Duration.ofSeconds(15), completionTimeout))\n .filter(job -> JobState.FAILED == job.getState())\n .flatMap(JobUtils::getError);\n }",
"public static base_response delete(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager deleteresource = new snmpmanager();\n\t\tdeleteresource.ipaddress = resource.ipaddress;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"@VisibleForTesting\n protected static Dimension getSize(\n final ScalebarAttributeValues scalebarParams,\n final ScaleBarRenderSettings settings, final Dimension maxLabelSize) {\n final float width;\n final float height;\n if (scalebarParams.getOrientation().isHorizontal()) {\n width = 2 * settings.getPadding()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getLeftLabelMargin() + settings.getRightLabelMargin();\n height = 2 * settings.getPadding()\n + settings.getBarSize() + settings.getLabelDistance()\n + Label.getRotatedHeight(maxLabelSize, scalebarParams.getLabelRotation());\n } else {\n width = 2 * settings.getPadding()\n + settings.getLabelDistance() + settings.getBarSize()\n + Label.getRotatedWidth(maxLabelSize, scalebarParams.getLabelRotation());\n height = 2 * settings.getPadding()\n + settings.getTopLabelMargin()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getBottomLabelMargin();\n }\n return new Dimension((int) Math.ceil(width), (int) Math.ceil(height));\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", clientService.findClient(clientUUID, profileId));\n return valueHash;\n }",
"public DbOrganization getOrganization(final String organizationId) {\n final DbOrganization dbOrganization = repositoryHandler.getOrganization(organizationId);\n\n if(dbOrganization == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Organization \" + organizationId + \" does not exist.\").build());\n }\n\n return dbOrganization;\n }"
] |
Creates a REST client used to perform Voldemort operations against the
Coordinator
@param storeName Name of the store to perform the operations on
@param resolver Custom resolver as specified by the application
@return | [
"@Override\n public <K, V> StoreClient<K, V> getStoreClient(final String storeName,\n final InconsistencyResolver<Versioned<V>> resolver) {\n // wrap it in LazyStoreClient here so any direct calls to this method\n // returns a lazy client\n return new LazyStoreClient<K, V>(new Callable<StoreClient<K, V>>() {\n\n @Override\n public StoreClient<K, V> call() throws Exception {\n Store<K, V, Object> clientStore = getRawStore(storeName, resolver);\n return new RESTClient<K, V>(storeName, clientStore);\n }\n }, true);\n }"
] | [
"private CmsMessageBundleEditorTypes.BundleType initBundleType() {\n\n String resourceTypeName = OpenCms.getResourceManager().getResourceType(m_resource).getTypeName();\n return CmsMessageBundleEditorTypes.BundleType.toBundleType(resourceTypeName);\n }",
"public static nsacl6 get(nitro_service service, String acl6name) throws Exception{\n\t\tnsacl6 obj = new nsacl6();\n\t\tobj.set_acl6name(acl6name);\n\t\tnsacl6 response = (nsacl6) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void init() {\n logger.info(\"metadata init().\");\n\n writeLock.lock();\n try {\n // Required keys\n initCache(CLUSTER_KEY);\n\n // If stores definition storage engine is not null, initialize metadata\n // Add the mapping from key to the storage engine used\n if(this.storeDefinitionsStorageEngine != null) {\n initStoreDefinitions(null);\n } else {\n initCache(STORES_KEY);\n }\n\n // Initialize system store in the metadata cache\n initSystemCache();\n initSystemRoutingStrategies(getCluster());\n\n // Initialize with default if not present\n initCache(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY, true);\n initCache(QUOTA_ENFORCEMENT_ENABLED_KEY, true);\n initCache(REBALANCING_STEAL_INFO, new RebalancerState(new ArrayList<RebalanceTaskInfo>()));\n initCache(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER.toString());\n initCache(REBALANCING_SOURCE_CLUSTER_XML, null);\n initCache(REBALANCING_SOURCE_STORES_XML, null);\n\n\n } finally {\n writeLock.unlock();\n }\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}",
"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 CollectionRequest<Task> subtasks(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public static XMLStreamException unexpectedEndElement(final XMLExtendedStreamReader reader) {\n return ControllerLogger.ROOT_LOGGER.unexpectedEndElement(reader.getName(), reader.getLocation());\n }",
"@Programmatic\n public <T> List<T> fromExcel(\n final Blob excelBlob,\n final Class<T> cls,\n final String sheetName) throws ExcelService.Exception {\n return fromExcel(excelBlob, new WorksheetSpec(cls, sheetName));\n }",
"public String getScopes() {\n final StringBuilder sb = new StringBuilder();\n for (final Scope scope : Scope.values()) {\n sb.append(scope);\n sb.append(\", \");\n }\n final String scopes = sb.toString().trim();\n return scopes.substring(0, scopes.length() - 1);\n }"
] |
Gets the favorite entry for a given row.
@param row the widget used to display the favorite
@return the favorite entry for the widget | [
"private CmsFavoriteEntry getEntry(Component row) {\n\n if (row instanceof CmsFavInfo) {\n\n return ((CmsFavInfo)row).getEntry();\n\n }\n return null;\n\n }"
] | [
"private void readHeaderProperties(BufferedInputStream stream) throws IOException\n {\n String header = readHeaderString(stream);\n for (String property : header.split(\"\\\\|\"))\n {\n String[] expression = property.split(\"=\");\n m_properties.put(expression[0], expression[1]);\n }\n }",
"private BigInteger getDaysOfTheWeek(RecurringData data)\n {\n int value = 0;\n for (Day day : Day.values())\n {\n if (data.getWeeklyDay(day))\n {\n value = value | DAY_MASKS[day.getValue()];\n }\n }\n return BigInteger.valueOf(value);\n }",
"public Object getRealSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tif (_realSubject == null)\r\n\t\t{\r\n\t\t\tbeforeMaterialization();\r\n\t\t\t_realSubject = materializeSubject();\r\n\t\t\tafterMaterialization();\r\n\t\t}\r\n\t\treturn _realSubject;\r\n\t}",
"public RangeInfo subListBorders(int size) {\n if (inclusive == null) throw new IllegalStateException(\"Should not call subListBorders on a non-inclusive aware IntRange\");\n int tempFrom = from;\n if (tempFrom < 0) {\n tempFrom += size;\n }\n int tempTo = to;\n if (tempTo < 0) {\n tempTo += size;\n }\n if (tempFrom > tempTo) {\n return new RangeInfo(inclusive ? tempTo : tempTo + 1, tempFrom + 1, true);\n }\n return new RangeInfo(tempFrom, inclusive ? tempTo + 1 : tempTo, false);\n }",
"public SqlStatement getPreparedDeleteStatement(ClassDescriptor cld)\r\n {\r\n SqlForClass sfc = getSqlForClass(cld);\r\n SqlStatement sql = sfc.getDeleteSql();\r\n if(sql == null)\r\n {\r\n ProcedureDescriptor pd = cld.getDeleteProcedure();\r\n\r\n if(pd == null)\r\n {\r\n sql = new SqlDeleteByPkStatement(cld, logger);\r\n }\r\n else\r\n {\r\n sql = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setDeleteSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }",
"private static void close(Closeable closeable) {\n\t\tif (closeable != null) {\n\t\t\ttry {\n\t\t\t\tcloseable.close();\n\t\t\t} catch (IOException ignored) {\n\t\t\t\tlogger.error(\"Failed to close output stream: \"\n\t\t\t\t\t\t+ ignored.getMessage());\n\t\t\t}\n\t\t}\n\t}",
"private void stop() {\n\t\tfor (int i = 0; i < mDownloadDispatchers.length; i++) {\n\t\t\tif (mDownloadDispatchers[i] != null) {\n\t\t\t\tmDownloadDispatchers[i].quit();\n\t\t\t}\n\t\t}\n\t}",
"public File getStylesheetPath()\n {\n String path = System.getProperty(STYLESHEET_KEY);\n return path == null ? null : new File(path);\n }",
"private void addColumns(MpxjTreeNode parentNode, Table table)\n {\n for (Column column : table.getColumns())\n {\n final Column c = column;\n MpxjTreeNode childNode = new MpxjTreeNode(column)\n {\n @Override public String toString()\n {\n return c.getTitle();\n }\n };\n parentNode.add(childNode);\n }\n }"
] |
Helper method for variance calculations.
@return The sum of the squares of the differences between
each value and the arithmetic mean.
@throws EmptyDataSetException If the data set is empty. | [
"private double sumSquaredDiffs()\n { \n double mean = getArithmeticMean();\n double squaredDiffs = 0;\n for (int i = 0; i < getSize(); i++)\n {\n double diff = mean - dataSet[i];\n squaredDiffs += (diff * diff);\n }\n return squaredDiffs;\n }"
] | [
"public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"@OnClick(R.id.navigateToModule1Service)\n public void onNavigationServiceCTAClick() {\n Intent intentService = HensonNavigator.gotoModule1Service(this)\n .stringExtra(\"foo\")\n .build();\n\n startService(intentService);\n }",
"public Object lookup(Identity oid)\r\n {\r\n Object ret = null;\r\n if (oid != null)\r\n {\r\n ObjectCache cache = getCache(oid, null, METHOD_LOOKUP);\r\n if (cache != null)\r\n {\r\n ret = cache.lookup(oid);\r\n }\r\n }\r\n return ret;\r\n }",
"private static <T> void readTableField(DatabaseTableConfig<T> config, String field, String value) {\n\t\tif (field.equals(FIELD_NAME_DATA_CLASS)) {\n\t\t\ttry {\n\t\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\t\tClass<T> clazz = (Class<T>) Class.forName(value);\n\t\t\t\tconfig.setDataClass(clazz);\n\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\tthrow new IllegalArgumentException(\"Unknown class specified for dataClass: \" + value);\n\t\t\t}\n\t\t} else if (field.equals(FIELD_NAME_TABLE_NAME)) {\n\t\t\tconfig.setTableName(value);\n\t\t}\n\t}",
"public static Transformers.ResourceIgnoredTransformationRegistry createServerIgnoredRegistry(final RequiredConfigurationHolder rc, final Transformers.ResourceIgnoredTransformationRegistry delegate) {\n return new Transformers.ResourceIgnoredTransformationRegistry() {\n @Override\n public boolean isResourceTransformationIgnored(PathAddress address) {\n final int length = address.size();\n if (length == 0) {\n return false;\n } else if (length >= 1) {\n if (delegate.isResourceTransformationIgnored(address)) {\n return true;\n }\n\n final PathElement element = address.getElement(0);\n final String type = element.getKey();\n switch (type) {\n case ModelDescriptionConstants.EXTENSION:\n // Don't ignore extensions for now\n return false;\n// if (local) {\n// return false; // Always include all local extensions\n// } else if (rc.getExtensions().contains(element.getValue())) {\n// return false;\n// }\n// break;\n case ModelDescriptionConstants.PROFILE:\n if (rc.getProfiles().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SERVER_GROUP:\n if (rc.getServerGroups().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SOCKET_BINDING_GROUP:\n if (rc.getSocketBindings().contains(element.getValue())) {\n return false;\n }\n break;\n }\n }\n return true;\n }\n };\n }",
"public static void writeFlowId(Message message, String flowId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage)message;\n Header hdFlowId = soapMessage.getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n LOG.warning(\"FlowId already existing in soap header, need not to write FlowId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(FLOW_ID_QNAME, flowId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored flowId '\" + flowId + \"' in soap header: \" + FLOW_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create flowId header.\", e);\n }\n\n }",
"public int getLinkId(@NotNull final PersistentStoreTransaction txn, @NotNull final String linkName, final boolean allowCreate) {\n return allowCreate ? linkIds.getOrAllocateId(txn, linkName) : linkIds.getId(txn, linkName);\n }",
"private DiscountCurve createDiscountCurve(String discountCurveName) {\n\t\tDiscountCurve discountCurve\t= model.getDiscountCurve(discountCurveName);\n\t\tif(discountCurve == null) {\n\t\t\tdiscountCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(discountCurveName, new double[] { 0.0 }, new double[] { 1.0 });\n\t\t\tmodel = model.addCurves(discountCurve);\n\t\t}\n\n\t\treturn discountCurve;\n\t}",
"public ModelNode getDeploymentSubsystemModel(final String subsystemName) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit);\n }"
] |
Sets the options contained in the DJCrosstab to the JRDesignCrosstab.
Also fits the correct width | [
"private void setCrosstabOptions() {\n\t\tif (djcross.isUseFullWidth()){\n\t\t\tjrcross.setWidth(layoutManager.getReport().getOptions().getPrintableWidth());\n\t\t} else {\n\t\t\tjrcross.setWidth(djcross.getWidth());\n\t\t}\n\t\tjrcross.setHeight(djcross.getHeight());\n\n\t\tjrcross.setColumnBreakOffset(djcross.getColumnBreakOffset());\n\n jrcross.setIgnoreWidth(djcross.isIgnoreWidth());\n\t}"
] | [
"synchronized long storeUserProfile(String id, JSONObject obj) {\n\n if (id == null) return DB_UPDATE_ERROR;\n\n if (!this.belowMemThreshold()) {\n getConfigLogger().verbose(\"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.USER_PROFILES.getName();\n\n long ret = DB_UPDATE_ERROR;\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(\"_id\", id);\n ret = db.insertWithOnConflict(tableName, null, cv, SQLiteDatabase.CONFLICT_REPLACE);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n return ret;\n }",
"public Bundler put(String key, CharSequence value) {\n delegate.putCharSequence(key, value);\n return this;\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}",
"protected Channel awaitChannel() throws IOException {\n Channel channel = this.channel;\n if(channel != null) {\n return channel;\n }\n synchronized (lock) {\n for(;;) {\n if(state == State.CLOSED) {\n throw ProtocolLogger.ROOT_LOGGER.channelClosed();\n }\n channel = this.channel;\n if(channel != null) {\n return channel;\n }\n if(state == State.CLOSING) {\n throw ProtocolLogger.ROOT_LOGGER.channelClosed();\n }\n try {\n lock.wait();\n } catch (InterruptedException e) {\n throw new IOException(e);\n }\n }\n }\n }",
"public static appfwlearningsettings[] get(nitro_service service) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\tappfwlearningsettings[] response = (appfwlearningsettings[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"protected Object[] getFieldObjects(Object data) throws SQLException {\n\t\tObject[] objects = new Object[argFieldTypes.length];\n\t\tfor (int i = 0; i < argFieldTypes.length; i++) {\n\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\tif (fieldType.isAllowGeneratedIdInsert()) {\n\t\t\t\tobjects[i] = fieldType.getFieldValueIfNotDefault(data);\n\t\t\t} else {\n\t\t\t\tobjects[i] = fieldType.extractJavaFieldToSqlArgValue(data);\n\t\t\t}\n\t\t\tif (objects[i] == null) {\n\t\t\t\t// NOTE: the default value could be null as well\n\t\t\t\tobjects[i] = fieldType.getDefaultValue();\n\t\t\t}\n\t\t}\n\t\treturn objects;\n\t}",
"private TaskField getTaskField(int field)\n {\n TaskField result = MPPTaskField14.getInstance(field);\n\n if (result != null)\n {\n switch (result)\n {\n case START_TEXT:\n {\n result = TaskField.START;\n break;\n }\n\n case FINISH_TEXT:\n {\n result = TaskField.FINISH;\n break;\n }\n\n case DURATION_TEXT:\n {\n result = TaskField.DURATION;\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n return result;\n }",
"private InputStream prepareInputStream(InputStream stream) throws IOException\n {\n InputStream result;\n BufferedInputStream bis = new BufferedInputStream(stream);\n readHeaderProperties(bis);\n if (isCompressed())\n {\n result = new InflaterInputStream(bis);\n }\n else\n {\n result = bis;\n }\n return result;\n }",
"static <T> boolean syncInstantiation(T objectType) {\n List<Template> templates = new ArrayList<>();\n Templates tr = TEMP_FINDER.findAnnotations(templates, objectType);\n if (tr == null) {\n /* Default to synchronous instantiation */\n return true;\n } else {\n return tr.syncInstantiation();\n }\n }"
] |
Prepare a parallel HTTP POST Task.
@param url
the UrlPostfix: e.g. in http://localhost:8080/index.html.,the url is "/index.html"
@return the parallel task builder | [
"public ParallelTaskBuilder prepareHttpPost(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.POST);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }"
] | [
"public CustomHeadersInterceptor addHeaderMap(Map<String, String> headers) {\n for (Map.Entry<String, String> header : headers.entrySet()) {\n this.headers.put(header.getKey(), Collections.singletonList(header.getValue()));\n }\n return this;\n }",
"public void writeNameValuePair(String name, Date value) throws IOException\n {\n internalWriteNameValuePair(name, m_format.format(value));\n }",
"@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n String dir = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean verbose = false;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_DIR)) {\n dir = (String) options.valueOf(AdminParserUtils.OPT_DIR);\n }\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n if(options.has(OPT_VERBOSE)) {\n verbose = true;\n }\n\n // execute command\n File directory = AdminToolUtils.createDir(dir);\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {\n metaKeys = Lists.newArrayList();\n for(Object key: MetadataStore.METADATA_KEYS) {\n metaKeys.add((String) key);\n }\n }\n\n doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose);\n }",
"protected void mergeSameCost(LinkedList<TimephasedCost> list)\n {\n LinkedList<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n TimephasedCost previousAssignment = null;\n for (TimephasedCost assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Number previousAssignmentCost = previousAssignment.getAmountPerDay();\n Number assignmentCost = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentCost.doubleValue(), assignmentCost.doubleValue(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().doubleValue();\n total += assignmentCost.doubleValue();\n\n TimephasedCost merged = new TimephasedCost();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentCost);\n merged.setTotalAmount(Double.valueOf(total));\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }",
"private void readUDFTypes(FieldContainer mpxj, List<UDFAssignmentType> udfs)\n {\n for (UDFAssignmentType udf : udfs)\n {\n FieldType fieldType = m_fieldTypeMap.get(Integer.valueOf(udf.getTypeObjectId()));\n if (fieldType != null)\n {\n mpxj.set(fieldType, getUdfValue(udf));\n }\n }\n }",
"public static <T> void injectEEFields(Iterable<Set<ResourceInjection<?>>> resourceInjectionsHierarchy,\n T beanInstance, CreationalContext<T> ctx) {\n for (Set<ResourceInjection<?>> resourceInjections : resourceInjectionsHierarchy) {\n for (ResourceInjection<?> resourceInjection : resourceInjections) {\n resourceInjection.injectResourceReference(beanInstance, ctx);\n }\n }\n }",
"public Set<TupleOperation> getOperations() {\n\t\tif ( currentState == null ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\treturn new SetFromCollection<TupleOperation>( currentState.values() );\n\t\t}\n\t}",
"public static void munlock(Pointer addr, long len) {\n\n if(Delegate.munlock(addr, new NativeLong(len)) != 0) {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking failed with errno:\" + errno.strerror());\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"munlocking region\");\n }\n }",
"public ParallelTaskBuilder prepareUdp(String command) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.UDP);\n cb.getUdpMeta().setCommand(command);\n return cb;\n }"
] |
Returns the command line options to be used for scalaxb, excluding the
input file names. | [
"protected List<String> arguments() {\n List<String> args = new ArgumentsBuilder()\n .flag(\"-v\", verbose)\n .flag(\"--package-dir\", packageDir)\n .param(\"-d\", outputDirectory.getPath())\n .param(\"-p\", packageName)\n .map(\"--package:\", packageNameMap())\n .param(\"--class-prefix\", classPrefix)\n .param(\"--param-prefix\", parameterPrefix)\n .param(\"--chunk-size\", chunkSize)\n .flag(\"--no-dispatch-client\", !generateDispatchClient)\n .flag(\"--dispatch-as\", generateDispatchAs)\n .param(\"--dispatch-version\", dispatchVersion)\n .flag(\"--no-runtime\", !generateRuntime)\n .intersperse(\"--wrap-contents\", wrapContents)\n .param(\"--protocol-file\", protocolFile)\n .param(\"--protocol-package\", protocolPackage)\n .param(\"--attribute-prefix\", attributePrefix)\n .flag(\"--prepend-family\", prependFamily)\n .flag(\"--blocking\", !async)\n .flag(\"--lax-any\", laxAny)\n .flag(\"--no-varargs\", !varArgs)\n .flag(\"--ignore-unknown\", ignoreUnknown)\n .flag(\"--autopackages\", autoPackages)\n .flag(\"--mutable\", mutable)\n .flag(\"--visitor\", visitor)\n\n .getArguments();\n return unmodifiableList(args);\n }"
] | [
"private void populateRelation(TaskField field, Task sourceTask, String relationship) throws MPXJException\n {\n int index = 0;\n int length = relationship.length();\n\n //\n // Extract the identifier\n //\n while ((index < length) && (Character.isDigit(relationship.charAt(index)) == true))\n {\n ++index;\n }\n\n Integer taskID;\n try\n {\n taskID = Integer.valueOf(relationship.substring(0, index));\n }\n\n catch (NumberFormatException ex)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n //\n // Now find the task, so we can extract the unique ID\n //\n Task targetTask;\n if (field == TaskField.PREDECESSORS)\n {\n targetTask = m_projectFile.getTaskByID(taskID);\n }\n else\n {\n targetTask = m_projectFile.getTaskByUniqueID(taskID);\n }\n\n //\n // If we haven't reached the end, we next expect to find\n // SF, SS, FS, FF\n //\n RelationType type = null;\n Duration lag = null;\n\n if (index == length)\n {\n type = RelationType.FINISH_START;\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n else\n {\n if ((index + 1) == length)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n type = RelationTypeUtility.getInstance(m_locale, relationship.substring(index, index + 2));\n\n index += 2;\n\n if (index == length)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n else\n {\n if (relationship.charAt(index) == '+')\n {\n ++index;\n }\n\n lag = DurationUtility.getInstance(relationship.substring(index), m_formats.getDurationDecimalFormat(), m_locale);\n }\n }\n\n if (type == null)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT + \" '\" + relationship + \"'\");\n }\n\n // We have seen at least one example MPX file where an invalid task ID\n // is present. We'll ignore this as the schedule is otherwise valid.\n if (targetTask != null)\n {\n Relation relation = sourceTask.addPredecessor(targetTask, type, lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }",
"private void deliverSyncCommand(byte command) {\n for (final SyncListener listener : getSyncListeners()) {\n try {\n switch (command) {\n\n case 0x01:\n listener.becomeMaster();\n\n case 0x10:\n listener.setSyncMode(true);\n break;\n\n case 0x20:\n listener.setSyncMode(false);\n break;\n\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering sync command to listener\", t);\n }\n }\n }",
"public static int brightnessNTSC(int rgb) {\n\t\tint r = (rgb >> 16) & 0xff;\n\t\tint g = (rgb >> 8) & 0xff;\n\t\tint b = rgb & 0xff;\n\t\treturn (int)(r*0.299f + g*0.587f + b*0.114f);\n\t}",
"public Object newInstance(String className) {\n try {\n return classLoader.loadClass(className).newInstance();\n } catch (Exception e) {\n throw new ScalaInstanceNotFound(className);\n }\n }",
"public static nsrpcnode get(nitro_service service, String ipaddress) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tobj.set_ipaddress(ipaddress);\n\t\tnsrpcnode response = (nsrpcnode) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public boolean checkXpathStartsWithXpathEventableCondition(Document dom,\n\t\t\tEventableCondition eventableCondition, String xpath) throws XPathExpressionException {\n\t\tif (eventableCondition == null || Strings\n\t\t\t\t.isNullOrEmpty(eventableCondition.getInXPath())) {\n\t\t\tthrow new CrawljaxException(\"Eventable has no XPath condition\");\n\t\t}\n\t\tList<String> expressions =\n\t\t\t\tXPathHelper.getXpathForXPathExpressions(dom, eventableCondition.getInXPath());\n\n\t\treturn checkXPathUnderXPaths(xpath, expressions);\n\t}",
"public void setControllerModel(GVRSceneObject controllerModel)\n {\n if (mControllerModel != null)\n {\n mControllerGroup.removeChildObject(mControllerModel);\n }\n mControllerModel = controllerModel;\n mControllerGroup.addChildObject(mControllerModel);\n mControllerModel.setEnable(mShowControllerModel);\n }",
"private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars, HashMap<Integer, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null && baseCal.getName() != null)\n {\n cal.setParent(baseCal);\n }\n else\n {\n // Remove invalid calendar to avoid serious problems later.\n m_file.removeCalendar(cal);\n }\n }\n }",
"public static final Bytes of(byte[] array) {\n Objects.requireNonNull(array);\n if (array.length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[array.length];\n System.arraycopy(array, 0, copy, 0, array.length);\n return new Bytes(copy);\n }"
] |
Puts as many of the given bytes as possible into this buffer.
@return number of bytes actually put into this buffer (0 if the buffer is full) | [
"public synchronized int put(byte[] src, int off, int len) {\n if (available == capacity) {\n return 0;\n }\n\n // limit is last index to put + 1\n int limit = idxPut < idxGet ? idxGet : capacity;\n int count = Math.min(limit - idxPut, len);\n System.arraycopy(src, off, buffer, idxPut, count);\n idxPut += count;\n\n if (idxPut == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxGet);\n if (count2 > 0) {\n System.arraycopy(src, off + count, buffer, 0, count2);\n idxPut = count2;\n count += count2;\n } else {\n idxPut = 0;\n }\n }\n available += count;\n return count;\n }"
] | [
"public Collection getAllObjects(Class target)\r\n {\r\n PersistenceBroker broker = getBroker();\r\n Collection result;\r\n try\r\n {\r\n Query q = new QueryByCriteria(target);\r\n result = broker.getCollectionByQuery(q);\r\n }\r\n finally\r\n {\r\n if (broker != null) broker.close();\r\n }\r\n return result;\r\n }",
"public static boolean validate(final String ip) {\n Matcher matcher = pattern.matcher(ip);\n return matcher.matches();\n }",
"public static boolean isIdentity(DMatrix a , double tol )\n {\n for( int i = 0; i < a.getNumRows(); i++ ) {\n for( int j = 0; j < a.getNumCols(); j++ ) {\n if( i == j ) {\n if( Math.abs(a.get(i,j)-1.0) > tol )\n return false;\n } else {\n if( Math.abs(a.get(i,j)) > tol )\n return false;\n }\n }\n }\n return true;\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 }",
"@Override\n public Optional<String> hash(final Optional<URL> url) throws IOException {\n if (!url.isPresent()) {\n return Optional.absent();\n }\n logger.debug(\"Calculating md5 hash, url:{}\", url);\n if (isHotReloadModeOff()) {\n final String md5 = cache.getIfPresent(url.get());\n\n logger.debug(\"md5 hash:{}\", md5);\n\n if (md5 != null) {\n return Optional.of(md5);\n }\n }\n\n final InputStream is = url.get().openStream();\n final String md5 = getMD5Checksum(is);\n\n if (isHotReloadModeOff()) {\n logger.debug(\"caching url:{} with hash:{}\", url, md5);\n\n cache.put(url.get(), md5);\n }\n\n return Optional.fromNullable(md5);\n }",
"public static final String printExtendedAttributeDate(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }",
"public Node findEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getFindEntityQuery(), params );\n\t\treturn singleResult( result );\n\t}",
"public AsciiTable setTextAlignment(TextAlignment textAlignment){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public StandaloneCommandBuilder addSecurityProperty(final String key, final String value) {\n securityProperties.put(key, value);\n return this;\n }"
] |
A smoothed step function. A cubic function is used to smooth the step between two thresholds.
@param a the lower threshold position
@param b the upper threshold position
@param x the input parameter
@return the output value | [
"public static float smoothStep(float a, float b, float x) {\n\t\tif (x < a)\n\t\t\treturn 0;\n\t\tif (x >= b)\n\t\t\treturn 1;\n\t\tx = (x - a) / (b - a);\n\t\treturn x*x * (3 - 2*x);\n\t}"
] | [
"protected synchronized PersistenceBroker getBroker() throws PBFactoryException\r\n {\r\n /*\r\n mkalen:\r\n NB! The loadProfileIfNeeded must be called _before_ acquiring a broker below,\r\n since some methods in PersistenceBrokerImpl will keep a local reference to\r\n the descriptor repository that was active during broker construction/refresh\r\n (not checking the repository beeing used on method invocation).\r\n\r\n PersistenceBrokerImpl#getClassDescriptor(Class clazz) is such a method,\r\n that will throw ClassNotPersistenceCapableException on the following scenario:\r\n\r\n (All happens in one thread only):\r\n t0: activate per-thread metadata changes\r\n t1: load, register and activate profile A\r\n t2: load object O1 witch collection proxy C to objects {O2} (C stores profile key K(A))\r\n t3: close broker from t2\r\n t4: load, register and activate profile B\r\n t5: reference O1.getO2Collection, causing C loadData() to be invoked\r\n t6: C calls getBroker\r\n broker B is created and descriptorRepository is set to descriptors from profile B\r\n t7: C calls loadProfileIfNeeded, re-activating profile A\r\n t8: C calls B.getCollectionByQuery\r\n t9: B gets callback (via QueryReferenceBroker) to getClassDescriptor\r\n the local descriptorRepository from t6 is used!\r\n => We will now try to query for {O2} with profile B\r\n (even though we re-activated profile A in t7)\r\n => ClassNotPersistenceCapableException\r\n\r\n Keeping loadProfileIfNeeded() at the start of this method changes everything from t6:\r\n t6: C calls loadProfileIfNeeded, re-activating profile A\r\n t7: C calls getBroker,\r\n broker B is created and descriptorRepository is set to descriptors from profile A\r\n t8: C calls B.getCollectionByQuery\r\n t9: B gets callback to getClassDescriptor,\r\n the local descriptorRepository from t6 is used\r\n => We query for {O2} with profile A\r\n => All good :-)\r\n */\r\n if (_perThreadDescriptorsEnabled)\r\n {\r\n loadProfileIfNeeded();\r\n }\r\n\r\n PersistenceBroker broker;\r\n if (getBrokerKey() == null)\r\n {\r\n /*\r\n arminw:\r\n if no PBKey is set we throw an exception, because we don't\r\n know which PB (connection) should be used.\r\n */\r\n throw new OJBRuntimeException(\"Can't find associated PBKey. Need PBKey to obtain a valid\" +\r\n \"PersistenceBroker instance from intern resources.\");\r\n }\r\n // first try to use the current threaded broker to avoid blocking\r\n broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey());\r\n // current broker not found or was closed, create a intern new one\r\n if (broker == null || broker.isClosed())\r\n {\r\n broker = PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey());\r\n // signal that we use a new internal obtained PB instance to read the\r\n // data and that this instance have to be closed after use\r\n _needsClose = true;\r\n }\r\n return broker;\r\n }",
"public static boolean isCompleteZip(File file) throws IOException, NonScannableZipException {\n\n FileChannel channel = null;\n try {\n channel = new FileInputStream(file).getChannel();\n\n long size = channel.size();\n if (size < ENDLEN) { // Obvious case\n return false;\n }\n else if (validateEndRecord(file, channel, size - ENDLEN)) { // typical case where file is complete and end record has no comment\n return true;\n }\n\n // Either file is incomplete or the end of central directory record includes an arbitrary length comment\n // So, we have to scan backwards looking for an end of central directory record\n return scanForEndSig(file, channel);\n }\n finally {\n safeClose(channel);\n }\n }",
"public static String getPrefix(String column) {\n\t\treturn column.contains( \".\" ) ? DOT_SEPARATOR_PATTERN.split( column )[0] : null;\n\t}",
"@Override\r\n public V remove(Object key) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n V result = temp.remove(key);\r\n map = temp;\r\n return (result);\r\n }\r\n } else {\r\n synchronized (map) {\r\n return (map.remove(key));\r\n }\r\n }\r\n }",
"private String quoteFormatCharacters(String literal)\n {\n StringBuilder sb = new StringBuilder();\n int length = literal.length();\n char c;\n\n for (int loop = 0; loop < length; loop++)\n {\n c = literal.charAt(loop);\n switch (c)\n {\n case '0':\n case '#':\n case '.':\n case '-':\n case ',':\n case 'E':\n case ';':\n case '%':\n {\n sb.append(\"'\");\n sb.append(c);\n sb.append(\"'\");\n break;\n }\n\n default:\n {\n sb.append(c);\n break;\n }\n }\n }\n\n return (sb.toString());\n }",
"String getStatus(CmsUser user, boolean disabled, boolean newUser) {\n\n if (disabled) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_0);\n }\n if (newUser) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_0);\n }\n if (OpenCms.getLoginManager().isUserTempDisabled(user.getName())) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_UNLOCK_USER_STATUS_0);\n }\n if (isUserPasswordReset(user)) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_0);\n }\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_ACTIVE_0);\n }",
"public Date getStartTime(Date date)\n {\n Date result = m_startTimeCache.get(date);\n if (result == null)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n if (ranges == null)\n {\n result = getParentFile().getProjectProperties().getDefaultStartTime();\n }\n else\n {\n result = ranges.getRange(0).getStart();\n }\n result = DateHelper.getCanonicalTime(result);\n m_startTimeCache.put(new Date(date.getTime()), result);\n }\n return result;\n }",
"public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}",
"public static boolean promoteAndCheckResponse(Promotion promotion, ArtifactoryBuildInfoClient client, TaskListener listener,\n String buildName, String buildNumber) throws IOException {\n // If failFast is true, perform dry run first\n if (promotion.isFailFast()) {\n promotion.setDryRun(true);\n listener.getLogger().println(\"Performing dry run promotion (no changes are made during dry run) ...\");\n HttpResponse dryResponse = client.stageBuild(buildName, buildNumber, promotion);\n try {\n validatePromotionSuccessful(dryResponse, true, promotion.isFailFast(), listener);\n } catch (IOException e) {\n listener.error(e.getMessage());\n return false;\n }\n listener.getLogger().println(\"Dry run finished successfully.\\nPerforming promotion ...\");\n }\n\n // Perform promotion\n promotion.setDryRun(false);\n HttpResponse response = client.stageBuild(buildName, buildNumber, promotion);\n try {\n validatePromotionSuccessful(response, false, promotion.isFailFast(), listener);\n } catch (IOException e) {\n listener.error(e.getMessage());\n return false;\n }\n listener.getLogger().println(\"Promotion completed successfully!\");\n\n return true;\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.