query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
This main method provides an easy command line tool to compare two
schemas. | [
"public static void main(String[] args) {\n if(args.length != 2) {\n System.out.println(\"Usage: SchemaEvolutionValidator pathToOldSchema pathToNewSchema\");\n return;\n }\n\n Schema oldSchema;\n Schema newSchema;\n\n try {\n oldSchema = Schema.parse(new File(args[0]));\n } catch(Exception ex) {\n oldSchema = null;\n System.out.println(\"Could not open or parse the old schema (\" + args[0] + \") due to \"\n + ex);\n }\n\n try {\n newSchema = Schema.parse(new File(args[1]));\n } catch(Exception ex) {\n newSchema = null;\n System.out.println(\"Could not open or parse the new schema (\" + args[1] + \") due to \"\n + ex);\n }\n\n if(oldSchema == null || newSchema == null) {\n return;\n }\n\n System.out.println(\"Comparing: \");\n System.out.println(\"\\t\" + args[0]);\n System.out.println(\"\\t\" + args[1]);\n\n List<Message> messages = SchemaEvolutionValidator.checkBackwardCompatibility(oldSchema,\n newSchema,\n oldSchema.getName());\n Level maxLevel = Level.ALL;\n for(Message message: messages) {\n System.out.println(message.getLevel() + \": \" + message.getMessage());\n if(message.getLevel().isGreaterOrEqual(maxLevel)) {\n maxLevel = message.getLevel();\n }\n }\n\n if(maxLevel.isGreaterOrEqual(Level.ERROR)) {\n System.out.println(Level.ERROR\n + \": The schema is not backward compatible. New clients will not be able to read existing data.\");\n } else if(maxLevel.isGreaterOrEqual(Level.WARN)) {\n System.out.println(Level.WARN\n + \": The schema is partially backward compatible, but old clients will not be able to read data serialized in the new format.\");\n } else {\n System.out.println(Level.INFO\n + \": The schema is backward compatible. Old and new clients will be able to read records serialized by one another.\");\n }\n }"
] | [
"public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int written = 0;\n for (int i = 0; i < srcLen; ++i) {\n written += Character.toChars(src[srcOff + i], dest, destOff + written);\n }\n return written;\n }",
"protected void copyClasspathResource(File outputDirectory,\n String resourceName,\n String targetFileName) throws IOException\n {\n String resourcePath = classpathPrefix + resourceName;\n InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourcePath);\n copyStream(outputDirectory, resourceStream, targetFileName);\n }",
"public static base_response flush(nitro_service client, cacheobject resource) throws Exception {\n\t\tcacheobject flushresource = new cacheobject();\n\t\tflushresource.locator = resource.locator;\n\t\tflushresource.url = resource.url;\n\t\tflushresource.host = resource.host;\n\t\tflushresource.port = resource.port;\n\t\tflushresource.groupname = resource.groupname;\n\t\tflushresource.httpmethod = resource.httpmethod;\n\t\tflushresource.force = resource.force;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}",
"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 }",
"public static ForwardCurveInterpolation createForwardCurveFromMonteCarloLiborModel(String name, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\n\t\tint timeIndex\t= model.getTimeIndex(startTime);\n\t\t// Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves\n\t\tArrayList<RandomVariable> liborsAtTimeIndex = new ArrayList<>();\n\t\tint firstLiborIndex = model.getLiborPeriodDiscretization().getTimeIndexNearestGreaterOrEqual(startTime);\n\t\tdouble firstLiborTime = model.getLiborPeriodDiscretization().getTime(firstLiborIndex);\n\t\tif(firstLiborTime>startTime) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(startTime, startTime, firstLiborTime));\n\t\t}\n\t\t// Vector of times for the forward curve\n\t\tdouble[] times = new double[firstLiborTime==startTime ? (model.getNumberOfLibors()-firstLiborIndex) : (model.getNumberOfLibors()-firstLiborIndex+1)];\n\t\ttimes[0]=0;\n\t\tint indexOffset = firstLiborTime==startTime ? 0 : 1;\n\t\tfor(int i=firstLiborIndex;i<model.getNumberOfLibors();i++) {\n\t\t\tliborsAtTimeIndex.add(model.getLIBOR(timeIndex,i));\n\t\t\ttimes[i-firstLiborIndex+indexOffset]=model.getLiborPeriodDiscretization().getTime(i)-startTime;\n\t\t}\n\n\t\tRandomVariable[] libors = liborsAtTimeIndex.toArray(new RandomVariable[liborsAtTimeIndex.size()]);\n\t\treturn ForwardCurveInterpolation.createForwardCurveFromForwards(name, times, libors, model.getLiborPeriodDiscretization().getTimeStep(firstLiborIndex));\n\n\t}",
"private void addGreeting(String guestbookName, String user, String message)\n throws DatastoreException {\n Entity.Builder greeting = Entity.newBuilder();\n greeting.setKey(makeKey(GUESTBOOK_KIND, guestbookName, GREETING_KIND));\n greeting.getMutableProperties().put(USER_PROPERTY, makeValue(user).build());\n greeting.getMutableProperties().put(MESSAGE_PROPERTY, makeValue(message).build());\n greeting.getMutableProperties().put(DATE_PROPERTY, makeValue(new Date()).build());\n Key greetingKey = insert(greeting.build());\n System.out.println(\"greeting key is: \" + greetingKey);\n }",
"@SuppressWarnings(\"unchecked\")\n public Map<BsonValue, ChangeEvent<BsonDocument>> getEvents() {\n nsLock.readLock().lock();\n final Map<BsonValue, ChangeEvent<BsonDocument>> events;\n try {\n events = new HashMap<>(this.events);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.clear();\n return events;\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"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 void addProducer(Broker broker) {\n Properties props = new Properties();\n props.put(\"host\", broker.host);\n props.put(\"port\", \"\" + broker.port);\n props.putAll(config.getProperties());\n if (sync) {\n SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));\n logger.info(\"Creating sync producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n syncProducers.put(broker.id, producer);\n } else {\n AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//\n new SyncProducer(new SyncProducerConfig(props)),//\n serializer,//\n eventHandler,//\n config.getEventHandlerProperties(),//\n this.callbackHandler, //\n config.getCbkHandlerProperties());\n producer.start();\n logger.info(\"Creating async producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n asyncProducers.put(broker.id, producer);\n }\n }"
] |
Helper method called recursively to list child tasks.
@param task task whose children are to be displayed
@param indent whitespace used to indent hierarchy levels | [
"private static void listHierarchy(Task task, String indent)\n {\n for (Task child : task.getChildTasks())\n {\n System.out.println(indent + \"Task: \" + child.getName() + \"\\t\" + child.getStart() + \"\\t\" + child.getFinish());\n listHierarchy(child, indent + \" \");\n }\n }"
] | [
"private void initStoreDefinitions(Version storesXmlVersion) {\n if(this.storeDefinitionsStorageEngine == null) {\n throw new VoldemortException(\"The store definitions directory is empty\");\n }\n\n String allStoreDefinitions = \"<stores>\";\n Version finalStoresXmlVersion = null;\n if(storesXmlVersion != null) {\n finalStoresXmlVersion = storesXmlVersion;\n }\n this.storeNames.clear();\n\n ClosableIterator<Pair<String, Versioned<String>>> storesIterator = this.storeDefinitionsStorageEngine.entries();\n\n // Some test setups may result in duplicate entries for 'store' element.\n // Do the de-dup here\n Map<String, Versioned<String>> storeNameToDefMap = new HashMap<String, Versioned<String>>();\n Version maxVersion = null;\n while(storesIterator.hasNext()) {\n Pair<String, Versioned<String>> storeDetail = storesIterator.next();\n String storeName = storeDetail.getFirst();\n Versioned<String> versionedStoreDef = storeDetail.getSecond();\n storeNameToDefMap.put(storeName, versionedStoreDef);\n Version curVersion = versionedStoreDef.getVersion();\n\n // Get the highest version from all the store entries\n if(maxVersion == null) {\n maxVersion = curVersion;\n } else if(maxVersion.compare(curVersion) == Occurred.BEFORE) {\n maxVersion = curVersion;\n }\n }\n\n // If the specified version is null, assign highest Version to\n // 'stores.xml' key\n if(finalStoresXmlVersion == null) {\n finalStoresXmlVersion = maxVersion;\n }\n\n // Go through all the individual stores and update metadata\n for(Entry<String, Versioned<String>> storeEntry: storeNameToDefMap.entrySet()) {\n String storeName = storeEntry.getKey();\n Versioned<String> versionedStoreDef = storeEntry.getValue();\n\n // Add all the store names to the list of storeNames\n this.storeNames.add(storeName);\n\n this.metadataCache.put(storeName, new Versioned<Object>(versionedStoreDef.getValue(),\n versionedStoreDef.getVersion()));\n }\n\n Collections.sort(this.storeNames);\n for(String storeName: this.storeNames) {\n Versioned<String> versionedStoreDef = storeNameToDefMap.get(storeName);\n // Stitch together to form the complete store definition list.\n allStoreDefinitions += versionedStoreDef.getValue();\n\n }\n\n allStoreDefinitions += \"</stores>\";\n\n // Update cache with the composite store definition list.\n metadataCache.put(STORES_KEY,\n convertStringToObject(STORES_KEY,\n new Versioned<String>(allStoreDefinitions,\n finalStoresXmlVersion)));\n }",
"public Object remove(String name) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\t\treturn context.remove(name);\n\t}",
"public static void validateZip(File file) throws IOException {\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n zipEntry = zipInput.getNextEntry();\n }\n\n try {\n if (zipInput != null) {\n zipInput.close();\n }\n } catch (IOException e) {\n }\n }",
"private long getTime(Date start1, Date end1, Date start2, Date end2)\n {\n long total = 0;\n\n if (start1 != null && end1 != null && start2 != null && end2 != null)\n {\n long start;\n long end;\n\n if (start1.getTime() < start2.getTime())\n {\n start = start2.getTime();\n }\n else\n {\n start = start1.getTime();\n }\n\n if (end1.getTime() < end2.getTime())\n {\n end = end1.getTime();\n }\n else\n {\n end = end2.getTime();\n }\n\n if (start < end)\n {\n total = end - start;\n }\n }\n\n return (total);\n }",
"public static base_response unset(nitro_service client, clusterinstance resource, String[] args) throws Exception{\n\t\tclusterinstance unsetresource = new clusterinstance();\n\t\tunsetresource.clid = resource.clid;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static float checkFloat(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInFloatRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), FLOAT_MIN, FLOAT_MAX);\n\t\t}\n\n\t\treturn number.floatValue();\n\t}",
"@Inject\n public void setQueue(EventQueue queue) {\n if (epi == null) {\n MessageToEventMapper mapper = new MessageToEventMapper();\n mapper.setMaxContentLength(maxContentLength);\n\n epi = new EventProducerInterceptor(mapper, queue);\n }\n }",
"public boolean removeWriter(Object key, Object resourceId)\r\n {\r\n boolean result = false;\r\n ObjectLocks objectLocks = null;\r\n synchronized(locktable)\r\n {\r\n objectLocks = (ObjectLocks) locktable.get(resourceId);\r\n if(objectLocks != null)\r\n {\r\n /**\r\n * MBAIRD, last one out, close the door and turn off the lights.\r\n * if no locks (readers or writers) exist for this object, let's remove\r\n * it from the locktable.\r\n */\r\n LockEntry entry = objectLocks.getWriter();\r\n if(entry != null && entry.isOwnedBy(key))\r\n {\r\n objectLocks.setWriter(null);\r\n result = true;\r\n\r\n // no need to check if writer is null, we just set it.\r\n if(objectLocks.getReaders().size() == 0)\r\n {\r\n locktable.remove(resourceId);\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }",
"private void updateMetadata(CdjStatus update, TrackMetadata data) {\n hotCache.put(DeckReference.getDeckReference(update.getDeviceNumber(), 0), data); // Main deck\n if (data.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : data.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.getDeviceNumber(), entry.hotCueNumber), data);\n }\n }\n }\n deliverTrackMetadataUpdate(update.getDeviceNumber(), data);\n }"
] |
Initialize the domain registry.
@param registry the domain registry | [
"public static void initializeDomainRegistry(final TransformerRegistry registry) {\n\n //The chains for transforming will be as follows\n //For JBoss EAP: 8.0.0 -> 5.0.0 -> 4.0.0 -> 1.8.0 -> 1.7.0 -> 1.6.0 -> 1.5.0\n\n registerRootTransformers(registry);\n registerChainedManagementTransformers(registry);\n registerChainedServerGroupTransformers(registry);\n registerProfileTransformers(registry);\n registerSocketBindingGroupTransformers(registry);\n registerDeploymentTransformers(registry);\n }"
] | [
"protected ViewPort load() {\n resize = Window.addResizeHandler(event -> {\n execute(event.getWidth(), event.getHeight());\n });\n\n execute(window().width(), (int)window().height());\n return viewPort;\n }",
"public void remove(Identity oid)\r\n {\r\n //processQueue();\r\n if(oid != null)\r\n {\r\n removeTracedIdentity(oid);\r\n objectTable.remove(buildKey(oid));\r\n if(log.isDebugEnabled()) log.debug(\"Remove object \" + oid);\r\n }\r\n }",
"private void persistDecorator(XMLExtendedStreamWriter writer, ModelNode model) throws XMLStreamException {\n if (shouldWriteDecoratorAndElements(model)) {\n writer.writeStartElement(decoratorElement);\n persistChildren(writer, model);\n writer.writeEndElement();\n }\n }",
"public static BoxAPIConnection getTransactionConnection(String accessToken, String scope, String resource) {\n BoxAPIConnection apiConnection = new BoxAPIConnection(accessToken);\n\n URL url;\n try {\n url = new URL(apiConnection.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid token URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid token URL indicates a bug in the SDK.\", e);\n }\n\n String urlParameters;\n try {\n urlParameters = String.format(\"grant_type=%s&subject_token=%s&subject_token_type=%s&scope=%s\", GRANT_TYPE,\n URLEncoder.encode(accessToken, \"UTF-8\"), SUBJECT_TOKEN_TYPE, URLEncoder.encode(scope, \"UTF-8\"));\n\n if (resource != null) {\n urlParameters += \"&resource=\" + URLEncoder.encode(resource, \"UTF-8\");\n }\n } catch (UnsupportedEncodingException e) {\n throw new BoxAPIException(\n \"An error occurred while attempting to encode url parameters for a transactional token request\"\n );\n }\n\n BoxAPIRequest request = new BoxAPIRequest(apiConnection, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n final String fileToken = responseJSON.get(\"access_token\").asString();\n BoxTransactionalAPIConnection transactionConnection = new BoxTransactionalAPIConnection(fileToken);\n transactionConnection.setExpires(responseJSON.get(\"expires_in\").asLong() * 1000);\n\n return transactionConnection;\n }",
"public static boolean canUseAsDelayedQueue(final Jedis jedis, final String key) {\n final String type = jedis.type(key);\n return (ZSET.equalsIgnoreCase(type) || NONE.equalsIgnoreCase(type));\n }",
"public void delete(boolean notifyUser, boolean force) {\n String queryString = new QueryStringBuilder()\n .appendParam(\"notify\", String.valueOf(notifyUser))\n .appendParam(\"force\", String.valueOf(force))\n .toString();\n\n URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"public void switchDataSource(BoneCPConfig newConfig) throws SQLException {\n\t\tlogger.info(\"Switch to new datasource requested. New Config: \"+newConfig);\n\t\tDataSource oldDS = getTargetDataSource();\n \n\t\tif (!(oldDS instanceof BoneCPDataSource)){\n\t\t\tthrow new SQLException(\"Unknown datasource type! Was expecting BoneCPDataSource but received \"+oldDS.getClass()+\". Not switching datasource!\");\n\t\t}\n\t\t\n\t\tBoneCPDataSource newDS = new BoneCPDataSource(newConfig);\n\t\tnewDS.getConnection().close(); // initialize a connection (+ throw it away) to force the datasource to initialize the pool\n\t\t\n\t\t// force application to start using the new one \n\t\tsetTargetDataSource(newDS);\n\t\t\n\t\tlogger.info(\"Shutting down old datasource slowly. Old Config: \"+oldDS);\n\t\t// tell the old datasource to terminate. This terminates the pool lazily so existing checked out connections can still be used.\n\t\t((BoneCPDataSource)oldDS).close();\n\t}",
"public static ComponentsMultiThread getComponentsMultiThread() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.componentsMultiThread;\n }",
"@SuppressWarnings(\"unchecked\")\r\n public static boolean addPropertyDefault(PropertiesImpl props, PropertyDefinition<?> propDef) {\r\n\r\n if ((props == null) || (props.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Props must not be null!\");\r\n }\r\n\r\n if (propDef == null) {\r\n return false;\r\n }\r\n\r\n List<?> defaultValue = propDef.getDefaultValue();\r\n if ((defaultValue != null) && (!defaultValue.isEmpty())) {\r\n switch (propDef.getPropertyType()) {\r\n case BOOLEAN:\r\n props.addProperty(new PropertyBooleanImpl(propDef.getId(), (List<Boolean>)defaultValue));\r\n break;\r\n case DATETIME:\r\n props.addProperty(new PropertyDateTimeImpl(propDef.getId(), (List<GregorianCalendar>)defaultValue));\r\n break;\r\n case DECIMAL:\r\n props.addProperty(new PropertyDecimalImpl(propDef.getId(), (List<BigDecimal>)defaultValue));\r\n break;\r\n case HTML:\r\n props.addProperty(new PropertyHtmlImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case ID:\r\n props.addProperty(new PropertyIdImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case INTEGER:\r\n props.addProperty(new PropertyIntegerImpl(propDef.getId(), (List<BigInteger>)defaultValue));\r\n break;\r\n case STRING:\r\n props.addProperty(new PropertyStringImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case URI:\r\n props.addProperty(new PropertyUriImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n default:\r\n throw new RuntimeException(\"Unknown datatype! Spec change?\");\r\n }\r\n\r\n return true;\r\n }\r\n\r\n return false;\r\n }"
] |
Builds a configuration object based on given properties.
@param properties the properties.
@return a configuration and never null. | [
"public GreenMailConfiguration build(Properties properties) {\n GreenMailConfiguration configuration = new GreenMailConfiguration();\n String usersParam = properties.getProperty(GREENMAIL_USERS);\n if (null != usersParam) {\n String[] usersArray = usersParam.split(\",\");\n for (String user : usersArray) {\n extractAndAddUser(configuration, user);\n }\n }\n String disabledAuthentication = properties.getProperty(GREENMAIL_AUTH_DISABLED);\n if (null != disabledAuthentication) {\n configuration.withDisabledAuthentication();\n }\n return configuration;\n }"
] | [
"protected void aliasGeneric( Object variable , String name ) {\n if( variable.getClass() == Integer.class ) {\n alias(((Integer)variable).intValue(),name);\n } else if( variable.getClass() == Double.class ) {\n alias(((Double)variable).doubleValue(),name);\n } else if( variable.getClass() == DMatrixRMaj.class ) {\n alias((DMatrixRMaj)variable,name);\n } else if( variable.getClass() == FMatrixRMaj.class ) {\n alias((FMatrixRMaj)variable,name);\n } else if( variable.getClass() == DMatrixSparseCSC.class ) {\n alias((DMatrixSparseCSC)variable,name);\n } else if( variable.getClass() == SimpleMatrix.class ) {\n alias((SimpleMatrix) variable, name);\n } else if( variable instanceof DMatrixFixed ) {\n DMatrixRMaj M = new DMatrixRMaj(1,1);\n ConvertDMatrixStruct.convert((DMatrixFixed)variable,M);\n alias(M,name);\n } else if( variable instanceof FMatrixFixed ) {\n FMatrixRMaj M = new FMatrixRMaj(1,1);\n ConvertFMatrixStruct.convert((FMatrixFixed)variable,M);\n alias(M,name);\n } else {\n throw new RuntimeException(\"Unknown value type of \"+\n (variable.getClass().getSimpleName())+\" for variable \"+name);\n }\n }",
"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 }",
"public static void outputString(final HttpServletResponse response, final Object obj) {\n try {\n response.setContentType(\"text/javascript\");\n response.setCharacterEncoding(\"utf-8\");\n disableCache(response);\n response.getWriter().write(obj.toString());\n response.getWriter().flush();\n response.getWriter().close();\n } catch (IOException e) {\n }\n }",
"public static String encode(String value) throws UnsupportedEncodingException {\n if (isNullOrEmpty(value)) return value;\n return URLEncoder.encode(value, URL_ENCODING);\n }",
"public void updateColor(TestColor color) {\n\n switch (color) {\n case green:\n m_forwardButton.setEnabled(true);\n m_confirmCheckbox.setVisible(false);\n m_status.setValue(STATUS_GREEN);\n break;\n case yellow:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_YELLOW);\n break;\n case red:\n m_forwardButton.setEnabled(false);\n m_confirmCheckbox.setVisible(true);\n m_status.setValue(STATUS_RED);\n break;\n default:\n break;\n }\n }",
"public <FV> FV getFieldValueIfNotDefault(Object object) throws SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tFV fieldValue = (FV) extractJavaFieldValue(object);\n\t\tif (isFieldValueDefault(fieldValue)) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldValue;\n\t\t}\n\t}",
"public AddonChange removeAddon(String appName, String addonName) {\n return connection.execute(new AddonRemove(appName, addonName), apiKey);\n }",
"public double getRate(AnalyticModel model) {\n\t\tif(model==null) {\n\t\t\tthrow new IllegalArgumentException(\"model==null\");\n\t\t}\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve==null) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve of name '\" + forwardCurveName + \"' found in given model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble fixingDate = schedule.getFixing(0);\n\t\treturn forwardCurve.getForward(model,fixingDate);\n\t}",
"private float MIN(float first, float second, float third) {\r\n\r\n float min = Integer.MAX_VALUE;\r\n if (first < min) {\r\n min = first;\r\n }\r\n if (second < min) {\r\n min = second;\r\n }\r\n if (third < min) {\r\n min = third;\r\n }\r\n return min;\r\n }"
] |
Read a nested table. Instantiates the supplied reader class to
extract the data.
@param reader table reader class
@return table rows | [
"public List<MapRow> readTable(TableReader reader) throws IOException\n {\n reader.read();\n return reader.getRows();\n }"
] | [
"public static lbsipparameters get(nitro_service service) throws Exception{\n\t\tlbsipparameters obj = new lbsipparameters();\n\t\tlbsipparameters[] response = (lbsipparameters[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static String getDumpFileWebDirectory(\n\t\t\tDumpContentType dumpContentType, String projectName) {\n\t\tif (dumpContentType == DumpContentType.JSON) {\n\t\t\tif (\"wikidatawiki\".equals(projectName)) {\n\t\t\t\treturn WmfDumpFile.DUMP_SITE_BASE_URL\n\t\t\t\t\t\t+ WmfDumpFile.WEB_DIRECTORY.get(dumpContentType)\n\t\t\t\t\t\t+ \"wikidata\" + \"/\";\n\t\t\t} else {\n\t\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\t\"Wikimedia Foundation uses non-systematic directory names for this type of dump file.\"\n\t\t\t\t\t\t\t\t+ \" I don't know where to find dumps of project \"\n\t\t\t\t\t\t\t\t+ projectName);\n\t\t\t}\n\t\t} else if (WmfDumpFile.WEB_DIRECTORY.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.DUMP_SITE_BASE_URL\n\t\t\t\t\t+ WmfDumpFile.WEB_DIRECTORY.get(dumpContentType)\n\t\t\t\t\t+ projectName + \"/\";\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}",
"private void checkOrMarkPrivateAccess(Expression source, FieldNode fn) {\n if (fn!=null && Modifier.isPrivate(fn.getModifiers()) &&\n (fn.getDeclaringClass() != typeCheckingContext.getEnclosingClassNode() || typeCheckingContext.getEnclosingClosure()!=null) &&\n fn.getDeclaringClass().getModule() == typeCheckingContext.getEnclosingClassNode().getModule()) {\n addPrivateFieldOrMethodAccess(source, fn.getDeclaringClass(), StaticTypesMarker.PV_FIELDS_ACCESS, fn);\n }\n }",
"private XopBean createXopBean() throws Exception {\n XopBean xop = new XopBean();\n xop.setName(\"xopName\");\n \n InputStream is = getClass().getResourceAsStream(\"/java.jpg\");\n byte[] data = IOUtils.readBytesFromStream(is);\n \n // Pass java.jpg as an array of bytes\n xop.setBytes(data);\n \n // Wrap java.jpg as a DataHandler\n xop.setDatahandler(new DataHandler(\n new ByteArrayDataSource(data, \"application/octet-stream\")));\n \n if (Boolean.getBoolean(\"java.awt.headless\")) {\n System.out.println(\"Running headless. Ignoring an Image property.\");\n } else {\n xop.setImage(getImage(\"/java.jpg\"));\n }\n \n return xop;\n }",
"public static Envelope getTileBounds(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble[] layerSize = getTileLayerSize(code, maxExtent, scale);\n\t\tif (layerSize[0] == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tdouble cX = maxExtent.getMinX() + code.getX() * layerSize[0];\n\t\tdouble cY = maxExtent.getMinY() + code.getY() * layerSize[1];\n\t\treturn new Envelope(cX, cX + layerSize[0], cY, cY + layerSize[1]);\n\t}",
"public static String getStateKey(CmsResourceState state) {\n\n StringBuffer sb = new StringBuffer(STATE_PREFIX);\n sb.append(state);\n sb.append(STATE_POSTFIX);\n return sb.toString();\n\n }",
"protected long save() {\n // save leaf nodes\n ReclaimFlag flag = saveChildren();\n // save self. complementary to {@link load()}\n final byte type = getType();\n final BTreeBase tree = getTree();\n final int structureId = tree.structureId;\n final Log log = tree.log;\n if (flag == ReclaimFlag.PRESERVE) {\n // there is a chance to update the flag to RECLAIM\n if (log.getWrittenHighAddress() % log.getFileLengthBound() == 0) {\n // page will be exactly on file border\n flag = ReclaimFlag.RECLAIM;\n } else {\n final ByteIterable[] iterables = getByteIterables(flag);\n long result = log.tryWrite(type, structureId, new CompoundByteIterable(iterables));\n if (result < 0) {\n iterables[0] = CompressedUnsignedLongByteIterable.getIterable(\n (size << 1) + ReclaimFlag.RECLAIM.value\n );\n result = log.writeContinuously(type, structureId, new CompoundByteIterable(iterables));\n\n if (result < 0) {\n throw new TooBigLoggableException();\n }\n }\n return result;\n }\n }\n return log.write(type, structureId, new CompoundByteIterable(getByteIterables(flag)));\n }",
"public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline,\n Class<? extends WindupVertexFrame> clazz)\n {\n pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz));\n return pipeline;\n }",
"public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }"
] |
Clear all overrides, reset repeat counts for a request path
@param pathId ID of path
@param clientUUID UUID of client
@throws Exception exception | [
"public void clearRequestSettings(int pathId, String clientUUID) throws Exception {\n this.setRequestEnabled(pathId, false, clientUUID);\n OverrideService.getInstance().disableAllOverrides(pathId, clientUUID, Constants.OVERRIDE_TYPE_REQUEST);\n EditService.getInstance().updateRepeatNumber(Constants.OVERRIDE_TYPE_REQUEST, pathId, clientUUID);\n }"
] | [
"@Override\n public void setExpectedMaxSize( int numRows , int numCols ) {\n super.setExpectedMaxSize(numRows,numCols);\n\n // if the matrix that is being decomposed is smaller than the block we really don't\n // see the B matrix.\n if( numRows < blockWidth)\n B = new DMatrixRMaj(0,0);\n else\n B = new DMatrixRMaj(blockWidth,maxWidth);\n\n chol = new CholeskyBlockHelper_DDRM(blockWidth);\n }",
"public RedwoodConfiguration clear(){\r\n tasks = new LinkedList<Runnable>();\r\n tasks.add(new Runnable(){ public void run(){\r\n Redwood.clearHandlers();\r\n Redwood.restoreSystemStreams();\r\n Redwood.clearLoggingClasses();\r\n } });\r\n return this;\r\n }",
"public static cacheselector[] get(nitro_service service, options option) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tcacheselector[] response = (cacheselector[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"public List<Complex_F64> getEigenvalues() {\n List<Complex_F64> ret = new ArrayList<Complex_F64>();\n\n if( is64 ) {\n EigenDecomposition_F64 d = (EigenDecomposition_F64)eig;\n for (int i = 0; i < eig.getNumberOfEigenvalues(); i++) {\n ret.add(d.getEigenvalue(i));\n }\n } else {\n EigenDecomposition_F32 d = (EigenDecomposition_F32)eig;\n for (int i = 0; i < eig.getNumberOfEigenvalues(); i++) {\n Complex_F32 c = d.getEigenvalue(i);\n ret.add(new Complex_F64(c.real, c.imaginary));\n }\n }\n\n return ret;\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 }",
"private static boolean containsObject(Object searchFor, Object[] searchIn)\r\n {\r\n for (int i = 0; i < searchIn.length; i++)\r\n {\r\n if (searchFor == searchIn[i])\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public static ResourceField getInstance(int value)\n {\n ResourceField result = null;\n\n if (value >= 0 && value < FIELD_ARRAY.length)\n {\n result = FIELD_ARRAY[value];\n }\n else\n {\n if ((value & 0x8000) != 0)\n {\n int baseValue = ResourceField.ENTERPRISE_CUSTOM_FIELD1.getValue();\n int id = baseValue + (value & 0xFFF);\n result = ResourceField.getInstance(id);\n }\n }\n\n return (result);\n }",
"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 }",
"private boolean isInInnerCircle(float x, float y) {\n return GearWearableUtility.isInCircle(x, y, CENTER_X, CENTER_Y, INNER_RADIUS);\n }"
] |
Set the view frustum to pick against from the field of view, aspect
ratio and near, far clip planes. The viewpoint of the frustum
is the center of the scene object the picker is attached to.
The view direction is the forward direction of that scene object.
The frustum will pick what a camera attached to the scene object
with that view frustum would see. If the frustum is not attached
to a scene object, it defaults to the view frustum of the main camera of the scene.
@param fovy vertical field of view in degrees
@param aspect aspect ratio (width / height) | [
"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 }"
] | [
"@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (summaryFile != null) {\n try {\n Persister persister = new Persister();\n persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize summary report.\", x, Project.MSG_WARN);\n }\n }\n }",
"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 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 }",
"public CollectionRequest<Attachment> findByTask(String task) {\n \n String path = String.format(\"/tasks/%s/attachments\", task);\n return new CollectionRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }",
"@Override\n public View getView(int position, View convertView, ViewGroup parent) {\n if (position == super.getCount() && isEnableRefreshing()) {\n return (mFooter);\n }\n return (super.getView(position, convertView, parent));\n }",
"private void processCustomValueLists() throws IOException\n {\n CustomFieldValueReader9 reader = new CustomFieldValueReader9(m_projectDir, m_file.getProjectProperties(), m_projectProps, m_file.getCustomFields());\n reader.process();\n }",
"protected void checkProducerMethod(EnhancedAnnotatedMethod<T, ? super X> method) {\n if (method.getEnhancedParameters(Observes.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@Observes\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (method.getEnhancedParameters(ObservesAsync.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@ObservesAsync\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (method.getEnhancedParameters(Disposes.class).size() > 0) {\n throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, \"@Disposes\", this.method,\n Formats.formatAsStackTraceElement(method.getJavaMember()));\n } else if (getDeclaringBean() instanceof SessionBean<?> && !Modifier.isStatic(method.slim().getJavaMember().getModifiers())) {\n boolean methodDeclaredOnTypes = false;\n for (Type type : getDeclaringBean().getTypes()) {\n Class<?> clazz = Reflections.getRawType(type);\n try {\n AccessController.doPrivileged(new GetMethodAction(clazz, method.getName(), method.getParameterTypesAsArray()));\n methodDeclaredOnTypes = true;\n break;\n } catch (PrivilegedActionException ignored) {\n }\n }\n if (!methodDeclaredOnTypes) {\n throw BeanLogger.LOG.methodNotBusinessMethod(\"Producer\", this, getDeclaringBean(), Formats.formatAsStackTraceElement(method.getJavaMember()));\n }\n }\n }",
"private void addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n try\n {\n switch (fieldType)\n {\n case TASK:\n TaskField taskField;\n\n do\n {\n taskField = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (m_taskFields.containsKey(taskField) || m_wbsFields.containsKey(taskField));\n\n m_project.getCustomFields().getCustomField(taskField).setAlias(name);\n\n break;\n case RESOURCE:\n ResourceField resourceField;\n\n do\n {\n resourceField = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n }\n while (m_resourceFields.containsKey(resourceField));\n\n m_project.getCustomFields().getCustomField(resourceField).setAlias(name);\n\n break;\n case ASSIGNMENT:\n AssignmentField assignmentField;\n\n do\n {\n assignmentField = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n }\n while (m_assignmentFields.containsKey(assignmentField));\n\n m_project.getCustomFields().getCustomField(assignmentField).setAlias(name);\n\n break;\n default:\n break;\n }\n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\n }",
"public DynamicReport build() {\n\n if (built) {\n throw new DJBuilderException(\"DynamicReport already built. Cannot use more than once.\");\n } else {\n built = true;\n }\n\n report.setOptions(options);\n if (!globalVariablesGroup.getFooterVariables().isEmpty() || !globalVariablesGroup.getHeaderVariables().isEmpty() || !globalVariablesGroup.getVariables().isEmpty() || hasPercentageColumn()) {\n report.getColumnsGroups().add(0, globalVariablesGroup);\n }\n\n createChartGroups();\n\n addGlobalCrosstabs();\n\n addSubreportsToGroups();\n\n concatenateReports();\n\n report.setAutoTexts(autoTexts);\n return report;\n }"
] |
Used to finish up pushing the bulge off the matrix. | [
"private void rotatorPushRight2( int m , int offset)\n {\n double b11 = bulge;\n double b12 = diag[m+offset];\n\n computeRotator(b12,-b11);\n\n diag[m+offset] = b12*c-b11*s;\n\n if( m+offset<N-1) {\n double b22 = off[m+offset];\n off[m+offset] = b22*c;\n bulge = b22*s;\n }\n\n// SimpleMatrix Q = createQ(m,m+offset, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+offset,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }"
] | [
"public static base_responses delete(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 deleteresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new route6();\n\t\t\t\tdeleteresources[i].network = resources[i].network;\n\t\t\t\tdeleteresources[i].gateway = resources[i].gateway;\n\t\t\t\tdeleteresources[i].vlan = resources[i].vlan;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static final BigDecimal printDurationInDecimalThousandthsOfMinutes(Duration duration)\n {\n BigDecimal result = null;\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigDecimal.valueOf(printDurationFractionsOfMinutes(duration, 1000));\n }\n return result;\n }",
"public int nextToken() throws IOException\n {\n int c;\n int nextc = -1;\n boolean quoted = false;\n int result = m_next;\n if (m_next != 0)\n {\n m_next = 0;\n }\n\n m_buffer.setLength(0);\n\n while (result == 0)\n {\n if (nextc != -1)\n {\n c = nextc;\n nextc = -1;\n }\n else\n {\n c = read();\n }\n\n switch (c)\n {\n case TT_EOF:\n {\n if (m_buffer.length() != 0)\n {\n result = TT_WORD;\n m_next = TT_EOF;\n }\n else\n {\n result = TT_EOF;\n }\n break;\n }\n\n case TT_EOL:\n {\n int length = m_buffer.length();\n\n if (length != 0 && m_buffer.charAt(length - 1) == '\\r')\n {\n --length;\n m_buffer.setLength(length);\n }\n\n if (length == 0)\n {\n result = TT_EOL;\n }\n else\n {\n result = TT_WORD;\n m_next = TT_EOL;\n }\n\n break;\n }\n\n default:\n {\n if (c == m_quote)\n {\n if (quoted == false && startQuotedIsValid(m_buffer))\n {\n quoted = true;\n }\n else\n {\n if (quoted == false)\n {\n m_buffer.append((char) c);\n }\n else\n {\n nextc = read();\n if (nextc == m_quote)\n {\n m_buffer.append((char) c);\n nextc = -1;\n }\n else\n {\n quoted = false;\n }\n }\n }\n }\n else\n {\n if (c == m_delimiter && quoted == false)\n {\n result = TT_WORD;\n }\n else\n {\n m_buffer.append((char) c);\n }\n }\n }\n }\n }\n\n m_type = result;\n\n return (result);\n }",
"public static String readFlowId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String flowId = null;\n Header hdFlowId = ((SoapMessage)message).getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n if (hdFlowId.getObject() instanceof String) {\n flowId = (String)hdFlowId.getObject();\n } else if (hdFlowId.getObject() instanceof Node) {\n Node headerNode = (Node)hdFlowId.getObject();\n flowId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found FlowId soap header but value is not a String or a Node! Value: \"\n + hdFlowId.getObject().toString());\n }\n }\n return flowId;\n }",
"protected List<String> parseWords(String line) {\n List<String> words = new ArrayList<String>();\n boolean insideWord = !isSpace(line.charAt(0));\n int last = 0;\n for( int i = 0; i < line.length(); i++) {\n char c = line.charAt(i);\n\n if( insideWord ) {\n // see if its at the end of a word\n if( isSpace(c)) {\n words.add( line.substring(last,i) );\n insideWord = false;\n }\n } else {\n if( !isSpace(c)) {\n last = i;\n insideWord = true;\n }\n }\n }\n\n // if the line ended add the final word\n if( insideWord ) {\n words.add( line.substring(last));\n }\n return words;\n }",
"public TokenList extractSubList( Token begin , Token end ) {\n if( begin == end ) {\n remove(begin);\n return new TokenList(begin,begin);\n } else {\n if( first == begin ) {\n first = end.next;\n }\n if( last == end ) {\n last = begin.previous;\n }\n if( begin.previous != null ) {\n begin.previous.next = end.next;\n }\n if( end.next != null ) {\n end.next.previous = begin.previous;\n }\n begin.previous = null;\n end.next = null;\n\n TokenList ret = new TokenList(begin,end);\n size -= ret.size();\n return ret;\n }\n }",
"public boolean detectBlackBerryTouch() {\r\n\r\n if (detectBlackBerry()\r\n && ((userAgent.indexOf(deviceBBStorm) != -1)\r\n || (userAgent.indexOf(deviceBBTorch) != -1)\r\n || (userAgent.indexOf(deviceBBBoldTouch) != -1)\r\n || (userAgent.indexOf(deviceBBCurveTouch) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }",
"static String findNonProgressingOp(Resource resource, boolean forServer, long timeout) throws OperationFailedException {\n\n Resource.ResourceEntry nonProgressing = null;\n for (Resource.ResourceEntry child : resource.getChildren(ACTIVE_OPERATION)) {\n ModelNode model = child.getModel();\n if (model.get(EXCLUSIVE_RUNNING_TIME).asLong() > timeout) {\n nonProgressing = child;\n ControllerLogger.MGMT_OP_LOGGER.tracef(\"non-progressing op: %s\", nonProgressing.getModel());\n break;\n }\n }\n if (nonProgressing != null && !forServer) {\n // WFCORE-263\n // See if the op is non-progressing because it's the HC op waiting for commit\n // from the DC while other ops (i.e. ops proxied to our servers) associated\n // with the same domain-uuid are not completing\n ModelNode model = nonProgressing.getModel();\n if (model.get(DOMAIN_ROLLOUT).asBoolean()\n && OperationContext.ExecutionStatus.COMPLETING.toString().equals(model.get(EXECUTION_STATUS).asString())\n && model.hasDefined(DOMAIN_UUID)) {\n ControllerLogger.MGMT_OP_LOGGER.trace(\"Potential domain rollout issue\");\n String domainUUID = model.get(DOMAIN_UUID).asString();\n\n Set<String> relatedIds = null;\n List<Resource.ResourceEntry> relatedExecutingOps = null;\n for (Resource.ResourceEntry activeOp : resource.getChildren(ACTIVE_OPERATION)) {\n if (nonProgressing.getName().equals(activeOp.getName())) {\n continue; // ignore self\n }\n ModelNode opModel = activeOp.getModel();\n if (opModel.hasDefined(DOMAIN_UUID) && domainUUID.equals(opModel.get(DOMAIN_UUID).asString())\n && opModel.get(RUNNING_TIME).asLong() > timeout) {\n if (relatedIds == null) {\n relatedIds = new TreeSet<String>(); // order these as an aid to unit testing\n }\n relatedIds.add(activeOp.getName());\n\n // If the op is ExecutionStatus.EXECUTING that means it's still EXECUTING on the\n // server or a prepare message got lost. It would be COMPLETING if the server\n // had sent a prepare message, as that would result in ProxyStepHandler calling completeStep\n if (OperationContext.ExecutionStatus.EXECUTING.toString().equals(opModel.get(EXECUTION_STATUS).asString())) {\n if (relatedExecutingOps == null) {\n relatedExecutingOps = new ArrayList<Resource.ResourceEntry>();\n }\n relatedExecutingOps.add(activeOp);\n ControllerLogger.MGMT_OP_LOGGER.tracef(\"Related executing: %s\", opModel);\n } else ControllerLogger.MGMT_OP_LOGGER.tracef(\"Related non-executing: %s\", opModel);\n } else ControllerLogger.MGMT_OP_LOGGER.tracef(\"unrelated: %s\", opModel);\n }\n\n if (relatedIds != null) {\n // There are other ops associated with this domain-uuid that are also not completing\n // in the desired time, so we can't treat the one holding the lock as the problem.\n if (relatedExecutingOps != null && relatedExecutingOps.size() == 1) {\n // There's a single related op that's executing for too long. So we can report that one.\n // Note that it's possible that the same problem exists on other hosts as well\n // and that this cancellation will not resolve the overall problem. But, we only\n // get here on a slave HC and if the user is invoking this on a slave and not the\n // master, we'll assume they have a reason for doing that and want us to treat this\n // as a problem on this particular host.\n nonProgressing = relatedExecutingOps.get(0);\n } else {\n // Fail and provide a useful failure message.\n throw DomainManagementLogger.ROOT_LOGGER.domainRolloutNotProgressing(nonProgressing.getName(),\n timeout, domainUUID, relatedIds);\n }\n }\n }\n }\n\n return nonProgressing == null ? null : nonProgressing.getName();\n }",
"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 }"
] |
Encode a path segment, escaping characters not valid for a URL.
<p>The following characters are not escaped:
<ul>
<li>{@code a..z, A..Z, 0..9}
<li>{@code . - * _}
</ul>
<p>' ' (space) is encoded as '+'.
<p>All other characters (including '/') are converted to the triplet "%xy" where "xy" is the
hex representation of the character in UTF-8.
@param component a string containing text to encode.
@return a string with all invalid URL characters escaped. | [
"public static String encode(String component) {\n if (component != null) {\n try {\n return URLEncoder.encode(component, UTF_8.name());\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"JVM must support UTF-8\", e);\n }\n }\n return null;\n }"
] | [
"public static List<String> getStoreNames(List<StoreDefinition> storeDefList) {\n List<String> storeList = new ArrayList<String>();\n for(StoreDefinition def: storeDefList) {\n storeList.add(def.getName());\n }\n return storeList;\n }",
"public final void notifyHeaderItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newHeaderItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (newHeaderItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart, itemCount);\n }",
"public static GlobalParameter create(DbConn cnx, String key, String value)\n {\n QueryResult r = cnx.runUpdate(\"globalprm_insert\", key, value);\n GlobalParameter res = new GlobalParameter();\n res.id = r.getGeneratedId();\n res.key = key;\n res.value = value;\n return res;\n }",
"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 }",
"public static List<DockerImage> getAndDiscardImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n synchronized(images) {\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId) {\n if (image.hasManifest()) {\n list.add(image);\n }\n it.remove();\n } else // Remove old images from the cache, for which build-info hasn't been published to Artifactory:\n if (image.isExpired()) {\n it.remove();\n }\n }\n }\n return list;\n }",
"private static Iterator<String> splitIntoDocs(Reader r) {\r\n if (TREAT_FILE_AS_ONE_DOCUMENT) {\r\n return Collections.singleton(IOUtils.slurpReader(r)).iterator();\r\n } else {\r\n Collection<String> docs = new ArrayList<String>();\r\n ObjectBank<String> ob = ObjectBank.getLineIterator(r);\r\n StringBuilder current = new StringBuilder();\r\n for (String line : ob) {\r\n if (docPattern.matcher(line).lookingAt()) {\r\n // Start new doc, store old one if non-empty\r\n if (current.length() > 0) {\r\n docs.add(current.toString());\r\n current = new StringBuilder();\r\n }\r\n }\r\n current.append(line);\r\n current.append('\\n');\r\n }\r\n if (current.length() > 0) {\r\n docs.add(current.toString());\r\n }\r\n return docs.iterator();\r\n }\r\n }",
"public synchronized void addNodesToWorkerList(List<Integer> nodeIds) {\n // Bookkeeping for nodes that will be involved in the next task\n nodeIdsWithWork.addAll(nodeIds);\n logger.info(\"Node IDs with work: \" + nodeIdsWithWork + \" Newly added nodes \" + nodeIds);\n }",
"public boolean detectMobileQuick() {\r\n\r\n //Let's exclude tablets\r\n if (isTierTablet) {\r\n return false;\r\n }\r\n //Most mobile browsing is done on smartphones\r\n if (detectSmartphone()) {\r\n return true;\r\n }\r\n\r\n //Catch-all for many mobile devices\r\n if (userAgent.indexOf(mobile) != -1) {\r\n return true;\r\n }\r\n\r\n if (detectOperaMobile()) {\r\n return true;\r\n }\r\n\r\n //We also look for Kindle devices\r\n if (detectKindle() || detectAmazonSilk()) {\r\n return true;\r\n }\r\n\r\n if (detectWapWml() || detectMidpCapable() || detectBrewDevice()) {\r\n return true;\r\n }\r\n\r\n if ((userAgent.indexOf(engineNetfront) != -1) || (userAgent.indexOf(engineUpBrowser) != -1)) {\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"private static Constructor retrieveCollectionProxyConstructor(Class proxyClass, Class baseType, String typeDesc)\r\n {\r\n if(proxyClass == null)\r\n {\r\n throw new MetadataException(\"No \" + typeDesc + \" specified.\");\r\n }\r\n if(proxyClass.isInterface() || Modifier.isAbstract(proxyClass.getModifiers()) || !baseType.isAssignableFrom(proxyClass))\r\n {\r\n throw new MetadataException(\"Illegal class \"\r\n + proxyClass.getName()\r\n + \" specified for \"\r\n + typeDesc\r\n + \". Must be a concrete subclass of \"\r\n + baseType.getName());\r\n }\r\n\r\n Class[] paramType = {PBKey.class, Class.class, Query.class};\r\n\r\n try\r\n {\r\n return proxyClass.getConstructor(paramType);\r\n }\r\n catch(NoSuchMethodException ex)\r\n {\r\n throw new MetadataException(\"The class \"\r\n + proxyClass.getName()\r\n + \" specified for \"\r\n + typeDesc\r\n + \" is required to have a public constructor with signature (\"\r\n + PBKey.class.getName()\r\n + \", \"\r\n + Class.class.getName()\r\n + \", \"\r\n + Query.class.getName()\r\n + \").\");\r\n }\r\n }"
] |
See if a simple sequence can be used to extract the array. A simple extent is a continuous block from
a min to max index
@return true if it is a simple range or false if not | [
"private static boolean extractSimpleExtents(Variable var, Extents e, boolean row, int length) {\n int lower;\n int upper;\n if( var.getType() == VariableType.INTEGER_SEQUENCE ) {\n IntegerSequence sequence = ((VariableIntegerSequence)var).sequence;\n if( sequence.getType() == IntegerSequence.Type.FOR ) {\n IntegerSequence.For seqFor = (IntegerSequence.For)sequence;\n seqFor.initialize(length);\n if( seqFor.getStep() == 1 ) {\n lower = seqFor.getStart();\n upper = seqFor.getEnd();\n } else {\n return false;\n }\n } else {\n return false;\n }\n } else if( var.getType() == VariableType.SCALAR ) {\n lower = upper = ((VariableInteger)var).value;\n } else {\n throw new RuntimeException(\"How did a bad variable get put here?!?!\");\n }\n if( row ) {\n e.row0 = lower;\n e.row1 = upper;\n } else {\n e.col0 = lower;\n e.col1 = upper;\n }\n return true;\n }"
] | [
"private boolean activityIsMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"Milestone\") != -1;\n }",
"public void addTags(String photoId, String[] tags) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_TAGS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \", true));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"private static void waitUntilFinished(FluoConfiguration config) {\n try (Environment env = new Environment(config)) {\n List<TableRange> ranges = getRanges(env);\n\n outer: while (true) {\n long ts1 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n for (TableRange range : ranges) {\n boolean sawNotifications = waitTillNoNotifications(env, range);\n if (sawNotifications) {\n ranges = getRanges(env);\n // This range had notifications. Processing those notifications may have created\n // notifications in previously scanned ranges, so start over.\n continue outer;\n }\n }\n long ts2 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n\n // Check to ensure the Oracle issued no timestamps during the scan for notifications.\n if (ts2 - ts1 == 1) {\n break;\n }\n }\n } catch (Exception e) {\n log.error(\"An exception was thrown -\", e);\n System.exit(-1);\n }\n }",
"@Override\n public EditMode editMode() {\n if(readInputrc) {\n try {\n return EditModeBuilder.builder().parseInputrc(new FileInputStream(inputrc())).create();\n }\n catch(FileNotFoundException e) {\n return EditModeBuilder.builder(mode()).create();\n }\n }\n else\n return EditModeBuilder.builder(mode()).create();\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 }",
"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 TimeUnit getFormat(int format)\n {\n TimeUnit result;\n if (format == 0xFFFF)\n {\n result = TimeUnit.HOURS;\n }\n else\n {\n result = MPPUtility.getWorkTimeUnits(format);\n }\n return result;\n }",
"public int getSridFromCrs(String crs) {\n\t\tint crsInt;\n\t\tif (crs.indexOf(':') != -1) {\n\t\t\tcrsInt = Integer.parseInt(crs.substring(crs.indexOf(':') + 1));\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tcrsInt = Integer.parseInt(crs);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\tcrsInt = 0;\n\t\t\t}\n\t\t}\n\t\treturn crsInt;\n\t}",
"protected void addFreeConnection(ConnectionHandle connectionHandle) throws SQLException{\r\n\t\tconnectionHandle.setOriginatingPartition(this);\r\n\t\t// assume success to avoid racing where we insert an item in a queue and having that item immediately\r\n\t\t// taken and closed off thus decrementing the created connection count.\r\n\t\tupdateCreatedConnections(1);\r\n\t\tif (!this.disableTracking){\r\n\t\t\ttrackConnectionFinalizer(connectionHandle); \r\n\t\t}\r\n\t\t\r\n\t\t// the instant the following line is executed, consumers can start making use of this \r\n\t\t// connection.\r\n\t\tif (!this.freeConnections.offer(connectionHandle)){\r\n\t\t\t// we failed. rollback.\r\n\t\t\tupdateCreatedConnections(-1); // compensate our createdConnection count.\r\n\t\t\t\r\n\t\t\tif (!this.disableTracking){\r\n\t\t\t\tthis.pool.getFinalizableRefs().remove(connectionHandle.getInternalConnection());\r\n\t\t\t}\r\n\t\t\t// terminate the internal handle.\r\n\t\t\tconnectionHandle.internalClose();\r\n\t\t}\r\n\t}"
] |
Sets all elements in this matrix to their absolute values. Note
that this operation is in-place.
@see MatrixFunctions#abs(DoubleMatrix)
@return this matrix | [
"public static DoubleMatrix absi(DoubleMatrix x) { \n\t\t/*# mapfct('Math.abs') #*/\n//RJPP-BEGIN------------------------------------------------------------\n\t for (int i = 0; i < x.length; i++)\n\t x.put(i, (double) Math.abs(x.get(i)));\n\t return x;\n//RJPP-END--------------------------------------------------------------\n\t}"
] | [
"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 }",
"private static Query buildQuery(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n Criteria crit = new Criteria();\r\n\r\n for(int i = 0; i < pkFields.length; i++)\r\n {\r\n crit.addEqualTo(pkFields[i].getAttributeName(), null);\r\n }\r\n return new QueryByCriteria(cld.getClassOfObject(), crit);\r\n }",
"private Profile getProfileFromResultSet(ResultSet result) throws Exception {\n Profile profile = new Profile();\n profile.setId(result.getInt(Constants.GENERIC_ID));\n Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);\n String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());\n profile.setName(profileName);\n return profile;\n }",
"public ValueContainer[] getCurrentLockingValues(Object o) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n ValueContainer[] result = new ValueContainer[fields.length];\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n result[i] = new ValueContainer(fields[i].getPersistentField().get(o), fields[i].getJdbcType());\r\n }\r\n return result;\r\n }",
"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 }",
"@Pure\n\tpublic static <T> List<T> reverseView(List<T> list) {\n\t\treturn Lists.reverse(list);\n\t}",
"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 static base_response unset(nitro_service client, snmpmanager resource, String[] args) throws Exception{\n\t\tsnmpmanager unsetresource = new snmpmanager();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\tunsetresource.netmask = resource.netmask;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static <T> String extractTableName(DatabaseType databaseType, Class<T> clazz) {\n\t\tDatabaseTable databaseTable = clazz.getAnnotation(DatabaseTable.class);\n\t\tString name = null;\n\t\tif (databaseTable != null && databaseTable.tableName() != null && databaseTable.tableName().length() > 0) {\n\t\t\tname = databaseTable.tableName();\n\t\t}\n\t\tif (name == null && javaxPersistenceConfigurer != null) {\n\t\t\tname = javaxPersistenceConfigurer.getEntityName(clazz);\n\t\t}\n\t\tif (name == null) {\n\t\t\t// if the name isn't specified, it is the class name lowercased\n\t\t\tif (databaseType == null) {\n\t\t\t\t// database-type is optional so if it is not specified we just use english\n\t\t\t\tname = clazz.getSimpleName().toLowerCase(Locale.ENGLISH);\n\t\t\t} else {\n\t\t\t\tname = databaseType.downCaseString(clazz.getSimpleName(), true);\n\t\t\t}\n\t\t}\n\t\treturn name;\n\t}"
] |
Generates timephased costs from timephased work where multiple cost rates
apply to the assignment.
@param standardWorkList timephased work
@param overtimeWorkList timephased work
@return timephased cost | [
"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 }"
] | [
"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 static void acceptsNodeSingle(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), \"node id\")\n .withRequiredArg()\n .describedAs(\"node-id\")\n .ofType(Integer.class);\n }",
"public static int getLineNumber(Member member) {\n\n if (!(member instanceof Method || member instanceof Constructor)) {\n // We are not able to get this info for fields\n return 0;\n }\n\n // BCEL is an optional dependency, if we cannot load it, simply return 0\n if (!Reflections.isClassLoadable(BCEL_CLASS, WeldClassLoaderResourceLoader.INSTANCE)) {\n return 0;\n }\n\n String classFile = member.getDeclaringClass().getName().replace('.', '/');\n ClassLoaderResourceLoader classFileResourceLoader = new ClassLoaderResourceLoader(member.getDeclaringClass().getClassLoader());\n InputStream in = null;\n\n try {\n URL classFileUrl = classFileResourceLoader.getResource(classFile + \".class\");\n\n if (classFileUrl == null) {\n // The class file is not available\n return 0;\n }\n in = classFileUrl.openStream();\n\n ClassParser cp = new ClassParser(in, classFile);\n JavaClass javaClass = cp.parse();\n\n // First get all declared methods and constructors\n // Note that in bytecode constructor is translated into a method\n org.apache.bcel.classfile.Method[] methods = javaClass.getMethods();\n org.apache.bcel.classfile.Method match = null;\n\n String signature;\n String name;\n if (member instanceof Method) {\n signature = DescriptorUtils.methodDescriptor((Method) member);\n name = member.getName();\n } else if (member instanceof Constructor) {\n signature = DescriptorUtils.makeDescriptor((Constructor<?>) member);\n name = INIT_METHOD_NAME;\n } else {\n return 0;\n }\n\n for (org.apache.bcel.classfile.Method method : methods) {\n // Matching method must have the same name, modifiers and signature\n if (method.getName().equals(name)\n && member.getModifiers() == method.getModifiers()\n && method.getSignature().equals(signature)) {\n match = method;\n }\n }\n if (match != null) {\n // If a method is found, try to obtain the optional LineNumberTable attribute\n LineNumberTable lineNumberTable = match.getLineNumberTable();\n if (lineNumberTable != null) {\n int line = lineNumberTable.getSourceLine(0);\n return line == -1 ? 0 : line;\n }\n }\n // No suitable method found\n return 0;\n\n } catch (Throwable t) {\n return 0;\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (Exception e) {\n return 0;\n }\n }\n }\n }",
"public static void log(String label, String data)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(data);\n LOG.flush();\n }\n }",
"public static BoxDeveloperEditionAPIConnection getAppUserConnection(String userId, String clientId,\n String clientSecret, JWTEncryptionPreferences encryptionPref, IAccessTokenCache accessTokenCache) {\n\n BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection(userId,\n DeveloperEditionEntityType.USER, clientId, clientSecret, encryptionPref, accessTokenCache);\n\n connection.tryRestoreUsingAccessTokenCache();\n\n return connection;\n }",
"private void configureConfigurationSelector() {\n\n if (m_checkinBean.getConfigurations().size() < 2) {\n // Do not show the configuration selection at all.\n removeComponent(m_configurationSelectionPanel);\n } else {\n for (CmsGitConfiguration configuration : m_checkinBean.getConfigurations()) {\n m_configurationSelector.addItem(configuration);\n m_configurationSelector.setItemCaption(configuration, configuration.getName());\n }\n m_configurationSelector.setNullSelectionAllowed(false);\n m_configurationSelector.setNewItemsAllowed(false);\n m_configurationSelector.setWidth(\"350px\");\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n\n // There is really a choice between configurations\n m_configurationSelector.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"synthetic-access\")\n public void valueChange(ValueChangeEvent event) {\n\n updateForNewConfiguration((CmsGitConfiguration)event.getProperty().getValue());\n restoreFieldsFromUserInfo();\n\n }\n });\n }\n }",
"@Override\n public Symmetry454Date date(int prolepticYear, int month, int dayOfMonth) {\n return Symmetry454Date.of(prolepticYear, month, dayOfMonth);\n }",
"public static MediaType nonBinaryUtf8( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, UTF_8 );\n }",
"public Excerpt typeParameters() {\n if (getTypeParameters().isEmpty()) {\n return Excerpts.EMPTY;\n } else {\n return Excerpts.add(\"<%s>\", Excerpts.join(\", \", getTypeParameters()));\n }\n }"
] |
Gets a SerialMessage with the BASIC SET command
@param the level to set.
@return the serial message | [
"public SerialMessage setValueMessage(int level) {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_SET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) BASIC_SET,\r\n\t\t\t\t\t\t\t\t(byte) level\r\n\t\t\t\t\t\t\t\t};\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}"
] | [
"protected synchronized Object materializeSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tTemporaryBrokerWrapper tmp = getBroker();\r\n try\r\n\t\t{\r\n\t\t\tObject realSubject = tmp.broker.getObjectByIdentity(_id);\r\n\t\t\tif (realSubject == null)\r\n\t\t\t{\r\n\t\t\t\tLoggerFactory.getLogger(IndirectionHandler.class).warn(\r\n\t\t\t\t\t\t\"Can not materialize object for Identity \" + _id + \" - using PBKey \" + getBrokerKey());\r\n\t\t\t}\r\n\t\t\treturn realSubject;\r\n\t\t} catch (Exception ex)\r\n\t\t{\r\n\t\t\tthrow new PersistenceBrokerException(ex);\r\n\t\t} finally\r\n\t\t{\r\n\t\t\ttmp.close();\r\n\t\t}\r\n\t}",
"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 readRelationships(Storepoint phoenixProject)\n {\n for (Relationship relation : phoenixProject.getRelationships().getRelationship())\n {\n readRelation(relation);\n }\n }",
"public static Filter.Builder makeAncestorFilter(Key ancestor) {\n return makeFilter(\n DatastoreHelper.KEY_PROPERTY_NAME, PropertyFilter.Operator.HAS_ANCESTOR,\n makeValue(ancestor));\n }",
"public void setOutlineCode(int index, String value)\n {\n set(selectField(TaskFieldLists.CUSTOM_OUTLINE_CODE, index), value);\n }",
"public static String lookupIfEmpty( final String value,\n final Map<String, String> props,\n final String key ) {\n return value != null ? value : props.get(key);\n }",
"private void writeMapFile(String mapFileName, File jarFile, boolean mapClassMethods) throws IOException, XMLStreamException, ClassNotFoundException, IntrospectionException\n {\n FileWriter fw = new FileWriter(mapFileName);\n XMLOutputFactory xof = XMLOutputFactory.newInstance();\n XMLStreamWriter writer = xof.createXMLStreamWriter(fw);\n //XMLStreamWriter writer = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(fw));\n\n writer.writeStartDocument();\n writer.writeStartElement(\"root\");\n writer.writeStartElement(\"assembly\");\n\n addClasses(writer, jarFile, mapClassMethods);\n\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndDocument();\n writer.flush();\n writer.close();\n\n fw.flush();\n fw.close();\n }",
"public ItemRequest<OrganizationExport> findById(String organizationExport) {\n \n String path = String.format(\"/organization_exports/%s\", organizationExport);\n return new ItemRequest<OrganizationExport>(this, OrganizationExport.class, path, \"GET\");\n }",
"public static snmpuser get(nitro_service service, String name) throws Exception{\n\t\tsnmpuser obj = new snmpuser();\n\t\tobj.set_name(name);\n\t\tsnmpuser response = (snmpuser) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Pause between cluster change in metadata and starting server rebalancing
work. | [
"private void proxyPause() {\n logger.info(\"Pausing after cluster state has changed to allow proxy bridges to be established. \"\n + \"Will start rebalancing work on servers in \"\n + proxyPauseSec\n + \" seconds.\");\n try {\n Thread.sleep(TimeUnit.SECONDS.toMillis(proxyPauseSec));\n } catch(InterruptedException e) {\n logger.warn(\"Sleep interrupted in proxy pause.\");\n }\n }"
] | [
"public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModel calibrationModel, final Vector<AnalyticProduct> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters, final ParameterTransformation parameterTransformation, OptimizerFactory optimizerFactory) throws SolverException {\n\t\tif(calibrationParameters == null) {\n\t\t\tcalibrationParameters = new HashMap<>();\n\t\t}\n\t\tInteger maxIterationsParameter\t= (Integer)calibrationParameters.get(\"maxIterations\");\n\t\tDouble\taccuracyParameter\t\t= (Double)calibrationParameters.get(\"accuracy\");\n\t\tDouble\tevaluationTimeParameter\t\t= (Double)calibrationParameters.get(\"evaluationTime\");\n\n\t\t// @TODO currently ignored, we use the setting form the OptimizerFactory\n\t\tint maxIterations\t\t= maxIterationsParameter != null ? maxIterationsParameter.intValue() : 600;\n\t\tdouble accuracy\t\t\t= accuracyParameter != null ? accuracyParameter.doubleValue() : 1E-8;\n\t\tdouble evaluationTime\t= evaluationTimeParameter != null ? evaluationTimeParameter.doubleValue() : 0.0;\n\n\t\tAnalyticModel model = calibrationModel.addVolatilitySurfaces(this);\n\t\tSolver solver = new Solver(model, calibrationProducts, calibrationTargetValues, parameterTransformation, evaluationTime, optimizerFactory);\n\n\t\tSet<ParameterObject> objectsToCalibrate = new HashSet<>();\n\t\tobjectsToCalibrate.add(this);\n\t\tAnalyticModel modelCalibrated = solver.getCalibratedModel(objectsToCalibrate);\n\n\t\t// Diagnostic output\n\t\tif (logger.isLoggable(Level.FINE)) {\n\t\t\tdouble lastAccuracy\t\t= solver.getAccuracy();\n\t\t\tint \tlastIterations\t= solver.getIterations();\n\n\t\t\tlogger.fine(\"The solver achieved an accuracy of \" + lastAccuracy + \" in \" + lastIterations + \".\");\n\t\t}\n\n\t\treturn (AbstractVolatilitySurfaceParametric)modelCalibrated.getVolatilitySurface(this.getName());\n\t}",
"public Date getNextWorkStart(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToNextWorkStart(cal);\n return cal.getTime();\n }",
"@Override\n public Response doRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doRequestUrl(stitchReq, getHostname());\n }",
"@NonNull\n private List<String> mapObsoleteElements(List<String> names) {\n List<String> elementsToRemove = new ArrayList<>(names.size());\n for (String name : names) {\n if (name.startsWith(\"android\")) continue;\n elementsToRemove.add(name);\n }\n return elementsToRemove;\n }",
"private Object instanceNotYetLoaded(\n\t\tfinal Tuple resultset,\n\t\tfinal int i,\n\t\tfinal Loadable persister,\n\t\tfinal String rowIdAlias,\n\t\tfinal org.hibernate.engine.spi.EntityKey key,\n\t\tfinal LockMode lockMode,\n\t\tfinal org.hibernate.engine.spi.EntityKey optionalObjectKey,\n\t\tfinal Object optionalObject,\n\t\tfinal List hydratedObjects,\n\t\tfinal SharedSessionContractImplementor session)\n\tthrows HibernateException {\n\t\tfinal String instanceClass = getInstanceClass(\n\t\t\t\tresultset,\n\t\t\t\ti,\n\t\t\t\tpersister,\n\t\t\t\tkey.getIdentifier(),\n\t\t\t\tsession\n\t\t\t);\n\n\t\tfinal Object object;\n\t\tif ( optionalObjectKey != null && key.equals( optionalObjectKey ) ) {\n\t\t\t//its the given optional object\n\t\t\tobject = optionalObject;\n\t\t}\n\t\telse {\n\t\t\t// instantiate a new instance\n\t\t\tobject = session.instantiate( instanceClass, key.getIdentifier() );\n\t\t}\n\n\t\t//need to hydrate it.\n\n\t\t// grab its state from the ResultSet and keep it in the Session\n\t\t// (but don't yet initialize the object itself)\n\t\t// note that we acquire LockMode.READ even if it was not requested\n\t\tLockMode acquiredLockMode = lockMode == LockMode.NONE ? LockMode.READ : lockMode;\n\t\tloadFromResultSet(\n\t\t\t\tresultset,\n\t\t\t\ti,\n\t\t\t\tobject,\n\t\t\t\tinstanceClass,\n\t\t\t\tkey,\n\t\t\t\trowIdAlias,\n\t\t\t\tacquiredLockMode,\n\t\t\t\tpersister,\n\t\t\t\tsession\n\t\t\t);\n\n\t\t//materialize associations (and initialize the object) later\n\t\thydratedObjects.add( object );\n\n\t\treturn object;\n\t}",
"private Client getClientFromResultSet(ResultSet result) throws Exception {\n Client client = new Client();\n client.setId(result.getInt(Constants.GENERIC_ID));\n client.setUUID(result.getString(Constants.CLIENT_CLIENT_UUID));\n client.setFriendlyName(result.getString(Constants.CLIENT_FRIENDLY_NAME));\n client.setProfile(ProfileService.getInstance().findProfile(result.getInt(Constants.GENERIC_PROFILE_ID)));\n client.setIsActive(result.getBoolean(Constants.CLIENT_IS_ACTIVE));\n client.setActiveServerGroup(result.getInt(Constants.CLIENT_ACTIVESERVERGROUP));\n return client;\n }",
"public <T> T find(Class<T> classType, String id) {\n return db.find(classType, id);\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 }",
"public List<T> resolveConflicts(List<T> values) {\n if(values.size() > 1)\n return values;\n else\n return Collections.singletonList(values.get(0));\n }"
] |
Asynchronously put the work into the pending map so we can work on submitting it to the worker
if we wanted. Could possibly cause duplicate work if we execute the work, then add to the map.
@param task
@return | [
"public Future<HazeltaskTask<GROUP>> addPendingTaskAsync(HazeltaskTask<GROUP> task) {\n return pendingTask.putAsync(task.getId(), task);\n }"
] | [
"public byte[] getMessageBuffer() {\n\t\tByteArrayOutputStream resultByteBuffer = new ByteArrayOutputStream();\n\t\tbyte[] result;\n\t\tresultByteBuffer.write((byte)0x01);\n\t\tint messageLength = messagePayload.length + \n\t\t\t\t(this.messageClass == SerialMessageClass.SendData && \n\t\t\t\tthis.messageType == SerialMessageType.Request ? 5 : 3); // calculate and set length\n\t\t\n\t\tresultByteBuffer.write((byte) messageLength);\n\t\tresultByteBuffer.write((byte) messageType.ordinal());\n\t\tresultByteBuffer.write((byte) messageClass.getKey());\n\t\t\n\t\ttry {\n\t\t\tresultByteBuffer.write(messagePayload);\n\t\t} catch (IOException e) {\n\t\t\t\n\t\t}\n\n\t\t// callback ID and transmit options for a Send Data message.\n\t\tif (this.messageClass == SerialMessageClass.SendData && this.messageType == SerialMessageType.Request) {\n\t\t\tresultByteBuffer.write(transmitOptions);\n\t\t\tresultByteBuffer.write(callbackId);\n\t\t}\n\t\t\n\t\tresultByteBuffer.write((byte) 0x00);\n\t\tresult = resultByteBuffer.toByteArray();\n\t\tresult[result.length - 1] = 0x01;\n\t\tresult[result.length - 1] = calculateChecksum(result);\n\t\tlogger.debug(\"Assembled message buffer = \" + SerialMessage.bb2hex(result));\n\t\treturn result;\n\t}",
"public static String readTextFile(Context context, int resourceId) {\n InputStream inputStream = context.getResources().openRawResource(\n resourceId);\n return readTextFile(inputStream);\n }",
"@RequestMapping(value = \"api/edit/enable/custom\", method = RequestMethod.POST)\n public\n @ResponseBody\n String enableCustomResponse(Model model, String custom, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n if (custom.equals(\"undefined\"))\n return null;\n editService.enableCustomResponse(custom, path_id, clientUUID);\n return null;\n }",
"protected I_CmsSearchDocument appendFieldMappingsFromElementsOnThePage(\n I_CmsSearchDocument document,\n CmsObject cms,\n CmsResource resource,\n List<String> systemFields) {\n\n try {\n CmsFile file = cms.readFile(resource);\n CmsXmlContainerPage containerPage = CmsXmlContainerPageFactory.unmarshal(cms, file);\n CmsContainerPageBean containerBean = containerPage.getContainerPage(cms);\n if (containerBean != null) {\n for (CmsContainerElementBean element : containerBean.getElements()) {\n element.initResource(cms);\n CmsResource elemResource = element.getResource();\n Set<CmsSearchField> mappedFields = getXSDMappingsForPage(cms, elemResource);\n if (mappedFields != null) {\n\n for (CmsSearchField field : mappedFields) {\n if (!systemFields.contains(field.getName())) {\n document = appendFieldMapping(\n document,\n field,\n cms,\n elemResource,\n CmsSolrDocumentXmlContent.extractXmlContent(cms, elemResource, getIndex()),\n cms.readPropertyObjects(resource, false),\n cms.readPropertyObjects(resource, true));\n } else {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.LOG_SOLR_ERR_MAPPING_TO_INTERNALLY_USED_FIELD_3,\n elemResource.getRootPath(),\n field.getName(),\n resource.getRootPath()));\n }\n }\n }\n }\n }\n } catch (CmsException e) {\n // Should be thrown if element on the page does not exist anymore - this is possible, but not necessarily an error.\n // Hence, just notice it in the debug log.\n if (LOG.isDebugEnabled()) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n }\n return document;\n }",
"private void parseMetadataItem(Message item) {\n switch (item.getMenuItemType()) {\n case TRACK_TITLE:\n title = ((StringField) item.arguments.get(3)).getValue();\n artworkId = (int) ((NumberField) item.arguments.get(8)).getValue();\n break;\n\n case ARTIST:\n artist = buildSearchableItem(item);\n break;\n\n case ORIGINAL_ARTIST:\n originalArtist = buildSearchableItem(item);\n break;\n\n case REMIXER:\n remixer = buildSearchableItem(item);\n\n case ALBUM_TITLE:\n album = buildSearchableItem(item);\n break;\n\n case LABEL:\n label = buildSearchableItem(item);\n break;\n\n case DURATION:\n duration = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case TEMPO:\n tempo = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case COMMENT:\n comment = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case KEY:\n key = buildSearchableItem(item);\n break;\n\n case RATING:\n rating = (int) ((NumberField)item.arguments.get(1)).getValue();\n break;\n\n case COLOR_NONE:\n case COLOR_AQUA:\n case COLOR_BLUE:\n case COLOR_GREEN:\n case COLOR_ORANGE:\n case COLOR_PINK:\n case COLOR_PURPLE:\n case COLOR_RED:\n case COLOR_YELLOW:\n color = buildColorItem(item);\n break;\n\n case GENRE:\n genre = buildSearchableItem(item);\n break;\n\n case DATE_ADDED:\n dateAdded = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case YEAR:\n year = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case BIT_RATE:\n bitRate = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n default:\n logger.warn(\"Ignoring track metadata item with unknown type: {}\", item);\n }\n }",
"ArgumentsBuilder param(String param, String value) {\n if (value != null) {\n args.add(param);\n args.add(value);\n }\n return this;\n }",
"public static base_responses delete(nitro_service client, String sitename[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite deleteresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tdeleteresources[i] = new gslbsite();\n\t\t\t\tdeleteresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public ParallelTaskBuilder prepareHttpPost(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.POST);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }",
"@Override\n public boolean isTempoMaster() {\n DeviceUpdate master = VirtualCdj.getInstance().getTempoMaster();\n return (master != null) && master.getAddress().equals(address);\n }"
] |
Invoke an HTTP GET request on a remote host. You must close the InputStream after you are done with.
@param path The request path
@param parameters The parameters (collection of Parameter objects)
@return The Response | [
"@Override\n public com.flickr4java.flickr.Response get(String path, Map<String, Object> parameters, String apiKey, String sharedSecret) throws FlickrException {\n\n OAuthRequest request = new OAuthRequest(Verb.GET, buildUrl(path));\n for (Map.Entry<String, Object> entry : parameters.entrySet()) {\n request.addQuerystringParameter(entry.getKey(), String.valueOf(entry.getValue()));\n }\n\n if (proxyAuth) {\n request.addHeader(\"Proxy-Authorization\", \"Basic \" + getProxyCredentials());\n }\n\n RequestContext requestContext = RequestContext.getRequestContext();\n Auth auth = requestContext.getAuth();\n OAuth10aService service = createOAuthService(apiKey, sharedSecret);\n if (auth != null) {\n OAuth1AccessToken requestToken = new OAuth1AccessToken(auth.getToken(), auth.getTokenSecret());\n service.signRequest(requestToken, request);\n } else {\n // For calls that do not require authorization e.g. flickr.people.findByUsername which could be the\n // first call if the user did not supply the user-id (i.e. nsid).\n if (!parameters.containsKey(Flickr.API_KEY)) {\n request.addQuerystringParameter(Flickr.API_KEY, apiKey);\n }\n }\n\n if (Flickr.debugRequest) {\n logger.debug(\"GET: \" + request.getCompleteUrl());\n }\n\n try {\n return handleResponse(request, service);\n } catch (IllegalAccessException | InstantiationException | SAXException | IOException | InterruptedException | ExecutionException | ParserConfigurationException e) {\n throw new FlickrRuntimeException(e);\n }\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 }",
"private Options getOptions() {\n\t\tOptions options = new Options();\n\t\toptions.addOption(\"h\", HELP, false, \"print this message\");\n\t\toptions.addOption(VERSION, false, \"print the version information and exit\");\n\n\t\toptions.addOption(\"b\", BROWSER, true,\n\t\t \"browser type: \" + availableBrowsers() + \". Default is Firefox\");\n\n\t\toptions.addOption(BROWSER_REMOTE_URL, true,\n\t\t \"The remote url if you have configured a remote browser\");\n\n\t\toptions.addOption(\"d\", DEPTH, true, \"crawl depth level. Default is 2\");\n\n\t\toptions.addOption(\"s\", MAXSTATES, true,\n\t\t \"max number of states to crawl. Default is 0 (unlimited)\");\n\n\t\toptions.addOption(\"p\", PARALLEL, true,\n\t\t \"Number of browsers to use for crawling. Default is 1\");\n\t\toptions.addOption(\"o\", OVERRIDE, false, \"Override the output directory if non-empty\");\n\n\t\toptions.addOption(\"a\", CRAWL_HIDDEN_ANCHORS, false,\n\t\t \"Crawl anchors even if they are not visible in the browser.\");\n\n\t\toptions.addOption(\"t\", TIME_OUT, true,\n\t\t \"Specify the maximum crawl time in minutes\");\n\n\t\toptions.addOption(CLICK, true,\n\t\t \"a comma separated list of HTML tags that should be clicked. Default is A and BUTTON\");\n\n\t\toptions.addOption(WAIT_AFTER_EVENT, true,\n\t\t \"the time to wait after an event has been fired in milliseconds. Default is \"\n\t\t + CrawlRules.DEFAULT_WAIT_AFTER_EVENT);\n\n\t\toptions.addOption(WAIT_AFTER_RELOAD, true,\n\t\t \"the time to wait after an URL has been loaded in milliseconds. Default is \"\n\t\t + CrawlRules.DEFAULT_WAIT_AFTER_RELOAD);\n\n\t\toptions.addOption(\"v\", VERBOSE, false, \"Be extra verbose\");\n\t\toptions.addOption(LOG_FILE, true, \"Log to this file instead of the console\");\n\n\t\treturn options;\n\t}",
"private ColumnDef addColumnFor(FieldDescriptorDef fieldDef, TableDef tableDef)\r\n {\r\n String name = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);\r\n ColumnDef columnDef = tableDef.getColumn(name);\r\n\r\n if (columnDef == null)\r\n {\r\n columnDef = new ColumnDef(name);\r\n tableDef.addColumn(columnDef);\r\n }\r\n if (!fieldDef.isNested())\r\n { \r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_JAVANAME, fieldDef.getName());\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_ID, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID));\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_PRIMARYKEY, \"true\");\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n else if (!fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_NULLABLE, true))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n if (\"database\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT)))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_AUTOINCREMENT, \"true\");\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_SIZE, fieldDef.getSizeConstraint());\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION));\r\n }\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION));\r\n }\r\n return columnDef;\r\n }",
"static void initializeExtension(ExtensionRegistry extensionRegistry, String module,\n ManagementResourceRegistration rootRegistration,\n ExtensionRegistryType extensionRegistryType) {\n try {\n boolean unknownModule = false;\n boolean initialized = false;\n for (Extension extension : Module.loadServiceFromCallerModuleLoader(module, Extension.class)) {\n ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(extension.getClass());\n try {\n if (unknownModule || !extensionRegistry.getExtensionModuleNames().contains(module)) {\n // This extension wasn't handled by the standalone.xml or domain.xml parsing logic, so we\n // need to initialize its parsers so we can display what XML namespaces it supports\n extensionRegistry.initializeParsers(extension, module, null);\n // AS7-6190 - ensure we initialize parsers for other extensions from this module\n // now that we know the registry was unaware of the module\n unknownModule = true;\n }\n extension.initialize(extensionRegistry.getExtensionContext(module, rootRegistration, extensionRegistryType));\n } finally {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);\n }\n initialized = true;\n }\n if (!initialized) {\n throw ControllerLogger.ROOT_LOGGER.notFound(\"META-INF/services/\", Extension.class.getName(), module);\n }\n } catch (ModuleNotFoundException e) {\n // Treat this as a user mistake, e.g. incorrect module name.\n // Throw OFE so post-boot it only gets logged at DEBUG.\n throw ControllerLogger.ROOT_LOGGER.extensionModuleNotFound(e, module);\n } catch (ModuleLoadException e) {\n // The module is there but can't be loaded. Treat this as an internal problem.\n // Throw a runtime exception so it always gets logged at ERROR in the server log with stack trace details.\n throw ControllerLogger.ROOT_LOGGER.extensionModuleLoadingFailure(e, module);\n }\n }",
"public static boolean isSinglePositionPrefix(FieldInfo fieldInfo,\n String prefix) throws IOException {\n if (fieldInfo == null) {\n throw new IOException(\"no fieldInfo\");\n } else {\n String info = fieldInfo.getAttribute(\n MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n if (info == null) {\n throw new IOException(\"no \"\n + MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n } else {\n return Arrays.asList(info.split(Pattern.quote(MtasToken.DELIMITER)))\n .contains(prefix);\n }\n }\n }",
"public static Span prefix(Bytes rowPrefix) {\n Objects.requireNonNull(rowPrefix);\n Bytes fp = followingPrefix(rowPrefix);\n return new Span(rowPrefix, true, fp == null ? Bytes.EMPTY : fp, false);\n }",
"@UiThread\n public int getChildAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) {\n return RecyclerView.NO_POSITION;\n }\n\n return mExpandableAdapter.getChildPosition(flatPosition);\n }",
"public Collection<Tag> getListUser(String userId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_USER);\n\n parameters.put(\"user_id\", userId);\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 whoElement = response.getPayload();\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) whoElement.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.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n return tags;\n }",
"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 }"
] |
Use this API to fetch appfwprofile_safeobject_binding resources of given name . | [
"public static appfwprofile_safeobject_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_safeobject_binding obj = new appfwprofile_safeobject_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_safeobject_binding response[] = (appfwprofile_safeobject_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public void promoteModule(final String moduleId) {\n final DbModule module = getModule(moduleId);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n final DbArtifact artifact = repositoryHandler.getArtifact(gavc);\n artifact.setPromoted(true);\n repositoryHandler.store(artifact);\n }\n\n repositoryHandler.promoteModule(module);\n }",
"private <T> RequestBuilder doPrepareRequestBuilderImpl(\n ResponseReader responseReader, String methodName, RpcStatsContext statsContext,\n String requestData, AsyncCallback<T> callback) {\n\n if (getServiceEntryPoint() == null) {\n throw new NoServiceEntryPointSpecifiedException();\n }\n\n RequestCallback responseHandler = doCreateRequestCallback(responseReader,\n methodName, statsContext, callback);\n\n ensureRpcRequestBuilder();\n\n rpcRequestBuilder.create(getServiceEntryPoint());\n rpcRequestBuilder.setCallback(responseHandler);\n \n // changed code\n rpcRequestBuilder.setSync(isSync(methodName));\n // changed code\n \n rpcRequestBuilder.setContentType(RPC_CONTENT_TYPE);\n rpcRequestBuilder.setRequestData(requestData);\n rpcRequestBuilder.setRequestId(statsContext.getRequestId());\n return rpcRequestBuilder.finish();\n }",
"public boolean deleteWithCustomTimeout(CompositeVoldemortRequest<K, V> deleteRequestObject) {\n List<Versioned<V>> versionedValues;\n\n validateTimeout(deleteRequestObject.getRoutingTimeoutInMs());\n boolean hasVersion = deleteRequestObject.getVersion() == null ? false : true;\n String keyHexString = \"\";\n if(!hasVersion) {\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"DELETE without version requested for key: \" + keyHexString\n + \" , for store: \" + this.storeName + \" at time(in ms): \"\n + startTimeInMs + \" . Nested GET and DELETE requests to follow ---\");\n }\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent delete might be faster all the\n // steps might finish within the allotted time\n deleteRequestObject.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(deleteRequestObject);\n Versioned<V> versioned = getItemOrThrow(deleteRequestObject.getKey(),\n null,\n versionedValues);\n\n if(versioned == null) {\n return false;\n }\n\n long timeLeft = deleteRequestObject.getRoutingTimeoutInMs()\n - (System.currentTimeMillis() - startTimeInMs);\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n if(timeLeft < 0) {\n throw new StoreTimeoutException(\"DELETE request timed out\");\n }\n\n // Update the version and the new timeout\n deleteRequestObject.setVersion(versioned.getVersion());\n deleteRequestObject.setRoutingTimeoutInMs(timeLeft);\n\n }\n long deleteVersionStartTimeInNs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) deleteRequestObject.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n keyHexString);\n }\n boolean result = store.delete(deleteRequestObject);\n if(logger.isDebugEnabled()) {\n debugLogEnd(\"DELETE\",\n deleteRequestObject.getRequestOriginTimeInMs(),\n deleteVersionStartTimeInNs,\n System.currentTimeMillis(),\n keyHexString,\n 0);\n }\n if(!hasVersion && logger.isDebugEnabled()) {\n logger.debug(\"DELETE without version response received for key: \" + keyHexString\n + \", for store: \" + this.storeName + \" at time(in ms): \"\n + System.currentTimeMillis());\n }\n return result;\n }",
"String decodeCString(ByteBuf buffer) throws IOException {\n int length = buffer.bytesBefore(BsonConstants.STRING_TERMINATION);\n if (length < 0)\n throw new IOException(\"string termination not found\");\n\n String result = buffer.toString(buffer.readerIndex(), length, StandardCharsets.UTF_8);\n buffer.skipBytes(length + 1);\n return result;\n }",
"private ServerSetup[] createServerSetup() {\n List<ServerSetup> setups = new ArrayList<>();\n if (smtpProtocol) {\n smtpServerSetup = createTestServerSetup(ServerSetup.SMTP);\n setups.add(smtpServerSetup);\n }\n if (smtpsProtocol) {\n smtpsServerSetup = createTestServerSetup(ServerSetup.SMTPS);\n setups.add(smtpsServerSetup);\n }\n if (pop3Protocol) {\n setups.add(createTestServerSetup(ServerSetup.POP3));\n }\n if (pop3sProtocol) {\n setups.add(createTestServerSetup(ServerSetup.POP3S));\n }\n if (imapProtocol) {\n setups.add(createTestServerSetup(ServerSetup.IMAP));\n }\n if (imapsProtocol) {\n setups.add(createTestServerSetup(ServerSetup.IMAPS));\n }\n return setups.toArray(new ServerSetup[setups.size()]);\n }",
"public static CuratorFramework newCurator(String zookeepers, int timeout, String secret) {\n\n final ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10);\n if (secret.isEmpty()) {\n return CuratorFrameworkFactory.newClient(zookeepers, timeout, timeout, retry);\n } else {\n return CuratorFrameworkFactory.builder().connectString(zookeepers)\n .connectionTimeoutMs(timeout).sessionTimeoutMs(timeout).retryPolicy(retry)\n .authorization(\"digest\", (\"fluo:\" + secret).getBytes(StandardCharsets.UTF_8))\n .aclProvider(new ACLProvider() {\n @Override\n public List<ACL> getDefaultAcl() {\n return CREATOR_ALL_ACL;\n }\n\n @Override\n public List<ACL> getAclForPath(String path) {\n switch (path) {\n case ZookeeperPath.ORACLE_GC_TIMESTAMP:\n // The garbage collection iterator running in Accumulo tservers needs to read this\n // value w/o authenticating.\n return PUBLICLY_READABLE_ACL;\n default:\n return CREATOR_ALL_ACL;\n }\n }\n }).build();\n }\n }",
"public void setScale(final float scale) {\n if (equal(mScale, scale) != true) {\n Log.d(TAG, \"setScale(): old: %.2f, new: %.2f\", mScale, scale);\n mScale = scale;\n setScale(mSceneRootObject, scale);\n setScale(mMainCameraRootObject, scale);\n setScale(mLeftCameraRootObject, scale);\n setScale(mRightCameraRootObject, scale);\n for (OnScaledListener listener : mOnScaledListeners) {\n try {\n listener.onScaled(scale);\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(TAG, e, \"setScale()\");\n }\n }\n }\n }",
"private static int getBlockLength(String text, int offset)\n {\n int startIndex = offset;\n boolean finished = false;\n char c;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case '\\r':\n case '\\n':\n case '}':\n {\n finished = true;\n break;\n }\n\n default:\n {\n ++offset;\n break;\n }\n }\n }\n\n int length = offset - startIndex;\n\n return (length);\n }",
"private static boolean typeEquals(ParameterizedType from,\n\t\t\tParameterizedType to, Map<String, Type> typeVarMap) {\n\t\tif (from.getRawType().equals(to.getRawType())) {\n\t\t\tType[] fromArgs = from.getActualTypeArguments();\n\t\t\tType[] toArgs = to.getActualTypeArguments();\n\t\t\tfor (int i = 0; i < fromArgs.length; i++) {\n\t\t\t\tif (!matches(fromArgs[i], toArgs[i], typeVarMap)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}"
] |
Retrieve the Charset used to read the file.
@return Charset instance | [
"private Charset getCharset()\n {\n Charset result = m_charset;\n if (result == null)\n {\n // We default to CP1252 as this seems to be the most common encoding\n result = m_encoding == null ? CharsetHelper.CP1252 : Charset.forName(m_encoding);\n }\n return result;\n }"
] | [
"@Override\n public void handleExceptions(MessageEvent messageEvent, Exception exception) {\n\n if(exception instanceof InvalidMetadataException) {\n logger.error(\"Exception when deleting. The requested key does not exist in this partition\",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,\n \"The requested key does not exist in this partition\");\n } else if(exception instanceof PersistenceFailureException) {\n logger.error(\"Exception when deleting. Operation failed\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Operation failed\");\n } else if(exception instanceof UnsupportedOperationException) {\n logger.error(\"Exception when deleting. Operation not supported in read-only store \",\n exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.METHOD_NOT_ALLOWED,\n \"Operation not supported in read-only store\");\n } else if(exception instanceof StoreTimeoutException) {\n String errorDescription = \"DELETE Request timed out: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);\n } else if(exception instanceof InsufficientOperationalNodesException) {\n String errorDescription = \"DELETE Request failed: \" + exception.getMessage();\n logger.error(errorDescription);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n errorDescription);\n } else {\n super.handleExceptions(messageEvent, exception);\n }\n }",
"public String urlEncode(String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n\n return URL.encodeQueryString(s);\n }",
"private static boolean isCollectionMatching(Joinable mainSideJoinable, OgmCollectionPersister inverseSidePersister) {\n\t\tboolean isSameTable = mainSideJoinable.getTableName().equals( inverseSidePersister.getTableName() );\n\n\t\tif ( !isSameTable ) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn Arrays.equals( mainSideJoinable.getKeyColumnNames(), inverseSidePersister.getElementColumnNames() );\n\t}",
"public void postPhoto(Photo photo, String blogId, String blogPassword) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_POST_PHOTO);\r\n\r\n parameters.put(\"blog_id\", blogId);\r\n parameters.put(\"photo_id\", photo.getId());\r\n parameters.put(\"title\", photo.getTitle());\r\n parameters.put(\"description\", photo.getDescription());\r\n if (blogPassword != null) {\r\n parameters.put(\"blog_password\", blogPassword);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public static base_response update(nitro_service client, clusternodegroup resource) throws Exception {\n\t\tclusternodegroup updateresource = new clusternodegroup();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.strict = resource.strict;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public CollectionRequest<Task> getTasksWithTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"@UiThread\n protected void expandView() {\n setExpanded(true);\n onExpansionToggled(false);\n\n if (mParentViewHolderExpandCollapseListener != null) {\n mParentViewHolderExpandCollapseListener.onParentExpanded(getAdapterPosition());\n }\n }",
"public static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.util.Date(gc.getTime().getTime());\n }",
"public static boolean isBeanProxyable(Bean<?> bean, BeanManagerImpl manager) {\n if (bean instanceof RIBean<?>) {\n return ((RIBean<?>) bean).isProxyable();\n } else {\n return Proxies.isTypesProxyable(bean.getTypes(), manager.getServices());\n }\n }"
] |
Add all headers in a header multimap.
@param headers a multimap of headers.
@return the interceptor instance itself. | [
"public CustomHeadersInterceptor addHeaderMultimap(Map<String, List<String>> headers) {\n this.headers.putAll(headers);\n return this;\n }"
] | [
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> updateClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID,\n @RequestParam(required = false) Boolean active,\n @RequestParam(required = false) String friendlyName,\n @RequestParam(required = false) Boolean reset) throws Exception {\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n if (active != null) {\n logger.info(\"Active: {}\", active);\n clientService.updateActive(profileId, clientUUID, active);\n }\n\n if (friendlyName != null) {\n clientService.setFriendlyName(profileId, clientUUID, friendlyName);\n }\n\n if (reset != null && reset) {\n clientService.reset(profileId, clientUUID);\n }\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"client\", clientService.findClient(clientUUID, profileId));\n return valueHash;\n }",
"public 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 void removeFile(String name) {\n if(files.containsKey(name)) {\n files.remove(name);\n }\n\n if(fileStreams.containsKey(name)) {\n fileStreams.remove(name);\n }\n }",
"public static final BigInteger getBigInteger(Number value)\n {\n BigInteger result = null;\n if (value != null)\n {\n if (value instanceof BigInteger)\n {\n result = (BigInteger) value;\n }\n else\n {\n result = BigInteger.valueOf(Math.round(value.doubleValue()));\n }\n }\n return (result);\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/delete\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @RequestParam(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(\"clientUUID\") String[] clientUUID) throws Exception {\n\n logger.info(\"Attempting to remove clients from the profile: \", profileIdentifier);\n logger.info(\"Attempting to remove the following clients: {}\", Arrays.toString(clientUUID));\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n for( int i = 0; i < clientUUID.length; i++ )\n {\n if (clientUUID[i].compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n clientService.remove(profileId, clientUUID[i]);\n }\n\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }",
"public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }",
"public PeriodicEvent runEvery(Runnable task, float delay, float period,\n int repetitions) {\n if (repetitions < 1) {\n return null;\n } else if (repetitions == 1) {\n // Better to burn a handful of CPU cycles than to churn memory by\n // creating a new callback\n return runAfter(task, delay);\n } else {\n return runEvery(task, delay, period, new RunFor(repetitions));\n }\n }",
"public static String md5(byte[] source) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(source);\n byte tmp[] = md.digest();\n char str[] = new char[32];\n int k = 0;\n for (byte b : tmp) {\n str[k++] = hexDigits[b >>> 4 & 0xf];\n str[k++] = hexDigits[b & 0xf];\n }\n return new String(str);\n\n } catch (Exception e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public void setFileExtensions(final String fileExtensions) {\n this.fileExtensions = IterableExtensions.<String>toList(((Iterable<String>)Conversions.doWrapArray(fileExtensions.trim().split(\"\\\\s*,\\\\s*\"))));\n }"
] |
Helper method to retrieve a canonical revision for git commits migrated from SVN. Migrated commits are
detected by the presence of 'git-svn-id' in the commit message.
@param revision the commit/revision to inspect
@param branch the name of the branch it came from
@return the original SVN revision if it was a migrated commit from the branch specified, otherwise the git revision | [
"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 }"
] | [
"private static JsonObject getFieldJsonObject(Field field) {\n JsonObject fieldObj = new JsonObject();\n fieldObj.add(\"type\", field.getType());\n fieldObj.add(\"key\", field.getKey());\n fieldObj.add(\"displayName\", field.getDisplayName());\n\n String fieldDesc = field.getDescription();\n if (fieldDesc != null) {\n fieldObj.add(\"description\", field.getDescription());\n }\n\n Boolean fieldIsHidden = field.getIsHidden();\n if (fieldIsHidden != null) {\n fieldObj.add(\"hidden\", field.getIsHidden());\n }\n\n JsonArray array = new JsonArray();\n List<String> options = field.getOptions();\n if (options != null && !options.isEmpty()) {\n for (String option : options) {\n JsonObject optionObj = new JsonObject();\n optionObj.add(\"key\", option);\n\n array.add(optionObj);\n }\n fieldObj.add(\"options\", array);\n }\n\n return fieldObj;\n }",
"public void process(File file) throws Exception\n {\n openLogFile();\n\n int blockIndex = 0;\n int length = (int) file.length();\n m_buffer = new byte[length];\n FileInputStream is = new FileInputStream(file);\n try\n {\n int bytesRead = is.read(m_buffer);\n if (bytesRead != length)\n {\n throw new RuntimeException(\"Read count different\");\n }\n }\n finally\n {\n is.close();\n }\n\n List<Integer> blocks = new ArrayList<Integer>();\n for (int index = 64; index < m_buffer.length - 11; index++)\n {\n if (matchPattern(PARENT_BLOCK_PATTERNS, index))\n {\n blocks.add(Integer.valueOf(index));\n }\n }\n\n int startIndex = 0;\n for (int endIndex : blocks)\n {\n int blockLength = endIndex - startIndex;\n readBlock(blockIndex, startIndex, blockLength);\n startIndex = endIndex;\n ++blockIndex;\n }\n\n int blockLength = m_buffer.length - startIndex;\n readBlock(blockIndex, startIndex, blockLength);\n\n closeLogFile();\n }",
"public FilePath getModuleRoot(Map<String, String> globalEnv) throws IOException, InterruptedException {\n FilePath someWorkspace = project.getSomeWorkspace();\n if (someWorkspace == null) {\n throw new IllegalStateException(\"Couldn't find workspace\");\n }\n\n Map<String, String> workspaceEnv = Maps.newHashMap();\n workspaceEnv.put(\"WORKSPACE\", someWorkspace.getRemote());\n\n for (Builder builder : getBuilders()) {\n if (builder instanceof Gradle) {\n Gradle gradleBuilder = (Gradle) builder;\n String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir();\n if (rootBuildScriptDir != null && rootBuildScriptDir.trim().length() != 0) {\n String rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptDir.trim(), workspaceEnv);\n rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptNormalized, globalEnv);\n return new FilePath(someWorkspace, rootBuildScriptNormalized);\n } else {\n return someWorkspace;\n }\n }\n }\n\n throw new IllegalArgumentException(\"Couldn't find Gradle builder in the current builders list\");\n }",
"public void setPosition(float x, float y, float z) {\n if (isActive()) {\n mIODevice.setPosition(x, y, z);\n }\n }",
"public List<Callouts.Callout> getCallout()\n {\n if (callout == null)\n {\n callout = new ArrayList<Callouts.Callout>();\n }\n return this.callout;\n }",
"public static nspbr6_stats[] get(nitro_service service, options option) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tnspbr6_stats[] response = (nspbr6_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}",
"static void i(String message){\n if (getStaticDebugLevel() >= CleverTapAPI.LogLevel.INFO.intValue()){\n Log.i(Constants.CLEVERTAP_LOG_TAG,message);\n }\n }",
"public static CmsResource getDescriptor(CmsObject cms, String basename) {\n\n CmsSolrQuery query = new CmsSolrQuery();\n query.setResourceTypes(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString());\n query.setFilterQueries(\"filename:\\\"\" + basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX + \"\\\"\");\n query.add(\"fl\", \"path\");\n CmsSolrResultList results;\n try {\n boolean isOnlineProject = cms.getRequestContext().getCurrentProject().isOnlineProject();\n String indexName = isOnlineProject\n ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE\n : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE;\n results = OpenCms.getSearchManager().getIndexSolr(indexName).search(cms, query, true, null, true, null);\n } catch (CmsSearchException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_SEARCH_ERROR_0), e);\n return null;\n }\n\n switch (results.size()) {\n case 0:\n return null;\n case 1:\n return results.get(0);\n default:\n String files = \"\";\n for (CmsResource res : results) {\n files += \" \" + res.getRootPath();\n }\n LOG.warn(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_NOT_UNIQUE_1, files));\n return results.get(0);\n }\n }",
"public synchronized final void closeStream() {\n try {\n if ((stream != null) && (streamState == StreamStates.OPEN)) {\n stream.close();\n stream = null;\n }\n streamState = StreamStates.CLOSED;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }"
] |
Bhattacharyya distance between two normalized histograms.
@param histogram1 Normalized histogram.
@param histogram2 Normalized histogram.
@return The Bhattacharyya distance between the two histograms. | [
"public static double Bhattacharyya(double[] histogram1, double[] histogram2) {\n int bins = histogram1.length; // histogram bins\n double b = 0; // Bhattacharyya's coefficient\n\n for (int i = 0; i < bins; i++)\n b += Math.sqrt(histogram1[i]) * Math.sqrt(histogram2[i]);\n\n // Bhattacharyya distance between the two distributions\n return Math.sqrt(1.0 - b);\n }"
] | [
"private <T> T readIntoBean(final T bean, final String[] nameMapping, final CellProcessor[] processors)\n\t\tthrows IOException {\n\t\t\n\t\tif( readRow() ) {\n\t\t\tif( nameMapping.length != length() ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\n\t\t\t\t\t\"the nameMapping array and the number of columns read \"\n\t\t\t\t\t\t+ \"should be the same size (nameMapping length = %d, columns = %d)\", nameMapping.length,\n\t\t\t\t\tlength()));\n\t\t\t}\n\t\t\t\n\t\t\tif( processors == null ) {\n\t\t\t\tprocessedColumns.clear();\n\t\t\t\tprocessedColumns.addAll(getColumns());\n\t\t\t} else {\n\t\t\t\texecuteProcessors(processedColumns, processors);\n\t\t\t}\n\t\t\t\n\t\t\treturn populateBean(bean, nameMapping);\n\t\t}\n\t\t\n\t\treturn null; // EOF\n\t}",
"protected NodeData createBodyStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"background-color\", tf.createColor(255, 255, 255)));\n return ret;\n }",
"@Override\n public View getDropDownView(int position, View convertView, ViewGroup parent) {\n final ViewHolder viewHolder;\n if (convertView == null) {\n convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false);\n viewHolder = new ViewHolder();\n viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image);\n viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name);\n viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode);\n convertView.setTag(viewHolder);\n } else {\n viewHolder = (ViewHolder) convertView.getTag();\n }\n\n Country country = getItem(position);\n viewHolder.mImageView.setImageResource(getFlagResource(country));\n viewHolder.mNameView.setText(country.getName());\n viewHolder.mDialCode.setText(String.format(\"+%s\", country.getDialCode()));\n return convertView;\n }",
"public static base_responses add(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 addresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nspbr6();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].action = resources[i].action;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].msr = resources[i].msr;\n\t\t\t\taddresources[i].monitor = resources[i].monitor;\n\t\t\t\taddresources[i].nexthop = resources[i].nexthop;\n\t\t\t\taddresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\taddresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Optional<Project> findProject(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return getProject(name);\n }",
"public static void scale(GVRMesh mesh, float x, float y, float z) {\n final float [] vertices = mesh.getVertices();\n final int vsize = vertices.length;\n\n for (int i = 0; i < vsize; i += 3) {\n vertices[i] *= x;\n vertices[i + 1] *= y;\n vertices[i + 2] *= z;\n }\n\n mesh.setVertices(vertices);\n }",
"public List<Tag> getPrimeTags()\n {\n return this.definedTags.values().stream()\n .filter(Tag::isPrime)\n .collect(Collectors.toList());\n }",
"public static int positionOf(char value, char[] array) {\n for (int i = 0; i < array.length; i++) {\n if (value == array[i]) {\n return i;\n }\n }\n throw new OkapiException(\"Unable to find character '\" + value + \"' in character array.\");\n }",
"public static boolean isBadXmlCharacter(char c) {\n boolean cDataCharacter = c < '\\u0020' && c != '\\t' && c != '\\r' && c != '\\n';\n cDataCharacter |= (c >= '\\uD800' && c < '\\uE000');\n cDataCharacter |= (c == '\\uFFFE' || c == '\\uFFFF');\n return cDataCharacter;\n }"
] |
Returns the integer value o the given belief | [
"public int getIntegerBelief(String name){\n Object belief = introspector.getBeliefBase(this).get(name);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n return (Integer) count;\n }"
] | [
"public 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 static base_responses unset(nitro_service client, gslbservice resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice unsetresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new gslbservice();\n\t\t\t\tunsetresources[i].servicename = resources[i].servicename;\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n\n if (previous != null)\n {\n parent.getTasks().unmapID(previous);\n }\n\n parent.getTasks().mapID(val, this);\n\n set(TaskField.ID, val);\n }",
"private InputStream getErrorStream() {\n InputStream errorStream = this.connection.getErrorStream();\n if (errorStream != null) {\n final String contentEncoding = this.connection.getContentEncoding();\n if (contentEncoding != null && contentEncoding.equalsIgnoreCase(\"gzip\")) {\n try {\n errorStream = new GZIPInputStream(errorStream);\n } catch (IOException e) {\n // just return the error stream as is\n }\n }\n }\n\n return errorStream;\n }",
"public static DMatrixRMaj symmetricWithEigenvalues(int num, Random rand , double ...eigenvalues ) {\n DMatrixRMaj V = RandomMatrices_DDRM.orthogonal(num,num,rand);\n DMatrixRMaj D = CommonOps_DDRM.diag(eigenvalues);\n\n DMatrixRMaj temp = new DMatrixRMaj(num,num);\n\n CommonOps_DDRM.mult(V,D,temp);\n CommonOps_DDRM.multTransB(temp,V,D);\n\n return D;\n }",
"private Map<String, Integer> runSampling(\n final ProctorContext proctorContext,\n final Set<String> targetTestNames,\n final TestType testType,\n final int determinationsToRun\n ) {\n final Set<String> targetTestGroups = getTargetTestGroups(targetTestNames);\n final Map<String, Integer> testGroupToOccurrences = Maps.newTreeMap();\n for (final String testGroup : targetTestGroups) {\n testGroupToOccurrences.put(testGroup, 0);\n }\n\n for (int i = 0; i < determinationsToRun; ++i) {\n final Identifiers identifiers = TestType.RANDOM.equals(testType)\n ? new Identifiers(Collections.<TestType, String>emptyMap(), /* randomEnabled */ true)\n : Identifiers.of(testType, Long.toString(random.nextLong()));\n final AbstractGroups groups = supplier.getRandomGroups(proctorContext, identifiers);\n for (final Entry<String, TestBucket> e : groups.getProctorResult().getBuckets().entrySet()) {\n final String testName = e.getKey();\n if (targetTestNames.contains(testName)) {\n final int group = e.getValue().getValue();\n final String testGroup = testName + group;\n testGroupToOccurrences.put(testGroup, testGroupToOccurrences.get(testGroup) + 1);\n }\n }\n }\n\n return testGroupToOccurrences;\n }",
"private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) {\n\n if (null == response) {\n return null;\n }\n\n final JSONObject suggestions = new JSONObject();\n final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap();\n\n // Add suggestions to the response\n for (final String key : solrSuggestions.keySet()) {\n\n // Indicator to ignore words that are erroneously marked as misspelled.\n boolean ignoreWord = false;\n\n // Suggestions that are in the form \"Xxxx\" -> \"xxxx\" should be ignored.\n if (Character.isUpperCase(key.codePointAt(0))) {\n final String lowercaseKey = key.toLowerCase();\n // If the suggestion map doesn't contain the lowercased word, ignore this entry.\n if (!solrSuggestions.containsKey(lowercaseKey)) {\n ignoreWord = true;\n }\n }\n\n if (!ignoreWord) {\n try {\n // Get suggestions as List\n final List<String> l = solrSuggestions.get(key).getAlternatives();\n suggestions.put(key, l);\n } catch (JSONException e) {\n LOG.debug(\"Exception while converting Solr spellcheckresponse to JSON. \", e);\n }\n }\n }\n\n return suggestions;\n }",
"@VisibleForTesting\n protected static Dimension getSize(\n final ScalebarAttributeValues scalebarParams,\n final ScaleBarRenderSettings settings, final Dimension maxLabelSize) {\n final float width;\n final float height;\n if (scalebarParams.getOrientation().isHorizontal()) {\n width = 2 * settings.getPadding()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getLeftLabelMargin() + settings.getRightLabelMargin();\n height = 2 * settings.getPadding()\n + settings.getBarSize() + settings.getLabelDistance()\n + Label.getRotatedHeight(maxLabelSize, scalebarParams.getLabelRotation());\n } else {\n width = 2 * settings.getPadding()\n + settings.getLabelDistance() + settings.getBarSize()\n + Label.getRotatedWidth(maxLabelSize, scalebarParams.getLabelRotation());\n height = 2 * settings.getPadding()\n + settings.getTopLabelMargin()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getBottomLabelMargin();\n }\n return new Dimension((int) Math.ceil(width), (int) Math.ceil(height));\n }",
"public EventBus emit(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }"
] |
Creates and populates a new task relationship.
@param field which task field source of data
@param sourceTask relationship source task
@param relationship relationship string
@throws MPXJException | [
"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 }"
] | [
"public void setEndTime(final Date date) {\r\n\r\n if (!Objects.equals(m_model.getEnd(), date)) {\r\n m_model.setEnd(date);\r\n valueChanged();\r\n }\r\n\r\n }",
"private boolean hasReceivedHeartbeat() {\n long currentTimeMillis = System.currentTimeMillis();\n boolean result = lastTimeMessageReceived + heartbeatTimeoutMs >= currentTimeMillis;\n\n if (!result)\n Jvm.warn().on(getClass(), Integer.toHexString(hashCode()) + \" missed heartbeat, lastTimeMessageReceived=\" + lastTimeMessageReceived\n + \", currentTimeMillis=\" + currentTimeMillis);\n return result;\n }",
"private static String getPath(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Scheme) {\n return ((Scheme) q).value();\n }\n }\n\n if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {\n String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME);\n if (s != null && s.isEmpty()) {\n return s;\n }\n }\n return DEFAULT_PATH;\n }",
"public void addLicense(final String gavc, final String licenseId) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n\n // Try to find an existing license that match the new one\n final LicenseHandler licenseHandler = new LicenseHandler(repositoryHandler);\n final DbLicense license = licenseHandler.resolve(licenseId);\n\n // If there is no existing license that match this one let's use the provided value but\n // only if the artifact has no license yet. Otherwise it could mean that users has already\n // identify the license manually.\n if(license == null){\n if(dbArtifact.getLicenses().isEmpty()){\n LOG.warn(\"Add reference to a non existing license called \" + licenseId + \" in artifact \" + dbArtifact.getGavc());\n repositoryHandler.addLicenseToArtifact(dbArtifact, licenseId);\n }\n }\n // Add only if the license is not already referenced\n else if(!dbArtifact.getLicenses().contains(license.getName())){\n repositoryHandler.addLicenseToArtifact(dbArtifact, license.getName());\n }\n }",
"private static String findOutputPath(String[][] options) {\n\tfor (int i = 0; i < options.length; i++) {\n\t if (options[i][0].equals(\"-d\"))\n\t\treturn options[i][1];\n\t}\n\treturn \".\";\n }",
"public synchronized int cancelByTag(String tagToCancel) {\n int i = 0;\n if (taskList.containsKey(tagToCancel)) {\n removeDoneTasks();\n\n for (Future<BlurWorker.Result> future : taskList.get(tagToCancel)) {\n BuilderUtil.logVerbose(Dali.getConfig().logTag, \"Canceling task with tag \" + tagToCancel, Dali.getConfig().debugMode);\n future.cancel(true);\n i++;\n }\n\n //remove all canceled tasks\n Iterator<Future<BlurWorker.Result>> iter = taskList.get(tagToCancel).iterator();\n while (iter.hasNext()) {\n if (iter.next().isCancelled()) {\n iter.remove();\n }\n }\n }\n return i;\n }",
"public List<T> resolveConflicts(List<T> values) {\n if(values.size() > 1)\n return values;\n else\n return Collections.singletonList(values.get(0));\n }",
"private int decode(Huffman h) throws IOException\n {\n int len; /* current number of bits in code */\n int code; /* len bits being decoded */\n int first; /* first code of length len */\n int count; /* number of codes of length len */\n int index; /* index of first code of length len in symbol table */\n int bitbuf; /* bits from stream */\n int left; /* bits left in next or left to process */\n //short *next; /* next number of codes */\n\n bitbuf = m_bitbuf;\n left = m_bitcnt;\n code = first = index = 0;\n len = 1;\n int nextIndex = 1; // next = h->count + 1;\n while (true)\n {\n while (left-- != 0)\n {\n code |= (bitbuf & 1) ^ 1; /* invert code */\n bitbuf >>= 1;\n //count = *next++;\n count = h.m_count[nextIndex++];\n if (code < first + count)\n { /* if length len, return symbol */\n m_bitbuf = bitbuf;\n m_bitcnt = (m_bitcnt - len) & 7;\n return h.m_symbol[index + (code - first)];\n }\n index += count; /* else update for next length */\n first += count;\n first <<= 1;\n code <<= 1;\n len++;\n }\n left = (MAXBITS + 1) - len;\n if (left == 0)\n {\n break;\n }\n if (m_left == 0)\n {\n m_in = m_input.read();\n m_left = m_in == -1 ? 0 : 1;\n if (m_left == 0)\n {\n throw new IOException(\"out of input\"); /* out of input */\n }\n }\n bitbuf = m_in;\n m_left--;\n if (left > 8)\n {\n left = 8;\n }\n }\n return -9; /* ran out of codes */\n }",
"public float getChildSize(final int dataIndex, final Axis axis) {\n float size = 0;\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n switch (axis) {\n case X:\n size = child.getLayoutWidth();\n break;\n case Y:\n size = child.getLayoutHeight();\n break;\n case Z:\n size = child.getLayoutDepth();\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }\n return size;\n }"
] |
Get a list of topics from a group.
@param groupId
Unique identifier of a group returns a list of topics for a given group {@link Group}.
@param perPage
Number of records per page.
@param page
Result-section.
@return A group topic list
@throws FlickrException
@see <a href="http://www.flickr.com/services/api/flickr.groups.discuss.topics.getList.html">API Documentation</a> | [
"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 }"
] | [
"private void checkOrderby(CollectionDescriptorDef collDef, 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 orderbySpec = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ORDERBY);\r\n\r\n if ((orderbySpec == null) || (orderbySpec.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef ownerClass = (ClassDescriptorDef)collDef.getOwner();\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF).replace('$', '.');\r\n ClassDescriptorDef elementClass = ((ModelDef)ownerClass.getOwner()).getClass(elementClassName);\r\n FieldDescriptorDef fieldDef;\r\n String token;\r\n String fieldName;\r\n String ordering;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(orderbySpec); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos == -1)\r\n {\r\n fieldName = token;\r\n ordering = null;\r\n }\r\n else\r\n {\r\n fieldName = token.substring(0, pos);\r\n ordering = token.substring(pos + 1);\r\n }\r\n fieldDef = elementClass.getField(fieldName);\r\n if (fieldDef == null)\r\n {\r\n throw new ConstraintException(\"The field \"+fieldName+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" hasn't been found in the element class \"+elementClass.getName());\r\n }\r\n if ((ordering != null) && (ordering.length() > 0) &&\r\n !\"ASC\".equals(ordering) && !\"DESC\".equals(ordering))\r\n {\r\n throw new ConstraintException(\"The ordering \"+ordering+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" is invalid\");\r\n }\r\n }\r\n }",
"public ReferrerList getPhotosetReferrers(Date date, String domain, String photosetId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTOSET_REFERRERS, domain, \"photoset_id\", photosetId, date, perPage, page);\n }",
"public static sslciphersuite get(nitro_service service, String ciphername) throws Exception{\n\t\tsslciphersuite obj = new sslciphersuite();\n\t\tobj.set_ciphername(ciphername);\n\t\tsslciphersuite response = (sslciphersuite) obj.get_resource(service);\n\t\treturn response;\n\t}",
"void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file, final String realm) throws IOException, StartException {\n final PropertiesFileLoader propertiesHandler = realm == null ? new PropertiesFileLoader(file.getAbsolutePath(), null) :\n new UserPropertiesFileLoader(file.getAbsolutePath(), null);\n try {\n propertiesHandler.start(null);\n if (realm != null) {\n ((UserPropertiesFileLoader) propertiesHandler).setRealmName(realm);\n }\n Properties prob = propertiesHandler.getProperties();\n if (value != null) {\n prob.setProperty(key, value);\n }\n if (enableDisableMode) {\n prob.setProperty(key + \"!disable\", String.valueOf(disable));\n }\n propertiesHandler.persistProperties();\n } finally {\n propertiesHandler.stop(null);\n }\n }",
"@Override public Integer[] getUniqueIdentifierArray()\n {\n Integer[] result = new Integer[m_table.size()];\n int index = 0;\n for (Integer value : m_table.keySet())\n {\n result[index] = value;\n ++index;\n }\n return (result);\n }",
"public void setBREE(String bree) {\n\t\tString old = mainAttributes.get(BUNDLE_REQUIREDEXECUTIONENVIRONMENT);\n\t\tif (!bree.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_REQUIREDEXECUTIONENVIRONMENT, bree);\n\t\t\tthis.modified = true;\n\t\t\tthis.bree = bree;\n\t\t}\n\t}",
"public static boolean isTrait(final ClassNode cNode) {\n return cNode!=null\n && ((cNode.isInterface() && !cNode.getAnnotations(TRAIT_CLASSNODE).isEmpty())\n || isAnnotatedWithTrait(cNode));\n }",
"private void processChildTasks(Task parentTask) throws SQLException\n {\n List<Row> rows = getRows(\"select * from zscheduleitem where zparentactivity_=? and z_ent=? order by zorderinparentactivity\", parentTask.getUniqueID(), m_entityMap.get(\"Activity\"));\n for (Row row : rows)\n {\n Task task = parentTask.addTask();\n populateTask(row, task);\n processChildTasks(task);\n }\n }",
"private static Class<?> getGenericReturnType(Method method, Class<?> source, int typeIndex, int nestingLevel) {\n\t\treturn extractType(method.getGenericReturnType(), source, typeIndex, null, null, nestingLevel, 1);\n\t}"
] |
This method is used to calculate the duration of work between two fixed
dates according to the work schedule defined in the named calendar. The
calendar used is the "Standard" calendar. If this calendar does not exist,
and exception will be thrown.
@param startDate start of the period
@param endDate end of the period
@return new Duration object
@throws MPXJException normally when no Standard calendar is available
@deprecated use calendar.getDuration(startDate, endDate) | [
"@Deprecated public Duration getDuration(Date startDate, Date endDate) throws MPXJException\n {\n return (getDuration(\"Standard\", startDate, endDate));\n }"
] | [
"private String[] readXMLDeclaration(Reader r) throws KNXMLException\r\n\t{\r\n\t\tfinal StringBuffer buf = new StringBuffer(100);\r\n\t\ttry {\r\n\t\t\tfor (int c = 0; (c = r.read()) != -1 && c != '?';)\r\n\t\t\t\tbuf.append((char) c);\r\n\t\t}\r\n\t\tcatch (final IOException e) {\r\n\t\t\tthrow new KNXMLException(\"reading XML declaration, \" + e.getMessage(), buf\r\n\t\t\t\t.toString(), 0);\r\n\t\t}\r\n\t\tString s = buf.toString().trim();\r\n\r\n\t\tString version = null;\r\n\t\tString encoding = null;\r\n\t\tString standalone = null;\r\n\r\n\t\tfor (int state = 0; state < 3; ++state)\r\n\t\t\tif (state == 0 && s.startsWith(\"version\")) {\r\n\t\t\t\tversion = getAttValue(s = s.substring(7));\r\n\t\t\t\ts = s.substring(s.indexOf(version) + version.length() + 1).trim();\r\n\t\t\t}\r\n\t\t\telse if (state == 1 && s.startsWith(\"encoding\")) {\r\n\t\t\t\tencoding = getAttValue(s = s.substring(8));\r\n\t\t\t\ts = s.substring(s.indexOf(encoding) + encoding.length() + 1).trim();\r\n\t\t\t}\r\n\t\t\telse if (state == 1 || state == 2) {\r\n\t\t\t\tif (s.startsWith(\"standalone\")) {\r\n\t\t\t\t\tstandalone = getAttValue(s);\r\n\t\t\t\t\tif (!standalone.equals(\"yes\") && !standalone.equals(\"no\"))\r\n\t\t\t\t\t\tthrow new KNXMLException(\"invalid standalone pseudo-attribute\",\r\n\t\t\t\t\t\t\tstandalone, 0);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tthrow new KNXMLException(\"unknown XML declaration pseudo-attribute\", s, 0);\r\n\t\treturn new String[] { version, encoding, standalone };\r\n\t}",
"public static Priority getInstance(Locale locale, String priority)\n {\n int index = DEFAULT_PRIORITY_INDEX;\n\n if (priority != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(locale, LocaleData.PRIORITY_TYPES);\n for (int loop = 0; loop < priorityTypes.length; loop++)\n {\n if (priorityTypes[loop].equalsIgnoreCase(priority) == true)\n {\n index = loop;\n break;\n }\n }\n }\n\n return (Priority.getInstance((index + 1) * 100));\n }",
"private String toResourceNameOnClasspath(String classPathRootOnDisk, File file) {\n String fileName = file.getAbsolutePath().replace(\"\\\\\", \"/\");\n return fileName.substring(classPathRootOnDisk.length());\n }",
"protected NodeData createBodyStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"background-color\", tf.createColor(255, 255, 255)));\n return ret;\n }",
"public static String getTemplateMapperConfig(ServletRequest request) {\n\n String result = null;\n CmsTemplateContext templateContext = (CmsTemplateContext)request.getAttribute(\n CmsTemplateContextManager.ATTR_TEMPLATE_CONTEXT);\n if (templateContext != null) {\n I_CmsTemplateContextProvider provider = templateContext.getProvider();\n if (provider instanceof I_CmsTemplateMappingContextProvider) {\n result = ((I_CmsTemplateMappingContextProvider)provider).getMappingConfigurationPath(\n templateContext.getKey());\n }\n }\n return result;\n }",
"public static vpnvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_cachepolicy_binding obj = new vpnvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_cachepolicy_binding response[] = (vpnvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Map<String,Object> getAttributeValues()\n throws AttributeNotFoundException, InstanceNotFoundException, ReflectionException {\n\n HashSet<String> attributeSet = new HashSet<String>();\n\n for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {\n attributeSet.add(attributeInfo.getName());\n }\n\n AttributeList attributeList =\n mBeanServer.getAttributes(objectName, attributeSet.toArray(new String[attributeSet.size()]));\n\n Map<String, Object> attributeValueMap = new TreeMap<String, Object>();\n for (Attribute attribute : attributeList.asList()) {\n attributeValueMap.put(attribute.getName(), sanitizer.escapeValue(attribute.getValue()));\n }\n\n return attributeValueMap;\n }",
"public static ScheduledExecutorService newScheduledDaemonThreadPool(int corePoolSize) {\n return Executors.newScheduledThreadPool(corePoolSize, r -> {\n Thread t = Executors.defaultThreadFactory().newThread(r);\n t.setDaemon(true);\n return t;\n });\n }",
"public Map<String, String> getAttributes() {\n if (attributes == null) {\n return null;\n } else {\n return Collections.unmodifiableMap(attributes);\n }\n }"
] |
Dumps the contents of a structured block made up from a header
and fixed sized records.
@param headerSize header zie
@param blockSize block size
@param data data block | [
"public static void dumpBlockData(int headerSize, int blockSize, byte[] data)\n {\n if (data != null)\n {\n System.out.println(ByteArrayHelper.hexdump(data, 0, headerSize, false));\n int index = headerSize;\n while (index < data.length)\n {\n System.out.println(ByteArrayHelper.hexdump(data, index, blockSize, false));\n index += blockSize;\n }\n }\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 }",
"public EventBus emitSync(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }",
"static DefaultContainerDescription lookup(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadResourceOperation(new ModelNode().setEmptyList());\n op.get(ClientConstants.INCLUDE_RUNTIME).set(true);\n final ModelNode result = client.execute(op);\n if (Operations.isSuccessfulOutcome(result)) {\n final ModelNode model = Operations.readResult(result);\n final String productName = getValue(model, \"product-name\", \"WildFly\");\n final String productVersion = getValue(model, \"product-version\");\n final String releaseVersion = getValue(model, \"release-version\");\n final String launchType = getValue(model, \"launch-type\");\n return new DefaultContainerDescription(productName, productVersion, releaseVersion, launchType, \"DOMAIN\".equalsIgnoreCase(launchType));\n }\n throw new OperationExecutionException(op, result);\n }",
"@Override public View getView(int position, View convertView, ViewGroup parent) {\n T content = getItem(position);\n rendererBuilder.withContent(content);\n rendererBuilder.withConvertView(convertView);\n rendererBuilder.withParent(parent);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext()));\n Renderer<T> renderer = rendererBuilder.build();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null Renderer\");\n }\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n return renderer.getRootView();\n }",
"private static boolean isVariableInteger(TokenList.Token t) {\n if( t == null )\n return false;\n\n return t.getScalarType() == VariableScalar.Type.INTEGER;\n }",
"private void updateArt(TrackMetadataUpdate update, AlbumArt art) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), art); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), art);\n }\n }\n }\n deliverAlbumArtUpdate(update.player, art);\n }",
"public void abortExternalTx(TransactionImpl odmgTrans)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"abortExternTransaction was called\");\r\n if (odmgTrans == null) return;\r\n TxBuffer buf = (TxBuffer) txRepository.get();\r\n Transaction extTx = buf != null ? buf.getExternTx() : null;\r\n try\r\n {\r\n if (extTx != null && extTx.getStatus() == Status.STATUS_ACTIVE)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Set extern transaction to rollback\");\r\n }\r\n extTx.setRollbackOnly();\r\n }\r\n }\r\n catch (Exception ignore)\r\n {\r\n }\r\n txRepository.set(null);\r\n }",
"public void writeTo(Writer destination) {\n Element eltRuleset = new Element(\"ruleset\");\n addAttribute(eltRuleset, \"name\", name);\n addChild(eltRuleset, \"description\", description);\n for (PmdRule pmdRule : rules) {\n Element eltRule = new Element(\"rule\");\n addAttribute(eltRule, \"ref\", pmdRule.getRef());\n addAttribute(eltRule, \"class\", pmdRule.getClazz());\n addAttribute(eltRule, \"message\", pmdRule.getMessage());\n addAttribute(eltRule, \"name\", pmdRule.getName());\n addAttribute(eltRule, \"language\", pmdRule.getLanguage());\n addChild(eltRule, \"priority\", String.valueOf(pmdRule.getPriority()));\n if (pmdRule.hasProperties()) {\n Element ruleProperties = processRuleProperties(pmdRule);\n if (ruleProperties.getContentSize() > 0) {\n eltRule.addContent(ruleProperties);\n }\n }\n eltRuleset.addContent(eltRule);\n }\n XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());\n try {\n serializer.output(new Document(eltRuleset), destination);\n } catch (IOException e) {\n throw new IllegalStateException(\"An exception occurred while serializing PmdRuleSet.\", e);\n }\n }",
"public HashMap<K2, HashMap<K3, V>> get(final K1 firstKey) {\n\t\treturn map.get(firstKey);\n\t}"
] |
Retrieve URL without parameters
@param sourceURI source URI
@return URL without parameters | [
"public static String getURL(String sourceURI) {\n String retval = sourceURI;\n int qPos = sourceURI.indexOf(\"?\");\n if (qPos != -1) {\n retval = retval.substring(0, qPos);\n }\n\n return retval;\n }"
] | [
"public Collection values()\r\n {\r\n if (values != null) return values;\r\n values = new AbstractCollection()\r\n {\r\n public int size()\r\n {\r\n return size;\r\n }\r\n\r\n public void clear()\r\n {\r\n ReferenceMap.this.clear();\r\n }\r\n\r\n public Iterator iterator()\r\n {\r\n return new ValueIterator();\r\n }\r\n };\r\n return values;\r\n }",
"private TaskField getTaskField(int field)\n {\n TaskField result = MPPTaskField14.getInstance(field);\n\n if (result != null)\n {\n switch (result)\n {\n case START_TEXT:\n {\n result = TaskField.START;\n break;\n }\n\n case FINISH_TEXT:\n {\n result = TaskField.FINISH;\n break;\n }\n\n case DURATION_TEXT:\n {\n result = TaskField.DURATION;\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n return result;\n }",
"public Number getMinutesPerYear()\n {\n return Integer.valueOf(NumberHelper.getInt(getMinutesPerDay()) * NumberHelper.getInt(getDaysPerMonth()) * 12);\n }",
"public static lbvserver_filterpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_filterpolicy_binding obj = new lbvserver_filterpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_filterpolicy_binding response[] = (lbvserver_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public 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 }",
"@Override\n\tpublic boolean retainAll(Collection<?> collection) {\n\t\tif (dao == null) {\n\t\t\treturn false;\n\t\t}\n\t\tboolean changed = false;\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\tT data = iterator.next();\n\t\t\t\tif (!collection.contains(data)) {\n\t\t\t\t\titerator.remove();\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn changed;\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}",
"public static Property getChildAddress(final ModelNode address) {\n if (address.getType() != ModelType.LIST) {\n throw new IllegalArgumentException(\"The address type must be a list.\");\n }\n final List<Property> addressParts = address.asPropertyList();\n if (addressParts.isEmpty()) {\n throw new IllegalArgumentException(\"The address is empty.\");\n }\n return addressParts.get(addressParts.size() - 1);\n }",
"private String formatRate(Rate value)\n {\n String result = null;\n if (value != null)\n {\n StringBuilder buffer = new StringBuilder(m_formats.getCurrencyFormat().format(value.getAmount()));\n buffer.append(\"/\");\n buffer.append(formatTimeUnit(value.getUnits()));\n result = buffer.toString();\n }\n return (result);\n }",
"public static <E> Collection<E> collectify(ObjectMapper mapper, Object source, Class<? extends Collection> targetCollectionType, Class<E> targetElementType) {\n CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(targetCollectionType, targetElementType);\n return objectify(mapper, convertToCollection(source), collectionType);\n }"
] |
Returns an iterator that will only offer leaf trace regions. If the nested regions have gaps, these will be
filled with parent data. If this region is a leaf, a singleton iterator will be returned.
@return an unmodifiable iterator for all leafs. Never <code>null</code>. | [
"public final Iterator<AbstractTraceRegion> leafIterator() {\n\t\tif (nestedRegions == null)\n\t\t\treturn Collections.<AbstractTraceRegion> singleton(this).iterator();\n\t\treturn new LeafIterator(this);\n\t}"
] | [
"private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure,\n final boolean initial) throws OperationFailedException {\n ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure);\n if (resolved.recursive) {\n // Some part of expressionString resolved into a different expression.\n // So, start over, ignoring failures. Ignore failures because we don't require\n // that expressions must not resolve to something that *looks like* an expression but isn't\n return resolveExpressionStringRecursively(resolved.result, true, false);\n } else if (resolved.modified) {\n // Typical case\n return new ModelNode(resolved.result);\n } else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) {\n // We should only get an unmodified expression string back if there was a resolution\n // failure that we ignored.\n assert ignoreDMRResolutionFailure;\n // expressionString came from a node of type expression, so since we did nothing send it back in the same type\n return new ModelNode(new ValueExpression(expressionString));\n } else {\n // The string wasn't really an expression. Two possible cases:\n // 1) if initial == true, someone created a expression node with a non-expression string, which is legal\n // 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an\n // expression but can't be resolved. We don't require that expressions must not resolve to something that\n // *looks like* an expression but isn't, so we'll just treat this as a string\n return new ModelNode(expressionString);\n }\n }",
"public Object toInternal(Attribute<?> attribute) throws GeomajasException {\n\t\tif (attribute instanceof PrimitiveAttribute<?>) {\n\t\t\treturn toPrimitiveObject((PrimitiveAttribute<?>) attribute);\n\t\t} else if (attribute instanceof AssociationAttribute<?>) {\n\t\t\treturn toAssociationObject((AssociationAttribute<?>) attribute);\n\t\t} else {\n\t\t\tthrow new GeomajasException(ExceptionCode.CONVERSION_PROBLEM, attribute);\n\t\t}\n\t}",
"public boolean ignoreOperation(final Resource domainResource, final Collection<ServerConfigInfo> serverConfigs, final PathAddress pathAddress) {\n if (pathAddress.size() == 0) {\n return false;\n }\n boolean ignore = ignoreResourceInternal(domainResource, serverConfigs, pathAddress);\n return ignore;\n }",
"private void appendJoin(StringBuffer where, StringBuffer buf, Join join)\r\n {\r\n buf.append(\",\");\r\n appendTableWithJoins(join.right, where, buf);\r\n if (where.length() > 0)\r\n {\r\n where.append(\" AND \");\r\n }\r\n join.appendJoinEqualities(where);\r\n }",
"boolean setFrameIndex(int frame) {\n if(frame < INITIAL_FRAME_POINTER || frame >= getFrameCount()) {\n return false;\n }\n framePointer = frame;\n return true;\n }",
"public void setSegmentReject(String reject) {\n\t\tif (!StringUtils.hasText(reject)) {\n\t\t\treturn;\n\t\t}\n\t\tInteger parsedLimit = null;\n\t\ttry {\n\t\t\tparsedLimit = Integer.parseInt(reject);\n\t\t\tsegmentRejectType = SegmentRejectType.ROWS;\n\t\t} catch (NumberFormatException e) {\n\t\t}\n\t\tif (parsedLimit == null && reject.contains(\"%\")) {\n\t\t\ttry {\n\t\t\t\tparsedLimit = Integer.parseInt(reject.replace(\"%\", \"\").trim());\n\t\t\t\tsegmentRejectType = SegmentRejectType.PERCENT;\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t}\n\t\t}\n\t\tsegmentRejectLimit = parsedLimit;\n\t}",
"public void start() {\n if (this.started) {\n throw new IllegalStateException(\"Cannot start the EventStream because it isn't stopped.\");\n }\n\n final long initialPosition;\n\n if (this.startingPosition == STREAM_POSITION_NOW) {\n BoxAPIRequest request = new BoxAPIRequest(this.api, EVENT_URL.build(this.api.getBaseURL(), \"now\"), \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n initialPosition = jsonObject.get(\"next_stream_position\").asLong();\n } else {\n assert this.startingPosition >= 0 : \"Starting position must be non-negative\";\n initialPosition = this.startingPosition;\n }\n\n this.poller = new Poller(initialPosition);\n\n this.pollerThread = new Thread(this.poller);\n this.pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {\n public void uncaughtException(Thread t, Throwable e) {\n EventStream.this.notifyException(e);\n }\n });\n this.pollerThread.start();\n\n this.started = true;\n }",
"public void setModelByText(String model) {\r\n try {\r\n InputStream is = new ByteArrayInputStream(model.getBytes());\r\n this.model = SCXMLParser.parse(new InputSource(is), null, customActionsFromTagExtensions());\r\n this.setStateMachine(this.model);\r\n } catch (IOException | SAXException | ModelException e) {\r\n e.printStackTrace();\r\n }\r\n }",
"public static cachecontentgroup[] get(nitro_service service) throws Exception{\n\t\tcachecontentgroup obj = new cachecontentgroup();\n\t\tcachecontentgroup[] response = (cachecontentgroup[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Gets the pathClasses.
A Map containing hints about what Class to be used for what path segment
If local instance not set, try parent Criteria's instance. If this is
the top-level Criteria, try the m_query's instance
@return Returns a Map | [
"public Map getPathClasses()\r\n\t{\r\n\t\tif (m_pathClasses.isEmpty())\r\n\t\t{\r\n\t\t\tif (m_parentCriteria == null)\r\n\t\t\t{\r\n\t\t\t\tif (m_query == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_pathClasses;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\treturn m_query.getPathClasses();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn m_parentCriteria.getPathClasses();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn m_pathClasses;\r\n\t\t}\r\n\t}"
] | [
"public static base_response disable(nitro_service client, String trapname) throws Exception {\n\t\tsnmpalarm disableresource = new snmpalarm();\n\t\tdisableresource.trapname = trapname;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public void setSpecularIntensity(float r, float g, float b, float a) {\n setVec4(\"specular_intensity\", r, g, b, a);\n }",
"protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n content.add(line);\n }",
"public static List<String> asListLinesIgnore(String content, Pattern ignorePattern) {\n List<String> retorno = new ArrayList<String>();\n content = content.replace(CARRIAGE_RETURN, RETURN);\n content = content.replace(RETURN, CARRIAGE_RETURN);\n for (String str : content.split(CARRIAGE_RETURN)) {\n if (!ignorePattern.matcher(str).matches()) {\n retorno.add(str);\n }\n }\n return retorno;\n }",
"public static base_responses add(nitro_service client, autoscaleprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleprofile addresources[] = new autoscaleprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleprofile();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].url = resources[i].url;\n\t\t\t\taddresources[i].apikey = resources[i].apikey;\n\t\t\t\taddresources[i].sharedsecret = resources[i].sharedsecret;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n\tpublic String getFirst(String headerName) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\treturn headerValues != null ? headerValues.get(0) : null;\n\t}",
"public void removePropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.removePropertyChangeListener(propertyName, listener);\r\n }",
"public Date getStart()\n {\n Date result = (Date) getCachedValue(AssignmentField.START);\n if (result == null)\n {\n result = getTask().getStart();\n }\n return result;\n }",
"void execute(ExecutableBuilder builder,\n int timeout,\n TimeUnit unit) throws\n CommandLineException,\n InterruptedException, ExecutionException, TimeoutException {\n Future<Void> task = executorService.submit(() -> {\n builder.build().execute();\n return null;\n });\n try {\n if (timeout <= 0) { //Synchronous\n task.get();\n } else { // Guarded execution\n try {\n task.get(timeout, unit);\n } catch (TimeoutException ex) {\n // First make the context unusable\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).timeout();\n }\n // Then cancel the task.\n task.cancel(true);\n throw ex;\n }\n }\n } catch (InterruptedException ex) {\n // Could have been interrupted by user (Ctrl-C)\n Thread.currentThread().interrupt();\n cancelTask(task, builder.getCommandContext(), null);\n // Interrupt running operation.\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).interrupted();\n }\n throw ex;\n }\n }"
] |
Get the time zone for a specific stock or index.
For stocks, the exchange suffix is extracted from the stock symbol to retrieve the time zone.
@param symbol stock symbol in YahooFinance
@return time zone of the exchange on which this stock is traded | [
"public static TimeZone getStockTimeZone(String symbol) {\n // First check if it's a known stock index\n if(INDEX_TIMEZONES.containsKey(symbol)) {\n return INDEX_TIMEZONES.get(symbol);\n }\n \n if(!symbol.contains(\".\")) {\n return ExchangeTimeZone.get(\"\");\n }\n String[] split = symbol.split(\"\\\\.\");\n return ExchangeTimeZone.get(split[split.length - 1]);\n }"
] | [
"public void set_protocol(String protocol) throws nitro_exception\n\t{\n\t\tif (protocol == null || !(protocol.equalsIgnoreCase(\"http\") ||protocol.equalsIgnoreCase(\"https\"))) {\n\t\t\tthrow new nitro_exception(\"error: protocol value \" + protocol + \" is not supported\");\n\t\t}\n\t\tthis.protocol = protocol;\n\t}",
"protected void updateFontTable()\n {\n PDResources resources = pdpage.getResources();\n if (resources != null)\n {\n try\n {\n processFontResources(resources, fontTable);\n } catch (IOException e) {\n log.error(\"Error processing font resources: \"\n + \"Exception: {} {}\", e.getMessage(), e.getClass());\n }\n }\n }",
"public static dbdbprofile[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tdbdbprofile[] response = (dbdbprofile[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public static base_responses kill(nitro_service client, systemsession resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemsession killresources[] = new systemsession[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tkillresources[i] = new systemsession();\n\t\t\t\tkillresources[i].sid = resources[i].sid;\n\t\t\t\tkillresources[i].all = resources[i].all;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, killresources,\"kill\");\n\t\t}\n\t\treturn result;\n\t}",
"public 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 }",
"public Object getObjectByQuery(Query query) throws PersistenceBrokerException\n {\n Object result = null;\n if (query instanceof QueryByIdentity)\n {\n // example obj may be an entity or an Identity\n Object obj = query.getExampleObject();\n if (obj instanceof Identity)\n {\n Identity oid = (Identity) obj;\n result = getObjectByIdentity(oid);\n }\n else\n {\n // TODO: This workaround doesn't allow 'null' for PK fields\n if (!serviceBrokerHelper().hasNullPKField(getClassDescriptor(obj.getClass()), obj))\n {\n Identity oid = serviceIdentity().buildIdentity(obj);\n result = getObjectByIdentity(oid);\n }\n }\n }\n else\n {\n Class itemClass = query.getSearchClass();\n ClassDescriptor cld = getClassDescriptor(itemClass);\n /*\n use OJB intern Iterator, thus we are able to close used\n resources instantly\n */\n OJBIterator it = getIteratorFromQuery(query, cld);\n /*\n arminw:\n patch by Andre Clute, instead of taking the first found result\n try to get the first found none null result.\n He wrote:\n I have a situation where an item with a certain criteria is in my\n database twice -- once deleted, and then a non-deleted version of it.\n When I do a PB.getObjectByQuery(), the RsIterator get's both results\n from the database, but the first row is the deleted row, so my RowReader\n filters it out, and do not get the right result.\n */\n try\n {\n while (result==null && it.hasNext())\n {\n result = it.next();\n }\n } // make sure that we close the used resources\n finally\n {\n if(it != null) it.releaseDbResources();\n }\n }\n return result;\n }",
"@Override\n\tpublic RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException {\n\t\tif(exerciseMethod == ExerciseMethod.UPPER_BOUND_METHOD) {\n\t\t\t// Find optimal lambda\n\t\t\tGoldenSectionSearch optimizer = new GoldenSectionSearch(-1.0, 1.0);\n\t\t\twhile(!optimizer.isDone()) {\n\t\t\t\tdouble lambda = optimizer.getNextPoint();\n\t\t\t\tdouble value = this.getValues(evaluationTime, model, lambda).getAverage();\n\t\t\t\toptimizer.setValue(value);\n\t\t\t}\n\t\t\treturn getValues(evaluationTime, model, optimizer.getBestPoint());\n\t\t}\n\t\telse {\n\t\t\treturn getValues(evaluationTime, model, 0.0);\n\t\t}\n\t}",
"public static List<String> getAllUserStoreNamesOnNode(AdminClient adminClient, Integer nodeId) {\n List<String> storeNames = Lists.newArrayList();\n List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n\n for(StoreDefinition storeDefinition: storeDefinitionList) {\n storeNames.add(storeDefinition.getName());\n }\n return storeNames;\n }",
"private void clearDeckPreview(TrackMetadataUpdate update) {\n if (previewHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverWaveformPreviewUpdate(update.player, null);\n }\n }"
] |
Add an accessory to be handled and advertised by this root. Any existing Homekit connections
will be terminated to allow the clients to reconnect and see the updated accessory list. When
using this for a bridge, the ID of the accessory must be greater than 1, as that ID is reserved
for the Bridge itself.
@param accessory to advertise and handle. | [
"public void addAccessory(HomekitAccessory accessory) {\n if (accessory.getId() <= 1 && !(accessory instanceof Bridge)) {\n throw new IndexOutOfBoundsException(\n \"The ID of an accessory used in a bridge must be greater than 1\");\n }\n addAccessorySkipRangeCheck(accessory);\n }"
] | [
"private boolean checkTagAndParam(XDoc doc, String tagName, String paramName, String paramValue)\r\n {\r\n if (tagName == null) {\r\n return true;\r\n }\r\n if (!doc.hasTag(tagName)) {\r\n return false;\r\n }\r\n if (paramName == null) {\r\n return true;\r\n }\r\n if (!doc.getTag(tagName).getAttributeNames().contains(paramName)) {\r\n return false;\r\n }\r\n return (paramValue == null) || paramValue.equals(doc.getTagAttributeValue(tagName, paramName));\r\n }",
"public void prepareForEnumeration() {\n if (isPreparer()) {\n for (NodeT node : nodeTable.values()) {\n // Prepare each node for traversal\n node.initialize();\n if (!this.isRootNode(node)) {\n // Mark other sub-DAGs as non-preparer\n node.setPreparer(false);\n }\n }\n initializeDependentKeys();\n initializeQueue();\n }\n }",
"private boolean checkConfig(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n return \"true\".equalsIgnoreCase((String)config.getProperties().get(\"collector.lifecycleEvent\"));\n }",
"private void installFastProcessAnnotatedTypeResolver(ServiceRegistry services) {\n ClassFileServices classFileServices = services.get(ClassFileServices.class);\n if (classFileServices != null) {\n final GlobalObserverNotifierService observers = services.get(GlobalObserverNotifierService.class);\n try {\n final FastProcessAnnotatedTypeResolver resolver = new FastProcessAnnotatedTypeResolver(observers.getAllObserverMethods());\n services.add(FastProcessAnnotatedTypeResolver.class, resolver);\n } catch (UnsupportedObserverMethodException e) {\n BootstrapLogger.LOG.notUsingFastResolver(e.getObserver());\n return;\n }\n }\n }",
"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 }",
"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 }",
"private Collection parseTreeCollection(Element collectionElement) {\n\n Collection collection = new Collection();\n parseCommonFields(collectionElement, collection);\n collection.setTitle(collectionElement.getAttribute(\"title\"));\n collection.setDescription(collectionElement.getAttribute(\"description\"));\n\n // Collections can contain either sets or collections (but not both)\n NodeList childCollectionElements = collectionElement.getElementsByTagName(\"collection\");\n for (int i = 0; i < childCollectionElements.getLength(); i++) {\n Element childCollectionElement = (Element) childCollectionElements.item(i);\n collection.addCollection(parseTreeCollection(childCollectionElement));\n }\n\n NodeList childPhotosetElements = collectionElement.getElementsByTagName(\"set\");\n for (int i = 0; i < childPhotosetElements.getLength(); i++) {\n Element childPhotosetElement = (Element) childPhotosetElements.item(i);\n collection.addPhotoset(createPhotoset(childPhotosetElement));\n }\n\n return collection;\n }",
"public void deleteMetadata(String templateName, String scope) {\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"private void revisitGateways(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n for (RootElement root : rootElements) {\n if (root instanceof Process) {\n setGatewayInfo((Process) root);\n }\n }\n }"
] |
Returns a "clean" version of the given filename in which spaces have
been converted to dashes and all non-alphanumeric chars are underscores. | [
"public static String fileNameClean(String s) {\r\n char[] chars = s.toCharArray();\r\n StringBuilder sb = new StringBuilder();\r\n for (char c : chars) {\r\n if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_')) {\r\n sb.append(c);\r\n } else {\r\n if (c == ' ' || c == '-') {\r\n sb.append('_');\r\n } else {\r\n sb.append('x').append((int) c).append('x');\r\n }\r\n }\r\n }\r\n return sb.toString();\r\n }"
] | [
"public static GVRTexture loadFutureCubemapTexture(\n GVRContext gvrContext, ResourceCache<GVRImage> textureCache,\n GVRAndroidResource resource, int priority,\n Map<String, Integer> faceIndexMap) {\n GVRTexture tex = new GVRTexture(gvrContext);\n GVRImage cached = textureCache.get(resource);\n if (cached != null)\n {\n Log.v(\"ASSET\", \"Future Texture: %s loaded from cache\", cached.getFileName());\n tex.setImage(cached);\n }\n else\n {\n AsyncCubemapTexture.get().loadTexture(gvrContext,\n CancelableCallbackWrapper.wrap(GVRCubemapImage.class, tex),\n resource, priority, faceIndexMap);\n\n }\n return tex;\n }",
"private void 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 }",
"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 Date getDate(String path) throws ParseException {\n return BoxDateFormat.parse(this.getValue(path).asString());\n }",
"public int compareTo(WordLemmaTag wordLemmaTag) {\r\n int first = word().compareTo(wordLemmaTag.word());\r\n if (first != 0)\r\n return first;\r\n int second = lemma().compareTo(wordLemmaTag.lemma());\r\n if (second != 0)\r\n return second;\r\n else\r\n return tag().compareTo(wordLemmaTag.tag());\r\n }",
"@Override\n public int getShadowSize() {\n\tElement shadowElement = shadow.getElement();\n\tshadowElement.setScrollTop(10000);\n\treturn shadowElement.getScrollTop();\n }",
"protected boolean hasKey() {\n boolean result = false;\n String requestURI = this.request.getUri();\n parseKeys(requestURI);\n\n if(this.parsedKeys != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. No key specified.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Error: No key specified !\");\n }\n return result;\n }",
"@SuppressWarnings(\"unchecked\")\n public static <E> TypeConverter<E> typeConverterFor(Class<E> cls) throws NoSuchTypeConverterException {\n TypeConverter<E> typeConverter = TYPE_CONVERTERS.get(cls);\n if (typeConverter == null) {\n throw new NoSuchTypeConverterException(cls);\n }\n return typeConverter;\n }",
"public T addContentModification(final ContentModification modification) {\n if (itemFilter.accepts(modification.getItem())) {\n internalAddModification(modification);\n }\n return returnThis();\n }"
] |
Determines how many primary partitions each node within each zone should
have. The list of integers returned per zone is the same length as the
number of nodes in that zone.
@param nextCandidateCluster
@param targetPartitionsPerZone
@return A map of zoneId to list of target number of partitions per node
within zone. | [
"public static HashMap<Integer, List<Integer>>\n getBalancedNumberOfPrimaryPartitionsPerNode(final Cluster nextCandidateCluster,\n Map<Integer, Integer> targetPartitionsPerZone) {\n HashMap<Integer, List<Integer>> numPartitionsPerNode = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n List<Integer> partitionsOnNode = Utils.distributeEvenlyIntoList(nextCandidateCluster.getNumberOfNodesInZone(zoneId),\n targetPartitionsPerZone.get(zoneId));\n numPartitionsPerNode.put(zoneId, partitionsOnNode);\n }\n return numPartitionsPerNode;\n }"
] | [
"public void setPerms(String photoId, Permissions permissions) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", permissions.isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", permissions.isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", permissions.isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"perm_comment\", Integer.toString(permissions.getComment()));\r\n parameters.put(\"perm_addmeta\", Integer.toString(permissions.getAddmeta()));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"static void processFile(final IdentityPatchContext context, final File file, final PatchingTaskContext.Mode mode) throws IOException {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n if (ENABLE_INVALIDATION) {\n updateJar(file, GOOD_ENDSIG_PATTERN, BAD_BYTE_SKIP, CRIPPLED_ENDSIG, GOOD_ENDSIG);\n backup(context, file);\n }\n } else if (mode == PatchingTaskContext.Mode.ROLLBACK) {\n updateJar(file, CRIPPLED_ENDSIG_PATTERN, BAD_BYTE_SKIP, GOOD_ENDSIG, CRIPPLED_ENDSIG);\n restore(context, file);\n } else {\n throw new IllegalStateException();\n }\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushNotificationViewedEvent(Bundle extras){\n\n if (extras == null || extras.isEmpty() || extras.get(Constants.NOTIFICATION_TAG) == null) {\n getConfigLogger().debug(getAccountId(), \"Push notification: \" + (extras == null ? \"NULL\" : extras.toString()) + \" not from CleverTap - will not process Notification Viewed event.\");\n return;\n }\n\n if (!extras.containsKey(Constants.NOTIFICATION_ID_TAG) || (extras.getString(Constants.NOTIFICATION_ID_TAG) == null)) {\n getConfigLogger().debug(getAccountId(), \"Push notification ID Tag is null, not processing Notification Viewed event for: \" + extras.toString());\n return;\n }\n\n // Check for dupe notification views; if same notficationdId within specified time interval (2 secs) don't process\n boolean isDuplicate = checkDuplicateNotificationIds(extras, notificationViewedIdTagMap, Constants.NOTIFICATION_VIEWED_ID_TAG_INTERVAL);\n if (isDuplicate) {\n getConfigLogger().debug(getAccountId(), \"Already processed Notification Viewed event for \" + extras.toString() + \", dropping duplicate.\");\n return;\n }\n\n JSONObject event = new JSONObject();\n try {\n JSONObject notif = getWzrkFields(extras);\n event.put(\"evtName\", Constants.NOTIFICATION_VIEWED_EVENT_NAME);\n event.put(\"evtData\", notif);\n } catch (Throwable ignored) {\n //no-op\n }\n queueEvent(context, event, Constants.RAISED_EVENT);\n }",
"static Shell createTerminalConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n PrintStream out = new PrintStream(output);\n\n // Build jline terminal\n jline.Terminal term = TerminalFactory.get();\n final ConsoleReader console = new ConsoleReader(input, output, term);\n console.setBellEnabled(true);\n console.setHistoryEnabled(true);\n\n // Build console\n BufferedReader in = new BufferedReader(new InputStreamReader(\n new ConsoleReaderInputStream(console)));\n\n ConsoleIO.PromptListener promptListener = new ConsoleIO.PromptListener() {\n @Override\n public boolean onPrompt(String prompt) {\n console.setPrompt(prompt);\n return true; // suppress normal prompt\n }\n };\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, promptListener);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }",
"private File[] getFilesFromProperty(final String name, final Properties props) {\n String sep = WildFlySecurityManager.getPropertyPrivileged(\"path.separator\", null);\n String value = props.getProperty(name, null);\n if (value != null) {\n final String[] paths = value.split(Pattern.quote(sep));\n final int len = paths.length;\n final File[] files = new File[len];\n for (int i = 0; i < len; i++) {\n files[i] = new File(paths[i]);\n }\n return files;\n }\n return NO_FILES;\n }",
"private boolean computeEigenValues() {\n // make a copy of the internal tridiagonal matrix data for later use\n diagSaved = helper.copyDiag(diagSaved);\n offSaved = helper.copyOff(offSaved);\n\n vector.setQ(null);\n vector.setFastEigenvalues(true);\n\n // extract the eigenvalues\n if( !vector.process(-1,null,null) )\n return false;\n\n // save a copy of them since this data structure will be recycled next\n values = helper.copyEigenvalues(values);\n return true;\n }",
"public static boolean sameLists(String list1, String list2)\r\n {\r\n return new CommaListIterator(list1).equals(new CommaListIterator(list2));\r\n }",
"public ManageableCollection getCollectionByQuery(Class collectionClass, Query query, boolean lazy) throws PersistenceBrokerException\r\n {\r\n ManageableCollection result;\r\n\r\n try\r\n {\r\n // BRJ: return empty Collection for null query\r\n if (query == null)\r\n {\r\n result = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n else\r\n {\r\n if (lazy)\r\n {\r\n result = pb.getProxyFactory().createCollectionProxy(pb.getPBKey(), query, collectionClass);\r\n }\r\n else\r\n {\r\n result = getCollectionByQuery(collectionClass, query.getSearchClass(), query);\r\n }\r\n }\r\n return result;\r\n }\r\n catch (Exception e)\r\n {\r\n if(e instanceof PersistenceBrokerException)\r\n {\r\n throw (PersistenceBrokerException) e;\r\n }\r\n else\r\n {\r\n throw new PersistenceBrokerException(e);\r\n }\r\n }\r\n }",
"private void addAssignments(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (ResourceAssignment assignment : file.getResourceAssignments())\n {\n final ResourceAssignment a = assignment;\n MpxjTreeNode childNode = new MpxjTreeNode(a)\n {\n @Override public String toString()\n {\n Resource resource = a.getResource();\n String resourceName = resource == null ? \"(unknown resource)\" : resource.getName();\n Task task = a.getTask();\n String taskName = task == null ? \"(unknown task)\" : task.getName();\n return resourceName + \"->\" + taskName;\n }\n };\n parentNode.add(childNode);\n }\n }"
] |
backing bootstrap method with all parameters | [
"private static CallSite realBootstrap(Lookup caller, String name, int callID, MethodType type, boolean safe, boolean thisCall, boolean spreadCall) {\n // since indy does not give us the runtime types\n // we produce first a dummy call site, which then changes the target to one,\n // that does the method selection including the the direct call to the \n // real method.\n MutableCallSite mc = new MutableCallSite(type);\n MethodHandle mh = makeFallBack(mc,caller.lookupClass(),name,callID,type,safe,thisCall,spreadCall);\n mc.setTarget(mh);\n return mc;\n }"
] | [
"public void setAddContentInfo(final Boolean doAddInfo) {\n\n if ((null != doAddInfo) && doAddInfo.booleanValue() && (null != m_addContentInfoForEntries)) {\n m_addContentInfoForEntries = Integer.valueOf(DEFAULT_CONTENTINFO_ROWS);\n }\n }",
"public void reverse() {\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).reverse();\n }\n }",
"public static int Median( int[] values ){\n int total = 0, n = values.length;\n\n // for all values\n for ( int i = 0; i < n; i++ )\n {\n // accumalate total\n total += values[i];\n }\n\n int halfTotal = total / 2;\n int median = 0, v = 0;\n\n // find median value\n for ( ; median < n; median++ )\n {\n v += values[median];\n if ( v >= halfTotal )\n break;\n }\n\n return median;\n }",
"public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy) throws PersistenceBrokerException\r\n {\r\n return getKeyValues(cld, objectOrProxy, true);\r\n }",
"public void setTexture(GVRRenderTexture texture)\n {\n mTexture = texture;\n NativeRenderTarget.setTexture(getNative(), texture.getNative());\n }",
"public StreamReader getTableData(String name) throws IOException\n {\n InputStream stream = new ByteArrayInputStream(m_tableData.get(name));\n if (m_majorVersion > 5)\n { \n byte[] header = new byte[24];\n stream.read(header);\n SynchroLogger.log(\"TABLE HEADER\", header);\n }\n return new StreamReader(m_majorVersion, stream);\n }",
"public void start(GVRAccessibilitySpeechListener speechListener) {\n mTts.setSpeechListener(speechListener);\n mTts.getSpeechRecognizer().startListening(mTts.getSpeechRecognizerIntent());\n }",
"@Override\n\tprotected void doProcessQueuedOps(PersistentCollection collection, Serializable key, int nextIndex, SharedSessionContractImplementor session)\n\t\t\tthrows HibernateException {\n\t\t// nothing to do\n\t}",
"private void flushHotCacheSlot(SlotReference slot) {\n // Iterate over a copy to avoid concurrent modification issues\n for (Map.Entry<DeckReference, TrackMetadata> entry : new HashMap<DeckReference,TrackMetadata>(hotCache).entrySet()) {\n if (slot == SlotReference.getSlotReference(entry.getValue().trackReference)) {\n logger.debug(\"Evicting cached metadata in response to unmount report {}\", entry.getValue());\n hotCache.remove(entry.getKey());\n }\n }\n }"
] |
Ensure that the node is not null.
@param node the node to ensure to be not null
@param expression the expression was used to find the node
@throws SpinXPathException if the node is null | [
"public static void ensureXPathNotNull(Node node, String expression) {\n if (node == null) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }"
] | [
"private void bubbleUpNodeTable(DAGraph<DataT, NodeT> from, LinkedList<String> path) {\n if (path.contains(from.rootNode.key())) {\n path.push(from.rootNode.key()); // For better error message\n throw new IllegalStateException(\"Detected circular dependency: \" + StringUtils.join(path, \" -> \"));\n }\n path.push(from.rootNode.key());\n for (DAGraph<DataT, NodeT> to : from.parentDAGs) {\n this.merge(from.nodeTable, to.nodeTable);\n this.bubbleUpNodeTable(to, path);\n }\n path.pop();\n }",
"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 Set<Annotation> getPropertyAnnotations()\n\t{\n\t\tif (accessor instanceof PropertyAwareAccessor)\n\t\t{\n\t\t\treturn unmodifiableSet(((PropertyAwareAccessor) accessor).getReadMethodAnnotations());\n\t\t}\n\t\treturn unmodifiableSet(Collections.<Annotation>emptySet());\n\t}",
"public static <T> ServiceFuture<T> fromResponse(final Observable<ServiceResponse<T>> observable) {\n final ServiceFuture<T> serviceFuture = new ServiceFuture<>();\n serviceFuture.subscription = observable\n .last()\n .subscribe(new Action1<ServiceResponse<T>>() {\n @Override\n public void call(ServiceResponse<T> t) {\n serviceFuture.set(t.body());\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\n }",
"public static String serialize(final Object obj) throws IOException {\n\t\tfinal ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n\t\treturn mapper.writeValueAsString(obj);\n\t\t\n\t}",
"public void updateBitmapShader() {\n\t\tif (image == null)\n\t\t\treturn;\n\n\t\tshader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);\n\n\t\tif(canvasSize != image.getWidth() || canvasSize != image.getHeight()) {\n\t\t\tMatrix matrix = new Matrix();\n\t\t\tfloat scale = (float) canvasSize / (float) image.getWidth();\n\t\t\tmatrix.setScale(scale, scale);\n\t\t\tshader.setLocalMatrix(matrix);\n\t\t}\n\t}",
"private static void listSlack(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n System.out.println(task.getName() + \" Total Slack=\" + task.getTotalSlack() + \" Start Slack=\" + task.getStartSlack() + \" Finish Slack=\" + task.getFinishSlack());\n }\n }",
"private void clearDeckPreview(TrackMetadataUpdate update) {\n if (previewHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverWaveformPreviewUpdate(update.player, null);\n }\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 }"
] |
Processes the template for all procedure arguments of the current procedure.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"public void forAllProcedureArguments(String template, Properties attributes) throws XDocletException\r\n {\r\n String argNameList = _curProcedureDef.getProperty(PropertyHelper.OJB_PROPERTY_ARGUMENTS);\r\n\r\n for (CommaListIterator it = new CommaListIterator(argNameList); it.hasNext();)\r\n {\r\n _curProcedureArgumentDef = _curClassDef.getProcedureArgument(it.getNext());\r\n generate(template);\r\n }\r\n _curProcedureArgumentDef = null;\r\n }"
] | [
"public <L extends Listener> void popEvent(Event<?, L> expected) {\n synchronized (this.stack) {\n final Event<?, ?> actual = this.stack.pop();\n if (actual != expected) {\n throw new IllegalStateException(String.format(\n \"Unbalanced pop: expected '%s' but encountered '%s'\",\n expected.getListenerClass(), actual));\n }\n }\n }",
"public DockerContainerObjectBuilder<T> withEnrichers(Collection<TestEnricher> enrichers) {\n if (enrichers == null) {\n throw new IllegalArgumentException(\"enrichers cannot be null\");\n }\n this.enrichers = enrichers;\n return this;\n }",
"public static SimpleFeatureType createGridFeatureType(\n @Nonnull final MapfishMapContext mapContext,\n @Nonnull final Class<? extends Geometry> geomClass) {\n final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();\n CoordinateReferenceSystem projection = mapContext.getBounds().getProjection();\n typeBuilder.add(Constants.Style.Grid.ATT_GEOM, geomClass, projection);\n typeBuilder.setName(Constants.Style.Grid.NAME_LINES);\n\n return typeBuilder.buildFeatureType();\n }",
"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 }",
"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 }",
"protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (getInputVariablesName() == null)\n {\n setInputVariablesName(Iteration.getPayloadVariableName(event, context));\n }\n }",
"static boolean isInCircle(float x, float y, float centerX, float centerY, float\n radius) {\n return Math.abs(x - centerX) < radius && Math.abs(y - centerY) < radius;\n }",
"public static vrid6 get(nitro_service service, Long id) throws Exception{\n\t\tvrid6 obj = new vrid6();\n\t\tobj.set_id(id);\n\t\tvrid6 response = (vrid6) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static AdminClient getAdminClient(String url) {\n ClientConfig config = new ClientConfig().setBootstrapUrls(url)\n .setConnectionTimeout(5, TimeUnit.SECONDS);\n\n AdminClientConfig adminConfig = new AdminClientConfig().setAdminSocketTimeoutSec(5);\n return new AdminClient(adminConfig, config);\n }"
] |
Write the config to the writer. | [
"private static <T> void writeConfig(BufferedWriter writer, DatabaseTableConfig<T> config) throws IOException,\n\t\t\tSQLException {\n\t\twriter.append(CONFIG_FILE_START_MARKER);\n\t\twriter.newLine();\n\t\tif (config.getDataClass() != null) {\n\t\t\twriter.append(FIELD_NAME_DATA_CLASS).append('=').append(config.getDataClass().getName());\n\t\t\twriter.newLine();\n\t\t}\n\t\tif (config.getTableName() != null) {\n\t\t\twriter.append(FIELD_NAME_TABLE_NAME).append('=').append(config.getTableName());\n\t\t\twriter.newLine();\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_START);\n\t\twriter.newLine();\n\t\tif (config.getFieldConfigs() != null) {\n\t\t\tfor (DatabaseFieldConfig field : config.getFieldConfigs()) {\n\t\t\t\tDatabaseFieldConfigLoader.write(writer, field, config.getTableName());\n\t\t\t}\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_END);\n\t\twriter.newLine();\n\t\twriter.append(CONFIG_FILE_END_MARKER);\n\t\twriter.newLine();\n\t}"
] | [
"private void processDeferredRelationship(DeferredRelationship dr) throws MPXJException\n {\n String data = dr.getData();\n Task task = dr.getTask();\n\n int length = data.length();\n\n if (length != 0)\n {\n int start = 0;\n int end = 0;\n\n while (end != length)\n {\n end = data.indexOf(m_delimiter, start);\n\n if (end == -1)\n {\n end = length;\n }\n\n populateRelation(dr.getField(), task, data.substring(start, end).trim());\n\n start = end + 1;\n }\n }\n }",
"public void onDrawFrame(float frameTime)\n {\n if (isEnabled() && (mScene != null) && mPickEventLock.tryLock())\n {\n // Don't call if we are in the middle of processing another pick\n try\n {\n doPick();\n }\n finally\n {\n mPickEventLock.unlock();\n }\n }\n }",
"public void delete(final String referenceId) {\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.equal(root.get(\"referenceId\"), referenceId));\n getSession().createQuery(delete).executeUpdate();\n }",
"private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {\n // updates the coordinator metadata with recent stores and cluster xml\n updateCoordinatorMetadataWithLatestState();\n\n logger.info(\"Creating a Fat client for store: \" + storeName);\n SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),\n storeClientProps);\n\n if(this.fatClientMap == null) {\n this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>();\n }\n DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,\n fatClientFactory,\n 1,\n this.coordinatorMetadata.getStoreDefs(),\n this.coordinatorMetadata.getClusterXmlStr());\n this.fatClientMap.put(storeName, fatClient);\n\n }",
"public final void notifyFooterItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n// if (position < 0 || position >= newFooterItemCount) {\n// throw new IndexOutOfBoundsException(\"The given position \" + position\n// + \" is not within the position bounds for footer items [0 - \"\n// + (newFooterItemCount - 1) + \"].\");\n// }\n notifyItemInserted(position + newHeaderItemCount + newContentItemCount);\n }",
"private StateVertex addStateToCurrentState(StateVertex newState, Eventable eventable) {\n\t\tLOGGER.debug(\"addStateToCurrentState currentState: {} newState {}\",\n\t\t\t\tcurrentState.getName(), newState.getName());\n\n\t\t// Add the state to the stateFlowGraph. Store the result\n\t\tStateVertex cloneState = stateFlowGraph.putIfAbsent(newState);\n\n\t\t// Is there a clone detected?\n\t\tif (cloneState != null) {\n\t\t\tLOGGER.info(\"CLONE State detected: {} and {} are the same.\", newState.getName(),\n\t\t\t\t\tcloneState.getName());\n\t\t\tLOGGER.debug(\"CLONE CURRENT STATE: {}\", currentState.getName());\n\t\t\tLOGGER.debug(\"CLONE STATE: {}\", cloneState.getName());\n\t\t\tLOGGER.debug(\"CLONE CLICKABLE: {}\", eventable);\n\t\t\tboolean added = stateFlowGraph.addEdge(currentState, cloneState, eventable);\n\t\t\tif (!added) {\n\t\t\t\tLOGGER.debug(\"Clone edge !! Need to fix the crawlPath??\");\n\t\t\t}\n\t\t} else {\n\t\t\tstateFlowGraph.addEdge(currentState, newState, eventable);\n\t\t\tLOGGER.info(\"State {} added to the StateMachine.\", newState.getName());\n\t\t}\n\n\t\treturn cloneState;\n\t}",
"public static scpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tscpolicy_stats obj = new scpolicy_stats();\n\t\tobj.set_name(name);\n\t\tscpolicy_stats response = (scpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static Statement open(String driverklass, String jdbcuri,\n Properties props) {\n try {\n Driver driver = (Driver) ObjectUtils.instantiate(driverklass);\n Connection conn = driver.connect(jdbcuri, props);\n if (conn == null)\n throw new DukeException(\"Couldn't connect to database at \" +\n jdbcuri);\n return conn.createStatement();\n\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }",
"private JsonArray formatBoxMetadataFilterRequest() {\n JsonArray boxMetadataFilterRequestArray = new JsonArray();\n\n JsonObject boxMetadataFilter = new JsonObject()\n .add(\"templateKey\", this.metadataFilter.getTemplateKey())\n .add(\"scope\", this.metadataFilter.getScope())\n .add(\"filters\", this.metadataFilter.getFiltersList());\n boxMetadataFilterRequestArray.add(boxMetadataFilter);\n\n return boxMetadataFilterRequestArray;\n }"
] |
this method is basically checking whether we can return "this" for getNetworkSection | [
"protected boolean isNetworkSection(int networkPrefixLength, boolean withPrefixLength) {\n\t\tint segmentCount = getSegmentCount();\n\t\tif(segmentCount == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tint bitsPerSegment = getBitsPerSegment();\n\t\tint prefixedSegmentIndex = getNetworkSegmentIndex(networkPrefixLength, getBytesPerSegment(), bitsPerSegment);\n\t\tif(prefixedSegmentIndex + 1 < segmentCount) {\n\t\t\treturn false; //not the right number of segments\n\t\t}\n\t\t//the segment count matches, now compare the prefixed segment\n\t\tint segPrefLength = getPrefixedSegmentPrefixLength(bitsPerSegment, networkPrefixLength, prefixedSegmentIndex);\n\t\treturn !getSegment(segmentCount - 1).isNetworkChangedByPrefix(segPrefLength, withPrefixLength);\n\t}"
] | [
"void resizeArray(int newArraySize) {\n\t\tlong[] newArray = new long[newArraySize];\n\t\tSystem.arraycopy(this.arrayOfBits, 0, newArray, 0,\n\t\t\t\tMath.min(this.arrayOfBits.length, newArraySize));\n\t\tthis.arrayOfBits = newArray;\n\t}",
"private static List<String> parseAndCompare(List<String> fileNames, int masterPartitionId) {\n List<String> sourceFileNames = new ArrayList<String>();\n for(String fileName: fileNames) {\n String[] partitionIdReplicaChunk = fileName.split(SPLIT_LITERAL);\n if(Integer.parseInt(partitionIdReplicaChunk[0]) == masterPartitionId) {\n sourceFileNames.add(fileName);\n }\n }\n return sourceFileNames;\n }",
"public MACAddress toEUI64(boolean asMAC) {\r\n\t\tif(!isExtended()) {//getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT\r\n\t\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\t\tMACAddressSegment segs[] = creator.createSegmentArray(EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT);\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tsection.getSegments(0, 3, segs, 0);\r\n\t\t\tMACAddressSegment ffSegment = creator.createSegment(0xff);\r\n\t\t\tsegs[3] = ffSegment;\r\n\t\t\tsegs[4] = asMAC ? ffSegment : creator.createSegment(0xfe);\r\n\t\t\tsection.getSegments(3, 6, segs, 5);\r\n\t\t\tInteger prefLength = getPrefixLength();\r\n\t\t\tif(prefLength != null) {\r\n\t\t\t\tMACAddressSection resultSection = creator.createSectionInternal(segs, true);\r\n\t\t\t\tif(prefLength >= 24) {\r\n\t\t\t\t\tprefLength += MACAddress.BITS_PER_SEGMENT << 1; //two segments\r\n\t\t\t\t}\r\n\t\t\t\tresultSection.assignPrefixLength(prefLength);\r\n\t\t\t}\r\n\t\t\treturn creator.createAddressInternal(segs);\r\n\t\t} else {\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tMACAddressSegment seg3 = section.getSegment(3);\r\n\t\t\tMACAddressSegment seg4 = section.getSegment(4);\r\n\t\t\tif(seg3.matches(0xff) && seg4.matches(asMAC ? 0xff : 0xfe)) {\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new IncompatibleAddressException(this, \"ipaddress.mac.error.not.eui.convertible\");\r\n\t}",
"public static base_response add(nitro_service client, authenticationradiusaction resource) throws Exception {\n\t\tauthenticationradiusaction addresource = new authenticationradiusaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.serverip = resource.serverip;\n\t\taddresource.serverport = resource.serverport;\n\t\taddresource.authtimeout = resource.authtimeout;\n\t\taddresource.radkey = resource.radkey;\n\t\taddresource.radnasip = resource.radnasip;\n\t\taddresource.radnasid = resource.radnasid;\n\t\taddresource.radvendorid = resource.radvendorid;\n\t\taddresource.radattributetype = resource.radattributetype;\n\t\taddresource.radgroupsprefix = resource.radgroupsprefix;\n\t\taddresource.radgroupseparator = resource.radgroupseparator;\n\t\taddresource.passencoding = resource.passencoding;\n\t\taddresource.ipvendorid = resource.ipvendorid;\n\t\taddresource.ipattributetype = resource.ipattributetype;\n\t\taddresource.accounting = resource.accounting;\n\t\taddresource.pwdvendorid = resource.pwdvendorid;\n\t\taddresource.pwdattributetype = resource.pwdattributetype;\n\t\taddresource.defaultauthenticationgroup = resource.defaultauthenticationgroup;\n\t\taddresource.callingstationid = resource.callingstationid;\n\t\treturn addresource.add_resource(client);\n\t}",
"public void setAlias(UserAlias userAlias)\r\n\t{\r\n\t\tm_alias = userAlias.getName();\r\n\r\n\t\t// propagate to SelectionCriteria,not to Criteria\r\n\t\tfor (int i = 0; i < m_criteria.size(); i++)\r\n\t\t{\r\n\t\t\tif (!(m_criteria.elementAt(i) instanceof Criteria))\r\n\t\t\t{\r\n\t\t\t\t((SelectionCriteria) m_criteria.elementAt(i)).setAlias(userAlias);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"@SuppressWarnings(\"unchecked\")\n public static <T> T convert(Object fromValue, Class<T> toType) throws TypeCastException {\n return convert(fromValue, toType, (String) null);\n }",
"public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getInsertStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }",
"@NonNull public CharSequence getQuery() {\n if (searchView != null) {\n return searchView.getQuery();\n } else if (supportView != null) {\n return supportView.getQuery();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }",
"@Override\n public void setExpectedMaxSize( int numRows , int numCols ) {\n super.setExpectedMaxSize(numRows,numCols);\n\n // if the matrix that is being decomposed is smaller than the block we really don't\n // see the B matrix.\n if( numRows < blockWidth)\n B = new DMatrixRMaj(0,0);\n else\n B = new DMatrixRMaj(blockWidth,maxWidth);\n\n chol = new CholeskyBlockHelper_DDRM(blockWidth);\n }"
] |
Stops the processing and prints the final time. | [
"@Override\n\tpublic void close() {\n\t\tlogger.info(\"Finished processing.\");\n\t\tthis.timer.stop();\n\t\tthis.lastSeconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\tprintStatus();\n\t}"
] | [
"public 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 }",
"protected void reportProgress(String taskDecription) {\n if (this.progress != null) {\n if (this.progress.isCanceled()) {\n // Only AbortCompilation can stop the compiler cleanly.\n // We check cancellation again following the call to compile.\n throw new AbortCompilation(true, null);\n }\n this.progress.setTaskName(taskDecription);\n }\n }",
"public CurrencyQueryBuilder setCurrencyCodes(String... codes) {\n return set(CurrencyQuery.KEY_QUERY_CURRENCY_CODES, Arrays.asList(codes));\n }",
"public static ModelNode createBootUpdates(final String serverName, final ModelNode domainModel, final ModelNode hostModel,\n final DomainController domainController, final ExpressionResolver expressionResolver) {\n final ManagedServerOperationsFactory factory = new ManagedServerOperationsFactory(serverName, domainModel,\n hostModel, domainController, expressionResolver);\n\n\n return factory.getBootUpdates();\n }",
"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 static base_responses update(nitro_service client, bridgetable resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable updateresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new bridgetable();\n\t\t\t\tupdateresources[i].bridgeage = resources[i].bridgeage;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases)\n {\n int uniqueID = MPPUtility.getInt(data, offset);\n FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4));\n Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8));\n int style = MPPUtility.getByte(data, offset + 9);\n ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10));\n int change = MPPUtility.getByte(data, offset + 12);\n\n FontBase fontBase = fontBases.get(index);\n\n boolean bold = ((style & 0x01) != 0);\n boolean italic = ((style & 0x02) != 0);\n boolean underline = ((style & 0x04) != 0);\n\n boolean boldChanged = ((change & 0x01) != 0);\n boolean underlineChanged = ((change & 0x02) != 0);\n boolean italicChanged = ((change & 0x04) != 0);\n boolean colorChanged = ((change & 0x08) != 0);\n boolean fontChanged = ((change & 0x10) != 0);\n boolean backgroundColorChanged = (uniqueID == -1);\n boolean backgroundPatternChanged = (uniqueID == -1);\n\n return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged));\n }",
"public static snmpoption get(nitro_service service) throws Exception{\n\t\tsnmpoption obj = new snmpoption();\n\t\tsnmpoption[] response = (snmpoption[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public Set<Class<?>> getPrevented() {\n if (this.prevent == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(this.prevent);\n }"
] |
Curries a function that takes two arguments.
@param function
the original function. May not be <code>null</code>.
@param argument
the fixed first argument of {@code function}.
@return a function that takes one argument. Never <code>null</code>. | [
"@Pure\n\tpublic static <P1, P2, RESULT> Function1<P2, RESULT> curry(final Function2<? super P1, ? super P2, ? extends RESULT> function,\n\t\t\tfinal P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function1<P2, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p) {\n\t\t\t\treturn function.apply(argument, p);\n\t\t\t}\n\t\t};\n\t}"
] | [
"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 }",
"void buildControl(BinaryPackageControlFile packageControlFile, File[] controlFiles, List<String> conffiles, StringBuilder checksums, File output) throws IOException, ParseException {\n final File dir = output.getParentFile();\n if (dir != null && (!dir.exists() || !dir.isDirectory())) {\n throw new IOException(\"Cannot write control file at '\" + output.getAbsolutePath() + \"'\");\n }\n\n final TarArchiveOutputStream outputStream = new TarArchiveOutputStream(new GZIPOutputStream(new FileOutputStream(output)));\n outputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);\n\n boolean foundConffiles = false;\n\n // create the final package control file out of the \"control\" file, copy all other files, ignore the directories\n for (File file : controlFiles) {\n if (file.isDirectory()) {\n // warn about the misplaced directory, except for directories ignored by default (.svn, cvs, etc)\n if (!isDefaultExcludes(file)) {\n console.warn(\"Found directory '\" + file + \"' in the control directory. Maybe you are pointing to wrong dir?\");\n }\n continue;\n }\n\n if (\"conffiles\".equals(file.getName())) {\n foundConffiles = true;\n }\n\n if (CONFIGURATION_FILENAMES.contains(file.getName()) || MAINTAINER_SCRIPTS.contains(file.getName())) {\n FilteredFile configurationFile = new FilteredFile(new FileInputStream(file), resolver);\n configurationFile.setOpenToken(openReplaceToken);\n configurationFile.setCloseToken(closeReplaceToken);\n addControlEntry(file.getName(), configurationFile.toString(), outputStream);\n\n } else if (!\"control\".equals(file.getName())) {\n // initialize the information stream to guess the type of the file\n InformationInputStream infoStream = new InformationInputStream(new FileInputStream(file));\n Utils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);\n infoStream.close();\n\n // fix line endings for shell scripts\n InputStream in = new FileInputStream(file);\n if (infoStream.isShell() && !infoStream.hasUnixLineEndings()) {\n byte[] buf = Utils.toUnixLineEndings(in);\n in = new ByteArrayInputStream(buf);\n }\n\n addControlEntry(file.getName(), IOUtils.toString(in), outputStream);\n\n in.close();\n }\n }\n\n if (foundConffiles) {\n console.info(\"Found file 'conffiles' in the control directory. Skipping conffiles generation.\");\n } else if ((conffiles != null) && (conffiles.size() > 0)) {\n addControlEntry(\"conffiles\", createPackageConffilesFile(conffiles), outputStream);\n } else {\n console.info(\"Skipping 'conffiles' generation. No entries defined in maven/pom or ant/build.xml.\");\n }\n\n if (packageControlFile == null) {\n throw new FileNotFoundException(\"No 'control' file found in \" + controlFiles.toString());\n }\n\n addControlEntry(\"control\", packageControlFile.toString(), outputStream);\n addControlEntry(\"md5sums\", checksums.toString(), outputStream);\n\n outputStream.close();\n }",
"public int compare(final Version other) throws IncomparableException{\n\t\t// Cannot compare branch versions and others \n\t\tif(!isBranch().equals(other.isBranch())){\n\t\t\tthrow new IncomparableException();\n\t\t}\n\t\t\n\t\t// Compare digits\n\t\tfinal int minDigitSize = getDigitsSize() < other.getDigitsSize()? getDigitsSize(): other.getDigitsSize();\n\t\t\n\t\tfor(int i = 0; i < minDigitSize ; i++){\n\t\t\tif(!getDigit(i).equals(other.getDigit(i))){\n\t\t\t\treturn getDigit(i).compareTo(other.getDigit(i));\n\t\t\t}\n\t\t}\n\t\t\n\t\t// If not the same number of digits and the first digits are equals, the longest is the newer\n\t\tif(!getDigitsSize().equals(other.getDigitsSize())){\n\t\t\treturn getDigitsSize() > other.getDigitsSize()? 1: -1;\n\t\t}\n\n if(isBranch() && !getBranchId().equals(other.getBranchId())){\n\t\t\treturn getBranchId().compareTo(other.getBranchId());\n\t\t}\n\t\t\n\t\t// if the digits are the same, a snapshot is newer than a release\n\t\tif(isSnapshot() && other.isRelease()){\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tif(isRelease() && other.isSnapshot()){\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t// if both versions are releases, compare the releaseID\n\t\tif(isRelease() && other.isRelease()){\n\t\t\treturn getReleaseId().compareTo(other.getReleaseId());\n\t\t}\n\t\t\n\t\treturn 0;\n\t}",
"@SuppressWarnings(\"unchecked\")\n public B setTargetType(Class<?> type) {\n Objects.requireNonNull(type);\n set(AbstractQuery.KEY_QUERY_TARGET_TYPE, type);\n return (B) this;\n }",
"public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, null);\n }",
"public boolean startsWith(Bytes prefix) {\n Objects.requireNonNull(prefix, \"startWith(Bytes prefix) cannot have null parameter\");\n\n if (prefix.length > this.length) {\n return false;\n } else {\n int end = this.offset + prefix.length;\n for (int i = this.offset, j = prefix.offset; i < end; i++, j++) {\n if (this.data[i] != prefix.data[j]) {\n return false;\n }\n }\n }\n return true;\n }",
"public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) {\n return JavaConverters.asScalaIterableConverter(linkedList).asScala();\n }",
"private static OriginatorType mapOriginator(Originator originator) {\n if (originator == null) {\n return null;\n }\n OriginatorType origType = new OriginatorType();\n origType.setProcessId(originator.getProcessId());\n origType.setIp(originator.getIp());\n origType.setHostname(originator.getHostname());\n origType.setCustomId(originator.getCustomId());\n origType.setPrincipal(originator.getPrincipal());\n return origType;\n }",
"public static DMatrixRMaj extractRow(DMatrixRMaj a , int row , DMatrixRMaj out ) {\n if( out == null)\n out = new DMatrixRMaj(1,a.numCols);\n else if( !MatrixFeatures_DDRM.isVector(out) || out.getNumElements() != a.numCols )\n throw new MatrixDimensionException(\"Output must be a vector of length \"+a.numCols);\n\n System.arraycopy(a.data,a.getIndex(row,0),out.data,0,a.numCols);\n\n return out;\n }"
] |
These exact lines are shared between three different tools, so
they have been moved here to reduce code duplication.
@return The parsed command-line, with options removed. | [
"public String[] init(String[] argv, int min, int max,\n Collection<CommandLineParser.Option> options)\n throws IOException, SAXException {\n // parse command line\n parser = new CommandLineParser();\n parser.setMinimumArguments(min);\n parser.setMaximumArguments(max);\n parser.registerOption(new CommandLineParser.BooleanOption(\"reindex\", 'I'));\n if (options != null)\n for (CommandLineParser.Option option : options)\n parser.registerOption(option);\n\n try {\n argv = parser.parse(argv);\n } catch (CommandLineParser.CommandLineParserException e) {\n System.err.println(\"ERROR: \" + e.getMessage());\n usage();\n System.exit(1);\n }\n\n // do we need to reindex?\n boolean reindex = parser.getOptionState(\"reindex\");\n\n // load configuration\n config = ConfigLoader.load(argv[0]);\n database = config.getDatabase(reindex); // overwrite iff reindex\n if (database.isInMemory())\n reindex = true; // no other way to do it in this case\n\n // reindex, if requested\n if (reindex)\n reindex(config, database);\n\n return argv;\n }"
] | [
"public static double getHaltonNumberForGivenBase(long index, int base) {\n\t\tindex += 1;\n\n\t\tdouble x = 0.0;\n\t\tdouble factor = 1.0 / base;\n\t\twhile(index > 0) {\n\t\t\tx += (index % base) * factor;\n\t\t\tfactor /= base;\n\t\t\tindex /= base;\n\t\t}\n\n\t\treturn x;\n\t}",
"public Set<String> postProcessingFields() {\n Set<String> fields = new LinkedHashSet<>();\n query.forEach(condition -> fields.addAll(condition.postProcessingFields()));\n sort.forEach(condition -> fields.addAll(condition.postProcessingFields()));\n return fields;\n }",
"synchronized boolean deleteMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, _ID + \" = ? AND \" + USER_ID + \" = ?\", new String[]{messageId,userId});\n return true;\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }",
"synchronized void started() {\n try {\n if(isConnected()) {\n channelHandler.executeRequest(new ServerStartedRequest(), null).getResult().await();\n }\n } catch (Exception e) {\n ServerLogger.AS_ROOT_LOGGER.debugf(e, \"failed to send started notification\");\n }\n }",
"private static void freeTempLOB(ClobWrapper clob, BlobWrapper blob)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif (clob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the CLOB is open, close it\r\n\t\t\t\tif (clob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tclob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this CLOB\r\n\t\t\t\tclob.freeTemporary();\r\n\t\t\t}\r\n\r\n\t\t\tif (blob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the BLOB is open, close it\r\n\t\t\t\tif (blob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tblob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this BLOB\r\n\t\t\t\tblob.freeTemporary();\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n logger.error(\"Error during temporary LOB release\", e);\r\n\t\t}\r\n\t}",
"public String get(final String key) {\n final Collection<Argument> args = map.get(key);\n if (args != null) {\n return args.iterator().hasNext() ? args.iterator().next().getValue() : null;\n }\n return null;\n }",
"private void addDependent(String pathName, String relativeTo) {\n if (relativeTo != null) {\n Set<String> dependents = dependenctRelativePaths.get(relativeTo);\n if (dependents == null) {\n dependents = new HashSet<String>();\n dependenctRelativePaths.put(relativeTo, dependents);\n }\n dependents.add(pathName);\n }\n }",
"public boolean runOnMainThreadNext(Runnable r) {\n assert handler != null;\n\n if (!sanityCheck(\"runOnMainThreadNext \" + r)) {\n return false;\n }\n return handler.post(r);\n }",
"public String getPromotionDetailsJsonModel() throws IOException {\n final PromotionEvaluationReport sampleReport = new PromotionEvaluationReport();\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNPROMOTED_MSG, \"com.acme.secure-smh:core-relay:1.2.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.DO_NOT_USE_MSG, \"com.google.guava:guava:20.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.MISSING_LICENSE_MSG, \"org.apache.maven.wagon:wagon-webdav-jackrabbit:2.12\"), MINOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNACCEPTABLE_LICENSE_MSG,\n \"aopaliance:aopaliance:1.0 licensed as Attribution-ShareAlike 2.5 Generic, \" +\n \"org.polyjdbc:polyjdbc0.7.1 licensed as Creative Commons Attribution-ShareAlike 3.0 Unported License\"),\n MINOR);\n\n sampleReport.addMessage(PromotionReportTranslator.SNAPSHOT_VERSION_MSG, Tag.CRITICAL);\n return JsonUtils.serialize(sampleReport);\n }"
] |
Returns a compact representation of all of the subtasks of a task.
@param task The task to get the subtasks of.
@return Request object | [
"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 Optional<Project> findProject(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return getProject(name);\n }",
"public static String getDays(RecurringTask task)\n {\n StringBuilder sb = new StringBuilder();\n for (Day day : Day.values())\n {\n sb.append(task.getWeeklyDay(day) ? \"1\" : \"0\");\n }\n return sb.toString();\n }",
"public static CoordinateReferenceSystem parseProjection(\n final String projection, final Boolean longitudeFirst) {\n try {\n if (longitudeFirst == null) {\n return CRS.decode(projection);\n } else {\n return CRS.decode(projection, longitudeFirst);\n }\n } catch (NoSuchAuthorityCodeException e) {\n throw new RuntimeException(projection + \" was not recognized as a crs code\", e);\n } catch (FactoryException e) {\n throw new RuntimeException(\"Error occurred while parsing: \" + projection, e);\n }\n }",
"public boolean projectExists(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return listProjects().stream()\n .map(p -> p.getMetadata().getName())\n .anyMatch(Predicate.isEqual(name));\n }",
"public static Map<Integer, Integer>\n getMapOfContiguousPartitionRunLengths(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId);\n Map<Integer, Integer> runLengthToCount = Maps.newHashMap();\n\n if(idToRunLength.isEmpty()) {\n return runLengthToCount;\n }\n\n for(int runLength: idToRunLength.values()) {\n if(!runLengthToCount.containsKey(runLength)) {\n runLengthToCount.put(runLength, 0);\n }\n runLengthToCount.put(runLength, runLengthToCount.get(runLength) + 1);\n }\n\n return runLengthToCount;\n }",
"private void tryToSetParsedValue(String value) throws Exception {\n\n JSONObject json = JSONParser.parseStrict(value).isObject();\n JSONValue val = json.get(JsonKey.START);\n setStart(readOptionalDate(val));\n val = json.get(JsonKey.END);\n setEnd(readOptionalDate(val));\n setWholeDay(readOptionalBoolean(json.get(JsonKey.WHOLE_DAY)));\n JSONObject patternJson = json.get(JsonKey.PATTERN).isObject();\n readPattern(patternJson);\n setExceptions(readDates(json.get(JsonKey.EXCEPTIONS)));\n setSeriesEndDate(readOptionalDate(json.get(JsonKey.SERIES_ENDDATE)));\n setOccurrences(readOptionalInt(json.get(JsonKey.SERIES_OCCURRENCES)));\n setDerivedEndType();\n setCurrentTillEnd(readOptionalBoolean(json.get(JsonKey.CURRENT_TILL_END)));\n setParentSeriesId(readOptionalUUID(json.get(JsonKey.PARENT_SERIES)));\n\n }",
"public SpinJsonDataFormatException unableToParseValue(String expectedType, JsonNodeType type) {\n return new SpinJsonDataFormatException(exceptionMessage(\"002\", \"Expected '{}', got '{}'\", expectedType, type.toString()));\n }",
"public void update(int width, int height, int sampleCount) {\n if (capturing) {\n throw new IllegalStateException(\"Cannot update backing texture while capturing\");\n }\n\n this.width = width;\n this.height = height;\n\n if (sampleCount == 0)\n captureTexture = new GVRRenderTexture(getGVRContext(), width, height);\n else\n captureTexture = new GVRRenderTexture(getGVRContext(), width, height, sampleCount);\n\n setRenderTexture(captureTexture);\n readBackBuffer = new int[width * height];\n }",
"private static String qualifiedName(Options opt, String r) {\n\tif (opt.hideGenerics)\n\t r = removeTemplate(r);\n\t// Fast path - nothing to do:\n\tif (opt.showQualified && (opt.showQualifiedGenerics || r.indexOf('<') < 0))\n\t return r;\n\tStringBuilder buf = new StringBuilder(r.length());\n\tqualifiedNameInner(opt, r, buf, 0, !opt.showQualified);\n\treturn buf.toString();\n }"
] |
Add a channel to the animation to animate the named bone.
@param boneName name of bone to animate.
@param channel The animation channel. | [
"public void addChannel(String boneName, GVRAnimationChannel channel)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n mBoneChannels[boneId] = channel;\n mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);\n Log.d(\"BONE\", \"Adding animation channel %d %s \", boneId, boneName);\n }\n }"
] | [
"public BoxFolder.Info restoreFolder(String folderID) {\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"\", \"\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }",
"protected void processOutlineCodeField(Integer entityID, Row row)\n {\n processField(row, \"OC_FIELD_ID\", entityID, row.getString(\"OC_NAME\"));\n }",
"public void addGroupBy(String[] fieldNames)\r\n {\r\n for (int i = 0; i < fieldNames.length; i++)\r\n {\r\n addGroupBy(fieldNames[i]);\r\n }\r\n }",
"public void addAll(OptionsContainerBuilder container) {\n\t\tfor ( Entry<Class<? extends Option<?, ?>>, ValueContainerBuilder<?, ?>> entry : container.optionValues.entrySet() ) {\n\t\t\taddAll( entry.getKey(), entry.getValue().build() );\n\t\t}\n\t}",
"public Date getFinishTime(Date date)\n {\n Date result = null;\n\n if (date != null)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n if (ranges == null)\n {\n result = getParentFile().getProjectProperties().getDefaultEndTime();\n result = DateHelper.getCanonicalTime(result);\n }\n else\n {\n Date rangeStart = result = ranges.getRange(0).getStart();\n Date rangeFinish = ranges.getRange(ranges.getRangeCount() - 1).getEnd();\n Date startDay = DateHelper.getDayStartDate(rangeStart);\n Date finishDay = DateHelper.getDayStartDate(rangeFinish);\n\n result = DateHelper.getCanonicalTime(rangeFinish);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay != null && finishDay != null && startDay.getTime() != finishDay.getTime())\n {\n result = DateHelper.addDays(result, 1);\n }\n }\n }\n return result;\n }",
"public static base_response unset(nitro_service client, nslimitselector resource, String[] args) throws Exception{\n\t\tnslimitselector unsetresource = new nslimitselector();\n\t\tunsetresource.selectorname = resource.selectorname;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static String getAt(String text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n String answer = text.substring(info.from, info.to);\n if (info.reverse) {\n answer = reverse(answer);\n }\n return answer;\n }",
"public static spilloverpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy_lbvserver_binding obj = new spilloverpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy_lbvserver_binding response[] = (spilloverpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"void successfulBoot() throws ConfigurationPersistenceException {\n synchronized (this) {\n if (doneBootup.get()) {\n return;\n }\n final File copySource;\n if (!interactionPolicy.isReadOnly()) {\n copySource = mainFile;\n } else {\n\n if ( FilePersistenceUtils.isParentFolderWritable(mainFile) ) {\n copySource = new File(mainFile.getParentFile(), mainFile.getName() + \".boot\");\n } else{\n copySource = new File(configurationDir, mainFile.getName() + \".boot\");\n }\n\n FilePersistenceUtils.deleteFile(copySource);\n }\n\n try {\n if (!bootFile.equals(copySource)) {\n FilePersistenceUtils.copyFile(bootFile, copySource);\n }\n\n createHistoryDirectory();\n\n final File historyBase = new File(historyRoot, mainFile.getName());\n lastFile = addSuffixToFile(historyBase, LAST);\n final File boot = addSuffixToFile(historyBase, BOOT);\n final File initial = addSuffixToFile(historyBase, INITIAL);\n\n if (!initial.exists()) {\n FilePersistenceUtils.copyFile(copySource, initial);\n }\n\n FilePersistenceUtils.copyFile(copySource, lastFile);\n FilePersistenceUtils.copyFile(copySource, boot);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToCreateConfigurationBackup(e, bootFile);\n } finally {\n if (interactionPolicy.isReadOnly()) {\n //Delete the temporary file\n try {\n FilePersistenceUtils.deleteFile(copySource);\n } catch (Exception ignore) {\n }\n }\n }\n doneBootup.set(true);\n }\n }"
] |
Returns the corresponding ModuleLoadService service name for the given module.
@param identifier The module identifier
@return The service name of the ModuleLoadService service | [
"public static ServiceName moduleServiceName(ModuleIdentifier identifier) {\n if (!identifier.getName().startsWith(MODULE_PREFIX)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }"
] | [
"public final void begin() {\n this.file = this.getAppender().getIoFile();\n if (this.file == null) {\n this.getAppender().getErrorHandler()\n .error(\"Scavenger not started: missing log file name\");\n return;\n }\n if (this.getProperties().getScavengeInterval() > -1) {\n final Thread thread = new Thread(this, \"Log4J File Scavenger\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }",
"public Rate getRate(int field) throws MPXJException\n {\n Rate result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n String rate = m_fields[field];\n int index = rate.indexOf('/');\n double amount;\n TimeUnit units;\n\n if (index == -1)\n {\n amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();\n units = TimeUnit.HOURS;\n }\n else\n {\n amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();\n units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);\n }\n\n result = new Rate(amount, units);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse rate\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }",
"private IndexedContainer createContainerForBundleWithoutDescriptor() throws IOException, CmsException {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n Set<Object> keySet = m_keyset.getKeySet();\n for (Object key : keySet) {\n\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object translation = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n }\n\n return container;\n }",
"private void processCalendarHours(byte[] data, ProjectCalendar defaultCalendar, ProjectCalendar cal, boolean isBaseCalendar)\n {\n // Dump out the calendar related data and fields.\n //MPPUtility.dataDump(data, true, false, false, false, true, false, true);\n\n int offset;\n ProjectCalendarHours hours;\n int periodIndex;\n int index;\n int defaultFlag;\n int periodCount;\n Date start;\n long duration;\n Day day;\n List<DateRange> dateRanges = new ArrayList<DateRange>(5);\n\n for (index = 0; index < 7; index++)\n {\n offset = getCalendarHoursOffset() + (60 * index);\n defaultFlag = data == null ? 1 : MPPUtility.getShort(data, offset);\n day = Day.getInstance(index + 1);\n\n if (defaultFlag == 1)\n {\n if (isBaseCalendar)\n {\n if (defaultCalendar == null)\n {\n cal.setWorkingDay(day, DEFAULT_WORKING_WEEK[index]);\n if (cal.isWorkingDay(day))\n {\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n else\n {\n boolean workingDay = defaultCalendar.isWorkingDay(day);\n cal.setWorkingDay(day, workingDay);\n if (workingDay)\n {\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n for (DateRange range : defaultCalendar.getHours(day))\n {\n hours.addRange(range);\n }\n }\n }\n }\n else\n {\n cal.setWorkingDay(day, DayType.DEFAULT);\n }\n }\n else\n {\n dateRanges.clear();\n\n periodIndex = 0;\n periodCount = MPPUtility.getShort(data, offset + 2);\n while (periodIndex < periodCount)\n {\n int startOffset = offset + 8 + (periodIndex * 2);\n start = MPPUtility.getTime(data, startOffset);\n int durationOffset = offset + 20 + (periodIndex * 4);\n duration = MPPUtility.getDuration(data, durationOffset);\n Date end = new Date(start.getTime() + duration);\n dateRanges.add(new DateRange(start, end));\n ++periodIndex;\n }\n\n if (dateRanges.isEmpty())\n {\n cal.setWorkingDay(day, false);\n }\n else\n {\n cal.setWorkingDay(day, true);\n hours = cal.addCalendarHours(Day.getInstance(index + 1));\n\n for (DateRange range : dateRanges)\n {\n hours.addRange(range);\n }\n }\n }\n }\n }",
"public static void configureProtocolHandler() {\n final String pkgs = System.getProperty(\"java.protocol.handler.pkgs\");\n String newValue = \"org.mapfish.print.url\";\n if (pkgs != null && !pkgs.contains(newValue)) {\n newValue = newValue + \"|\" + pkgs;\n } else if (pkgs != null) {\n newValue = pkgs;\n }\n System.setProperty(\"java.protocol.handler.pkgs\", newValue);\n }",
"private void checkQueryCustomizer(CollectionDescriptorDef collDef, 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 queryCustomizerName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_QUERY_CUSTOMIZER);\r\n\r\n if (queryCustomizerName == 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(queryCustomizerName, QUERY_CUSTOMIZER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+queryCustomizerName+\" specified as query-customizer of collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not implement the interface \"+QUERY_CUSTOMIZER_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+ex.getMessage()+\" specified as query-customizer of collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" was not found on the classpath\");\r\n }\r\n }",
"public static final Date parseExtendedAttributeDate(String value)\n {\n Date result = null;\n\n if (value != null)\n {\n try\n {\n result = DATE_FORMAT.get().parse(value);\n }\n\n catch (ParseException ex)\n {\n // ignore exceptions\n }\n }\n\n return (result);\n }",
"private void processSchedulingProjectProperties() throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"projprop where proj_id=? and prop_name='scheduling'\", m_projectID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n Record record = Record.getRecord(row.getString(\"prop_value\"));\n if (record != null)\n {\n String[] keyValues = record.getValue().split(\"\\\\|\");\n for (int i = 0; i < keyValues.length - 1; ++i)\n {\n if (\"sched_calendar_on_relationship_lag\".equals(keyValues[i]))\n {\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", keyValues[i + 1]);\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n break;\n }\n }\n }\n }\n }",
"public void downloadRange(OutputStream output, long rangeStart, long rangeEnd, ProgressListener listener) {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n if (rangeEnd > 0) {\n request.addHeader(\"Range\", String.format(\"bytes=%s-%s\", Long.toString(rangeStart),\n Long.toString(rangeEnd)));\n } else {\n request.addHeader(\"Range\", String.format(\"bytes=%s-\", Long.toString(rangeStart)));\n }\n\n BoxAPIResponse response = request.send();\n InputStream input = response.getBody(listener);\n\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = input.read(buffer);\n while (n != -1) {\n output.write(buffer, 0, n);\n n = input.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n } finally {\n response.disconnect();\n }\n }"
] |
Load entries from the storage.
Overriding methods should first delegate to super before adding their own entries. | [
"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 }"
] | [
"public static base_response unset(nitro_service client, filterhtmlinjectionparameter resource, String[] args) throws Exception{\n\t\tfilterhtmlinjectionparameter unsetresource = new filterhtmlinjectionparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static CharSequence getAt(CharSequence text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n CharSequence sequence = text.subSequence(info.from, info.to);\n return info.reverse ? reverse(sequence) : sequence;\n }",
"private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1));\n mpxjResource.setName(gpResource.getName());\n mpxjResource.setEmailAddress(gpResource.getContacts());\n mpxjResource.setText(1, gpResource.getPhone());\n mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction()));\n\n net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate();\n if (gpRate != null)\n {\n mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS));\n }\n readResourceCustomFields(gpResource, mpxjResource);\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }",
"public static base_responses enable(nitro_service client, String id[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (id != null && id.length > 0) {\n\t\t\tInterface enableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tenableresources[i] = new Interface();\n\t\t\t\tenableresources[i].id = id[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}",
"private void generateCopyingPart(WrappingHint.Builder builder) {\n ImmutableCollection<CopyMethod> copyMethods = ImmutableMultimap.<String, CopyMethod>builder()\n .putAll(configuration.FIELD_TYPE_TO_COPY_METHODS)\n .putAll(userDefinedCopyMethods)\n .build()\n .get(typeAssignedToField);\n \n if (copyMethods.isEmpty()) {\n throw new WrappingHintGenerationException();\n }\n \n CopyMethod firstSuitable = copyMethods.iterator().next();\n builder.setCopyMethodOwnerName(firstSuitable.owner.toString())\n .setCopyMethodName(firstSuitable.name);\n \n if (firstSuitable.isGeneric && typeSignature != null) {\n CollectionField withRemovedWildcards = CollectionField.from(typeAssignedToField, typeSignature)\n .transformGenericTree(GenericType::withoutWildcard);\n builder.setCopyTypeParameterName(formatTypeParameter(withRemovedWildcards.asSimpleString()));\n }\n }",
"private boolean moreDates(Calendar calendar, List<Date> dates)\n {\n boolean result;\n if (m_finishDate == null)\n {\n int occurrences = NumberHelper.getInt(m_occurrences);\n if (occurrences < 1)\n {\n occurrences = 1;\n }\n result = dates.size() < occurrences;\n }\n else\n {\n result = calendar.getTimeInMillis() <= m_finishDate.getTime();\n }\n return result;\n }",
"public ApiResponse<TagsEnvelope> getTagCategoriesWithHttpInfo() throws ApiException {\n com.squareup.okhttp.Call call = getTagCategoriesValidateBeforeCall(null, null);\n Type localVarReturnType = new TypeToken<TagsEnvelope>(){}.getType();\n return apiClient.execute(call, localVarReturnType);\n }",
"public boolean updateSelectedItemsList(int dataIndex, boolean select) {\n boolean done = false;\n boolean contains = isSelected(dataIndex);\n if (select) {\n if (!contains) {\n if (!mMultiSelectionSupported) {\n clearSelection(false);\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"updateSelectedItemsList add index = %d\", dataIndex);\n mSelectedItemsList.add(dataIndex);\n done = true;\n }\n } else {\n if (contains) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"updateSelectedItemsList remove index = %d\", dataIndex);\n mSelectedItemsList.remove(dataIndex);\n done = true;\n }\n }\n return done;\n }",
"protected synchronized void streamingSlopPut(ByteArray key,\n Versioned<byte[]> value,\n String storeName,\n int failedNodeId) throws IOException {\n\n Slop slop = new Slop(storeName,\n Slop.Operation.PUT,\n key,\n value.getValue(),\n null,\n failedNodeId,\n new Date());\n\n ByteArray slopKey = slop.makeKey();\n Versioned<byte[]> slopValue = new Versioned<byte[]>(slopSerializer.toBytes(slop),\n value.getVersion());\n\n Node failedNode = adminClient.getAdminClientCluster().getNodeById(failedNodeId);\n HandoffToAnyStrategy slopRoutingStrategy = new HandoffToAnyStrategy(adminClient.getAdminClientCluster(),\n true,\n failedNode.getZoneId());\n // node Id which will receive the slop\n int slopDestination = slopRoutingStrategy.routeHint(failedNode).get(0).getId();\n\n VAdminProto.PartitionEntry partitionEntry = VAdminProto.PartitionEntry.newBuilder()\n .setKey(ProtoUtils.encodeBytes(slopKey))\n .setVersioned(ProtoUtils.encodeVersioned(slopValue))\n .build();\n\n VAdminProto.UpdatePartitionEntriesRequest.Builder updateRequest = VAdminProto.UpdatePartitionEntriesRequest.newBuilder()\n .setStore(SLOP_STORE)\n .setPartitionEntry(partitionEntry);\n\n DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair<String, Integer>(SLOP_STORE,\n slopDestination));\n\n if(nodeIdStoreInitialized.get(new Pair<String, Integer>(SLOP_STORE, slopDestination))) {\n ProtoUtils.writeMessage(outputStream, updateRequest.build());\n } else {\n ProtoUtils.writeMessage(outputStream,\n VAdminProto.VoldemortAdminRequest.newBuilder()\n .setType(VAdminProto.AdminRequestType.UPDATE_PARTITION_ENTRIES)\n .setUpdatePartitionEntries(updateRequest)\n .build());\n outputStream.flush();\n nodeIdStoreInitialized.put(new Pair<String, Integer>(SLOP_STORE, slopDestination), true);\n\n }\n\n throttler.maybeThrottle(1);\n\n }"
] |
Sets the width and height of the canvas the text is drawn to.
@param width
width of the new canvas.
@param height
hegiht of the new canvas. | [
"public void setCanvasWidthHeight(int width, int height) {\n hudWidth = width;\n hudHeight = height;\n HUD = Bitmap.createBitmap(width, height, Config.ARGB_8888);\n canvas = new Canvas(HUD);\n texture = null;\n }"
] | [
"public static String getTypeValue(Class<? extends WindupFrame> clazz)\n {\n TypeValue typeValueAnnotation = clazz.getAnnotation(TypeValue.class);\n if (typeValueAnnotation == null)\n throw new IllegalArgumentException(\"Class \" + clazz.getCanonicalName() + \" lacks a @TypeValue annotation\");\n\n return typeValueAnnotation.value();\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 static String changeFirstLetterToLowerCase(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toLowerCase(a);\n return new String(letras);\n }",
"public boolean absolute(int row) throws PersistenceBrokerException\r\n {\r\n boolean retval;\r\n if (supportsAdvancedJDBCCursorControl())\r\n {\r\n retval = absoluteAdvanced(row);\r\n }\r\n else\r\n {\r\n retval = absoluteBasic(row);\r\n }\r\n return retval;\r\n }",
"public PartialCollection<BoxItem.Info> searchRange(long offset, long limit, final BoxSearchParameters bsp) {\n QueryStringBuilder builder = bsp.getQueryParameters()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n URL url = SEARCH_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> results = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray jsonArray = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : jsonArray) {\n JsonObject jsonObject = value.asObject();\n BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);\n if (parsedItemInfo != null) {\n results.add(parsedItemInfo);\n }\n }\n return results;\n }",
"private static void addFormatInfoEval(byte[] eval, int size, EccLevel ecc_level, int pattern) {\n\n int format = pattern;\n int seq;\n int i;\n\n switch(ecc_level) {\n case L: format += 0x08; break;\n case Q: format += 0x18; break;\n case H: format += 0x10; break;\n }\n\n seq = QR_ANNEX_C[format];\n\n for (i = 0; i < 6; i++) {\n eval[(i * size) + 8] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 8; i++) {\n eval[(8 * size) + (size - i - 1)] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 6; i++) {\n eval[(8 * size) + (5 - i)] = (byte) ((((seq >> (i + 9)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n for (i = 0; i < 7; i++) {\n eval[(((size - 7) + i) * size) + 8] = (byte) ((((seq >> (i + 8)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }\n\n eval[(7 * size) + 8] = (byte) ((((seq >> 6) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n eval[(8 * size) + 8] = (byte) ((((seq >> 7) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n eval[(8 * size) + 7] = (byte) ((((seq >> 8) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);\n }",
"public void logAttributeWarning(PathAddress address, ModelNode operation, String message, String attribute) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attribute));\n }",
"private void loadAllRemainingLocalizations() throws CmsException, UnsupportedEncodingException, IOException {\n\n if (!m_alreadyLoadedAllLocalizations) {\n // is only necessary for property bundles\n if (m_bundleType.equals(BundleType.PROPERTY)) {\n for (Locale l : m_locales) {\n if (null == m_localizations.get(l)) {\n CmsResource resource = m_bundleFiles.get(l);\n if (resource != null) {\n CmsFile file = m_cms.readFile(resource);\n m_bundleFiles.put(l, file);\n SortedProperties props = new SortedProperties();\n props.load(\n new InputStreamReader(\n new ByteArrayInputStream(file.getContents()),\n CmsFileUtil.getEncoding(m_cms, file)));\n m_localizations.put(l, props);\n }\n }\n }\n }\n if (m_bundleType.equals(BundleType.XML)) {\n for (Locale l : m_locales) {\n if (null == m_localizations.get(l)) {\n loadLocalizationFromXmlBundle(l);\n }\n }\n }\n m_alreadyLoadedAllLocalizations = true;\n }\n\n }",
"public static final BigDecimal printDurationInDecimalThousandthsOfMinutes(Duration duration)\n {\n BigDecimal result = null;\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigDecimal.valueOf(printDurationFractionsOfMinutes(duration, 1000));\n }\n return result;\n }"
] |
Use this API to fetch nspbr6 resource of given name . | [
"public static nspbr6 get(nitro_service service, String name) throws Exception{\n\t\tnspbr6 obj = new nspbr6();\n\t\tobj.set_name(name);\n\t\tnspbr6 response = (nspbr6) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"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}",
"public boolean isFunctionName( String s ) {\n if( input1.containsKey(s))\n return true;\n if( inputN.containsKey(s))\n return true;\n\n return false;\n }",
"public static List<BoxTermsOfService.Info> getAllTermsOfServices(final BoxAPIConnection api,\n BoxTermsOfService.TermsOfServiceType\n termsOfServiceType) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (termsOfServiceType != null) {\n builder.appendParam(\"tos_type\", termsOfServiceType.toString());\n }\n\n URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTermsOfService.Info> termsOfServices = new ArrayList<BoxTermsOfService.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject termsOfServiceJSON = value.asObject();\n BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get(\"id\").asString());\n BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON);\n termsOfServices.add(info);\n }\n\n return termsOfServices;\n }",
"private String[] getColumnNames(ResultSetMetaData rsmd) throws Exception {\n ArrayList<String> names = new ArrayList<String>();\n\n // Get result set meta data\n int numColumns = rsmd.getColumnCount();\n\n // Get the column names; column indices start from 1\n for (int i = 1; i < numColumns + 1; i++) {\n String columnName = rsmd.getColumnName(i);\n\n names.add(columnName);\n }\n\n return names.toArray(new String[0]);\n }",
"public RandomVariable[] getValues(double[] times) {\n\t\tRandomVariable[] values = new RandomVariable[times.length];\n\n\t\tfor(int i=0; i<times.length; i++) {\n\t\t\tvalues[i] = getValue(null, times[i]);\n\t\t}\n\n\t\treturn values;\n\t}",
"private void readRelationships(Document cdp)\n {\n for (Link link : cdp.getLinks().getLink())\n {\n readRelationship(link);\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}",
"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 }",
"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 }"
] |
Read task data from a PEP file. | [
"private void readTasks()\n {\n Integer rootID = Integer.valueOf(1);\n readWBS(m_projectFile, rootID);\n readTasks(rootID);\n m_projectFile.getTasks().synchronizeTaskIDToHierarchy();\n }"
] | [
"public void setModificationState(ModificationState newModificationState)\r\n {\r\n if(newModificationState != modificationState)\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"object state transition for object \" + this.oid + \" (\"\r\n + modificationState + \" --> \" + newModificationState + \")\");\r\n// try{throw new Exception();}catch(Exception e)\r\n// {\r\n// e.printStackTrace();\r\n// }\r\n }\r\n modificationState = newModificationState;\r\n }\r\n }",
"public UUID getUUID(FastTrackField type)\n {\n String value = getString(type);\n UUID result = null;\n if (value != null && !value.isEmpty() && value.length() >= 36)\n {\n if (value.startsWith(\"{\"))\n {\n value = value.substring(1, value.length() - 1);\n }\n if (value.length() > 16)\n {\n value = value.substring(0, 36);\n }\n result = UUID.fromString(value);\n }\n return result;\n }",
"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 }",
"private int getTaskCode(String field) throws MPXJException\n {\n Integer result = m_taskNumbers.get(field.trim());\n\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_TASK_FIELD_NAME + \" \" + field);\n }\n\n return (result.intValue());\n }",
"public static Date getDateFromLong(long date)\n {\n TimeZone tz = TimeZone.getDefault();\n return (new Date(date - tz.getRawOffset()));\n }",
"private Integer highlanderMode(JobDef jd, DbConn cnx)\n {\n if (!jd.isHighlander())\n {\n return null;\n }\n\n try\n {\n Integer existing = cnx.runSelectSingle(\"ji_select_existing_highlander\", Integer.class, jd.getId());\n return existing;\n }\n catch (NoResultException ex)\n {\n // Just continue, this means no existing waiting JI in queue.\n }\n\n // Now we need to actually synchronize through the database to avoid double posting\n // TODO: use a dedicated table, not the JobDef one. Will avoid locking the configuration.\n ResultSet rs = cnx.runSelect(true, \"jd_select_by_id\", jd.getId());\n\n // Now we have a lock, just retry - some other client may have created a job instance recently.\n try\n {\n Integer existing = cnx.runSelectSingle(\"ji_select_existing_highlander\", Integer.class, jd.getId());\n rs.close();\n cnx.commit(); // Do not keep the lock!\n return existing;\n }\n catch (NoResultException ex)\n {\n // Just continue, this means no existing waiting JI in queue. We keep the lock!\n }\n catch (SQLException e)\n {\n // Who cares.\n jqmlogger.warn(\"Issue when closing a ResultSet. Transaction or session leak is possible.\", e);\n }\n\n jqmlogger.trace(\"Highlander mode analysis is done: nor existing JO, must create a new one. Lock is hold.\");\n return null;\n }",
"private void readTasks(Document cdp)\n {\n //\n // Sort the projects into the correct order\n //\n List<Project> projects = new ArrayList<Project>(cdp.getProjects().getProject());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(projects, new Comparator<Project>()\n {\n @Override public int compare(Project o1, Project o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n for (Project project : cdp.getProjects().getProject())\n {\n readProject(project);\n }\n }",
"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 void postModule(final Module module, 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.moduleResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, module);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST module\";\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 }"
] |
Obtains a local date in Symmetry010 calendar system from the
proleptic-year, month-of-year and day-of-month fields.
@param prolepticYear the proleptic-year
@param month the month-of-year
@param dayOfMonth the day-of-month
@return the Symmetry010 local date, not null
@throws DateTimeException if unable to create the date | [
"@Override\n public Symmetry010Date date(int prolepticYear, int month, int dayOfMonth) {\n return Symmetry010Date.of(prolepticYear, month, dayOfMonth);\n }"
] | [
"public ReferrerList getPhotoReferrers(Date date, String domain, String photoId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTO_REFERRERS, domain, \"photo_id\", photoId, date, perPage, page);\n }",
"public ClassNode parent(String name) {\n this.parent = infoBase.node(name);\n this.parent.addChild(this);\n for (ClassNode intf : parent.interfaces.values()) {\n addInterface(intf);\n }\n return this;\n }",
"public static base_response update(nitro_service client, vridparam resource) throws Exception {\n\t\tvridparam updateresource = new vridparam();\n\t\tupdateresource.sendtomaster = resource.sendtomaster;\n\t\treturn updateresource.update_resource(client);\n\t}",
"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 }",
"public static void acceptsFormat(OptionParser parser) {\n parser.accepts(OPT_FORMAT, \"format of key or entry, could be hex, json or binary\")\n .withRequiredArg()\n .describedAs(\"hex | json | binary\")\n .ofType(String.class);\n }",
"public void recordServerGroupResult(final String serverGroup, final boolean failed) {\n\n synchronized (this) {\n if (groups.contains(serverGroup)) {\n responseCount++;\n if (failed) {\n this.failed = true;\n }\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recorded group result for '%s': failed = %s\",\n serverGroup, failed);\n notifyAll();\n }\n else {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServerGroup(serverGroup);\n }\n }\n }",
"public void setFarClippingDistance(float far) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setFarClippingDistance(far);\n centerCamera.setFarClippingDistance(far);\n ((GVRCameraClippingDistanceInterface)rightCamera).setFarClippingDistance(far);\n }\n }",
"public void end() {\n if (TransitionConfig.isPrintDebug()) {\n getTransitionStateHolder().end();\n getTransitionStateHolder().print();\n }\n\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).end();\n }\n }",
"public void cullHistory(final int profileId, final String clientUUID, final int limit) throws Exception {\n\n //Allow only 1 delete thread to run\n if (threadActive) {\n return;\n }\n\n threadActive = true;\n //Create a thread so proxy will continue to work during long delete\n Thread t1 = new Thread(new Runnable() {\n @Override\n public void run() {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n sqlQuery += \";\";\n\n Statement query = sqlConnection.createStatement();\n ResultSet results = query.executeQuery(sqlQuery);\n if (results.next()) {\n if (results.getInt(\"COUNT(\" + Constants.GENERIC_ID + \")\") < (limit + 10000)) {\n return;\n }\n }\n //Find the last item in the table\n statement = sqlConnection.prepareStatement(\"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" ORDER BY \" + Constants.GENERIC_ID + \" ASC LIMIT 1\");\n\n ResultSet resultSet = statement.executeQuery();\n if (resultSet.next()) {\n int currentSpot = resultSet.getInt(Constants.GENERIC_ID) + 100;\n int finalDelete = currentSpot + 10000;\n //Delete 100 items at a time until 10000 are deleted\n //Do this so table is unlocked frequently to allow other proxy items to access it\n while (currentSpot < finalDelete) {\n PreparedStatement deleteStatement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" AND \" + Constants.GENERIC_ID + \" < \" + currentSpot);\n deleteStatement.executeUpdate();\n currentSpot += 100;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n threadActive = false;\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }\n });\n\n t1.start();\n }"
] |
Returns the "msgCount" belief
@return int - the count | [
"private int getBeliefCount() {\n Integer count = (Integer)introspector.getBeliefBase(ListenerMockAgent.this).get(Definitions.RECEIVED_MESSAGE_COUNT);\n if (count == null) count = 0; // Just in case, not really sure if this is necessary.\n return count;\n }"
] | [
"public static <T> boolean containsAny(Collection<T> collection, Collection<T> toCheck){\r\n for(T c: toCheck){\r\n if(collection.contains(c))\r\n return true;\r\n }\r\n return false;\r\n \r\n }",
"public static SQLService getInstance() throws Exception {\n if (_instance == null) {\n _instance = new SQLService();\n _instance.startServer();\n\n // default pool size is 20\n // can be overriden by env variable\n int dbPool = 20;\n if (Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE) != null) {\n dbPool = Integer.valueOf(Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE));\n }\n\n // initialize connection pool\n PoolProperties p = new PoolProperties();\n String connectString = \"jdbc:h2:tcp://\" + _instance.databaseHost + \":\" + String.valueOf(_instance.port) + \"/\" +\n _instance.databaseName + \"/proxydb;MULTI_THREADED=true;AUTO_RECONNECT=TRUE;AUTOCOMMIT=ON\";\n p.setUrl(connectString);\n p.setDriverClassName(\"org.h2.Driver\");\n p.setUsername(\"sa\");\n p.setJmxEnabled(true);\n p.setTestWhileIdle(false);\n p.setTestOnBorrow(true);\n p.setValidationQuery(\"SELECT 1\");\n p.setTestOnReturn(false);\n p.setValidationInterval(5000);\n p.setTimeBetweenEvictionRunsMillis(30000);\n p.setMaxActive(dbPool);\n p.setInitialSize(5);\n p.setMaxWait(30000);\n p.setRemoveAbandonedTimeout(60);\n p.setMinEvictableIdleTimeMillis(30000);\n p.setMinIdle(10);\n p.setLogAbandoned(true);\n p.setRemoveAbandoned(true);\n _instance.datasource = new DataSource();\n _instance.datasource.setPoolProperties(p);\n }\n return _instance;\n }",
"private static int getTrimmedXStart(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int xStart = width;\n\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j < xStart) {\n xStart = j;\n break;\n }\n }\n }\n\n return xStart;\n }",
"public synchronized void resumeControlPoint(final String entryPoint) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getEntryPoint().equals(entryPoint)) {\n ep.resume();\n }\n }\n }",
"public static base_responses expire(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject expireresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texpireresources[i] = new cacheobject();\n\t\t\t\texpireresources[i].locator = resources[i].locator;\n\t\t\t\texpireresources[i].url = resources[i].url;\n\t\t\t\texpireresources[i].host = resources[i].host;\n\t\t\t\texpireresources[i].port = resources[i].port;\n\t\t\t\texpireresources[i].groupname = resources[i].groupname;\n\t\t\t\texpireresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, expireresources,\"expire\");\n\t\t}\n\t\treturn result;\n\t}",
"public PeriodicEvent runAfter(Runnable task, float delay) {\n validateDelay(delay);\n return new Event(task, delay);\n }",
"public BUILDER setAttributeGroup(String attributeGroup) {\n assert attributeGroup == null || attributeGroup.length() > 0;\n //noinspection deprecation\n this.attributeGroup = attributeGroup;\n return (BUILDER) this;\n }",
"@Pure\n\tpublic static <P1> Procedure0 curry(final Procedure1<? super P1> procedure, final P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure0() {\n\t\t\t@Override\n\t\t\tpublic void apply() {\n\t\t\t\tprocedure.apply(argument);\n\t\t\t}\n\t\t};\n\t}",
"public void generateMapFile(File jarFile, String mapFileName, boolean mapClassMethods) throws XMLStreamException, IOException, ClassNotFoundException, IntrospectionException\n {\n m_responseList = new LinkedList<String>();\n writeMapFile(mapFileName, jarFile, mapClassMethods);\n }"
] |
Update the currency format.
@param properties project properties
@param decimalSeparator decimal separator
@param thousandsSeparator thousands separator | [
"private void updateCurrencyFormats(ProjectProperties properties, char decimalSeparator, char thousandsSeparator)\n {\n String prefix = \"\";\n String suffix = \"\";\n String currencySymbol = quoteFormatCharacters(properties.getCurrencySymbol());\n\n switch (properties.getSymbolPosition())\n {\n case AFTER:\n {\n suffix = currencySymbol;\n break;\n }\n\n case BEFORE:\n {\n prefix = currencySymbol;\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n suffix = \" \" + currencySymbol;\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n prefix = currencySymbol + \" \";\n break;\n }\n }\n\n StringBuilder pattern = new StringBuilder(prefix);\n pattern.append(\"#0\");\n\n int digits = properties.getCurrencyDigits().intValue();\n if (digits > 0)\n {\n pattern.append('.');\n for (int i = 0; i < digits; i++)\n {\n pattern.append(\"0\");\n }\n }\n\n pattern.append(suffix);\n\n String primaryPattern = pattern.toString();\n\n String[] alternativePatterns = new String[7];\n alternativePatterns[0] = primaryPattern + \";(\" + primaryPattern + \")\";\n pattern.insert(prefix.length(), \"#,#\");\n String secondaryPattern = pattern.toString();\n alternativePatterns[1] = secondaryPattern;\n alternativePatterns[2] = secondaryPattern + \";(\" + secondaryPattern + \")\";\n\n pattern.setLength(0);\n pattern.append(\"#0\");\n\n if (digits > 0)\n {\n pattern.append('.');\n for (int i = 0; i < digits; i++)\n {\n pattern.append(\"0\");\n }\n }\n\n String noSymbolPrimaryPattern = pattern.toString();\n alternativePatterns[3] = noSymbolPrimaryPattern;\n alternativePatterns[4] = noSymbolPrimaryPattern + \";(\" + noSymbolPrimaryPattern + \")\";\n pattern.insert(0, \"#,#\");\n String noSymbolSecondaryPattern = pattern.toString();\n alternativePatterns[5] = noSymbolSecondaryPattern;\n alternativePatterns[6] = noSymbolSecondaryPattern + \";(\" + noSymbolSecondaryPattern + \")\";\n\n m_currencyFormat.applyPattern(primaryPattern, alternativePatterns, decimalSeparator, thousandsSeparator);\n }"
] | [
"private void getMonthlyRelativeDates(Calendar calendar, int frequency, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int dayNumber = NumberHelper.getInt(m_dayNumber);\n\n while (moreDates(calendar, dates))\n {\n if (dayNumber > 4)\n {\n setCalendarToLastRelativeDay(calendar);\n }\n else\n {\n setCalendarToOrdinalRelativeDay(calendar, dayNumber);\n }\n\n if (calendar.getTimeInMillis() > startDate)\n {\n dates.add(calendar.getTime());\n if (!moreDates(calendar, dates))\n {\n break;\n }\n }\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }",
"public static base_responses update(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction updateresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].parameters = resources[i].parameters;\n\t\t\t\tupdateresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\tupdateresources[i].quiettime = resources[i].quiettime;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static double computeTauAndDivide(final int j, final int numRows ,\n final double[] u , final double max) {\n double tau = 0;\n// double div_max = 1.0/max;\n// if( Double.isInfinite(div_max)) {\n for( int i = j; i < numRows; i++ ) {\n double d = u[i] /= max;\n tau += d*d;\n }\n// } else {\n// for( int i = j; i < numRows; i++ ) {\n// double d = u[i] *= div_max;\n// tau += d*d;\n// }\n// }\n tau = Math.sqrt(tau);\n\n if( u[j] < 0 )\n tau = -tau;\n\n return tau;\n }",
"@SuppressWarnings(\"unchecked\")\n public <T extends GVRComponent> ArrayList<T> getAllComponents(long type) {\n ArrayList<T> list = new ArrayList<T>();\n GVRComponent component = getComponent(type);\n if (component != null)\n list.add((T) component);\n for (GVRSceneObject child : mChildren) {\n ArrayList<T> temp = child.getAllComponents(type);\n list.addAll(temp);\n }\n return list;\n }",
"private void persistEnabledVersion(long version) throws PersistenceFailureException {\n File disabledMarker = getDisabledMarkerFile(version);\n if (disabledMarker.exists()) {\n if (!disabledMarker.delete()) {\n throw new PersistenceFailureException(\"Failed to create the disabled marker at path: \" +\n disabledMarker.getAbsolutePath() + \"\\nThe store/version \" +\n \"will remain enabled only until the next restart.\");\n }\n }\n }",
"public static MatchInfo fromUri(final URI uri, final HttpMethod method) {\n int newPort = uri.getPort();\n if (newPort < 0) {\n try {\n newPort = uri.toURL().getDefaultPort();\n } catch (MalformedURLException | IllegalArgumentException e) {\n newPort = ANY_PORT;\n }\n }\n\n return new MatchInfo(uri.getScheme(), uri.getHost(), newPort, uri.getPath(), uri.getQuery(),\n uri.getFragment(), ANY_REALM, method);\n }",
"@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 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 }",
"void unbind(String key)\r\n {\r\n NamedEntry entry = new NamedEntry(key, null, false);\r\n localUnbind(key);\r\n addForDeletion(entry);\r\n }"
] |
Expands the directories from the given list and and returns a list of subfiles.
Files from the original list are kept as is. | [
"private static List<Path> expandMultiAppInputDirs(List<Path> input)\n {\n List<Path> expanded = new LinkedList<>();\n for (Path path : input)\n {\n if (Files.isRegularFile(path))\n {\n expanded.add(path);\n continue;\n }\n if (!Files.isDirectory(path))\n {\n String pathString = (path == null) ? \"\" : path.toString(); \n log.warning(\"Neither a file or directory found in input: \" + pathString);\n continue;\n }\n\n try\n {\n try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path))\n {\n for (Path subpath : directoryStream)\n {\n\n if (isJavaArchive(subpath))\n {\n expanded.add(subpath);\n }\n }\n }\n }\n catch (IOException e)\n {\n throw new WindupException(\"Failed to read directory contents of: \" + path);\n }\n }\n return expanded;\n }"
] | [
"public Metadata updateMetadata(Metadata metadata) {\n String scope;\n if (metadata.getScope().equals(Metadata.GLOBAL_METADATA_SCOPE)) {\n scope = Metadata.GLOBAL_METADATA_SCOPE;\n } else {\n scope = Metadata.ENTERPRISE_METADATA_SCOPE;\n }\n\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(),\n scope, metadata.getTemplateName());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n request.addHeader(\"Content-Type\", \"application/json-patch+json\");\n request.setBody(metadata.getPatch());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }",
"public static <T> List<T> asImmutable(List<? extends T> self) {\n return Collections.unmodifiableList(self);\n }",
"@VisibleForTesting\n protected static int getLabelDistance(final ScaleBarRenderSettings settings) {\n if (settings.getParams().labelDistance != null) {\n return settings.getParams().labelDistance;\n } else {\n if (settings.getParams().getOrientation().isHorizontal()) {\n return settings.getMaxSize().width / 40;\n } else {\n return settings.getMaxSize().height / 40;\n }\n }\n }",
"protected Violation createViolationForImport(SourceCode sourceCode, String className, String alias, String violationMessage) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, className, alias);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(violationMessage);\n return violation;\n }",
"public static BoxUser getCurrentUser(BoxAPIConnection api) {\n URL url = GET_ME_URL.build(api.getBaseURL());\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new BoxUser(api, jsonObject.get(\"id\").asString());\n }",
"private synchronized void setInitializationMethod(Method newMethod)\r\n {\r\n if (newMethod != null)\r\n {\r\n // make sure it's a no argument method\r\n if (newMethod.getParameterTypes().length > 0)\r\n {\r\n throw new MetadataException(\r\n \"Initialization methods must be zero argument methods: \"\r\n + newMethod.getClass().getName()\r\n + \".\"\r\n + newMethod.getName());\r\n }\r\n\r\n // make it accessible if it's not already\r\n if (!newMethod.isAccessible())\r\n {\r\n newMethod.setAccessible(true);\r\n }\r\n }\r\n this.initializationMethod = newMethod;\r\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 }",
"private void processPredecessor(Task task, MapRow row)\n {\n Task predecessor = m_taskMap.get(row.getUUID(\"PREDECESSOR_UUID\"));\n if (predecessor != null)\n {\n task.addPredecessor(predecessor, row.getRelationType(\"RELATION_TYPE\"), row.getDuration(\"LAG\"));\n }\n }",
"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 }"
] |
Get a collection of recent photos.
This method does not require authentication.
@see com.flickr4java.flickr.photos.Extras
@param extras
Set of extra-fields
@param perPage
The number of photos per page
@param page
The page offset
@return A collection of Photo objects
@throws FlickrException | [
"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 clearWorkingDateCache()\n {\n m_workingDateCache.clear();\n m_startTimeCache.clear();\n m_getDateLastResult = null;\n for (ProjectCalendar calendar : m_derivedCalendars)\n {\n calendar.clearWorkingDateCache();\n }\n }",
"private static String preparePlaceHolders(int length) {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < length; ) {\n builder.append(\"?\");\n if (++i < length) {\n builder.append(\",\");\n }\n }\n return builder.toString();\n }",
"public Map<Integer, String> getSignatures() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<Integer, String>(signatures));\n }",
"public boolean validation() throws ParallelTaskInvalidException {\n\n ParallelTask task = new ParallelTask();\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n task = new ParallelTask(requestProtocol, concurrency, httpMeta,\n targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null, responseContext,\n replacementVarMapNodeSpecific,\n replacementVarMap, requestReplacementType, config);\n boolean valid = false;\n\n try {\n valid = task.validateWithFillDefault();\n } catch (ParallelTaskInvalidException e) {\n logger.info(\"task is invalid \" + e);\n }\n\n return valid;\n\n }",
"public static int nullity(SingularValueDecomposition_F64 svd , double threshold ) {\n int ret = 0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n int numCol = svd.numCols();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] <= threshold) ret++;\n }\n return ret + numCol-N;\n }",
"public 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 }",
"public static DMatrixRMaj stripReal(ZMatrixD1 input , DMatrixRMaj output ) {\n if( output == null ) {\n output = new DMatrixRMaj(input.numRows,input.numCols);\n } else if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n final int length = input.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i/2] = input.data[i];\n }\n return output;\n }",
"private Map<String, String> mergeItem(\r\n String item,\r\n Map<String, String> localeValues,\r\n Map<String, String> resultLocaleValues) {\r\n\r\n if (resultLocaleValues.get(item) != null) {\r\n if (localeValues.get(item) != null) {\r\n localeValues.put(item, localeValues.get(item) + \" \" + resultLocaleValues.get(item));\r\n } else {\r\n localeValues.put(item, resultLocaleValues.get(item));\r\n }\r\n }\r\n\r\n return localeValues;\r\n }",
"private void swapROStores(List<String> swappedStoreNames, boolean useSwappedStoreNames) {\n\n try {\n for(StoreDefinition storeDef: metadataStore.getStoreDefList()) {\n\n // Only pick up the RO stores\n if(storeDef.getType().compareTo(ReadOnlyStorageConfiguration.TYPE_NAME) == 0) {\n\n if(useSwappedStoreNames && !swappedStoreNames.contains(storeDef.getName())) {\n continue;\n }\n\n ReadOnlyStorageEngine engine = (ReadOnlyStorageEngine) storeRepository.getStorageEngine(storeDef.getName());\n\n if(engine == null) {\n throw new VoldemortException(\"Could not find storage engine for \"\n + storeDef.getName() + \" to swap \");\n }\n\n logger.info(\"Swapping RO store \" + storeDef.getName());\n\n // Time to swap this store - Could have used admin client,\n // but why incur the overhead?\n engine.swapFiles(engine.getCurrentDirPath());\n\n // Add to list of stores already swapped\n if(!useSwappedStoreNames)\n swappedStoreNames.add(storeDef.getName());\n }\n }\n } catch(Exception e) {\n logger.error(\"Error while swapping RO store\");\n throw new VoldemortException(e);\n }\n }"
] |
Reads a stringtemplate group from a stream.
This will always return a group (empty if necessary), even if reading it from the stream fails.
@param stream the stream to read from
@return the string template group | [
"public static StringTemplateGroup readStringTemplateGroup(InputStream stream) {\n\n try {\n return new StringTemplateGroup(\n new InputStreamReader(stream, \"UTF-8\"),\n DefaultTemplateLexer.class,\n new StringTemplateErrorListener() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void error(String arg0, Throwable arg1) {\n\n LOG.error(arg0 + \": \" + arg1.getMessage(), arg1);\n }\n\n @SuppressWarnings(\"synthetic-access\")\n public void warning(String arg0) {\n\n LOG.warn(arg0);\n\n }\n });\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return new StringTemplateGroup(\"dummy\");\n }\n }"
] | [
"public static final UUID getUUID(InputStream is) throws IOException\n {\n byte[] data = new byte[16];\n is.read(data);\n\n long long1 = 0;\n long1 |= ((long) (data[3] & 0xFF)) << 56;\n long1 |= ((long) (data[2] & 0xFF)) << 48;\n long1 |= ((long) (data[1] & 0xFF)) << 40;\n long1 |= ((long) (data[0] & 0xFF)) << 32;\n long1 |= ((long) (data[5] & 0xFF)) << 24;\n long1 |= ((long) (data[4] & 0xFF)) << 16;\n long1 |= ((long) (data[7] & 0xFF)) << 8;\n long1 |= ((long) (data[6] & 0xFF)) << 0;\n\n long long2 = 0;\n long2 |= ((long) (data[8] & 0xFF)) << 56;\n long2 |= ((long) (data[9] & 0xFF)) << 48;\n long2 |= ((long) (data[10] & 0xFF)) << 40;\n long2 |= ((long) (data[11] & 0xFF)) << 32;\n long2 |= ((long) (data[12] & 0xFF)) << 24;\n long2 |= ((long) (data[13] & 0xFF)) << 16;\n long2 |= ((long) (data[14] & 0xFF)) << 8;\n long2 |= ((long) (data[15] & 0xFF)) << 0;\n\n return new UUID(long1, long2);\n }",
"public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\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 List<ClassReference> analyze(WildcardImportResolver importResolver, Set<String> libraryPaths, Set<String> sourcePaths,\n Path sourceFile)\n {\n ASTParser parser = ASTParser.newParser(AST.JLS11);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]), sourcePaths.toArray(new String[sourcePaths.size()]), null, true);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n parser.setCompilerOptions(options);\n String fileName = sourceFile.getFileName().toString();\n parser.setUnitName(fileName);\n try\n {\n parser.setSource(FileUtils.readFileToString(sourceFile.toFile()).toCharArray());\n }\n catch (IOException e)\n {\n throw new ASTException(\"Failed to get source for file: \" + sourceFile.toString() + \" due to: \" + e.getMessage(), e);\n }\n parser.setKind(ASTParser.K_COMPILATION_UNIT);\n CompilationUnit cu = (CompilationUnit) parser.createAST(null);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, cu, sourceFile.toString());\n cu.accept(visitor);\n return visitor.getJavaClassReferences();\n }",
"public static BoxCollaborationWhitelist.Info create(final BoxAPIConnection api, String domain,\n WhitelistDirection direction) {\n\n URL url = COLLABORATION_WHITELIST_ENTRIES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"domain\", domain)\n .add(\"direction\", direction.toString());\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxCollaborationWhitelist domainWhitelist =\n new BoxCollaborationWhitelist(api, responseJSON.get(\"id\").asString());\n\n return domainWhitelist.new Info(responseJSON);\n }",
"public long removeAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.srem(getKey(), members);\n }\n });\n }",
"public List<Response> bulk(List<?> objects, boolean allOrNothing) {\n assertNotEmpty(objects, \"objects\");\n InputStream responseStream = null;\n HttpConnection connection;\n try {\n final JsonObject jsonObject = new JsonObject();\n if(allOrNothing) {\n jsonObject.addProperty(\"all_or_nothing\", true);\n }\n final URI uri = new DatabaseURIHelper(dbUri).bulkDocsUri();\n jsonObject.add(\"docs\", getGson().toJsonTree(objects));\n connection = Http.POST(uri, \"application/json\");\n if (jsonObject.toString().length() != 0) {\n connection.setRequestBody(jsonObject.toString());\n }\n couchDbClient.execute(connection);\n responseStream = connection.responseAsInputStream();\n List<Response> bulkResponses = getResponseList(responseStream, getGson(),\n DeserializationTypes.LC_RESPONSES);\n for(Response response : bulkResponses) {\n response.setStatusCode(connection.getConnection().getResponseCode());\n }\n return bulkResponses;\n }\n catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response input stream.\", e);\n } finally {\n close(responseStream);\n }\n }",
"private synchronized void closeIdleClients() {\n List<Client> candidates = new LinkedList<Client>(openClients.values());\n logger.debug(\"Scanning for idle clients; \" + candidates.size() + \" candidates.\");\n for (Client client : candidates) {\n if ((useCounts.get(client) < 1) &&\n ((timestamps.get(client) + idleLimit.get() * 1000) <= System.currentTimeMillis())) {\n logger.debug(\"Idle time reached for unused client {}\", client);\n closeClient(client);\n }\n }\n }",
"protected final void setDerivedEndType() {\n\n m_endType = getPatternType().equals(PatternType.NONE) || getPatternType().equals(PatternType.INDIVIDUAL)\n ? EndType.SINGLE\n : null != getSeriesEndDate() ? EndType.DATE : EndType.TIMES;\n }"
] |
Sets the specified float attribute to the specified value.
@param name name of the attribute
@param value value of the attribute
@since 1.9.0 | [
"public void setFloatAttribute(String name, Float value) {\n\t\tensureValue();\n\t\tAttribute attribute = new FloatAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}"
] | [
"static String encodeUriComponent(String source, String encoding, Type type) throws UnsupportedEncodingException {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\tAssert.hasLength(encoding, \"Encoding must not be empty\");\n\t\tbyte[] bytes = encodeBytes(source.getBytes(encoding), type);\n\t\treturn new String(bytes, \"US-ASCII\");\n\t}",
"public void handleConnectOriginal(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException {\n URI uri = request.getURI();\n\n try {\n LOG.fine(\"CONNECT: \" + uri);\n InetAddrPort addrPort;\n // When logging, we'll attempt to send messages to hosts that don't exist\n if (uri.toString().endsWith(\".selenium.doesnotexist:443\")) {\n // so we have to do set the host to be localhost (you can't new up an IAP with a non-existent hostname)\n addrPort = new InetAddrPort(443);\n } else {\n addrPort = new InetAddrPort(uri.toString());\n }\n\n if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) {\n sendForbid(request, response, uri);\n } else {\n HttpConnection http_connection = request.getHttpConnection();\n http_connection.forceClose();\n\n HttpServer server = http_connection.getHttpServer();\n\n SslListener listener = getSslRelayOrCreateNewOdo(uri, addrPort, server);\n\n int port = listener.getPort();\n\n // Get the timeout\n int timeoutMs = 30000;\n Object maybesocket = http_connection.getConnection();\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n timeoutMs = s.getSoTimeout();\n }\n\n // Create the tunnel\n HttpTunnel tunnel = newHttpTunnel(request, response, InetAddress.getByName(null), port, timeoutMs);\n\n if (tunnel != null) {\n // TODO - need to setup semi-busy loop for IE.\n if (_tunnelTimeoutMs > 0) {\n tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs);\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n s.setSoTimeout(_tunnelTimeoutMs);\n }\n }\n tunnel.setTimeoutMs(timeoutMs);\n\n customizeConnection(pathInContext, pathParams, request, tunnel.getSocket());\n request.getHttpConnection().setHttpTunnel(tunnel);\n response.setStatus(HttpResponse.__200_OK);\n response.setContentLength(0);\n }\n request.setHandled(true);\n }\n } catch (Exception e) {\n LOG.fine(\"error during handleConnect\", e);\n response.sendError(HttpResponse.__500_Internal_Server_Error, e.toString());\n }\n }",
"private static void bodyWithConcatenation(\n SourceBuilder code,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename) {\n code.add(\" return \\\"%s{\", typename);\n String prefix = \"\";\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n code.add(\"%s%s=\\\" + %s + \\\"\",\n prefix, property.getName(), (Excerpt) generator::addToStringValue);\n prefix = \", \";\n }\n code.add(\"}\\\";%n\");\n }",
"@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }",
"public void addComparator(Comparator<T> comparator, boolean ascending) {\n\t\tthis.comparators.add(new InvertibleComparator<T>(comparator, ascending));\n\t}",
"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 }",
"protected TypeReference<?> getBeanPropertyType(Class<?> clazz,\r\n\t\t\tString propertyName, TypeReference<?> originalType) {\r\n\t\tTypeReference<?> propertyDestinationType = null;\r\n\t\tif (beanDestinationPropertyTypeProvider != null) {\r\n\t\t\tpropertyDestinationType = beanDestinationPropertyTypeProvider\r\n\t\t\t\t\t.getPropertyType(clazz, propertyName, originalType);\r\n\t\t}\r\n\t\tif (propertyDestinationType == null) {\r\n\t\t\tpropertyDestinationType = originalType;\r\n\t\t}\r\n\t\treturn propertyDestinationType;\r\n\t}",
"public static void addJarToClasspath(ClassLoader loader, URL url) throws IOException,\n IllegalAccessException, IllegalArgumentException, InvocationTargetException,\n NoSuchMethodException, SecurityException {\n URLClassLoader sysloader = (URLClassLoader) loader;\n Class<?> sysclass = URLClassLoader.class;\n\n Method method =\n sysclass.getDeclaredMethod(MyClasspathUtils.ADD_URL_METHOD, new Class[] {URL.class});\n method.setAccessible(true);\n method.invoke(sysloader, new Object[] {url});\n\n }",
"public ItemRequest<Task> update(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"PUT\");\n }"
] |
Add a new PropertyChangeListener to this node for a specific property.
This functionality has
been borrowed from the java.beans package, though this class has
nothing to do with a bean | [
"public void addPropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.addPropertyChangeListener(propertyName, listener);\r\n }"
] | [
"private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {\n\t\tif (to.equals(from))\n\t\t\treturn true;\n\n\t\tif (from instanceof TypeVariable) {\n\t\t\treturn to.equals(typeMap.get(((TypeVariable<?>) from).getName()));\n\t\t}\n\n\t\treturn false;\n\t}",
"private void extractFile(InputStream stream, File dir) throws IOException\n {\n byte[] header = new byte[8];\n byte[] fileName = new byte[13];\n byte[] dataSize = new byte[4];\n\n stream.read(header);\n stream.read(fileName);\n stream.read(dataSize);\n\n int dataSizeValue = getInt(dataSize, 0);\n String fileNameValue = getString(fileName, 0);\n File file = new File(dir, fileNameValue);\n\n if (dataSizeValue == 0)\n {\n FileHelper.createNewFile(file);\n }\n else\n {\n OutputStream os = new FileOutputStream(file);\n FixedLengthInputStream inputStream = new FixedLengthInputStream(stream, dataSizeValue);\n Blast blast = new Blast();\n blast.blast(inputStream, os);\n os.close();\n }\n }",
"public ResponseOnSingeRequest onComplete(Response response) {\n\n cancelCancellable();\n try {\n \n Map<String, List<String>> responseHeaders = null;\n if (responseHeaderMeta != null) {\n responseHeaders = new LinkedHashMap<String, List<String>>();\n if (responseHeaderMeta.isGetAll()) {\n for (Map.Entry<String, List<String>> header : response\n .getHeaders()) {\n responseHeaders.put(header.getKey().toLowerCase(Locale.ROOT), header.getValue());\n }\n } else {\n for (String key : responseHeaderMeta.getKeys()) {\n if (response.getHeaders().containsKey(key)) {\n responseHeaders.put(key.toLowerCase(Locale.ROOT),\n response.getHeaders().get(key));\n }\n }\n }\n }\n\n int statusCodeInt = response.getStatusCode();\n String statusCode = statusCodeInt + \" \" + response.getStatusText();\n String charset = ParallecGlobalConfig.httpResponseBodyCharsetUsesResponseContentType &&\n response.getContentType()!=null ? \n AsyncHttpProviderUtils.parseCharset(response.getContentType())\n : ParallecGlobalConfig.httpResponseBodyDefaultCharset;\n if(charset == null){\n getLogger().error(\"charset is not provided from response content type. Use default\");\n charset = ParallecGlobalConfig.httpResponseBodyDefaultCharset; \n }\n reply(response.getResponseBody(charset), false, null, null, statusCode,\n statusCodeInt, responseHeaders);\n } catch (IOException e) {\n getLogger().error(\"fail response.getResponseBody \" + e);\n }\n\n return null;\n }",
"private File decompileType(final DecompilerSettings settings, final WindupMetadataSystem metadataSystem, final String typeName) throws IOException\n {\n log.fine(\"Decompiling \" + typeName);\n\n final TypeReference type;\n\n // Hack to get around classes whose descriptors clash with primitive types.\n if (typeName.length() == 1)\n {\n final MetadataParser parser = new MetadataParser(IMetadataResolver.EMPTY);\n final TypeReference reference = parser.parseTypeDescriptor(typeName);\n type = metadataSystem.resolve(reference);\n }\n else\n type = metadataSystem.lookupType(typeName);\n\n if (type == null)\n {\n log.severe(\"Failed to load class: \" + typeName);\n return null;\n }\n\n final TypeDefinition resolvedType = type.resolve();\n if (resolvedType == null)\n {\n log.severe(\"Failed to resolve type: \" + typeName);\n return null;\n }\n\n boolean nested = resolvedType.isNested() || resolvedType.isAnonymous() || resolvedType.isSynthetic();\n if (!this.procyonConf.isIncludeNested() && nested)\n return null;\n\n settings.setJavaFormattingOptions(new JavaFormattingOptions());\n\n final FileOutputWriter writer = createFileWriter(resolvedType, settings);\n final PlainTextOutput output;\n\n output = new PlainTextOutput(writer);\n output.setUnicodeOutputEnabled(settings.isUnicodeOutputEnabled());\n if (settings.getLanguage() instanceof BytecodeLanguage)\n output.setIndentToken(\" \");\n\n DecompilationOptions options = new DecompilationOptions();\n options.setSettings(settings); // I'm missing why these two classes are split.\n\n // --------- DECOMPILE ---------\n final TypeDecompilationResults results = settings.getLanguage().decompileType(resolvedType, output, options);\n\n writer.flush();\n writer.close();\n\n // If we're writing to a file and we were asked to include line numbers in any way,\n // then reformat the file to include that line number information.\n final List<LineNumberPosition> lineNumberPositions = results.getLineNumberPositions();\n\n if (!this.procyonConf.getLineNumberOptions().isEmpty())\n {\n\n final LineNumberFormatter lineFormatter = new LineNumberFormatter(writer.getFile(), lineNumberPositions,\n this.procyonConf.getLineNumberOptions());\n\n lineFormatter.reformatFile();\n }\n return writer.getFile();\n }",
"private boolean relevant(File currentLogFile, GregorianCalendar lastRelevantDate) {\n\t\tString fileName=currentLogFile.getName();\n\t\tPattern p = Pattern.compile(APPENER_DATE_DEFAULT_PATTERN);\n\t\tMatcher m = p.matcher(fileName);\n\t\tif(m.find()){\n\t\t\tint year=Integer.parseInt(m.group(1));\n\t\t\tint month=Integer.parseInt(m.group(2));\n\t\t\tint dayOfMonth=Integer.parseInt(m.group(3));\n\t\t\tGregorianCalendar fileDate=new GregorianCalendar(year, month, dayOfMonth);\n\t\t\tfileDate.add(Calendar.MONTH,-1); //Because of Calendar save the month such that January is 0\n\t\t\treturn fileDate.compareTo(lastRelevantDate)>0;\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t}\n\t}",
"public void addImportedPackages(Set<String> importedPackages) {\n\t\taddImportedPackages(importedPackages.toArray(new String[importedPackages.size()]));\n\t}",
"public CredentialsConfig getResolvingCredentialsConfig() {\n if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) {\n return getResolverCredentialsConfig();\n }\n if (deployerCredentialsConfig != null) {\n return getDeployerCredentialsConfig();\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }",
"public static void applyWsdlExtensions(Bus bus) {\n\n ExtensionRegistry registry = bus.getExtension(WSDLManager.class).getExtensionRegistry();\n\n try {\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Definition.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.PLType.class);\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Binding.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.CallbackExtension.class);\n\n } catch (JAXBException e) {\n throw new RuntimeException(\"Failed to add WSDL JAXB extensions\", e);\n }\n }",
"private Collection<? extends ResourceRoot> handleClassPathItems(final DeploymentUnit deploymentUnit) {\n final Set<ResourceRoot> additionalRoots = new HashSet<ResourceRoot>();\n final ArrayDeque<ResourceRoot> toProcess = new ArrayDeque<ResourceRoot>();\n final List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);\n toProcess.addAll(resourceRoots);\n final Set<ResourceRoot> processed = new HashSet<ResourceRoot>(resourceRoots);\n\n while (!toProcess.isEmpty()) {\n final ResourceRoot root = toProcess.pop();\n final List<ResourceRoot> classPathRoots = root.getAttachmentList(Attachments.CLASS_PATH_RESOURCE_ROOTS);\n for(ResourceRoot cpRoot : classPathRoots) {\n if(!processed.contains(cpRoot)) {\n additionalRoots.add(cpRoot);\n toProcess.add(cpRoot);\n processed.add(cpRoot);\n }\n }\n }\n return additionalRoots;\n }"
] |
Returns the constructor of the indirection handler class.
@return The constructor for indirection handlers | [
"private synchronized Constructor getIndirectionHandlerConstructor()\r\n {\r\n if(_indirectionHandlerConstructor == null)\r\n {\r\n Class[] paramType = {PBKey.class, Identity.class};\r\n\r\n try\r\n {\r\n _indirectionHandlerConstructor = getIndirectionHandlerClass().getConstructor(paramType);\r\n }\r\n catch(NoSuchMethodException ex)\r\n {\r\n throw new MetadataException(\"The class \"\r\n + _indirectionHandlerClass.getName()\r\n + \" specified for IndirectionHandlerClass\"\r\n + \" is required to have a public constructor with signature (\"\r\n + PBKey.class.getName()\r\n + \", \"\r\n + Identity.class.getName()\r\n + \").\");\r\n }\r\n }\r\n return _indirectionHandlerConstructor;\r\n }"
] | [
"String getQuery(String key)\n {\n String res = this.adapter.getSqlText(key);\n if (res == null)\n {\n throw new DatabaseException(\"Query \" + key + \" does not exist\");\n }\n return res;\n }",
"public synchronized static SQLiteDatabase getConnection(Context context) {\n\t\tif (database == null) {\n\t\t\t// Construct the single helper and open the unique(!) db connection for the app\n\t\t\tdatabase = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase();\n\t\t}\n\t\treturn database;\n\t}",
"public ProjectCalendar addDefaultBaseCalendar()\n {\n ProjectCalendar calendar = add();\n\n calendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n calendar.setWorkingDay(Day.SUNDAY, false);\n calendar.setWorkingDay(Day.MONDAY, true);\n calendar.setWorkingDay(Day.TUESDAY, true);\n calendar.setWorkingDay(Day.WEDNESDAY, true);\n calendar.setWorkingDay(Day.THURSDAY, true);\n calendar.setWorkingDay(Day.FRIDAY, true);\n calendar.setWorkingDay(Day.SATURDAY, false);\n\n calendar.addDefaultCalendarHours();\n\n return (calendar);\n }",
"protected void mergeVerticalBlocks() {\n for(int i = 0; i < rectangles.size() - 1; i++) {\n for(int j = i + 1; j < rectangles.size(); j++) {\n Rectangle2D.Double firstRect = rectangles.get(i);\n Rectangle2D.Double secondRect = rectangles.get(j);\n if (roughlyEqual(firstRect.x, secondRect.x) && roughlyEqual(firstRect.width, secondRect.width)) {\n if (roughlyEqual(firstRect.y + firstRect.height, secondRect.y)) {\n firstRect.height += secondRect.height;\n rectangles.set(i, firstRect);\n rectangles.remove(j);\n }\n }\n }\n }\n }",
"public long removeAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.srem(getKey(), members);\n }\n });\n }",
"@Override\n public void begin(String namespace, String name, Attributes attributes) throws Exception {\n\n // not now: 6.0.0\n // digester.setLogger(CmsLog.getLog(digester.getClass()));\n\n // Push an array to capture the parameter values if necessary\n if (m_paramCount > 0) {\n Object[] parameters = new Object[m_paramCount];\n for (int i = 0; i < parameters.length; i++) {\n parameters[i] = null;\n }\n getDigester().pushParams(parameters);\n }\n }",
"private void onRead0() {\n assert inWire.startUse();\n\n ensureCapacity();\n\n try {\n\n while (!inWire.bytes().isEmpty()) {\n\n try (DocumentContext dc = inWire.readingDocument()) {\n if (!dc.isPresent())\n return;\n\n try {\n if (YamlLogging.showServerReads())\n logYaml(dc);\n onRead(dc, outWire);\n onWrite(outWire);\n } catch (Exception e) {\n Jvm.warn().on(getClass(), \"inWire=\" + inWire.getClass() + \",yaml=\" + Wires.fromSizePrefixedBlobs(dc), e);\n }\n }\n }\n\n } finally {\n assert inWire.endUse();\n }\n }",
"public static Duration getVariance(Task task, Date date1, Date date2, TimeUnit format)\n {\n Duration variance = null;\n\n if (date1 != null && date2 != null)\n {\n ProjectCalendar calendar = task.getEffectiveCalendar();\n if (calendar != null)\n {\n variance = calendar.getWork(date1, date2, format);\n }\n }\n\n if (variance == null)\n {\n variance = Duration.getInstance(0, format);\n }\n\n return (variance);\n }",
"public static base_responses add(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice addresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new gslbservice();\n\t\t\t\taddresources[i].servicename = resources[i].servicename;\n\t\t\t\taddresources[i].cnameentry = resources[i].cnameentry;\n\t\t\t\taddresources[i].ip = resources[i].ip;\n\t\t\t\taddresources[i].servername = resources[i].servername;\n\t\t\t\taddresources[i].servicetype = resources[i].servicetype;\n\t\t\t\taddresources[i].port = resources[i].port;\n\t\t\t\taddresources[i].publicip = resources[i].publicip;\n\t\t\t\taddresources[i].publicport = resources[i].publicport;\n\t\t\t\taddresources[i].maxclient = resources[i].maxclient;\n\t\t\t\taddresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\taddresources[i].sitename = resources[i].sitename;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].cip = resources[i].cip;\n\t\t\t\taddresources[i].cipheader = resources[i].cipheader;\n\t\t\t\taddresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\taddresources[i].cookietimeout = resources[i].cookietimeout;\n\t\t\t\taddresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\taddresources[i].clttimeout = resources[i].clttimeout;\n\t\t\t\taddresources[i].svrtimeout = resources[i].svrtimeout;\n\t\t\t\taddresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\taddresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\taddresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\taddresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\taddresources[i].hashid = resources[i].hashid;\n\t\t\t\taddresources[i].comment = resources[i].comment;\n\t\t\t\taddresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Must be called with pathEntries lock taken | [
"private void addDependent(String pathName, String relativeTo) {\n if (relativeTo != null) {\n Set<String> dependents = dependenctRelativePaths.get(relativeTo);\n if (dependents == null) {\n dependents = new HashSet<String>();\n dependenctRelativePaths.put(relativeTo, dependents);\n }\n dependents.add(pathName);\n }\n }"
] | [
"public static dnsview[] get(nitro_service service) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tdnsview[] response = (dnsview[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Credentials toGrgit() {\n if (username != null && password != null) {\n return new Credentials(username, password);\n } else {\n return null;\n }\n }",
"public void setGroupName(String name, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" SET \" + Constants.GENERIC_NAME + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public static Cluster cloneCluster(Cluster cluster) {\n // Could add a better .clone() implementation that clones the derived\n // data structures. The constructor invoked by this clone implementation\n // can be slow for large numbers of partitions. Probably faster to copy\n // all the maps and stuff.\n return new Cluster(cluster.getName(),\n new ArrayList<Node>(cluster.getNodes()),\n new ArrayList<Zone>(cluster.getZones()));\n /*-\n * Historic \"clone\" code being kept in case this, for some reason, was the \"right\" way to be doing this.\n ClusterMapper mapper = new ClusterMapper();\n return mapper.readCluster(new StringReader(mapper.writeCluster(cluster)));\n */\n }",
"public Collection<Service> getServices() throws FlickrException {\r\n List<Service> list = new ArrayList<Service>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SERVICES);\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 servicesElement = response.getPayload();\r\n NodeList serviceNodes = servicesElement.getElementsByTagName(\"service\");\r\n for (int i = 0; i < serviceNodes.getLength(); i++) {\r\n Element serviceElement = (Element) serviceNodes.item(i);\r\n Service srv = new Service();\r\n srv.setId(serviceElement.getAttribute(\"id\"));\r\n srv.setName(XMLUtilities.getValue(serviceElement));\r\n list.add(srv);\r\n }\r\n return list;\r\n }",
"public LuaScript endScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }",
"public static Observable<byte[]> downloadFileAsync(String url, Retrofit retrofit) {\n FileService service = retrofit.create(FileService.class);\n Observable<ResponseBody> response = service.download(url);\n return response.map(new Func1<ResponseBody, byte[]>() {\n @Override\n public byte[] call(ResponseBody responseBody) {\n try {\n return responseBody.bytes();\n } catch (IOException e) {\n throw Exceptions.propagate(e);\n }\n }\n });\n }",
"public void useSimpleProxy() {\n String webAppAddress = \"http://localhost:\" + port + \"/services/personservice\";\n PersonService proxy = JAXRSClientFactory.create(webAppAddress, PersonService.class);\n\n new PersonServiceProxyClient(proxy).useService();\n }",
"public double response( double[] sample ) {\n if( sample.length != A.numCols )\n throw new IllegalArgumentException(\"Expected input vector to be in sample space\");\n\n DMatrixRMaj dots = new DMatrixRMaj(numComponents,1);\n DMatrixRMaj s = DMatrixRMaj.wrap(A.numCols,1,sample);\n\n CommonOps_DDRM.mult(V_t,s,dots);\n\n return NormOps_DDRM.normF(dots);\n }"
] |
Returns the list of colliders attached to scene objects that are
visible from the viewpoint of the camera.
<p>
This method is thread safe because it guarantees that only
one thread at a time is picking against particular scene graph,
and it extracts the hit data during within its synchronized block. You
can then examine the return list without worrying about another thread
corrupting your hit data.
The hit location returned is the world position of the scene object center.
@param scene
The {@link GVRScene} with all the objects to be tested.
@return A list of {@link org.gearvrf.GVRPicker.GVRPickedObject}, sorted by distance from the
camera rig. Each {@link org.gearvrf.GVRPicker.GVRPickedObject} contains the scene object
which owns the {@link GVRCollider} along with the hit
location and distance from the camera.
@since 1.6.6 | [
"public static final GVRPickedObject[] pickVisible(GVRScene scene) {\n sFindObjectsLock.lock();\n try {\n final GVRPickedObject[] result = NativePicker.pickVisible(scene.getNative());\n return result;\n } finally {\n sFindObjectsLock.unlock();\n }\n }"
] | [
"public static String encode(String value) throws UnsupportedEncodingException {\n if (isNullOrEmpty(value)) return value;\n return URLEncoder.encode(value, URL_ENCODING);\n }",
"@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = getStringCache().fullString) == null) {\n\t\t\tgetStringCache().fullString = result = toNormalizedString(IPv6StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}",
"public boolean uploadConfigurationAndProfile(String fileName, String odoImport) {\n File file = new File(fileName);\n MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();\n FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);\n multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n multipartEntityBuilder.addPart(\"fileData\", fileBody);\n multipartEntityBuilder.addTextBody(\"odoImport\", odoImport);\n try {\n JSONObject response = new JSONObject(doMultipartPost(BASE_BACKUP_PROFILE + \"/\" + uriEncode(this._profileName) + \"/\" + this._clientId, multipartEntityBuilder));\n if (response.length() == 0) {\n return true;\n } else {\n return false;\n }\n } catch (Exception e) {\n return false;\n }\n }",
"private void logUnexpectedStructure()\n {\n if (m_log != null)\n {\n m_log.println(\"ABORTED COLUMN - unexpected structure: \" + m_currentColumn.getClass().getSimpleName() + \" \" + m_currentColumn.getName());\n }\n }",
"public CRFDatum<List<String>, CRFLabel> makeDatum(List<IN> info, int loc,\r\n edu.stanford.nlp.sequences.FeatureFactory<IN> featureFactory) {\r\n pad.set(AnswerAnnotation.class, flags.backgroundSymbol);\r\n PaddedList<IN> pInfo = new PaddedList<IN>(info, pad);\r\n\r\n ArrayList<List<String>> features = new ArrayList<List<String>>();\r\n\r\n // for (int i = 0; i < windowSize; i++) {\r\n // List featuresC = new ArrayList();\r\n // for (int j = 0; j < FeatureFactory.win[i].length; j++) {\r\n // featuresC.addAll(featureFactory.features(info, loc,\r\n // FeatureFactory.win[i][j]));\r\n // }\r\n // features.add(featuresC);\r\n // }\r\n\r\n Collection<Clique> done = new HashSet<Clique>();\r\n for (int i = 0; i < windowSize; i++) {\r\n List<String> featuresC = new ArrayList<String>();\r\n List<Clique> windowCliques = FeatureFactory.getCliques(i, 0);\r\n windowCliques.removeAll(done);\r\n done.addAll(windowCliques);\r\n for (Clique c : windowCliques) {\r\n featuresC.addAll(featureFactory.getCliqueFeatures(pInfo, loc, c)); //todo useless copy because of typing reasons\r\n }\r\n features.add(featuresC);\r\n }\r\n\r\n int[] labels = new int[windowSize];\r\n\r\n for (int i = 0; i < windowSize; i++) {\r\n String answer = pInfo.get(loc + i - windowSize + 1).get(AnswerAnnotation.class);\r\n labels[i] = classIndex.indexOf(answer);\r\n }\r\n\r\n printFeatureLists(pInfo.get(loc), features);\r\n\r\n CRFDatum<List<String>, CRFLabel> d = new CRFDatum<List<String>, CRFLabel>(features, new CRFLabel(labels));\r\n // System.err.println(d);\r\n return d;\r\n }",
"public void setKnotType(int n, int type) {\n\t\tknotTypes[n] = (byte)((knotTypes[n] & ~COLOR_MASK) | type);\n\t\trebuildGradient();\n\t}",
"public static void addInterceptors(InterceptorProvider provider) {\n PhaseManager phases = BusFactory.getDefaultBus().getExtension(PhaseManager.class);\n for (Phase p : phases.getInPhases()) {\n provider.getInInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getInFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n for (Phase p : phases.getOutPhases()) {\n provider.getOutInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getOutFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n }",
"public Duration getDuration(Date startDate, Date endDate)\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n int days = getDaysInRange(startDate, endDate);\n int duration = 0;\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n\n while (days > 0)\n {\n if (isWorkingDate(cal.getTime(), day) == true)\n {\n ++duration;\n }\n\n --days;\n day = day.getNextDay();\n cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1);\n }\n DateHelper.pushCalendar(cal);\n \n return (Duration.getInstance(duration, TimeUnit.DAYS));\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 }"
] |
Use this API to apply nspbr6. | [
"public static base_response apply(nitro_service client) throws Exception {\n\t\tnspbr6 applyresource = new nspbr6();\n\t\treturn applyresource.perform_operation(client,\"apply\");\n\t}"
] | [
"final protected void putChar(char c) {\n final int clen = _internalBuffer.length;\n if (clen == _bufferPosition) {\n final char[] next = new char[2 * clen + 1];\n\n System.arraycopy(_internalBuffer, 0, next, 0, _bufferPosition);\n _internalBuffer = next;\n }\n\n _internalBuffer[_bufferPosition++] = c;\n }",
"protected void appendWhereClause(ClassDescriptor cld, boolean useLocking, StringBuffer stmt)\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n FieldDescriptor[] fields;\r\n\r\n fields = pkFields;\r\n if(useLocking)\r\n {\r\n FieldDescriptor[] lockingFields = cld.getLockingFields();\r\n if(lockingFields.length > 0)\r\n {\r\n fields = new FieldDescriptor[pkFields.length + lockingFields.length];\r\n System.arraycopy(pkFields, 0, fields, 0, pkFields.length);\r\n System.arraycopy(lockingFields, 0, fields, pkFields.length, lockingFields.length);\r\n }\r\n }\r\n\r\n appendWhereClause(fields, stmt);\r\n }",
"public static AbstractBuild<?, ?> getRootBuild(AbstractBuild<?, ?> currentBuild) {\n AbstractBuild<?, ?> rootBuild = null;\n AbstractBuild<?, ?> parentBuild = getUpstreamBuild(currentBuild);\n while (parentBuild != null) {\n if (isPassIdentifiedDownstream(parentBuild)) {\n rootBuild = parentBuild;\n }\n parentBuild = getUpstreamBuild(parentBuild);\n }\n if (rootBuild == null && isPassIdentifiedDownstream(currentBuild)) {\n return currentBuild;\n }\n return rootBuild;\n }",
"public JaCoCoReportReader readJacocoReport(IExecutionDataVisitor executionDataVisitor, ISessionInfoVisitor sessionInfoStore) {\n if (jacocoExecutionData == null) {\n return this;\n }\n\n JaCoCoExtensions.logger().info(\"Analysing {}\", jacocoExecutionData);\n try (InputStream inputStream = new BufferedInputStream(new FileInputStream(jacocoExecutionData))) {\n if (useCurrentBinaryFormat) {\n ExecutionDataReader reader = new ExecutionDataReader(inputStream);\n reader.setSessionInfoVisitor(sessionInfoStore);\n reader.setExecutionDataVisitor(executionDataVisitor);\n reader.read();\n } else {\n org.jacoco.previous.core.data.ExecutionDataReader reader = new org.jacoco.previous.core.data.ExecutionDataReader(inputStream);\n reader.setSessionInfoVisitor(sessionInfoStore);\n reader.setExecutionDataVisitor(executionDataVisitor);\n reader.read();\n }\n } catch (IOException e) {\n throw new IllegalArgumentException(String.format(\"Unable to read %s\", jacocoExecutionData.getAbsolutePath()), e);\n }\n return this;\n }",
"public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name,\n CreateUserParams params) {\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"login\", login);\n requestJSON.add(\"name\", name);\n\n if (params != null) {\n if (params.getRole() != null) {\n requestJSON.add(\"role\", params.getRole().toJSONValue());\n }\n\n if (params.getStatus() != null) {\n requestJSON.add(\"status\", params.getStatus().toJSONValue());\n }\n\n requestJSON.add(\"language\", params.getLanguage());\n requestJSON.add(\"is_sync_enabled\", params.getIsSyncEnabled());\n requestJSON.add(\"job_title\", params.getJobTitle());\n requestJSON.add(\"phone\", params.getPhone());\n requestJSON.add(\"address\", params.getAddress());\n requestJSON.add(\"space_amount\", params.getSpaceAmount());\n requestJSON.add(\"can_see_managed_users\", params.getCanSeeManagedUsers());\n requestJSON.add(\"timezone\", params.getTimezone());\n requestJSON.add(\"is_exempt_from_device_limits\", params.getIsExemptFromDeviceLimits());\n requestJSON.add(\"is_exempt_from_login_verification\", params.getIsExemptFromLoginVerification());\n requestJSON.add(\"is_platform_access_only\", params.getIsPlatformAccessOnly());\n requestJSON.add(\"external_app_user_id\", params.getExternalAppUserId());\n }\n\n URL url = USERS_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxUser createdUser = new BoxUser(api, responseJSON.get(\"id\").asString());\n return createdUser.new Info(responseJSON);\n }",
"public String getString(String fieldName) {\n\t\treturn hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null;\n\t}",
"public static snmpuser[] get(nitro_service service, options option) throws Exception{\n\t\tsnmpuser obj = new snmpuser();\n\t\tsnmpuser[] response = (snmpuser[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"private FormInput formInputMatchingNode(Node element) {\n\t\tNamedNodeMap attributes = element.getAttributes();\n\t\tIdentification id;\n\n\t\tif (attributes.getNamedItem(\"id\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.id,\n\t\t\t\t\tattributes.getNamedItem(\"id\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tif (attributes.getNamedItem(\"name\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.name,\n\t\t\t\t\tattributes.getNamedItem(\"name\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tString xpathExpr = XPathHelper.getXPathExpression(element);\n\t\tif (xpathExpr != null && !xpathExpr.equals(\"\")) {\n\t\t\tid = new Identification(Identification.How.xpath, xpathExpr);\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"static String fromPackageName(String packageName) {\n List<String> tokens = tokenOf(packageName);\n return fromTokens(tokens);\n }"
] |
Finds for the given project.
@param name project name
@return given project or an empty {@code Optional} if project does not exist
@throws IllegalArgumentException | [
"public Optional<Project> findProject(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return getProject(name);\n }"
] | [
"public String getInvalidMessage(String key) {\n return invalidMessageOverride == null ? messageMixin.lookup(key, messageValueArgs) : MessageFormat.format(\n invalidMessageOverride, messageValueArgs);\n }",
"private ProjectFile readProjectFile(ProjectReader reader, InputStream stream) throws MPXJException\n {\n addListeners(reader);\n return reader.read(stream);\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 readRelationships()\n {\n for (MapRow row : getTable(\"CONTAB\"))\n {\n Task task1 = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID_1\"));\n Task task2 = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID_2\"));\n\n if (task1 != null && task2 != null)\n {\n RelationType type = row.getRelationType(\"TYPE\");\n Duration lag = row.getDuration(\"LAG\");\n Relation relation = task2.addPredecessor(task1, type, lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }",
"private void complete(final InstallationManager.InstallationModification modification, final FinalizeCallback callback) {\n final List<File> processed = new ArrayList<File>();\n List<File> reenabled = Collections.emptyList();\n List<File> disabled = Collections.emptyList();\n try {\n try {\n // Update the state to invalidate and process module resources\n if (stateUpdater.compareAndSet(this, State.PREPARED, State.INVALIDATE)) {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n // Only invalidate modules when applying patches; on rollback files are immediately restored\n for (final File invalidation : moduleInvalidations) {\n processed.add(invalidation);\n PatchModuleInvalidationUtils.processFile(this, invalidation, mode);\n }\n if (!modulesToReenable.isEmpty()) {\n reenabled = new ArrayList<File>(modulesToReenable.size());\n for (final File path : modulesToReenable) {\n reenabled.add(path);\n PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.ROLLBACK);\n }\n }\n } else if(mode == PatchingTaskContext.Mode.ROLLBACK) {\n if (!modulesToDisable.isEmpty()) {\n disabled = new ArrayList<File>(modulesToDisable.size());\n for (final File path : modulesToDisable) {\n disabled.add(path);\n PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.APPLY);\n }\n }\n }\n\n }\n modification.complete();\n callback.completed(this);\n state = State.COMPLETED;\n } catch (Exception e) {\n this.moduleInvalidations.clear();\n this.moduleInvalidations.addAll(processed);\n this.modulesToReenable.clear();\n this.modulesToReenable.addAll(reenabled);\n this.modulesToDisable.clear();\n this.moduleInvalidations.addAll(disabled);\n throw new RuntimeException(e);\n }\n } finally {\n if (state != State.COMPLETED) {\n try {\n modification.cancel();\n } finally {\n try {\n undoChanges();\n } finally {\n callback.operationCancelled(this);\n }\n }\n } else {\n try {\n if (checkForGarbageOnRestart) {\n final File cleanupMarker = new File(installedImage.getInstallationMetadata(), \"cleanup-patching-dirs\");\n cleanupMarker.createNewFile();\n }\n storeFailedRenaming();\n } catch (IOException e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to create cleanup marker\");\n }\n }\n }\n }",
"private PoolingHttpClientConnectionManager createConnectionMgr() {\n PoolingHttpClientConnectionManager connectionMgr;\n\n // prepare SSLContext\n SSLContext sslContext = buildSslContext();\n ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();\n // we allow to disable host name verification against CA certificate,\n // notice: in general this is insecure and should be avoided in production,\n // (this type of configuration is useful for development purposes)\n boolean noHostVerification = false;\n LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(\n sslContext,\n noHostVerification ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier()\n );\n Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()\n .register(\"http\", plainsf)\n .register(\"https\", sslsf)\n .build();\n connectionMgr = new PoolingHttpClientConnectionManager(r, null, null,\n null, connectionPoolTimeToLive, TimeUnit.SECONDS);\n\n connectionMgr.setMaxTotal(maxConnectionsTotal);\n connectionMgr.setDefaultMaxPerRoute(maxConnectionsPerRoute);\n HttpHost localhost = new HttpHost(\"localhost\", 80);\n connectionMgr.setMaxPerRoute(new HttpRoute(localhost), maxConnectionsPerRoute);\n return connectionMgr;\n }",
"public Membership getMembership() {\n URI uri = new URIBase(getBaseUri()).path(\"_membership\").build();\n Membership membership = couchDbClient.get(uri,\n Membership.class);\n return membership;\n }",
"public static void createMetadataCache(SlotReference slot, int playlistId, File cache) throws Exception {\n createMetadataCache(slot, playlistId, cache, null);\n }",
"public static base_response update(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 updateresource = new nsacl6();\n\t\tupdateresource.acl6name = resource.acl6name;\n\t\tupdateresource.aclaction = resource.aclaction;\n\t\tupdateresource.srcipv6 = resource.srcipv6;\n\t\tupdateresource.srcipop = resource.srcipop;\n\t\tupdateresource.srcipv6val = resource.srcipv6val;\n\t\tupdateresource.srcport = resource.srcport;\n\t\tupdateresource.srcportop = resource.srcportop;\n\t\tupdateresource.srcportval = resource.srcportval;\n\t\tupdateresource.destipv6 = resource.destipv6;\n\t\tupdateresource.destipop = resource.destipop;\n\t\tupdateresource.destipv6val = resource.destipv6val;\n\t\tupdateresource.destport = resource.destport;\n\t\tupdateresource.destportop = resource.destportop;\n\t\tupdateresource.destportval = resource.destportval;\n\t\tupdateresource.srcmac = resource.srcmac;\n\t\tupdateresource.protocol = resource.protocol;\n\t\tupdateresource.protocolnumber = resource.protocolnumber;\n\t\tupdateresource.icmptype = resource.icmptype;\n\t\tupdateresource.icmpcode = resource.icmpcode;\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.Interface = resource.Interface;\n\t\tupdateresource.priority = resource.priority;\n\t\tupdateresource.established = resource.established;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Minimize the function starting at the given initial point. | [
"@Override\n public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) {\n return minimize(function, point, null);\n }"
] | [
"private static <T> Set<Type> getSessionBeanTypes(EnhancedAnnotated<T, ?> annotated, EjbDescriptor<T> ejbDescriptor) {\n ImmutableSet.Builder<Type> types = ImmutableSet.builder();\n // session beans\n Map<Class<?>, Type> typeMap = new LinkedHashMap<Class<?>, Type>();\n HierarchyDiscovery beanClassDiscovery = HierarchyDiscovery.forNormalizedType(ejbDescriptor.getBeanClass());\n for (BusinessInterfaceDescriptor<?> businessInterfaceDescriptor : ejbDescriptor.getLocalBusinessInterfaces()) {\n // first we need to resolve the local interface\n Type resolvedLocalInterface = beanClassDiscovery.resolveType(Types.getCanonicalType(businessInterfaceDescriptor.getInterface()));\n SessionBeanHierarchyDiscovery interfaceDiscovery = new SessionBeanHierarchyDiscovery(resolvedLocalInterface);\n if (beanClassDiscovery.getTypeMap().containsKey(businessInterfaceDescriptor.getInterface())) {\n // WELD-1675 Only add types also included in Annotated.getTypeClosure()\n for (Entry<Class<?>, Type> entry : interfaceDiscovery.getTypeMap().entrySet()) {\n if (annotated.getTypeClosure().contains(entry.getValue())) {\n typeMap.put(entry.getKey(), entry.getValue());\n }\n }\n } else {\n // Session bean class does not implement the business interface and @javax.ejb.Local applied to the session bean class\n typeMap.putAll(interfaceDiscovery.getTypeMap());\n }\n }\n if (annotated.isAnnotationPresent(Typed.class)) {\n types.addAll(Beans.getTypedTypes(typeMap, annotated.getJavaClass(), annotated.getAnnotation(Typed.class)));\n } else {\n typeMap.put(Object.class, Object.class);\n types.addAll(typeMap.values());\n }\n return Beans.getLegalBeanTypes(types.build(), annotated);\n }",
"void resetCurrentRevisionData() {\n\t\tthis.revisionId = NO_REVISION_ID; // impossible as an id in MediaWiki\n\t\tthis.parentRevisionId = NO_REVISION_ID;\n\t\tthis.text = null;\n\t\tthis.comment = null;\n\t\tthis.format = null;\n\t\tthis.timeStamp = null;\n\t\tthis.model = null;\n\t}",
"protected void captureCenterEye(GVRRenderTarget renderTarget, boolean isMultiview) {\n if (mScreenshotCenterCallback == null) {\n return;\n }\n\n // TODO: when we will use multithreading, create new camera using centercamera as we are adding posteffects into it\n final GVRCamera centerCamera = mMainScene.getMainCameraRig().getCenterCamera();\n final GVRMaterial postEffect = new GVRMaterial(this, GVRMaterial.GVRShaderType.VerticalFlip.ID);\n\n centerCamera.addPostEffect(postEffect);\n\n GVRRenderTexture posteffectRenderTextureB = null;\n GVRRenderTexture posteffectRenderTextureA = null;\n\n if(isMultiview) {\n posteffectRenderTextureA = mRenderBundle.getEyeCapturePostEffectRenderTextureA();\n posteffectRenderTextureB = mRenderBundle.getEyeCapturePostEffectRenderTextureB();\n renderTarget = mRenderBundle.getEyeCaptureRenderTarget();\n renderTarget.cullFromCamera(mMainScene, centerCamera ,mRenderBundle.getShaderManager());\n renderTarget.beginRendering(centerCamera);\n }\n else {\n posteffectRenderTextureA = mRenderBundle.getPostEffectRenderTextureA();\n posteffectRenderTextureB = mRenderBundle.getPostEffectRenderTextureB();\n }\n\n renderTarget.render(mMainScene,centerCamera, mRenderBundle.getShaderManager(), posteffectRenderTextureA, posteffectRenderTextureB);\n centerCamera.removePostEffect(postEffect);\n readRenderResult(renderTarget, EYE.MULTIVIEW, false);\n\n if(isMultiview)\n renderTarget.endRendering();\n\n final Bitmap bitmap = Bitmap.createBitmap(mReadbackBufferWidth, mReadbackBufferHeight, Bitmap.Config.ARGB_8888);\n mReadbackBuffer.rewind();\n bitmap.copyPixelsFromBuffer(mReadbackBuffer);\n final GVRScreenshotCallback callback = mScreenshotCenterCallback;\n Threads.spawn(new Runnable() {\n public void run() {\n callback.onScreenCaptured(bitmap);\n }\n });\n\n mScreenshotCenterCallback = null;\n }",
"public static String common() {\n String common = SysProps.get(KEY_COMMON_CONF_TAG);\n if (S.blank(common)) {\n common = \"common\";\n }\n return common;\n }",
"protected AbsoluteURI getGeneratedLocation(PersistedTrace trace) {\n\t\tAbsoluteURI path = trace.getPath();\n\t\tString fileName = traceFileNameProvider.getJavaFromTrace(path.getURI().toString());\n\t\treturn new AbsoluteURI(fileName);\n\t}",
"public List<ProjectFile> readAll() throws MPXJException\n {\n Map<Integer, String> projects = listProjects();\n List<ProjectFile> result = new ArrayList<ProjectFile>(projects.keySet().size());\n for (Integer id : projects.keySet())\n {\n setProjectID(id.intValue());\n result.add(read());\n }\n return result;\n }",
"@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 static Map<String, ServerGroupDeploymentPlanResult> buildServerGroupResults(Map<UUID, DeploymentActionResult> deploymentActionResults) {\n Map<String, ServerGroupDeploymentPlanResult> serverGroupResults = new HashMap<String, ServerGroupDeploymentPlanResult>();\n\n for (Map.Entry<UUID, DeploymentActionResult> entry : deploymentActionResults.entrySet()) {\n\n UUID actionId = entry.getKey();\n DeploymentActionResult actionResult = entry.getValue();\n\n Map<String, ServerGroupDeploymentActionResult> actionResultsByServerGroup = actionResult.getResultsByServerGroup();\n for (ServerGroupDeploymentActionResult serverGroupActionResult : actionResultsByServerGroup.values()) {\n String serverGroupName = serverGroupActionResult.getServerGroupName();\n\n ServerGroupDeploymentPlanResultImpl sgdpr = (ServerGroupDeploymentPlanResultImpl) serverGroupResults.get(serverGroupName);\n if (sgdpr == null) {\n sgdpr = new ServerGroupDeploymentPlanResultImpl(serverGroupName);\n serverGroupResults.put(serverGroupName, sgdpr);\n }\n\n for (Map.Entry<String, ServerUpdateResult> serverEntry : serverGroupActionResult.getResultByServer().entrySet()) {\n String serverName = serverEntry.getKey();\n ServerUpdateResult sud = serverEntry.getValue();\n ServerDeploymentPlanResultImpl sdpr = (ServerDeploymentPlanResultImpl) sgdpr.getServerResult(serverName);\n if (sdpr == null) {\n sdpr = new ServerDeploymentPlanResultImpl(serverName);\n sgdpr.storeServerResult(serverName, sdpr);\n }\n sdpr.storeServerUpdateResult(actionId, sud);\n }\n }\n }\n return serverGroupResults;\n }",
"public static Iterable<Metadata> getAllMetadata(BoxItem item, String ... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new BoxResourceIterable<Metadata>(\n item.getAPI(),\n GET_ALL_METADATA_URL_TEMPLATE.buildWithQuery(item.getItemURL().toString(), builder.toString()),\n DEFAULT_LIMIT) {\n\n @Override\n protected Metadata factory(JsonObject jsonObject) {\n return new Metadata(jsonObject);\n }\n\n };\n }"
] |
Read custom fields for a GanttProject task.
@param gpTask GanttProject task
@param mpxjTask MPXJ Task instance | [
"private void readTaskCustomFields(net.sf.mpxj.ganttproject.schema.Task gpTask, Task mpxjTask)\n {\n //\n // Populate custom field default values\n //\n Map<FieldType, Object> customFields = new HashMap<FieldType, Object>();\n for (Pair<FieldType, String> definition : m_taskPropertyDefinitions.values())\n {\n customFields.put(definition.getFirst(), definition.getSecond());\n }\n\n //\n // Update with custom field actual values\n //\n for (CustomTaskProperty property : gpTask.getCustomproperty())\n {\n Pair<FieldType, String> definition = m_taskPropertyDefinitions.get(property.getTaskpropertyId());\n if (definition != null)\n {\n //\n // Retrieve the value. If it is empty, use the default.\n //\n String value = property.getValueAttribute();\n if (value.isEmpty())\n {\n value = null;\n }\n\n //\n // If we have a value,convert it to the correct type\n //\n if (value != null)\n {\n Object result;\n\n switch (definition.getFirst().getDataType())\n {\n case NUMERIC:\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n result = Double.valueOf(value);\n }\n break;\n }\n\n case DATE:\n {\n try\n {\n result = m_dateFormat.parse(value);\n }\n catch (ParseException ex)\n {\n result = null;\n }\n break;\n }\n\n case BOOLEAN:\n {\n result = Boolean.valueOf(value.equals(\"true\"));\n break;\n }\n\n default:\n {\n result = value;\n break;\n }\n }\n\n if (result != null)\n {\n customFields.put(definition.getFirst(), result);\n }\n }\n }\n }\n\n for (Map.Entry<FieldType, Object> item : customFields.entrySet())\n {\n if (item.getValue() != null)\n {\n mpxjTask.set(item.getKey(), item.getValue());\n }\n }\n }"
] | [
"public static int rank( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n int N = svd.numberOfSingularValues();\n double sv[] = svd.getSingularValues();\n\n double threshold = singularThreshold(sv,N);\n int count = 0;\n for (int i = 0; i < sv.length; i++) {\n if( sv[i] >= threshold ) {\n count++;\n }\n }\n return count;\n }",
"public ModelNode translateOperationForProxy(final ModelNode op) {\n return translateOperationForProxy(op, PathAddress.pathAddress(op.get(OP_ADDR)));\n }",
"public void setDateAttribute(String name, Date value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new DateAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\t}",
"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 }",
"public void setEnable(boolean flag)\n {\n if (mEnabled == flag)\n {\n return;\n }\n mEnabled = flag;\n if (flag)\n {\n mContext.registerDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().addListener(this);\n mAudioEngine.resume();\n }\n else\n {\n mContext.unregisterDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().removeListener(this);\n mAudioEngine.pause();\n }\n }",
"public static void fire(I_CmsHasDateBoxEventHandlers source, Date date, boolean isTyping) {\n\n if (TYPE != null) {\n CmsDateBoxEvent event = new CmsDateBoxEvent(date, isTyping);\n source.fireEvent(event);\n }\n }",
"public void setConnectTimeout(int connectTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}",
"public ConfigOptionBuilder setCommandLineOptionWithArgument( CommandLineOption commandLineOption, StringConverter converter ) {\n co.setCommandLineOption( commandLineOption );\n return setStringConverter( converter );\n }",
"public static sslpolicylabel[] get(nitro_service service) throws Exception{\n\t\tsslpolicylabel obj = new sslpolicylabel();\n\t\tsslpolicylabel[] response = (sslpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Use this API to add policydataset. | [
"public static base_response add(nitro_service client, policydataset resource) throws Exception {\n\t\tpolicydataset addresource = new policydataset();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.indextype = resource.indextype;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"private void registerChildInternal(IgnoreDomainResourceTypeResource child) {\n child.setParent(this);\n children.put(child.getName(), child);\n }",
"public static sslvserver_sslcipher_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcipher_binding obj = new sslvserver_sslcipher_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcipher_binding response[] = (sslvserver_sslcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public DocumentReaderAndWriter<IN> makePlainTextReaderAndWriter() {\r\n String readerClassName = flags.plainTextDocumentReaderAndWriter;\r\n // We set this default here if needed because there may be models\r\n // which don't have the reader flag set\r\n if (readerClassName == null) {\r\n readerClassName = SeqClassifierFlags.DEFAULT_PLAIN_TEXT_READER;\r\n }\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>) Class.forName(readerClassName).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.plainTextDocumentReaderAndWriter: '%s'\", flags.plainTextDocumentReaderAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }",
"public void addNotIn(String attribute, Query subQuery)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }",
"public static dnstxtrec[] get(nitro_service service) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\tdnstxtrec[] response = (dnstxtrec[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public float getTangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_tangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }",
"public static <T> List<T> flatten(Collection<List<T>> nestedList) {\r\n List<T> result = new ArrayList<T>();\r\n for (List<T> list : nestedList) {\r\n result.addAll(list);\r\n }\r\n return result;\r\n }",
"public static String[] randomResourceNames(String prefix, int maxLen, int count) {\n String[] names = new String[count];\n ResourceNamer resourceNamer = SdkContext.getResourceNamerFactory().createResourceNamer(\"\");\n for (int i = 0; i < count; i++) {\n names[i] = resourceNamer.randomName(prefix, maxLen);\n }\n return names;\n }",
"private void afterBatch(BatchBackend backend) {\n\t\tIndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );\n\t\tif ( this.optimizeAtEnd ) {\n\t\t\tbackend.optimize( targetedTypes );\n\t\t}\n\t\tbackend.flush( targetedTypes );\n\t}"
] |
Initialize the fat client for the given store.
1. Updates the coordinatorMetadata 2.Gets the new store configs from the
config file 3.Creates a new @SocketStoreClientFactory 4. Subsequently
caches the @StoreClient obtained from the factory.
This is synchronized because if Coordinator Admin is already doing some
change we want the AsyncMetadataVersionManager to wait.
@param storeName | [
"private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {\n // updates the coordinator metadata with recent stores and cluster xml\n updateCoordinatorMetadataWithLatestState();\n\n logger.info(\"Creating a Fat client for store: \" + storeName);\n SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),\n storeClientProps);\n\n if(this.fatClientMap == null) {\n this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>();\n }\n DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,\n fatClientFactory,\n 1,\n this.coordinatorMetadata.getStoreDefs(),\n this.coordinatorMetadata.getClusterXmlStr());\n this.fatClientMap.put(storeName, fatClient);\n\n }"
] | [
"public int addServerGroup(String groupName, int profileId) throws Exception {\n int groupId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVER_GROUPS\n + \"(\" + Constants.GENERIC_NAME + \",\" +\n Constants.GENERIC_PROFILE_ID + \")\"\n + \" VALUES (?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, groupName);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n groupId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add group\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return groupId;\n }",
"private AssignmentField selectField(AssignmentField[] fields, int index)\n {\n if (index < 1 || index > fields.length)\n {\n throw new IllegalArgumentException(index + \" is not a valid field index\");\n }\n return (fields[index - 1]);\n }",
"public final synchronized void shutdown() { // synchronize on 'this' to avoid races with registerStreams\n stopped = true;\n // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor\n if (cleanupTaskFuture != null) {\n cleanupTaskFuture.cancel(false);\n }\n\n // Close remaining streams\n for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) {\n InputStreamKey key = entry.getKey();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }",
"protected <T, A> ActiveOperation<T, A> registerActiveOperation(final Integer id, A attachment, ActiveOperation.CompletedCallback<T> callback) {\n lock.lock();\n try {\n // Check that we still allow registration\n // TODO WFCORE-199 distinguish client uses from server uses and limit this check to server uses\n // Using id==null may be one way to do this, but we need to consider ops that involve multiple requests\n // TODO WFCORE-845 consider using an IllegalStateException for this\n //assert ! shutdown;\n final Integer operationId;\n if(id == null) {\n // If we did not get an operationId, create a new one\n operationId = operationIdManager.createBatchId();\n } else {\n // Check that the operationId is not already taken\n if(! operationIdManager.lockBatchId(id)) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(id);\n }\n operationId = id;\n }\n final ActiveOperationImpl<T, A> request = new ActiveOperationImpl<T, A>(operationId, attachment, getCheckedCallback(callback), this);\n final ActiveOperation<?, ?> existing = activeRequests.putIfAbsent(operationId, request);\n if(existing != null) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(operationId);\n }\n ProtocolLogger.ROOT_LOGGER.tracef(\"Registered active operation %d\", operationId);\n activeCount++; // condition.signalAll();\n return request;\n } finally {\n lock.unlock();\n }\n }",
"public Task<Void> resendConfirmationEmail(@NonNull final String email) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n resendConfirmationEmailInternal(email);\n return null;\n }\n });\n }",
"protected static List<String> parseMandatoryStringValues(JSONObject json, String key) throws JSONException {\n\n List<String> list = null;\n JSONArray array = json.getJSONArray(key);\n list = new ArrayList<String>(array.length());\n for (int i = 0; i < array.length(); i++) {\n try {\n String entry = array.getString(i);\n list.add(entry);\n } catch (JSONException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_STRING_ENTRY_UNPARSABLE_1, key), e);\n }\n }\n return list;\n }",
"public int[] getCurrentValuesArray() {\n int[] currentValues = new int[5];\n\n currentValues[0] = getMinFilterType().getFilterValue(); // MIN FILTER\n currentValues[1] = getMagFilterType().getFilterValue(); // MAG FILTER\n currentValues[2] = getAnisotropicValue(); // ANISO FILTER\n currentValues[3] = getWrapSType().getWrapValue(); // WRAP S\n currentValues[4] = getWrapTType().getWrapValue(); // WRAP T\n\n return currentValues;\n }",
"private boolean fireEvent(Eventable eventable) {\n\t\tEventable eventToFire = eventable;\n\t\tif (eventable.getIdentification().getHow().toString().equals(\"xpath\")\n\t\t\t\t&& eventable.getRelatedFrame().equals(\"\")) {\n\t\t\teventToFire = resolveByXpath(eventable, eventToFire);\n\t\t}\n\t\tboolean isFired = false;\n\t\ttry {\n\t\t\tisFired = browser.fireEventAndWait(eventToFire);\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tif (crawlRules.isCrawlHiddenAnchors() && eventToFire.getElement() != null\n\t\t\t\t\t&& \"A\".equals(eventToFire.getElement().getTag())) {\n\t\t\t\tisFired = visitAnchorHrefIfPossible(eventToFire);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Ignoring invisible element {}\", eventToFire.getElement());\n\t\t\t}\n\t\t} catch (InterruptedException e) {\n\t\t\tLOG.debug(\"Interrupted during fire event\");\n\t\t\tinterruptThread();\n\t\t\treturn false;\n\t\t}\n\n\t\tLOG.debug(\"Event fired={} for eventable {}\", isFired, eventable);\n\n\t\tif (isFired) {\n\t\t\t// Let the controller execute its specified wait operation on the browser thread safe.\n\t\t\twaitConditionChecker.wait(browser);\n\t\t\tbrowser.closeOtherWindows();\n\t\t\treturn true;\n\t\t} else {\n\t\t\t/*\n\t\t\t * Execute the OnFireEventFailedPlugins with the current crawlPath with the crawlPath\n\t\t\t * removed 1 state to represent the path TO here.\n\t\t\t */\n\t\t\tplugins.runOnFireEventFailedPlugins(context, eventable,\n\t\t\t\t\tcrawlpath.immutableCopyWithoutLast());\n\t\t\treturn false; // no event fired\n\t\t}\n\t}",
"protected boolean computeOffset(CacheDataSet cache) {\n // offset computation: update offset for all items in the cache\n float startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n float layoutOffset = getLayoutOffset();\n\n boolean inBounds = startDataOffset < -layoutOffset;\n\n for (int pos = 0; pos < cache.count(); ++pos) {\n int id = cache.getId(pos);\n if (id != -1) {\n float endDataOffset = cache.setDataAfter(id, startDataOffset);\n inBounds = inBounds &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n startDataOffset = endDataOffset;\n Log.d(LAYOUT, TAG, \"computeOffset [%d] = %f\" , id, cache.getDataOffset(id));\n }\n }\n\n return inBounds;\n }"
] |
Get image parent ID from imageID on the current agent.
@param imageID
@return | [
"public static String getParentIdFromAgent(Launcher launcher, final String imageID, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getParentId(imageID, host);\n }\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 }",
"@Override\n\tpublic int getMinPrefixLengthForBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = getBitCount();\n\t\tfor(int i = count - 1; i >= 0 ; i--) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tint segBitCount = div.getBitCount();\n\t\t\tint segPrefix = div.getMinPrefixLengthForBlock();\n\t\t\tif(segPrefix == segBitCount) {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\ttotalPrefix -= segBitCount;\n\t\t\t\tif(segPrefix != 0) {\n\t\t\t\t\ttotalPrefix += segPrefix;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn totalPrefix;\n\t}",
"private void sortFileList() {\n if (this.size() > 1) {\n Collections.sort(this.fileList, new Comparator() {\n\n public final int compare(final Object o1, final Object o2) {\n final File f1 = (File) o1;\n final File f2 = (File) o2;\n final Object[] f1TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f1.getName(), baseFile);\n final Object[] f2TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f2.getName(), baseFile);\n final long f1TimeSuffix = ((Long) f1TimeAndCount[0]).longValue();\n final long f2TimeSuffix = ((Long) f2TimeAndCount[0]).longValue();\n if ((0L == f1TimeSuffix) && (0L == f2TimeSuffix)) {\n final long f1Time = f1.lastModified();\n final long f2Time = f2.lastModified();\n if (f1Time < f2Time) {\n return -1;\n }\n if (f1Time > f2Time) {\n return 1;\n }\n return 0;\n }\n if (f1TimeSuffix < f2TimeSuffix) {\n return -1;\n }\n if (f1TimeSuffix > f2TimeSuffix) {\n return 1;\n }\n final int f1Count = ((Integer) f1TimeAndCount[1]).intValue();\n final int f2Count = ((Integer) f2TimeAndCount[1]).intValue();\n if (f1Count < f2Count) {\n return -1;\n }\n if (f1Count > f2Count) {\n return 1;\n }\n if (f1Count == f2Count) {\n if (fileHelper.isCompressed(f1)) {\n return -1;\n }\n if (fileHelper.isCompressed(f2)) {\n return 1;\n }\n }\n return 0;\n }\n });\n }\n }",
"public void unlinkFK(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds)\n {\n setFKField(targetObject, cld, rds, null);\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 }",
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static short checkShort(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInShortRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), SHORT_MIN, SHORT_MAX);\n\t\t}\n\n\t\treturn number.shortValue();\n\t}",
"public void updateLockingValues(Object obj) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n if (fmd.isUpdateLock())\r\n {\r\n PersistentField f = fmd.getPersistentField();\r\n Object cv = f.get(obj);\r\n // int\r\n if ((f.getType() == int.class) || (f.getType() == Integer.class))\r\n {\r\n int newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).intValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Integer(newCv));\r\n }\r\n // long\r\n else if ((f.getType() == long.class) || (f.getType() == Long.class))\r\n {\r\n long newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).longValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Long(newCv));\r\n }\r\n // Timestamp\r\n else if (f.getType() == Timestamp.class)\r\n {\r\n long newCv = System.currentTimeMillis();\r\n f.set(obj, new Timestamp(newCv));\r\n }\r\n }\r\n }\r\n }",
"public boolean isRunning(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n return this.runningProcessors.containsKey(processorGraphNode.getProcessor());\n } finally {\n this.processorLock.unlock();\n }\n }",
"static PathAddress toPathAddress(String domain, ImmutableManagementResourceRegistration registry, ObjectName name) {\n if (!name.getDomain().equals(domain)) {\n return PathAddress.EMPTY_ADDRESS;\n }\n if (name.equals(ModelControllerMBeanHelper.createRootObjectName(domain))) {\n return PathAddress.EMPTY_ADDRESS;\n }\n final Hashtable<String, String> properties = name.getKeyPropertyList();\n return searchPathAddress(PathAddress.EMPTY_ADDRESS, registry, properties);\n }"
] |
We have obtained album art for a device, so store it and alert any listeners.
@param update the update which caused us to retrieve this art
@param art the album art which we retrieved | [
"private void updateArt(TrackMetadataUpdate update, AlbumArt art) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), art); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), art);\n }\n }\n }\n deliverAlbumArtUpdate(update.player, art);\n }"
] | [
"public static String getAt(String text, int index) {\n index = normaliseIndex(index, text.length());\n return text.substring(index, index + 1);\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 }",
"public ApnsServiceBuilder withDelegate(ApnsDelegate delegate) {\n this.delegate = delegate == null ? ApnsDelegate.EMPTY : delegate;\n return this;\n }",
"public static void main(String[] args) {\r\n Treebank treebank = new DiskTreebank();\r\n treebank.loadPath(args[0]);\r\n WordStemmer ls = new WordStemmer();\r\n for (Tree tree : treebank) {\r\n ls.visitTree(tree);\r\n System.out.println(tree);\r\n }\r\n }",
"public static final Double getDouble(InputStream is) throws IOException\n {\n double result = Double.longBitsToDouble(getLong(is));\n if (Double.isNaN(result))\n {\n result = 0;\n }\n return Double.valueOf(result);\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 void setNewCenterColor(int color) {\n\t\tmCenterNewColor = color;\n\t\tmCenterNewPaint.setColor(color);\n\t\tif (mCenterOldColor == 0) {\n\t\t\tmCenterOldColor = color;\n\t\t\tmCenterOldPaint.setColor(color);\n\t\t}\n\t\tif (onColorChangedListener != null && color != oldChangedListenerColor ) {\n\t\t\tonColorChangedListener.onColorChanged(color);\n\t\t\toldChangedListenerColor = color;\n\t\t}\n\t\tinvalidate();\n\t}",
"public Iterable<? extends WindupVertexFrame> findVariable(String name, int maxDepth)\n {\n int currentDepth = 0;\n Iterable<? extends WindupVertexFrame> result = null;\n for (Map<String, Iterable<? extends WindupVertexFrame>> frame : deque)\n {\n result = frame.get(name);\n if (result != null)\n {\n break;\n }\n currentDepth++;\n if (currentDepth >= maxDepth)\n break;\n }\n return result;\n }",
"void start(String monitoredDirectory, Long pollingTime) {\n this.monitoredDirectory = monitoredDirectory;\n String deployerKlassName;\n if (klass.equals(ImportDeclaration.class)) {\n deployerKlassName = ImporterDeployer.class.getName();\n } else if (klass.equals(ExportDeclaration.class)) {\n deployerKlassName = ExporterDeployer.class.getName();\n } else {\n throw new IllegalStateException(\"\");\n }\n\n this.dm = new DirectoryMonitor(monitoredDirectory, pollingTime, deployerKlassName);\n try {\n dm.start(getBundleContext());\n } catch (DirectoryMonitoringException e) {\n LOG.error(\"Failed to start \" + DirectoryMonitor.class.getName() + \" for the directory \" + monitoredDirectory + \" and polling time \" + pollingTime.toString(), e);\n }\n }"
] |
Load the related repositories, plugins and a promotion config associated to the buildId.
Called from the UI.
@param buildId - The unique build id.
@return LoadBuildsResponse e.g. list of repositories, plugins and a promotion config. | [
"@JavaScriptMethod\n @SuppressWarnings({\"UnusedDeclaration\"})\n public LoadBuildsResponse loadBuild(String buildId) {\n LoadBuildsResponse response = new LoadBuildsResponse();\n // When we load a new build we need also to reset the promotion plugin.\n // The null plugin is related to 'None' plugin.\n setPromotionPlugin(null);\n try {\n this.currentPromotionCandidate = promotionCandidates.get(buildId);\n if (this.currentPromotionCandidate == null) {\n throw new IllegalArgumentException(\"Can't find build by ID: \" + buildId);\n }\n List<String> repositoryKeys = getRepositoryKeys();\n List<UserPluginInfo> plugins = getPromotionsUserPluginInfo();\n PromotionConfig promotionConfig = getPromotionConfig();\n String defaultTargetRepository = getDefaultPromotionTargetRepository();\n if (StringUtils.isNotBlank(defaultTargetRepository) && repositoryKeys.contains(defaultTargetRepository)) {\n promotionConfig.setTargetRepo(defaultTargetRepository);\n }\n response.addRepositories(repositoryKeys);\n response.setPlugins(plugins);\n response.setPromotionConfig(promotionConfig);\n response.setSuccess(true);\n } catch (Exception e) {\n response.setResponseMessage(e.getMessage());\n }\n return response;\n }"
] | [
"private void readTasks(Project plannerProject) throws MPXJException\n {\n Tasks tasks = plannerProject.getTasks();\n if (tasks != null)\n {\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readTask(null, task);\n }\n\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readPredecessors(task);\n }\n }\n\n m_projectFile.updateStructure();\n }",
"public <Result> Result process(IUnitOfWork<Result, State> work) {\n\t\treleaseReadLock();\n\t\tacquireWriteLock();\n\t\ttry {\n\t\t\tif (log.isTraceEnabled())\n\t\t\t\tlog.trace(\"process - \" + Thread.currentThread().getName());\n\t\t\treturn modify(work);\n\t\t} finally {\n\t\t\tif (log.isTraceEnabled())\n\t\t\t\tlog.trace(\"Downgrading from write lock to read lock...\");\n\t\t\tacquireReadLock();\n\t\t\treleaseWriteLock();\n\t\t}\n\t}",
"public static String getGalleryNotFoundKey(String gallery) {\n\n StringBuffer sb = new StringBuffer(ERROR_REASON_NO_PREFIX);\n sb.append(gallery.toUpperCase());\n sb.append(GUI_TITLE_POSTFIX);\n return sb.toString();\n }",
"public Map<String, Table> process(File directory, String prefix) throws IOException\n {\n String filePrefix = prefix.toUpperCase();\n Map<String, Table> tables = new HashMap<String, Table>();\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n String name = file.getName().toUpperCase();\n if (!name.startsWith(filePrefix))\n {\n continue;\n }\n\n int typeIndex = name.lastIndexOf('.') - 3;\n String type = name.substring(typeIndex, typeIndex + 3);\n TableDefinition definition = TABLE_DEFINITIONS.get(type);\n if (definition != null)\n {\n Table table = new Table();\n TableReader reader = new TableReader(definition);\n reader.read(file, table);\n tables.put(type, table);\n //dumpCSV(type, definition, table);\n }\n }\n }\n return tables;\n }",
"public CurrencyQueryBuilder setNumericCodes(int... codes) {\n return set(CurrencyQuery.KEY_QUERY_NUMERIC_CODES,\n Arrays.stream(codes).boxed().collect(Collectors.toList()));\n }",
"public static appfwpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tappfwpolicy_stats[] response = (appfwpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"private static long scanForLocSig(FileChannel channel) throws IOException {\n\n channel.position(0);\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long end = channel.size();\n while (channel.position() <= end) {\n\n read(bb, channel);\n\n int bufferPos = 0;\n while (bufferPos <= bb.limit() - SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the size of the pattern is static\n // b) the pattern is static and has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && LOCSIG_PATTERN[patternPos] == bb.get(bufferPos + patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Outer switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid local file record\n long startLocRecord = channel.position() - bb.limit() + bufferPos;\n long currentPos = channel.position();\n if (validateLocalFileRecord(channel, startLocRecord, -1)) {\n return startLocRecord;\n }\n // Restore position in case it shifted\n channel.position(currentPos);\n\n // wasn't a valid local file record; continue scan\n bufferPos += 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos + patternPos) - Byte.MIN_VALUE;\n bufferPos += LOC_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos += 4;\n }\n }\n }\n\n return -1;\n }",
"public void stopDrag() {\n mPhysicsDragger.stopDrag();\n\n mPhysicsContext.runOnPhysicsThread(new Runnable() {\n @Override\n public void run() {\n if (mRigidBodyDragMe != null) {\n NativePhysics3DWorld.stopDrag(getNative());\n mRigidBodyDragMe = null;\n }\n }\n });\n }",
"public static ModelNode createRemoveOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createRemoveOperation(address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }"
] |
Inserts a Bundle value into the mapping of the underlying Bundle, replacing any existing value
for the given key. Either key or value may be null.
@param key a String, or null
@param value a Bundle object, or null
@return this bundler instance to chain method calls | [
"public Bundler put(String key, Bundle value) {\n delegate.putBundle(key, value);\n return this;\n }"
] | [
"public Identity refreshIdentity()\r\n {\r\n Identity oldOid = getIdentity();\r\n this.oid = getBroker().serviceIdentity().buildIdentity(myObj);\r\n return oldOid;\r\n }",
"@Override\n public ActivityInterface getActivityInterface() {\n if (activityInterface == null) {\n activityInterface = new ActivityInterface(apiKey, sharedSecret, transport);\n }\n return activityInterface;\n }",
"public float getPositionX(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat(vertex * 3 * SIZEOF_FLOAT);\n }",
"private static I_CmsResourceBundle tryBundle(String localizedName) {\n\n I_CmsResourceBundle result = null;\n\n try {\n\n String resourceName = localizedName.replace('.', '/') + \".properties\";\n URL url = CmsResourceBundleLoader.class.getClassLoader().getResource(resourceName);\n\n I_CmsResourceBundle additionalBundle = m_permanentCache.get(localizedName);\n if (additionalBundle != null) {\n result = additionalBundle.getClone();\n } else if (url != null) {\n // the resource was found on the file system\n InputStream is = null;\n String path = CmsFileUtil.normalizePath(url);\n File file = new File(path);\n try {\n // try to load the resource bundle from a file, NOT with the resource loader first\n // this is important since using #getResourceAsStream() may return cached results,\n // for example Tomcat by default does cache all resources loaded by the class loader\n // this means a changed resource bundle file is not loaded\n is = new FileInputStream(file);\n } catch (IOException ex) {\n // this will happen if the resource is contained for example in a .jar file\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n } catch (AccessControlException acex) {\n // fixed bug #1550\n // this will happen if the resource is contained for example in a .jar file\n // and security manager is turned on.\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n }\n if (is != null) {\n result = new CmsPropertyResourceBundle(is);\n }\n }\n } catch (IOException ex) {\n // can't localized these message since this may lead to a chicken-egg problem\n MissingResourceException mre = new MissingResourceException(\n \"Failed to load bundle '\" + localizedName + \"'\",\n localizedName,\n \"\");\n mre.initCause(ex);\n throw mre;\n }\n\n return result;\n }",
"public void addRequiredBundles(Set<String> bundles) {\n\t\t// TODO manage transitive dependencies\n\t\t// don't require self\n\t\tSet<String> bundlesToMerge;\n\t\tString bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME);\n\t\tif (bundleName != null) {\n\t\t\tint idx = bundleName.indexOf(';');\n\t\t\tif (idx >= 0) {\n\t\t\t\tbundleName = bundleName.substring(0, idx);\n\t\t\t}\n\t\t}\n\t\tif (bundleName != null && bundles.contains(bundleName)\n\t\t\t\t|| projectName != null && bundles.contains(projectName)) {\n\t\t\tbundlesToMerge = new LinkedHashSet<String>(bundles);\n\t\t\tbundlesToMerge.remove(bundleName);\n\t\t\tbundlesToMerge.remove(projectName);\n\t\t} else {\n\t\t\tbundlesToMerge = bundles;\n\t\t}\n\t\tString s = (String) getMainAttributes().get(REQUIRE_BUNDLE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(REQUIRE_BUNDLE, result);\n\t}",
"@DELETE\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response removeCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam(\"name\") final String organizationId, final String corporateGroupId){\n LOG.info(\"Got an remove a corporate groupId prefix request for organization \" + organizationId +\".\");\n if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){\n throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());\n }\n\n if(corporateGroupId == null || corporateGroupId.isEmpty()){\n LOG.error(\"No corporate GroupId to remove!\");\n return Response.serverError().status(HttpStatus.BAD_REQUEST_400).build();\n }\n\n getOrganizationHandler().removeCorporateGroupId(organizationId, corporateGroupId);\n\n return Response.ok(\"done\").build();\n }",
"private void setTableAliasForClassDescriptor(ClassDescriptor aCld, TableAlias anAlias)\r\n {\r\n if (m_cldToAlias.get(aCld) == null)\r\n {\r\n m_cldToAlias.put(aCld, anAlias);\r\n } \r\n }",
"public void appointTempoMaster(int deviceNumber) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n appointTempoMaster(update);\n }",
"public static double[][] invert(double[][] matrix) {\n\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tLUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = lu.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}"
] |
Performs a streaming request against a Stitch app server determined by the deployment model
of the underlying app. Throws a Stitch specific exception if the request fails.
@param stitchReq the request to perform.
@return an {@link EventStream} that will provide response events. | [
"@Override\n public EventStream doStreamRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doStreamRequestUrl(stitchReq, getHostname());\n }"
] | [
"@Override\n protected void denyImportDeclaration(ImportDeclaration importDeclaration) {\n LOG.debug(\"CXFImporter destroy a proxy for \" + importDeclaration);\n ServiceRegistration serviceRegistration = map.get(importDeclaration);\n serviceRegistration.unregister();\n\n // set the importDeclaration has unhandled\n super.unhandleImportDeclaration(importDeclaration);\n\n map.remove(importDeclaration);\n }",
"public void delete() {\r\n URL url = DEVICE_PIN_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\r\n BoxAPIResponse response = request.send();\r\n response.disconnect();\r\n }",
"private void readBitmap() {\n // (sub)image position & size.\n header.currentFrame.ix = readShort();\n header.currentFrame.iy = readShort();\n header.currentFrame.iw = readShort();\n header.currentFrame.ih = readShort();\n\n int packed = read();\n // 1 - local color table flag interlace\n boolean lctFlag = (packed & 0x80) != 0;\n int lctSize = (int) Math.pow(2, (packed & 0x07) + 1);\n // 3 - sort flag\n // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color\n // table size\n header.currentFrame.interlace = (packed & 0x40) != 0;\n if (lctFlag) {\n // Read table.\n header.currentFrame.lct = readColorTable(lctSize);\n } else {\n // No local color table.\n header.currentFrame.lct = null;\n }\n\n // Save this as the decoding position pointer.\n header.currentFrame.bufferFrameStart = rawData.position();\n\n // False decode pixel data to advance buffer.\n skipImageData();\n\n if (err()) {\n return;\n }\n\n header.frameCount++;\n // Add image to frame.\n header.frames.add(header.currentFrame);\n }",
"public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException {\n return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType );\n }",
"protected static boolean isMaskCompatibleWithRange(long value, long upperValue, long maskValue, long maxValue) {\n\t\tif(value == upperValue || maskValue == maxValue || maskValue == 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\t//algorithm:\n\t\t//here we find the highest bit that is part of the range, highestDifferingBitInRange (ie changes from lower to upper)\n\t\t//then we find the highest bit in the mask that is 1 that is the same or below highestDifferingBitInRange (if such a bit exists)\n\t\t\n\t\t//this gives us the highest bit that is part of the masked range (ie changes from lower to upper after applying the mask)\n\t\t//if this latter bit exists, then any bit below it in the mask must be 1 to include the entire range.\n\t\t\n\t\tlong differing = value ^ upperValue;\n\t\tboolean foundDiffering = (differing != 0);\n\t\tboolean differingIsLowestBit = (differing == 1);\n\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\tint highestDifferingBitInRange = Long.numberOfLeadingZeros(differing);\n\t\t\tlong maskMask = ~0L >>> highestDifferingBitInRange;\n\t\t\tlong differingMasked = maskValue & maskMask;\n\t\t\tfoundDiffering = (differingMasked != 0);\n\t\t\tdifferingIsLowestBit = (differingMasked == 1);\n\t\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\t\t//anything below highestDifferingBitMasked in the mask must be ones\n\t\t\t\t//Also, if we have masked out any 1 bit in the original, then anything that we do not mask out that follows must be all 1s\n\t\t\t\tint highestDifferingBitMasked = Long.numberOfLeadingZeros(differingMasked);\n\t\t\t\tlong hostMask = ~0L >>> (highestDifferingBitMasked + 1);//for the first mask bit that is 1, all bits that follow must also be 1\n\t\t\t\tif((maskValue & hostMask) != hostMask) { //check if all ones below\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif(highestDifferingBitMasked > highestDifferingBitInRange) {\n\t\t\t\t\t//We have masked out a 1 bit, so we need to check that all bits in upper value that we do not mask out are also 1 bits, otherwise we end up missing values in the masked range\n\t\t\t\t\t//This check is unnecessary for prefix-length subnets, only non-standard ranges might fail this check.\n\t\t\t\t\t//For instance, if we have range 0000 to 1010\n\t\t\t\t\t//and we mask upper and lower with 0111\n\t\t\t\t\t//we get 0000 to 0010, but 0111 was in original range, and the mask of that value retains that value\n\t\t\t\t\t//so that value needs to be in final range, and it's not.\n\t\t\t\t\t//What went wrong is that we masked out the top bit, and any other bit that is not masked out must be 1.\n\t\t\t\t\t//To work, our original range needed to be 0000 to 1111, with the three 1s following the first masked-out 1\n\t\t\t\t\tlong hostMaskUpper = ~0L >>> highestDifferingBitMasked;\n\t\t\t\t\tif((upperValue & hostMaskUpper) != hostMaskUpper) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n //\n // Retrieve the LHS value\n //\n FieldType field = m_leftValue;\n Object lhs;\n\n if (field == null)\n {\n lhs = null;\n }\n else\n {\n lhs = container.getCurrentValue(field);\n switch (field.getDataType())\n {\n case DATE:\n {\n if (lhs != null)\n {\n lhs = DateHelper.getDayStartDate((Date) lhs);\n }\n break;\n }\n\n case DURATION:\n {\n if (lhs != null)\n {\n Duration dur = (Duration) lhs;\n lhs = dur.convertUnits(TimeUnit.HOURS, m_properties);\n }\n else\n {\n lhs = Duration.getInstance(0, TimeUnit.HOURS);\n }\n break;\n }\n\n case STRING:\n {\n lhs = lhs == null ? \"\" : lhs;\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n //\n // Retrieve the RHS values\n //\n Object[] rhs;\n if (m_symbolicValues == true)\n {\n rhs = processSymbolicValues(m_workingRightValues, container, promptValues);\n }\n else\n {\n rhs = m_workingRightValues;\n }\n\n //\n // Evaluate\n //\n boolean result;\n switch (m_operator)\n {\n case AND:\n case OR:\n {\n result = evaluateLogicalOperator(container, promptValues);\n break;\n }\n\n default:\n {\n result = m_operator.evaluate(lhs, rhs);\n break;\n }\n }\n\n return result;\n }",
"@Override\n\tpublic String getInputToParse(String completeInput, int offset, int completionOffset) {\n\t\tint fixedOffset = getOffsetIncludingWhitespace(completeInput, offset, Math.min(completeInput.length(), completionOffset));\n\t\treturn super.getInputToParse(completeInput, fixedOffset, completionOffset);\n\t}",
"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 ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }"
] |
Disallow the job type from being executed.
@param jobType the job type to disallow | [
"public void removeJobType(final Class<?> jobType) {\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n this.jobTypes.values().remove(jobType);\n }"
] | [
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal);\n }",
"public static clusterinstance[] get(nitro_service service) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tclusterinstance[] response = (clusterinstance[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String decodeUrlIso(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"ISO-8859-1\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\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 }",
"@Override\n @SuppressFBWarnings(value = \"UL_UNRELEASED_LOCK\", justification = \"False positive from FindBugs\")\n public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n checkContextInitialized();\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n return null;\n }\n if (contextual == null) {\n throw ContextLogger.LOG.contextualIsNull();\n }\n BeanIdentifier id = getId(contextual);\n ContextualInstance<T> beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n } else if (creationalContext != null) {\n LockedBean lock = null;\n try {\n if (multithreaded) {\n lock = beanStore.lock(id);\n beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n }\n }\n T instance = contextual.create(creationalContext);\n if (instance != null) {\n beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));\n beanStore.put(id, beanInstance);\n }\n return instance;\n } finally {\n if (lock != null) {\n lock.unlock();\n }\n }\n } else {\n return null;\n }\n }",
"public static String getAt(String text, IntRange range) {\n return getAt(text, (Range) range);\n }",
"@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> N getSceneRoot(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n\n return (N) m_sceneRoot;\n }",
"@Override\n public boolean setA(DMatrixRBlock A) {\n if( A.numRows < A.numCols )\n throw new IllegalArgumentException(\"Number of rows must be more than or equal to the number of columns. \" +\n \"Can't solve an underdetermined system.\");\n\n if( !decomposer.decompose(A))\n return false;\n\n this.QR = decomposer.getQR();\n\n return true;\n }",
"public DbOrganization getOrganization(final DbArtifact dbArtifact) {\n final DbModule module = getModule(dbArtifact);\n\n if(module == null || module.getOrganization() == null){\n return null;\n }\n\n return repositoryHandler.getOrganization(module.getOrganization());\n }"
] |
Attempts exclusive acquisition with a max wait time.
@param permit - the permit Integer for this operation. May not be {@code null}.
@param timeout - the time value to wait for acquiring the lock
@param unit - See {@code TimeUnit} for valid values
@return {@code boolean} true on success. | [
"boolean lock(final Integer permit, final long timeout, final TimeUnit unit) {\n boolean result = false;\n try {\n result = lockInterruptibly(permit, timeout, unit);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n return result;\n }"
] | [
"private void emitStatusLine(AggregatedResultEvent result, TestStatus status, long timeMillis) throws IOException {\n final StringBuilder line = new StringBuilder();\n\n line.append(shortTimestamp(result.getStartTimestamp()));\n line.append(Strings.padEnd(statusNames.get(status), 8, ' '));\n line.append(formatDurationInSeconds(timeMillis));\n if (forkedJvmCount > 1) {\n line.append(String.format(Locale.ROOT, jvmIdFormat, result.getSlave().id));\n }\n line.append(\" | \");\n\n line.append(formatDescription(result.getDescription()));\n if (!result.isSuccessful()) {\n line.append(FAILURE_MARKER);\n }\n line.append(\"\\n\");\n\n if (showThrowable) {\n // GH-82 (cause for ignored tests). \n if (status == TestStatus.IGNORED && result instanceof AggregatedTestResultEvent) {\n final StringWriter sw = new StringWriter();\n PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH);\n pos.write(\"Cause: \");\n pos.write(((AggregatedTestResultEvent) result).getCauseForIgnored());\n pos.completeLine();\n line.append(sw.toString());\n }\n\n final List<FailureMirror> failures = result.getFailures();\n if (!failures.isEmpty()) {\n final StringWriter sw = new StringWriter();\n PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH);\n int count = 0;\n for (FailureMirror fm : failures) {\n count++;\n if (fm.isAssumptionViolation()) {\n pos.write(String.format(Locale.ROOT, \n \"Assumption #%d: %s\",\n count, MoreObjects.firstNonNull(fm.getMessage(), \"(no message)\")));\n } else {\n pos.write(String.format(Locale.ROOT, \n \"Throwable #%d: %s\",\n count,\n showStackTraces ? filterStackTrace(fm.getTrace()) : fm.getThrowableString()));\n }\n }\n pos.completeLine();\n if (sw.getBuffer().length() > 0) {\n line.append(sw.toString());\n }\n }\n }\n\n logShort(line);\n }",
"private String getCacheFormatEntry() throws IOException {\n ZipEntry zipEntry = zipFile.getEntry(CACHE_FORMAT_ENTRY);\n InputStream is = zipFile.getInputStream(zipEntry);\n try {\n Scanner s = new Scanner(is, \"UTF-8\").useDelimiter(\"\\\\A\");\n String tag = null;\n if (s.hasNext()) tag = s.next();\n return tag;\n } finally {\n is.close();\n }\n }",
"public static hanode_routemonitor6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor6_binding obj = new hanode_routemonitor6_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor6_binding response[] = (hanode_routemonitor6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String createCustomExpressionInvocationText(CustomExpression customExpression, String customExpName, boolean usePreviousFieldValues) {\n String stringExpression;\n if (customExpression instanceof DJSimpleExpression) {\n DJSimpleExpression varexp = (DJSimpleExpression) customExpression;\n String symbol;\n switch (varexp.getType()) {\n case DJSimpleExpression.TYPE_FIELD:\n symbol = \"F\";\n break;\n case DJSimpleExpression.TYPE_VARIABLE:\n symbol = \"V\";\n break;\n case DJSimpleExpression.TYPE_PARAMATER:\n symbol = \"P\";\n break;\n default:\n throw new DJException(\"Invalid DJSimpleExpression, type must be FIELD, VARIABLE or PARAMETER\");\n }\n stringExpression = \"$\" + symbol + \"{\" + varexp.getVariableName() + \"}\";\n\n } else {\n String fieldsMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentFields()\";\n if (usePreviousFieldValues) {\n fieldsMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getPreviousFields()\";\n }\n\n String parametersMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentParams()\";\n String variablesMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentVariables()\";\n\n stringExpression = \"((\" + CustomExpression.class.getName() + \")$P{REPORT_PARAMETERS_MAP}.get(\\\"\" + customExpName + \"\\\")).\"\n + CustomExpression.EVAL_METHOD_NAME + \"( \" + fieldsMap + \", \" + variablesMap + \", \" + parametersMap + \" )\";\n }\n\n return stringExpression;\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}",
"@Override\n public String getPartialFilterSelector() {\n return (def.selector != null) ? def.selector.toString() : null;\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 boolean getEnterpriseFlag(int index)\n {\n return (BooleanHelper.getBoolean((Boolean) getCachedValue(selectField(TaskFieldLists.ENTERPRISE_FLAG, index))));\n }",
"public static base_response add(nitro_service client, gslbservice resource) throws Exception {\n\t\tgslbservice addresource = new gslbservice();\n\t\taddresource.servicename = resource.servicename;\n\t\taddresource.cnameentry = resource.cnameentry;\n\t\taddresource.ip = resource.ip;\n\t\taddresource.servername = resource.servername;\n\t\taddresource.servicetype = resource.servicetype;\n\t\taddresource.port = resource.port;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.publicport = resource.publicport;\n\t\taddresource.maxclient = resource.maxclient;\n\t\taddresource.healthmonitor = resource.healthmonitor;\n\t\taddresource.sitename = resource.sitename;\n\t\taddresource.state = resource.state;\n\t\taddresource.cip = resource.cip;\n\t\taddresource.cipheader = resource.cipheader;\n\t\taddresource.sitepersistence = resource.sitepersistence;\n\t\taddresource.cookietimeout = resource.cookietimeout;\n\t\taddresource.siteprefix = resource.siteprefix;\n\t\taddresource.clttimeout = resource.clttimeout;\n\t\taddresource.svrtimeout = resource.svrtimeout;\n\t\taddresource.maxbandwidth = resource.maxbandwidth;\n\t\taddresource.downstateflush = resource.downstateflush;\n\t\taddresource.maxaaausers = resource.maxaaausers;\n\t\taddresource.monthreshold = resource.monthreshold;\n\t\taddresource.hashid = resource.hashid;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.appflowlog = resource.appflowlog;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Produces the Soundex key for the given string. | [
"public static String soundex(String str) {\n if (str.length() < 1)\n return \"\"; // no soundex key for the empty string (could use 000)\n \n char[] key = new char[4];\n key[0] = str.charAt(0);\n int pos = 1;\n char prev = '0';\n for (int ix = 1; ix < str.length() && pos < 4; ix++) {\n char ch = str.charAt(ix);\n int charno;\n if (ch >= 'A' && ch <= 'Z')\n charno = ch - 'A';\n else if (ch >= 'a' && ch <= 'z')\n charno = ch - 'a';\n else\n continue;\n\n if (number[charno] != '0' && number[charno] != prev)\n key[pos++] = number[charno];\n prev = number[charno];\n }\n\n for ( ; pos < 4; pos++)\n key[pos] = '0';\n\n return new String(key);\n }"
] | [
"public boolean uploadConfigurationAndProfile(String fileName, String odoImport) {\n File file = new File(fileName);\n MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();\n FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);\n multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n multipartEntityBuilder.addPart(\"fileData\", fileBody);\n multipartEntityBuilder.addTextBody(\"odoImport\", odoImport);\n try {\n JSONObject response = new JSONObject(doMultipartPost(BASE_BACKUP_PROFILE + \"/\" + uriEncode(this._profileName) + \"/\" + this._clientId, multipartEntityBuilder));\n if (response.length() == 0) {\n return true;\n } else {\n return false;\n }\n } catch (Exception e) {\n return false;\n }\n }",
"void lockInterruptibly(final Integer permit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n sync.acquireInterruptibly(permit);\n }",
"public final void setFindDetails(boolean findDetails) {\n this.findDetails.set(findDetails);\n if (findDetails) {\n primeCache(); // Get details for any tracks that were already loaded on players.\n } else {\n // Inform our listeners, on the proper thread, that the detailed waveforms are no longer available\n final Set<DeckReference> dyingCache = new HashSet<DeckReference>(detailHotCache.keySet());\n detailHotCache.clear();\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingCache) {\n deliverWaveformDetailUpdate(deck.player, null);\n }\n }\n });\n }\n }",
"public boolean matchesWithMask(IPAddressSection other, IPAddressSection mask) {\n\t\tcheckMaskSectionCount(mask);\n\t\tcheckSectionCount(other);\n\t\tint divCount = getSegmentCount();\n\t\tfor(int i = 0; i < divCount; i++) {\n\t\t\tIPAddressSegment div = getSegment(i);\n\t\t\tIPAddressSegment maskSegment = mask.getSegment(i);\n\t\t\tIPAddressSegment otherSegment = other.getSegment(i);\n\t\t\tif(!div.matchesWithMask(\n\t\t\t\t\totherSegment.getSegmentValue(), \n\t\t\t\t\totherSegment.getUpperSegmentValue(), \n\t\t\t\t\tmaskSegment.getSegmentValue())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"public static boolean isTemplatePath(String string) {\n int sz = string.length();\n if (sz == 0) {\n return true;\n }\n for (int i = 0; i < sz; ++i) {\n char c = string.charAt(i);\n switch (c) {\n case ' ':\n case '\\t':\n case '\\b':\n case '<':\n case '>':\n case '(':\n case ')':\n case '[':\n case ']':\n case '{':\n case '}':\n case '!':\n case '@':\n case '#':\n case '*':\n case '?':\n case '%':\n case '|':\n case ',':\n case ':':\n case ';':\n case '^':\n case '&':\n return false;\n }\n }\n return true;\n }",
"public double areaSquared(HalfEdge hedge0, HalfEdge hedge1) {\n Point3d p0 = hedge0.tail().pnt;\n Point3d p1 = hedge0.head().pnt;\n Point3d p2 = hedge1.head().pnt;\n\n double dx1 = p1.x - p0.x;\n double dy1 = p1.y - p0.y;\n double dz1 = p1.z - p0.z;\n\n double dx2 = p2.x - p0.x;\n double dy2 = p2.y - p0.y;\n double dz2 = p2.z - p0.z;\n\n double x = dy1 * dz2 - dz1 * dy2;\n double y = dz1 * dx2 - dx1 * dz2;\n double z = dx1 * dy2 - dy1 * dx2;\n\n return x * x + y * y + z * z;\n }",
"public void ifHasName(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n\r\n if ((name != null) && (name.length() > 0))\r\n {\r\n generate(template);\r\n }\r\n }",
"private void populateDefaultSettings(Record record, ProjectProperties properties) throws MPXJException\n {\n properties.setDefaultDurationUnits(record.getTimeUnit(0));\n properties.setDefaultDurationIsFixed(record.getNumericBoolean(1));\n properties.setDefaultWorkUnits(record.getTimeUnit(2));\n properties.setMinutesPerDay(Double.valueOf(NumberHelper.getDouble(record.getFloat(3)) * 60));\n properties.setMinutesPerWeek(Double.valueOf(NumberHelper.getDouble(record.getFloat(4)) * 60));\n properties.setDefaultStandardRate(record.getRate(5));\n properties.setDefaultOvertimeRate(record.getRate(6));\n properties.setUpdatingTaskStatusUpdatesResourceStatus(record.getNumericBoolean(7));\n properties.setSplitInProgressTasks(record.getNumericBoolean(8));\n }",
"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 }"
] |
Assign target number of partitions per node to specific node IDs. Then,
separates Nodes into donorNodes and stealerNodes based on whether the
node needs to donate or steal primary partitions.
@param nextCandidateCluster
@param numPartitionsPerNodePerZone
@return a Pair. First element is donorNodes, second element is
stealerNodes. Each element in the pair is a HashMap of Node to
Integer where the integer value is the number of partitions to
store. | [
"public static Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>\n getDonorsAndStealersForBalance(final Cluster nextCandidateCluster,\n Map<Integer, List<Integer>> numPartitionsPerNodePerZone) {\n HashMap<Node, Integer> donorNodes = Maps.newHashMap();\n HashMap<Node, Integer> stealerNodes = Maps.newHashMap();\n\n HashMap<Integer, Integer> numNodesAssignedInZone = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n numNodesAssignedInZone.put(zoneId, 0);\n }\n for(Node node: nextCandidateCluster.getNodes()) {\n int zoneId = node.getZoneId();\n\n int offset = numNodesAssignedInZone.get(zoneId);\n numNodesAssignedInZone.put(zoneId, offset + 1);\n\n int numPartitions = numPartitionsPerNodePerZone.get(zoneId).get(offset);\n\n if(numPartitions < node.getNumberOfPartitions()) {\n donorNodes.put(node, numPartitions);\n } else if(numPartitions > node.getNumberOfPartitions()) {\n stealerNodes.put(node, numPartitions);\n }\n }\n\n // Print out donor/stealer information\n for(Node node: donorNodes.keySet()) {\n System.out.println(\"Donor Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + donorNodes.get(node));\n }\n for(Node node: stealerNodes.keySet()) {\n System.out.println(\"Stealer Node: \" + node.getId() + \", zoneId \" + node.getZoneId()\n + \", numPartitions \" + node.getNumberOfPartitions()\n + \", target number of partitions \" + stealerNodes.get(node));\n }\n\n return new Pair<HashMap<Node, Integer>, HashMap<Node, Integer>>(donorNodes, stealerNodes);\n }"
] | [
"public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {\n if (!t1.getJavaClass().equals(t2.getJavaClass())) {\n return false;\n }\n if (!compareAnnotated(t1, t2)) {\n return false;\n }\n\n if (t1.getFields().size() != t2.getFields().size()) {\n return false;\n }\n Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();\n for (AnnotatedField<?> f : t2.getFields()) {\n fields.put(f.getJavaMember(), f);\n }\n for (AnnotatedField<?> f : t1.getFields()) {\n if (fields.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n if (t1.getMethods().size() != t2.getMethods().size()) {\n return false;\n }\n Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();\n for (AnnotatedMethod<?> f : t2.getMethods()) {\n methods.put(f.getJavaMember(), f);\n }\n for (AnnotatedMethod<?> f : t1.getMethods()) {\n if (methods.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n if (t1.getConstructors().size() != t2.getConstructors().size()) {\n return false;\n }\n Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>();\n for (AnnotatedConstructor<?> f : t2.getConstructors()) {\n constructors.put(f.getJavaMember(), f);\n }\n for (AnnotatedConstructor<?> f : t1.getConstructors()) {\n if (constructors.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n\n }",
"public void parseRawValue(String value)\n {\n int valueIndex = 0;\n int elementIndex = 0;\n m_elements.clear();\n while (valueIndex < value.length() && elementIndex < m_elements.size())\n {\n int elementLength = m_lengths.get(elementIndex).intValue();\n if (elementIndex > 0)\n {\n m_elements.add(m_separators.get(elementIndex - 1));\n }\n int endIndex = valueIndex + elementLength;\n if (endIndex > value.length())\n {\n endIndex = value.length();\n }\n String element = value.substring(valueIndex, endIndex);\n m_elements.add(element);\n valueIndex += elementLength;\n elementIndex++;\n }\n }",
"public static void endTrack(final String title){\r\n if(isClosed){ return; }\r\n //--Make Task\r\n final long timestamp = System.currentTimeMillis();\r\n Runnable endTrack = new Runnable(){\r\n public void run(){\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n //(check name match)\r\n String expected = titleStack.pop();\r\n if(!expected.equalsIgnoreCase(title)){\r\n throw new IllegalArgumentException(\"Track names do not match: expected: \" + expected + \" found: \" + title);\r\n }\r\n //(decrement depth)\r\n depth -= 1;\r\n //(send signal)\r\n handlers.process(null, MessageType.END_TRACK, depth, timestamp);\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n long threadId = Thread.currentThread().getId();\r\n attemptThreadControl( threadId, endTrack );\r\n } else {\r\n //(case: no threading)\r\n endTrack.run();\r\n }\r\n }",
"public static appqoepolicy get(nitro_service service, String name) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\tobj.set_name(name);\n\t\tappqoepolicy response = (appqoepolicy) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private String dbProp(String name) {\n\n String dbType = m_setupBean.getDatabase();\n Object prop = m_setupBean.getDatabaseProperties().get(dbType).get(dbType + \".\" + name);\n if (prop == null) {\n return \"\";\n }\n return prop.toString();\n }",
"public void read(File file, Table table) throws IOException\n {\n //System.out.println(\"Reading \" + file.getName());\n InputStream is = null;\n try\n {\n is = new FileInputStream(file);\n read(is, table);\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n }\n }",
"public CollectionRequest<Team> users(String team) {\n \n String path = String.format(\"/teams/%s/users\", team);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"public static Set<Annotation> filterInterceptorBindings(BeanManagerImpl beanManager, Collection<Annotation> annotations) {\n Set<Annotation> interceptorBindings = new InterceptorBindingSet(beanManager);\n for (Annotation annotation : annotations) {\n if (beanManager.isInterceptorBinding(annotation.annotationType())) {\n interceptorBindings.add(annotation);\n }\n }\n return interceptorBindings;\n }",
"public static GVRMesh createQuad(GVRContext gvrContext, float width, float height) {\n GVRMesh mesh = new GVRMesh(gvrContext);\n\n float[] vertices = { width * -0.5f, height * 0.5f, 0.0f, width * -0.5f,\n height * -0.5f, 0.0f, width * 0.5f, height * 0.5f, 0.0f,\n width * 0.5f, height * -0.5f, 0.0f };\n mesh.setVertices(vertices);\n\n final float[] normals = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f, 1.0f };\n mesh.setNormals(normals);\n\n final float[] texCoords = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,\n 1.0f };\n mesh.setTexCoords(texCoords);\n\n char[] triangles = { 0, 1, 2, 1, 3, 2 };\n mesh.setIndices(triangles);\n\n return mesh;\n }"
] |
return currently-loaded Proctor instance, throwing IllegalStateException if not loaded | [
"private Proctor getProctorNotNull() {\n final Proctor proctor = proctorLoader.get();\n if (proctor == null) {\n throw new IllegalStateException(\"Proctor specification and/or text matrix has not been loaded\");\n }\n return proctor;\n }"
] | [
"public boolean getCritical()\n {\n Boolean critical = (Boolean) getCachedValue(TaskField.CRITICAL);\n if (critical == null)\n {\n Duration totalSlack = getTotalSlack();\n ProjectProperties props = getParentFile().getProjectProperties();\n int criticalSlackLimit = NumberHelper.getInt(props.getCriticalSlackLimit());\n if (criticalSlackLimit != 0 && totalSlack.getDuration() != 0 && totalSlack.getUnits() != TimeUnit.DAYS)\n {\n totalSlack = totalSlack.convertUnits(TimeUnit.DAYS, props);\n }\n critical = Boolean.valueOf(totalSlack.getDuration() <= criticalSlackLimit && NumberHelper.getInt(getPercentageComplete()) != 100 && ((getTaskMode() == TaskMode.AUTO_SCHEDULED) || (getDurationText() == null && getStartText() == null && getFinishText() == null)));\n set(TaskField.CRITICAL, critical);\n }\n return (BooleanHelper.getBoolean(critical));\n }",
"public static boolean isJavaLangType(String s) {\n\t\treturn getJavaDefaultTypes().contains(s) && Character.isUpperCase(s.charAt(0));\n\t}",
"public static final String vertexAsString(Vertex vertex, int depth, String withEdgesOfLabel)\n {\n StringBuilder sb = new StringBuilder();\n vertexAsString(vertex, depth, withEdgesOfLabel, sb, 0, new HashSet<>());\n return sb.toString();\n }",
"public static void composeThroughMask(Raster src, WritableRaster dst, Raster sel) {\n\t\tint x = src.getMinX();\n\t\tint y = src.getMinY();\n\t\tint w = src.getWidth();\n\t\tint h = src.getHeight();\n\n\t\tint srcRGB[] = null;\n\t\tint selRGB[] = null;\n\t\tint dstRGB[] = null;\n\n\t\tfor ( int i = 0; i < h; i++ ) {\n\t\t\tsrcRGB = src.getPixels(x, y, w, 1, srcRGB);\n\t\t\tselRGB = sel.getPixels(x, y, w, 1, selRGB);\n\t\t\tdstRGB = dst.getPixels(x, y, w, 1, dstRGB);\n\n\t\t\tint k = x;\n\t\t\tfor ( int j = 0; j < w; j++ ) {\n\t\t\t\tint sr = srcRGB[k];\n\t\t\t\tint dir = dstRGB[k];\n\t\t\t\tint sg = srcRGB[k+1];\n\t\t\t\tint dig = dstRGB[k+1];\n\t\t\t\tint sb = srcRGB[k+2];\n\t\t\t\tint dib = dstRGB[k+2];\n\t\t\t\tint sa = srcRGB[k+3];\n\t\t\t\tint dia = dstRGB[k+3];\n\n\t\t\t\tfloat a = selRGB[k+3]/255f;\n\t\t\t\tfloat ac = 1-a;\n\n\t\t\t\tdstRGB[k] = (int)(a*sr + ac*dir); \n\t\t\t\tdstRGB[k+1] = (int)(a*sg + ac*dig); \n\t\t\t\tdstRGB[k+2] = (int)(a*sb + ac*dib); \n\t\t\t\tdstRGB[k+3] = (int)(a*sa + ac*dia);\n\t\t\t\tk += 4;\n\t\t\t}\n\n\t\t\tdst.setPixels(x, y, w, 1, dstRGB);\n\t\t\ty++;\n\t\t}\n\t}",
"@Deprecated\r\n public InputStream getOriginalAsStream() throws IOException, FlickrException {\r\n if (originalFormat != null) {\r\n return getOriginalImageAsStream(\"_o.\" + originalFormat);\r\n }\r\n return getOriginalImageAsStream(DEFAULT_ORIGINAL_IMAGE_SUFFIX);\r\n }",
"private void populateProjectHeader(Record record, ProjectProperties properties) throws MPXJException\n {\n properties.setProjectTitle(record.getString(0));\n properties.setCompany(record.getString(1));\n properties.setManager(record.getString(2));\n properties.setDefaultCalendarName(record.getString(3));\n properties.setStartDate(record.getDateTime(4));\n properties.setFinishDate(record.getDateTime(5));\n properties.setScheduleFrom(record.getScheduleFrom(6));\n properties.setCurrentDate(record.getDateTime(7));\n properties.setComments(record.getString(8));\n properties.setCost(record.getCurrency(9));\n properties.setBaselineCost(record.getCurrency(10));\n properties.setActualCost(record.getCurrency(11));\n properties.setWork(record.getDuration(12));\n properties.setBaselineWork(record.getDuration(13));\n properties.setActualWork(record.getDuration(14));\n properties.setWork2(record.getPercentage(15));\n properties.setDuration(record.getDuration(16));\n properties.setBaselineDuration(record.getDuration(17));\n properties.setActualDuration(record.getDuration(18));\n properties.setPercentageComplete(record.getPercentage(19));\n properties.setBaselineStart(record.getDateTime(20));\n properties.setBaselineFinish(record.getDateTime(21));\n properties.setActualStart(record.getDateTime(22));\n properties.setActualFinish(record.getDateTime(23));\n properties.setStartVariance(record.getDuration(24));\n properties.setFinishVariance(record.getDuration(25));\n properties.setSubject(record.getString(26));\n properties.setAuthor(record.getString(27));\n properties.setKeywords(record.getString(28));\n }",
"public void setAccordion(boolean accordion) {\n getElement().setAttribute(\"data-collapsible\", accordion ? CssName.ACCORDION : CssName.EXPANDABLE);\n reload();\n }",
"protected I_CmsSearchConfigurationFacetRange parseRangeFacet(JSONObject rangeFacetObject) {\n\n try {\n String range = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_RANGE);\n String name = parseOptionalStringValue(rangeFacetObject, JSON_KEY_FACET_NAME);\n String label = parseOptionalStringValue(rangeFacetObject, JSON_KEY_FACET_LABEL);\n Integer minCount = parseOptionalIntValue(rangeFacetObject, JSON_KEY_FACET_MINCOUNT);\n String start = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_START);\n String end = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_END);\n String gap = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_GAP);\n List<String> sother = parseOptionalStringValues(rangeFacetObject, JSON_KEY_RANGE_FACET_OTHER);\n Boolean hardEnd = parseOptionalBooleanValue(rangeFacetObject, JSON_KEY_RANGE_FACET_HARDEND);\n List<I_CmsSearchConfigurationFacetRange.Other> other = null;\n if (sother != null) {\n other = new ArrayList<I_CmsSearchConfigurationFacetRange.Other>(sother.size());\n for (String so : sother) {\n try {\n I_CmsSearchConfigurationFacetRange.Other o = I_CmsSearchConfigurationFacetRange.Other.valueOf(\n so);\n other.add(o);\n } catch (Exception e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_INVALID_OTHER_OPTION_1, so), e);\n }\n }\n }\n Boolean isAndFacet = parseOptionalBooleanValue(rangeFacetObject, JSON_KEY_FACET_ISANDFACET);\n List<String> preselection = parseOptionalStringValues(rangeFacetObject, JSON_KEY_FACET_PRESELECTION);\n Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n rangeFacetObject,\n JSON_KEY_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetRange(\n range,\n start,\n end,\n gap,\n other,\n hardEnd,\n name,\n minCount,\n label,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (JSONException e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_RANGE_FACET_MANDATORY_KEY_MISSING_1,\n JSON_KEY_RANGE_FACET_RANGE\n + \", \"\n + JSON_KEY_RANGE_FACET_START\n + \", \"\n + JSON_KEY_RANGE_FACET_END\n + \", \"\n + JSON_KEY_RANGE_FACET_GAP),\n e);\n return null;\n }\n\n }",
"private boolean isSpecial(final char chr) {\n\t\treturn ((chr == '.') || (chr == '?') || (chr == '*') || (chr == '^') || (chr == '$') || (chr == '+')\n\t\t\t\t|| (chr == '[') || (chr == ']') || (chr == '(') || (chr == ')') || (chr == '|') || (chr == '\\\\')\n\t\t\t\t|| (chr == '&'));\n\t}"
] |
Use this API to fetch the statistics of all servicegroup_stats resources that are configured on netscaler. | [
"public static servicegroup_stats[] get(nitro_service service, options option) throws Exception{\n\t\tservicegroup_stats obj = new servicegroup_stats();\n\t\tservicegroup_stats[] response = (servicegroup_stats[])obj.stat_resources(service,option);\n\t\treturn response;\n\t}"
] | [
"public float get(int row, int col) {\n if (row < 0 || row > 3) {\n throw new IndexOutOfBoundsException(\"Index: \" + row + \", Size: 4\");\n }\n if (col < 0 || col > 3) {\n throw new IndexOutOfBoundsException(\"Index: \" + col + \", Size: 4\");\n }\n\n return m_data[row * 4 + col];\n }",
"public List<TimephasedWork> getCompleteWork(ProjectCalendar calendar, ResourceAssignment resourceAssignment, byte[] data)\n {\n LinkedList<TimephasedWork> list = new LinkedList<TimephasedWork>();\n\n if (calendar != null && data != null && data.length > 2 && MPPUtility.getShort(data, 0) > 0)\n {\n Date startDate = resourceAssignment.getStart();\n double finishTime = MPPUtility.getInt(data, 24);\n\n int blockCount = MPPUtility.getShort(data, 0);\n double previousCumulativeWork = 0;\n TimephasedWork previousAssignment = null;\n\n int index = 32;\n int currentBlock = 0;\n while (currentBlock < blockCount && index + 20 <= data.length)\n {\n double time = MPPUtility.getInt(data, index + 0);\n\n // If the start of this block is before the start of the assignment, or after the end of the assignment\n // the values don't make sense, so we'll just set the start of this block to be the start of the assignment.\n // This deals with an issue where odd timephased data like this was causing an MPP file to be read\n // extremely slowly.\n if (time < 0 || time > finishTime)\n {\n time = 0;\n }\n else\n {\n time /= 80;\n }\n Duration startWork = Duration.getInstance(time, TimeUnit.MINUTES);\n\n double currentCumulativeWork = (long) MPPUtility.getDouble(data, index + 4);\n double assignmentDuration = currentCumulativeWork - previousCumulativeWork;\n previousCumulativeWork = currentCumulativeWork;\n assignmentDuration /= 1000;\n Duration totalWork = Duration.getInstance(assignmentDuration, TimeUnit.MINUTES);\n time = (long) MPPUtility.getDouble(data, index + 12);\n time /= 125;\n time *= 6;\n Duration workPerDay = Duration.getInstance(time, TimeUnit.MINUTES);\n\n Date start;\n if (startWork.getDuration() == 0)\n {\n start = startDate;\n }\n else\n {\n start = calendar.getDate(startDate, startWork, true);\n }\n\n TimephasedWork assignment = new TimephasedWork();\n assignment.setStart(start);\n assignment.setAmountPerDay(workPerDay);\n assignment.setTotalAmount(totalWork);\n\n if (previousAssignment != null)\n {\n Date finish = calendar.getDate(startDate, startWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n\n list.add(assignment);\n previousAssignment = assignment;\n\n index += 20;\n ++currentBlock;\n }\n\n if (previousAssignment != null)\n {\n Duration finishWork = Duration.getInstance(finishTime / 80, TimeUnit.MINUTES);\n Date finish = calendar.getDate(startDate, finishWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n }\n\n return list;\n }",
"public void logError(String message, Object sender) {\n getEventManager().sendEvent(this, IErrorEvents.class, \"onError\", new Object[] { message, sender });\n }",
"public static <T> ServiceFuture<T> fromResponse(final Observable<ServiceResponse<T>> observable) {\n final ServiceFuture<T> serviceFuture = new ServiceFuture<>();\n serviceFuture.subscription = observable\n .last()\n .subscribe(new Action1<ServiceResponse<T>>() {\n @Override\n public void call(ServiceResponse<T> t) {\n serviceFuture.set(t.body());\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\n }",
"public Module generateBuildInfoModule(Run build, TaskListener listener, ArtifactoryConfigurator config, String buildName, String buildNumber, String timestamp) throws IOException {\n if (artifactsProps == null) {\n artifactsProps = ArrayListMultimap.create();\n }\n artifactsProps.put(\"build.name\", buildName);\n artifactsProps.put(\"build.number\", buildNumber);\n artifactsProps.put(\"build.timestamp\", timestamp);\n String artifactsPropsStr = ExtractorUtils.buildPropertiesString(artifactsProps);\n\n Properties buildInfoItemsProps = new Properties();\n buildInfoItemsProps.setProperty(\"build.name\", buildName);\n buildInfoItemsProps.setProperty(\"build.number\", buildNumber);\n buildInfoItemsProps.setProperty(\"build.timestamp\", timestamp);\n\n ArtifactoryServer server = config.getArtifactoryServer();\n CredentialsConfig preferredResolver = server.getDeployerCredentialsConfig();\n ArtifactoryDependenciesClient dependenciesClient = null;\n ArtifactoryBuildInfoClient propertyChangeClient = null;\n\n try {\n dependenciesClient = server.createArtifactoryDependenciesClient(\n preferredResolver.provideUsername(build.getParent()), preferredResolver.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy), listener);\n\n CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(config, server);\n propertyChangeClient = server.createArtifactoryClient(\n preferredDeployer.provideUsername(build.getParent()), preferredDeployer.providePassword(build.getParent()),\n server.createProxyConfiguration(Jenkins.getInstance().proxy));\n\n Module buildInfoModule = new Module();\n buildInfoModule.setId(imageTag.substring(imageTag.indexOf(\"/\") + 1));\n\n // If manifest and imagePath not found, return.\n if ((StringUtils.isEmpty(manifest) || StringUtils.isEmpty(imagePath)) && !findAndSetManifestFromArtifactory(server, dependenciesClient, listener)) {\n return buildInfoModule;\n }\n\n listener.getLogger().println(\"Fetching details of published docker layers from Artifactory...\");\n boolean includeVirtualReposSupported = propertyChangeClient.getArtifactoryVersion().isAtLeast(VIRTUAL_REPOS_SUPPORTED_VERSION);\n DockerLayers layers = createLayers(dependenciesClient, includeVirtualReposSupported);\n\n listener.getLogger().println(\"Tagging published docker layers with build properties in Artifactory...\");\n setDependenciesAndArtifacts(buildInfoModule, layers, artifactsPropsStr, buildInfoItemsProps,\n dependenciesClient, propertyChangeClient, server);\n setBuildInfoModuleProps(buildInfoModule);\n return buildInfoModule;\n } finally {\n if (dependenciesClient != null) {\n dependenciesClient.close();\n }\n if (propertyChangeClient != null) {\n propertyChangeClient.close();\n }\n }\n }",
"public void loadPhysics(String filename, GVRScene scene) throws IOException\n {\n GVRPhysicsLoader.loadPhysicsFile(getGVRContext(), filename, true, scene);\n }",
"public static cachepolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_policybinding_binding obj = new cachepolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_policybinding_binding response[] = (cachepolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static RelationType getInstance(Locale locale, String type)\n {\n int index = -1;\n\n String[] relationTypes = LocaleData.getStringArray(locale, LocaleData.RELATION_TYPES);\n for (int loop = 0; loop < relationTypes.length; loop++)\n {\n if (relationTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n RelationType result = null;\n if (index != -1)\n {\n result = RelationType.getInstance(index);\n }\n\n return (result);\n }",
"private RowKeyAndTuple createAndPutAssociationRowForInsert(Serializable key, PersistentCollection collection,\n\t\t\tAssociationPersister associationPersister, SharedSessionContractImplementor session, int i, Object entry) {\n\t\tRowKeyBuilder rowKeyBuilder = initializeRowKeyBuilder();\n\t\tTuple associationRow = new Tuple();\n\n\t\t// the collection has a surrogate key (see @CollectionId)\n\t\tif ( hasIdentifier ) {\n\t\t\tfinal Object identifier = collection.getIdentifier( entry, i );\n\t\t\tString[] names = { getIdentifierColumnName() };\n\t\t\tidentifierGridType.nullSafeSet( associationRow, identifier, names, session );\n\t\t}\n\n\t\tgetKeyGridType().nullSafeSet( associationRow, key, getKeyColumnNames(), session );\n\t\t// No need to write to where as we don't do where clauses in OGM :)\n\t\tif ( hasIndex ) {\n\t\t\tObject index = collection.getIndex( entry, i, this );\n\t\t\tindexGridType.nullSafeSet( associationRow, incrementIndexByBase( index ), getIndexColumnNames(), session );\n\t\t}\n\n\t\t// columns of referenced key\n\t\tfinal Object element = collection.getElement( entry );\n\t\tgetElementGridType().nullSafeSet( associationRow, element, getElementColumnNames(), session );\n\n\t\tRowKeyAndTuple result = new RowKeyAndTuple();\n\t\tresult.key = rowKeyBuilder.values( associationRow ).build();\n\t\tresult.tuple = associationRow;\n\n\t\tassociationPersister.getAssociation().put( result.key, result.tuple );\n\n\t\treturn result;\n\t}"
] |
Creates the final artifact name.
@return the artifact name | [
"public ArtifactName build() {\n String groupId = this.groupId;\n String artifactId = this.artifactId;\n String classifier = this.classifier;\n String packaging = this.packaging;\n String version = this.version;\n if (artifact != null && !artifact.isEmpty()) {\n final String[] artifactSegments = artifact.split(\":\");\n // groupId:artifactId:version[:packaging][:classifier].\n String value;\n switch (artifactSegments.length) {\n case 5:\n value = artifactSegments[4].trim();\n if (!value.isEmpty()) {\n classifier = value;\n }\n case 4:\n value = artifactSegments[3].trim();\n if (!value.isEmpty()) {\n packaging = value;\n }\n case 3:\n value = artifactSegments[2].trim();\n if (!value.isEmpty()) {\n version = value;\n }\n case 2:\n value = artifactSegments[1].trim();\n if (!value.isEmpty()) {\n artifactId = value;\n }\n case 1:\n value = artifactSegments[0].trim();\n if (!value.isEmpty()) {\n groupId = value;\n }\n }\n }\n return new ArtifactNameImpl(groupId, artifactId, classifier, packaging, version);\n }"
] | [
"public static org.jfrog.hudson.ArtifactoryServer prepareArtifactoryServer(String artifactoryServerID,\n ArtifactoryServer pipelineServer) {\n\n if (artifactoryServerID == null && pipelineServer == null) {\n return null;\n }\n if (artifactoryServerID != null && pipelineServer != null) {\n return null;\n }\n if (pipelineServer != null) {\n CredentialsConfig credentials = pipelineServer.createCredentialsConfig();\n\n return new org.jfrog.hudson.ArtifactoryServer(null, pipelineServer.getUrl(), credentials,\n credentials, pipelineServer.getConnection().getTimeout(), pipelineServer.isBypassProxy(), pipelineServer.getConnection().getRetry(), pipelineServer.getDeploymentThreads());\n }\n org.jfrog.hudson.ArtifactoryServer server = RepositoriesUtils.getArtifactoryServer(artifactoryServerID, RepositoriesUtils.getArtifactoryServers());\n if (server == null) {\n return null;\n }\n return server;\n }",
"private boolean shouldIgnore(String typeReference)\n {\n typeReference = typeReference.replace('/', '.').replace('\\\\', '.');\n return JavaClassIgnoreResolver.singletonInstance().matches(typeReference);\n }",
"protected void handleDeadSlop(SlopStorageEngine slopStorageEngine,\n Pair<ByteArray, Versioned<Slop>> keyAndVal) {\n Versioned<Slop> versioned = keyAndVal.getSecond();\n // If configured to delete the dead slop\n if(voldemortConfig.getAutoPurgeDeadSlops()) {\n slopStorageEngine.delete(keyAndVal.getFirst(), versioned.getVersion());\n\n if(getLogger().isDebugEnabled()) {\n getLogger().debug(\"Auto purging dead slop :\" + versioned.getValue());\n }\n } else {\n // Keep ignoring the dead slops\n if(getLogger().isDebugEnabled()) {\n getLogger().debug(\"Ignoring dead slop :\" + versioned.getValue());\n }\n }\n }",
"public static double Sin(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return x - (x * x * x) / 6D;\r\n } else {\r\n\r\n double mult = x * x * x;\r\n double fact = 6;\r\n double sign = 1;\r\n int factS = 5;\r\n double result = x - mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += sign * (mult / fact);\r\n sign *= -1;\r\n }\r\n\r\n return result;\r\n }\r\n }",
"public int getCostRateTableIndex()\n {\n Integer value = (Integer) getCachedValue(AssignmentField.COST_RATE_TABLE);\n return value == null ? 0 : value.intValue();\n }",
"protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }",
"public static <T> List<T> copyOf(T[] elements) {\n Preconditions.checkNotNull(elements);\n return ofInternal(elements.clone());\n }",
"public static final void setSize(UIObject o, Rect size) {\n o.setPixelSize(size.w, size.h);\n\n }",
"public Object selectElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return ((DList) this.query(predicate)).get(0);\r\n }"
] |
Returns the index descriptor definition of the given name if it exists.
@param name The name of the index
@return The index descriptor definition or <code>null</code> if there is no such index | [
"public IndexDescriptorDef getIndexDescriptor(String name)\r\n {\r\n IndexDescriptorDef indexDef = null;\r\n\r\n for (Iterator it = _indexDescriptors.iterator(); it.hasNext(); )\r\n {\r\n indexDef = (IndexDescriptorDef)it.next();\r\n if (indexDef.getName().equals(name))\r\n {\r\n return indexDef;\r\n }\r\n }\r\n return null;\r\n }"
] | [
"public static GVRTexture loadFutureCubemapTexture(\n GVRContext gvrContext, ResourceCache<GVRImage> textureCache,\n GVRAndroidResource resource, int priority,\n Map<String, Integer> faceIndexMap) {\n GVRTexture tex = new GVRTexture(gvrContext);\n GVRImage cached = textureCache.get(resource);\n if (cached != null)\n {\n Log.v(\"ASSET\", \"Future Texture: %s loaded from cache\", cached.getFileName());\n tex.setImage(cached);\n }\n else\n {\n AsyncCubemapTexture.get().loadTexture(gvrContext,\n CancelableCallbackWrapper.wrap(GVRCubemapImage.class, tex),\n resource, priority, faceIndexMap);\n\n }\n return tex;\n }",
"private void visitImplicitFirstFrame() {\n // There can be at most descriptor.length() + 1 locals\n int frameIndex = startFrame(0, descriptor.length() + 1, 0);\n if ((access & Opcodes.ACC_STATIC) == 0) {\n if ((access & ACC_CONSTRUCTOR) == 0) {\n frame[frameIndex++] = Frame.OBJECT | cw.addType(cw.thisName);\n } else {\n frame[frameIndex++] = Frame.UNINITIALIZED_THIS;\n }\n }\n int i = 1;\n loop: while (true) {\n int j = i;\n switch (descriptor.charAt(i++)) {\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n frame[frameIndex++] = Frame.INTEGER;\n break;\n case 'F':\n frame[frameIndex++] = Frame.FLOAT;\n break;\n case 'J':\n frame[frameIndex++] = Frame.LONG;\n break;\n case 'D':\n frame[frameIndex++] = Frame.DOUBLE;\n break;\n case '[':\n while (descriptor.charAt(i) == '[') {\n ++i;\n }\n if (descriptor.charAt(i) == 'L') {\n ++i;\n while (descriptor.charAt(i) != ';') {\n ++i;\n }\n }\n frame[frameIndex++] = Frame.type(cw, descriptor.substring(j, ++i));\n break;\n case 'L':\n while (descriptor.charAt(i) != ';') {\n ++i;\n }\n frame[frameIndex++] = Frame.OBJECT\n | cw.addType(descriptor.substring(j + 1, i++));\n break;\n default:\n break loop;\n }\n }\n frame[1] = frameIndex - 3;\n endFrame();\n }",
"public static Thread addShutdownHook(final Process process) {\n final Thread thread = new Thread(new Runnable() {\n @Override\n public void run() {\n if (process != null) {\n process.destroy();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n });\n thread.setDaemon(true);\n Runtime.getRuntime().addShutdownHook(thread);\n return thread;\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 }",
"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 base_responses delete(nitro_service client, String ciphergroupname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ciphergroupname != null && ciphergroupname.length > 0) {\n\t\t\tsslcipher deleteresources[] = new sslcipher[ciphergroupname.length];\n\t\t\tfor (int i=0;i<ciphergroupname.length;i++){\n\t\t\t\tdeleteresources[i] = new sslcipher();\n\t\t\t\tdeleteresources[i].ciphergroupname = ciphergroupname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Set<D> getMatchedDeclaration() {\n Set<D> bindedSet = new HashSet<D>();\n for (Map.Entry<ServiceReference<D>, Boolean> e : declarations.entrySet()) {\n if (e.getValue()) {\n bindedSet.add(getDeclaration(e.getKey()));\n }\n }\n return bindedSet;\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 }",
"@Override\n public void close() {\n status = TrStatus.CLOSED;\n try {\n node.close();\n } catch (IOException e) {\n log.error(\"Failed to close ephemeral node\");\n throw new IllegalStateException(e);\n }\n }"
] |
Use this API to fetch cachepolicylabel_binding resource of given name . | [
"public static cachepolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_binding obj = new cachepolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_binding response = (cachepolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public static lbvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_stats obj = new lbvserver_stats();\n\t\tobj.set_name(name);\n\t\tlbvserver_stats response = (lbvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"@PostConstruct\n public final void init() {\n this.cleanUpTimer = Executors.newScheduledThreadPool(1, timerTask -> {\n final Thread thread = new Thread(timerTask, \"Clean up old job records\");\n thread.setDaemon(true);\n return thread;\n });\n this.cleanUpTimer.scheduleAtFixedRate(this::cleanup, this.cleanupInterval, this.cleanupInterval,\n TimeUnit.SECONDS);\n }",
"public static java.util.Date newDateTime() {\n return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS);\n }",
"public static base_response unset(nitro_service client, responderparam resource, String[] args) throws Exception{\n\t\tresponderparam unsetresource = new responderparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"static String from(Class<?> entryClass) {\n List<String> tokens = tokenOf(entryClass);\n return fromTokens(tokens);\n }",
"public String getRecordSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String recSchema = schema.toString();\n return recSchema;\n }",
"public static SQLException create(String message, Throwable cause) {\n\t\tSQLException sqlException;\n\t\tif (cause instanceof SQLException) {\n\t\t\t// if the cause is another SQLException, pass alot of the SQL state\n\t\t\tsqlException = new SQLException(message, ((SQLException) cause).getSQLState());\n\t\t} else {\n\t\t\tsqlException = new SQLException(message);\n\t\t}\n\t\tsqlException.initCause(cause);\n\t\treturn sqlException;\n\t}",
"public final void cancelOld(\n final long starttimeThreshold, final long checkTimeThreshold, final String message) {\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.and(\n builder.equal(root.get(\"status\"), PrintJobStatus.Status.WAITING),\n builder.or(\n builder.lessThan(root.get(\"entry\").get(\"startTime\"), starttimeThreshold),\n builder.and(builder.isNotNull(root.get(\"lastCheckTime\")),\n builder.lessThan(root.get(\"lastCheckTime\"), checkTimeThreshold))\n )\n ));\n update.set(root.get(\"status\"), PrintJobStatus.Status.CANCELLED);\n update.set(root.get(\"error\"), message);\n getSession().createQuery(update).executeUpdate();\n }",
"private void updateDates(Task parentTask)\n {\n if (parentTask.hasChildTasks())\n {\n Date plannedStartDate = null;\n Date plannedFinishDate = null;\n\n for (Task task : parentTask.getChildTasks())\n {\n updateDates(task);\n plannedStartDate = DateHelper.min(plannedStartDate, task.getStart());\n plannedFinishDate = DateHelper.max(plannedFinishDate, task.getFinish());\n }\n\n parentTask.setStart(plannedStartDate);\n parentTask.setFinish(plannedFinishDate);\n }\n }"
] |
Creates a tar directory entry with defaults parameters.
@param dirName the directory name
@return dir entry with reasonable defaults | [
"static TarArchiveEntry defaultDirEntryWithName( final String dirName ) {\n TarArchiveEntry entry = new TarArchiveEntry(dirName, true);\n entry.setUserId(ROOT_UID);\n entry.setUserName(ROOT_NAME);\n entry.setGroupId(ROOT_UID);\n entry.setGroupName(ROOT_NAME);\n entry.setMode(TarArchiveEntry.DEFAULT_DIR_MODE);\n return entry;\n }"
] | [
"static void rethrowIrrecoverableConnectionFailures(IOException e) throws SlaveRegistrationException {\n Throwable cause = e;\n while ((cause = cause.getCause()) != null) {\n if (cause instanceof SaslException) {\n throw HostControllerLogger.ROOT_LOGGER.authenticationFailureUnableToConnect(cause);\n } else if (cause instanceof SSLHandshakeException) {\n throw HostControllerLogger.ROOT_LOGGER.sslFailureUnableToConnect(cause);\n } else if (cause instanceof SlaveRegistrationException) {\n throw (SlaveRegistrationException) cause;\n }\n }\n }",
"@Override\n\tpublic void close() {\n\t\tlogger.info(\"Finished processing.\");\n\t\tthis.timer.stop();\n\t\tthis.lastSeconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\tprintStatus();\n\t}",
"private void writeAssignments(Project project)\n {\n Project.Assignments assignments = m_factory.createProjectAssignments();\n project.setAssignments(assignments);\n List<Project.Assignments.Assignment> list = assignments.getAssignment();\n\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n list.add(writeAssignment(assignment));\n }\n\n //\n // Check to see if we have any tasks that have a percent complete value\n // but do not have resource assignments. If any exist, then we must\n // write a dummy resource assignment record to ensure that the MSPDI\n // file shows the correct percent complete amount for the task.\n //\n ProjectConfig config = m_projectFile.getProjectConfig();\n boolean autoUniqueID = config.getAutoAssignmentUniqueID();\n if (!autoUniqueID)\n {\n config.setAutoAssignmentUniqueID(true);\n }\n\n for (Task task : m_projectFile.getTasks())\n {\n double percentComplete = NumberHelper.getDouble(task.getPercentageComplete());\n if (percentComplete != 0 && task.getResourceAssignments().isEmpty() == true)\n {\n ResourceAssignment dummy = new ResourceAssignment(m_projectFile, task);\n Duration duration = task.getDuration();\n if (duration == null)\n {\n duration = Duration.getInstance(0, TimeUnit.HOURS);\n }\n double durationValue = duration.getDuration();\n TimeUnit durationUnits = duration.getUnits();\n double actualWork = (durationValue * percentComplete) / 100;\n double remainingWork = durationValue - actualWork;\n\n dummy.setResourceUniqueID(NULL_RESOURCE_ID);\n dummy.setWork(duration);\n dummy.setActualWork(Duration.getInstance(actualWork, durationUnits));\n dummy.setRemainingWork(Duration.getInstance(remainingWork, durationUnits));\n \n // Without this, MS Project will mark a 100% complete milestone as 99% complete\n if (percentComplete == 100 && duration.getDuration() == 0)\n { \n dummy.setActualFinish(task.getActualStart());\n }\n \n list.add(writeAssignment(dummy));\n }\n }\n\n config.setAutoAssignmentUniqueID(autoUniqueID);\n }",
"private static void firstDotConstellation(int[] dollarPositions, int[] dotPositions, int nestingLevel) {\n int i = 0;\n int unassigned = dotPositions.length - nestingLevel;\n\n for (; i < unassigned; ++i) {\n dotPositions[i] = -1;\n }\n\n for (; i < dotPositions.length; ++i) {\n dotPositions[i] = dollarPositions[i];\n }\n }",
"private static void listTimephasedWork(ResourceAssignment assignment)\n {\n Task task = assignment.getTask();\n int days = (int) ((task.getFinish().getTime() - task.getStart().getTime()) / (1000 * 60 * 60 * 24)) + 1;\n if (days > 1)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yy\");\n\n TimescaleUtility timescale = new TimescaleUtility();\n ArrayList<DateRange> dates = timescale.createTimescale(task.getStart(), TimescaleUnits.DAYS, days);\n TimephasedUtility timephased = new TimephasedUtility();\n\n ArrayList<Duration> durations = timephased.segmentWork(assignment.getCalendar(), assignment.getTimephasedWork(), TimescaleUnits.DAYS, dates);\n for (DateRange range : dates)\n {\n System.out.print(df.format(range.getStart()) + \"\\t\");\n }\n System.out.println();\n for (Duration duration : durations)\n {\n System.out.print(duration.toString() + \" \".substring(0, 7) + \"\\t\");\n }\n System.out.println();\n }\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 PoolingHttpClientConnectionManager createConnectionMgr() {\n PoolingHttpClientConnectionManager connectionMgr;\n\n // prepare SSLContext\n SSLContext sslContext = buildSslContext();\n ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();\n // we allow to disable host name verification against CA certificate,\n // notice: in general this is insecure and should be avoided in production,\n // (this type of configuration is useful for development purposes)\n boolean noHostVerification = false;\n LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(\n sslContext,\n noHostVerification ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier()\n );\n Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()\n .register(\"http\", plainsf)\n .register(\"https\", sslsf)\n .build();\n connectionMgr = new PoolingHttpClientConnectionManager(r, null, null,\n null, connectionPoolTimeToLive, TimeUnit.SECONDS);\n\n connectionMgr.setMaxTotal(maxConnectionsTotal);\n connectionMgr.setDefaultMaxPerRoute(maxConnectionsPerRoute);\n HttpHost localhost = new HttpHost(\"localhost\", 80);\n connectionMgr.setMaxPerRoute(new HttpRoute(localhost), maxConnectionsPerRoute);\n return connectionMgr;\n }",
"public void refreshCredentials() {\n if (this.credsProvider == null)\n return;\n\n try {\n AlibabaCloudCredentials creds = this.credsProvider.getCredentials();\n this.accessKeyID = creds.getAccessKeyId();\n this.accessKeySecret = creds.getAccessKeySecret();\n\n if (creds instanceof BasicSessionCredentials) {\n this.securityToken = ((BasicSessionCredentials) creds).getSessionToken();\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"public String getBaselineDurationText(int baselineNumber)\n {\n Object result = getCachedValue(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber));\n if (result == null)\n {\n result = getCachedValue(selectField(TaskFieldLists.BASELINE_ESTIMATED_DURATIONS, baselineNumber));\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }"
] |
Aggregates a list of templates specified by @Template | [
"static <T> List<Template> getTemplates(T objectType) {\n try {\n List<Template> templates = new ArrayList<>();\n TEMP_FINDER.findAnnotations(templates, objectType);\n return templates;\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }"
] | [
"private void stopAllServersAndRemoveCamelContext(CamelContext camelContext) {\n log.debug(\"Stopping all servers associated with {}\", camelContext);\n List<SingleBusLocatorRegistrar> registrars = locatorRegistrar.getAllRegistars(camelContext);\n registrars.forEach(registrar -> registrar.stopAllServersAndRemoveCamelContext());\n }",
"public void checkSpecialization() {\n if (isSpecializing()) {\n boolean isNameDefined = getAnnotated().isAnnotationPresent(Named.class);\n String previousSpecializedBeanName = null;\n for (AbstractBean<?, ?> specializedBean : getSpecializedBeans()) {\n String name = specializedBean.getName();\n if (previousSpecializedBeanName != null && name != null && !previousSpecializedBeanName.equals(specializedBean.getName())) {\n // there may be multiple beans specialized by this bean - make sure they all share the same name\n throw BeanLogger.LOG.beansWithDifferentBeanNamesCannotBeSpecialized(previousSpecializedBeanName, specializedBean.getName(), this);\n }\n previousSpecializedBeanName = name;\n if (isNameDefined && name != null) {\n throw BeanLogger.LOG.nameNotAllowedOnSpecialization(getAnnotated(), specializedBean.getAnnotated());\n }\n\n // When a specializing bean extends the raw type of a generic superclass, types of the generic superclass are\n // added into types of the specializing bean because of assignability rules. However, ParameterizedTypes among\n // these types are NOT types of the specializing bean (that's the way java works)\n boolean rawInsteadOfGeneric = (this instanceof AbstractClassBean<?>\n && specializedBean.getBeanClass().getTypeParameters().length > 0\n && !(((AbstractClassBean<?>) this).getBeanClass().getGenericSuperclass() instanceof ParameterizedType));\n for (Type specializedType : specializedBean.getTypes()) {\n if (rawInsteadOfGeneric && specializedType instanceof ParameterizedType) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n boolean contains = getTypes().contains(specializedType);\n if (!contains) {\n for (Type specializingType : getTypes()) {\n // In case 'type' is a ParameterizedType, two bean types equivalent in the CDI sense may not be\n // equal in the java sense. Therefore we have to use our own equality util.\n if (TypeEqualitySpecializationUtils.areTheSame(specializingType, specializedType)) {\n contains = true;\n break;\n }\n }\n }\n if (!contains) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n }\n }\n }\n }",
"private RgbaColor withHsl(int index, float value) {\n float[] HSL = convertToHsl();\n HSL[index] = value;\n return RgbaColor.fromHsl(HSL);\n }",
"protected Element createTextElement(String data, float width)\n {\n Element el = createTextElement(width);\n Text text = doc.createTextNode(data);\n el.appendChild(text);\n return el;\n }",
"public void validateUniqueIDsForMicrosoftProject()\n {\n if (!isEmpty())\n {\n for (T entity : this)\n {\n if (NumberHelper.getInt(entity.getUniqueID()) > MS_PROJECT_MAX_UNIQUE_ID)\n {\n renumberUniqueIDs();\n break;\n }\n }\n }\n }",
"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 String getDateTimeStrConcise(Date d) {\n if (d == null)\n return \"\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyyMMddHHmmssSSSZ\");\n return sdf.format(d);\n }",
"public static nsip6[] get(nitro_service service) throws Exception{\n\t\tnsip6 obj = new nsip6();\n\t\tnsip6[] response = (nsip6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"@NonNull public Context getContext() {\n if (searchView != null) {\n return searchView.getContext();\n } else if (supportView != null) {\n return supportView.getContext();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }"
] |
Dump an array of bytes in hexadecimal.
@param displayOffset the display offset (left column)
@param data the byte array of data
@param offset the offset to start dumping in the byte array
@param len the length of data to dump
@return the dump string | [
"public static String dump(final int displayOffset, final byte[] data, final int offset, final int len)\n {\n StringBuilder sb = new StringBuilder();\n Formatter formatter = new Formatter(sb);\n StringBuilder ascii = new StringBuilder();\n\n int dataNdx = offset;\n final int maxDataNdx = offset + len;\n final int lines = (len + 16) / 16;\n for (int i = 0; i < lines; i++) {\n ascii.append(\" |\");\n formatter.format(\"%08x \", displayOffset + (i * 16));\n\n for (int j = 0; j < 16; j++) {\n if (dataNdx < maxDataNdx) {\n byte b = data[dataNdx++];\n formatter.format(\"%02x \", b);\n ascii.append((b > MIN_VISIBLE && b < MAX_VISIBLE) ? (char) b : ' ');\n }\n else {\n sb.append(\" \");\n }\n\n if (j == 7) {\n sb.append(' ');\n }\n }\n\n ascii.append('|');\n sb.append(ascii).append('\\n');\n ascii.setLength(0);\n }\n\n formatter.close();\n return sb.toString();\n }"
] | [
"private FieldType getFieldType(byte[] data, int offset)\n {\n int fieldIndex = MPPUtility.getInt(data, offset);\n return FieldTypeHelper.mapTextFields(FieldTypeHelper.getInstance14(fieldIndex));\n }",
"public synchronized void setMonitoredPlayer(final int player) {\n if (player < 0) {\n throw new IllegalArgumentException(\"player cannot be negative\");\n }\n clearPlaybackState();\n monitoredPlayer.set(player);\n if (player > 0) { // Start monitoring the specified player\n setPlaybackState(player, 0, false); // Start with default values for required simple state.\n VirtualCdj.getInstance().addUpdateListener(updateListener);\n MetadataFinder.getInstance().addTrackMetadataListener(metadataListener);\n cueList.set(null); // Assume the worst, but see if we have one available next.\n if (MetadataFinder.getInstance().isRunning()) {\n TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(player);\n if (metadata != null) {\n cueList.set(metadata.getCueList());\n }\n }\n WaveformFinder.getInstance().addWaveformListener(waveformListener);\n if (WaveformFinder.getInstance().isRunning() && WaveformFinder.getInstance().isFindingDetails()) {\n waveform.set(WaveformFinder.getInstance().getLatestDetailFor(player));\n } else {\n waveform.set(null);\n }\n BeatGridFinder.getInstance().addBeatGridListener(beatGridListener);\n if (BeatGridFinder.getInstance().isRunning()) {\n beatGrid.set(BeatGridFinder.getInstance().getLatestBeatGridFor(player));\n } else {\n beatGrid.set(null);\n }\n try {\n TimeFinder.getInstance().start();\n if (!animating.getAndSet(true)) {\n // Create the thread to update our position smoothly as the track plays\n new Thread(new Runnable() {\n @Override\n public void run() {\n while (animating.get()) {\n try {\n Thread.sleep(33); // Animate at 30 fps\n } catch (InterruptedException e) {\n logger.warn(\"Waveform animation thread interrupted; ending\");\n animating.set(false);\n }\n setPlaybackPosition(TimeFinder.getInstance().getTimeFor(getMonitoredPlayer()));\n }\n }\n }).start();\n }\n } catch (Exception e) {\n logger.error(\"Unable to start the TimeFinder to animate the waveform detail view\");\n animating.set(false);\n }\n } else { // Stop monitoring any player\n animating.set(false);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n WaveformFinder.getInstance().removeWaveformListener(waveformListener);\n cueList.set(null);\n waveform.set(null);\n beatGrid.set(null);\n }\n if (!autoScroll.get()) {\n invalidate();\n }\n repaint();\n }",
"private static String getLogManagerLoggerName(final String name) {\n return (name.equals(RESOURCE_NAME) ? CommonAttributes.ROOT_LOGGER_NAME : name);\n }",
"public static base_responses unset(nitro_service client, Long clid[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance unsetresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tunsetresources[i] = new clusterinstance();\n\t\t\t\tunsetresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public PhotoContext getContext(String photoId, String groupId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"group_id\", groupId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Collection<Element> payload = response.getPayloadCollection();\r\n PhotoContext photoContext = new PhotoContext();\r\n for (Element element : payload) {\r\n String elementName = element.getTagName();\r\n if (elementName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (elementName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(element.getAttribute(\"id\"));\r\n photoContext.setNextPhoto(photo);\r\n } else if (!elementName.equals(\"count\")) {\r\n _log.warn(\"unsupported element name: \" + elementName);\r\n }\r\n }\r\n return photoContext;\r\n }",
"public final synchronized void shutdown() { // synchronize on 'this' to avoid races with registerStreams\n stopped = true;\n // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor\n if (cleanupTaskFuture != null) {\n cleanupTaskFuture.cancel(false);\n }\n\n // Close remaining streams\n for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) {\n InputStreamKey key = entry.getKey();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }",
"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 String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\n }",
"@SuppressWarnings(\"rawtypes\")\n private static <T> Constructor<T> findConstructor(final Class<T> clazz, final Object... args)\n throws NoSuchConstructorException, AmbiguousConstructorException {\n final Object[] cArgs = (args == null) ? new Object[0] : args;\n Constructor<T> constructorToUse = null;\n final Constructor<?>[] candidates = clazz.getConstructors();\n Arrays.sort(candidates, ConstructorComparator.INSTANCE);\n int minTypeDiffWeight = Integer.MAX_VALUE;\n Set<Constructor<?>> ambiguousConstructors = null;\n for (final Constructor candidate : candidates) {\n final Class[] paramTypes = candidate.getParameterTypes();\n if (constructorToUse != null && cArgs.length > paramTypes.length) {\n // Already found greedy constructor that can be satisfied.\n // Do not look any further, there are only less greedy\n // constructors left.\n break;\n }\n if (paramTypes.length != cArgs.length) {\n continue;\n }\n final int typeDiffWeight = getTypeDifferenceWeight(paramTypes, cArgs);\n if (typeDiffWeight < minTypeDiffWeight) { \n // Choose this constructor if it represents the closest match.\n constructorToUse = candidate;\n minTypeDiffWeight = typeDiffWeight;\n ambiguousConstructors = null;\n } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {\n if (ambiguousConstructors == null) {\n ambiguousConstructors = new LinkedHashSet<Constructor<?>>();\n ambiguousConstructors.add(constructorToUse);\n }\n ambiguousConstructors.add(candidate);\n }\n }\n if (ambiguousConstructors != null && !ambiguousConstructors.isEmpty()) {\n throw new AmbiguousConstructorException(clazz, cArgs, ambiguousConstructors);\n }\n if (constructorToUse == null) {\n throw new NoSuchConstructorException(clazz, cArgs);\n }\n return constructorToUse;\n }"
] |
Returns whether this represents a valid host name or address format.
@return | [
"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 writeAssignments()\n {\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n Task task = assignment.getTask();\n if (task != null && task.getUniqueID().intValue() != 0 && !task.getSummary())\n {\n writeAssignment(assignment);\n }\n }\n }\n }",
"public static auditnslogpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_authenticationvserver_binding obj = new auditnslogpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_authenticationvserver_binding response[] = (auditnslogpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public List<Dependency> getModuleDependencies(final String moduleName, final String moduleVersion, final Boolean fullRecursive, final Boolean corporate, final Boolean thirdParty) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactDependencies(moduleName, moduleVersion));\n final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_TEST_PARAM, \"true\")\n .queryParam(ServerAPI.RECURSIVE_PARAM, fullRecursive.toString())\n .queryParam(ServerAPI.SHOW_CORPORATE_PARAM, corporate.toString())\n .queryParam(ServerAPI.SHOW_THIRPARTY_PARAM, thirdParty.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module ancestors \", moduleName, moduleVersion);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<Dependency>>(){});\n }",
"private void init_jdbcTypes() throws SQLException\r\n {\r\n ReportQuery q = (ReportQuery) getQueryObject().getQuery();\r\n m_jdbcTypes = new int[m_attributeCount];\r\n \r\n // try to get jdbcTypes from Query\r\n if (q.getJdbcTypes() != null)\r\n {\r\n m_jdbcTypes = q.getJdbcTypes();\r\n }\r\n else\r\n {\r\n ResultSetMetaData rsMetaData = getRsAndStmt().m_rs.getMetaData();\r\n for (int i = 0; i < m_attributeCount; i++)\r\n {\r\n m_jdbcTypes[i] = rsMetaData.getColumnType(i + 1);\r\n }\r\n \r\n }\r\n }",
"public List<ServerGroup> tableServerGroups(int profileId) {\n ArrayList<ServerGroup> serverGroups = new ArrayList<>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ? \" +\n \"ORDER BY \" + Constants.GENERIC_NAME\n );\n queryStatement.setInt(1, profileId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n ServerGroup curServerGroup = new ServerGroup(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.GENERIC_NAME),\n results.getInt(Constants.GENERIC_PROFILE_ID));\n curServerGroup.setServers(tableServers(profileId, curServerGroup.getId()));\n serverGroups.add(curServerGroup);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return serverGroups;\n }",
"public void 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 Collection<Integer> getNumericCodes() {\n Collection<Integer> result = get(KEY_QUERY_NUMERIC_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }",
"public static base_response change(nitro_service client, responderhtmlpage resource) throws Exception {\n\t\tresponderhtmlpage updateresource = new responderhtmlpage();\n\t\tupdateresource.name = resource.name;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}",
"private String getActivityStatus(Task mpxj)\n {\n String result;\n if (mpxj.getActualStart() == null)\n {\n result = \"Not Started\";\n }\n else\n {\n if (mpxj.getActualFinish() == null)\n {\n result = \"In Progress\";\n }\n else\n {\n result = \"Completed\";\n }\n }\n return result;\n }"
] |
Destroys dependent instance
@param instance
@return true if the instance was destroyed, false otherwise | [
"public boolean destroyDependentInstance(T instance) {\n synchronized (dependentInstances) {\n for (Iterator<ContextualInstance<?>> iterator = dependentInstances.iterator(); iterator.hasNext();) {\n ContextualInstance<?> contextualInstance = iterator.next();\n if (contextualInstance.getInstance() == instance) {\n iterator.remove();\n destroy(contextualInstance);\n return true;\n }\n }\n }\n return false;\n }"
] | [
"public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax) {\n\t\treturn getMSDLineChart(t, lagMin, lagMax, new MeanSquaredDisplacmentFeature(t,\n\t\t\t\tlagMin));\n\t}",
"private long interpolateTimeFromUpdate(TrackPositionUpdate lastTrackUpdate, CdjStatus newDeviceUpdate,\n BeatGrid beatGrid) {\n final int beatNumber = newDeviceUpdate.getBeatNumber();\n final boolean noLongerPlaying = !newDeviceUpdate.isPlaying();\n\n // If we have just stopped, see if we are near a cue (assuming that information is available), and if so,\n // the best assumption is that the DJ jumped to that cue.\n if (lastTrackUpdate.playing && noLongerPlaying) {\n final CueList.Entry jumpedTo = findAdjacentCue(newDeviceUpdate, beatGrid);\n if (jumpedTo != null) return jumpedTo.cueTime;\n }\n\n // Handle the special case where we were not playing either in the previous or current update, but the DJ\n // might have jumped to a different place in the track.\n if (!lastTrackUpdate.playing) {\n if (lastTrackUpdate.beatNumber == beatNumber && noLongerPlaying) { // Haven't moved\n return lastTrackUpdate.milliseconds;\n } else {\n if (noLongerPlaying) { // Have jumped without playing.\n if (beatNumber < 0) {\n return -1; // We don't know the position any more; weird to get into this state and still have a grid?\n }\n // As a heuristic, assume we are right before the beat?\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n }\n }\n }\n\n // One way or another, we are now playing.\n long elapsedMillis = (newDeviceUpdate.getTimestamp() - lastTrackUpdate.timestamp) / 1000000;\n long moved = Math.round(lastTrackUpdate.pitch * elapsedMillis);\n long interpolated = (lastTrackUpdate.reverse)?\n (lastTrackUpdate.milliseconds - moved) : lastTrackUpdate.milliseconds + moved;\n if (Math.abs(beatGrid.findBeatAtTime(interpolated) - beatNumber) < 2) {\n return interpolated; // Our calculations still look plausible\n }\n // The player has jumped or drifted somewhere unexpected, correct.\n if (newDeviceUpdate.isPlayingForwards()) {\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n } else {\n return beatGrid.getTimeWithinTrack(Math.min(beatNumber + 1, beatGrid.beatCount));\n }\n }",
"public void setDates(SortedSet<Date> dates) {\n\n if (!m_model.getIndividualDates().equals(dates)) {\n m_model.setIndividualDates(dates);\n onValueChange();\n }\n\n }",
"public static base_response update(nitro_service client, appfwlearningsettings resource) throws Exception {\n\t\tappfwlearningsettings updateresource = new appfwlearningsettings();\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.starturlminthreshold = resource.starturlminthreshold;\n\t\tupdateresource.starturlpercentthreshold = resource.starturlpercentthreshold;\n\t\tupdateresource.cookieconsistencyminthreshold = resource.cookieconsistencyminthreshold;\n\t\tupdateresource.cookieconsistencypercentthreshold = resource.cookieconsistencypercentthreshold;\n\t\tupdateresource.csrftagminthreshold = resource.csrftagminthreshold;\n\t\tupdateresource.csrftagpercentthreshold = resource.csrftagpercentthreshold;\n\t\tupdateresource.fieldconsistencyminthreshold = resource.fieldconsistencyminthreshold;\n\t\tupdateresource.fieldconsistencypercentthreshold = resource.fieldconsistencypercentthreshold;\n\t\tupdateresource.crosssitescriptingminthreshold = resource.crosssitescriptingminthreshold;\n\t\tupdateresource.crosssitescriptingpercentthreshold = resource.crosssitescriptingpercentthreshold;\n\t\tupdateresource.sqlinjectionminthreshold = resource.sqlinjectionminthreshold;\n\t\tupdateresource.sqlinjectionpercentthreshold = resource.sqlinjectionpercentthreshold;\n\t\tupdateresource.fieldformatminthreshold = resource.fieldformatminthreshold;\n\t\tupdateresource.fieldformatpercentthreshold = resource.fieldformatpercentthreshold;\n\t\tupdateresource.xmlwsiminthreshold = resource.xmlwsiminthreshold;\n\t\tupdateresource.xmlwsipercentthreshold = resource.xmlwsipercentthreshold;\n\t\tupdateresource.xmlattachmentminthreshold = resource.xmlattachmentminthreshold;\n\t\tupdateresource.xmlattachmentpercentthreshold = resource.xmlattachmentpercentthreshold;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void addAttribute(String attributeName, String attributeValue)\r\n {\r\n if (attributeName != null && attributeName.startsWith(JDBC_PROPERTY_NAME_PREFIX))\r\n {\r\n final String jdbcPropertyName = attributeName.substring(JDBC_PROPERTY_NAME_LENGTH);\r\n jdbcProperties.setProperty(jdbcPropertyName, attributeValue);\r\n }\r\n else if (attributeName != null && attributeName.startsWith(DBCP_PROPERTY_NAME_PREFIX))\r\n {\r\n final String dbcpPropertyName = attributeName.substring(DBCP_PROPERTY_NAME_LENGTH);\r\n dbcpProperties.setProperty(dbcpPropertyName, attributeValue);\r\n }\r\n else\r\n {\r\n super.addAttribute(attributeName, attributeValue);\r\n }\r\n }",
"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 }",
"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 int[] getCompressIndexAndCount(CompressOptions options, boolean createMixed) {\n\t\tif(options != null) {\n\t\t\tCompressionChoiceOptions rangeSelection = options.rangeSelection;\n\t\t\tRangeList compressibleSegs = rangeSelection.compressHost() ? getZeroRangeSegments() : getZeroSegments();\n\t\t\tint maxIndex = -1, maxCount = 0;\n\t\t\tint segmentCount = getSegmentCount();\n\t\t\t\n\t\t\tboolean compressMixed = createMixed && options.compressMixedOptions.compressMixed(this);\n\t\t\tboolean preferHost = (rangeSelection == CompressOptions.CompressionChoiceOptions.HOST_PREFERRED);\n\t\t\tboolean preferMixed = createMixed && (rangeSelection == CompressOptions.CompressionChoiceOptions.MIXED_PREFERRED);\n\t\t\tfor(int i = compressibleSegs.size() - 1; i >= 0 ; i--) {\n\t\t\t\tRange range = compressibleSegs.getRange(i);\n\t\t\t\tint index = range.index;\n\t\t\t\tint count = range.length;\n\t\t\t\tif(createMixed) {\n\t\t\t\t\t//so here we shorten the range to exclude the mixed part if necessary\n\t\t\t\t\tint mixedIndex = IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT - addressSegmentIndex;\n\t\t\t\t\tif(!compressMixed ||\n\t\t\t\t\t\t\tindex > mixedIndex || index + count < segmentCount) { //range does not include entire mixed part. We never compress only part of a mixed part.\n\t\t\t\t\t\t//the compressible range must stop at the mixed part\n\t\t\t\t\t\tcount = Math.min(count, mixedIndex - index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//select this range if is the longest\n\t\t\t\tif(count > 0 && count >= maxCount && (options.compressSingle || count > 1)) {\n\t\t\t\t\tmaxIndex = index;\n\t\t\t\t\tmaxCount = count;\n\t\t\t\t}\n\t\t\t\tif(preferHost && isPrefixed() &&\n\t\t\t\t\t\t((index + count) * IPv6Address.BITS_PER_SEGMENT) > getNetworkPrefixLength()) { //this range contains the host\n\t\t\t\t\t//Since we are going backwards, this means we select as the maximum any zero segment that includes the host\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(preferMixed && index + count >= segmentCount) { //this range contains the mixed section\n\t\t\t\t\t//Since we are going backwards, this means we select to compress the mixed segment\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(maxIndex >= 0) {\n\t\t\t\treturn new int[] {maxIndex, maxCount};\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public Where<T, ID> like(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LIKE_OPERATION));\n\t\treturn this;\n\t}"
] |
Adds listeners and reads from a stream.
@param reader reader for file type
@param stream schedule data
@return ProjectFile instance | [
"private ProjectFile readProjectFile(ProjectReader reader, InputStream stream) throws MPXJException\n {\n addListeners(reader);\n return reader.read(stream);\n }"
] | [
"public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\n }",
"public void download(OutputStream output, ProgressListener listener) {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n InputStream input = response.getBody(listener);\n\n long totalRead = 0;\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = input.read(buffer);\n totalRead += n;\n while (n != -1) {\n output.write(buffer, 0, n);\n n = input.read(buffer);\n totalRead += n;\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n\n response.disconnect();\n }",
"public BsonDocument toBsonDocument() {\n final BsonDocument updateDescDoc = new BsonDocument();\n updateDescDoc.put(\n Fields.UPDATED_FIELDS_FIELD,\n this.getUpdatedFields());\n\n final BsonArray removedFields = new BsonArray();\n for (final String field : this.getRemovedFields()) {\n removedFields.add(new BsonString(field));\n }\n updateDescDoc.put(\n Fields.REMOVED_FIELDS_FIELD,\n removedFields);\n\n return updateDescDoc;\n }",
"public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}",
"public void createAssignmentFieldMap(Props props)\n {\n //System.out.println(\"ASSIGN\");\n byte[] fieldMapData = null;\n for (Integer key : ASSIGNMENT_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultAssignmentData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }",
"public static RgbaColor fromHsl(float H, float S, float L) {\n\n // convert to [0-1]\n H /= 360f;\n S /= 100f;\n L /= 100f;\n\n float R, G, B;\n\n if (S == 0) {\n // grey\n R = G = B = L;\n }\n else {\n float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S;\n float m1 = 2f * L - m2;\n R = hue2rgb(m1, m2, H + 1 / 3f);\n G = hue2rgb(m1, m2, H);\n B = hue2rgb(m1, m2, H - 1 / 3f);\n }\n\n // convert [0-1] to [0-255]\n int r = Math.round(R * 255f);\n int g = Math.round(G * 255f);\n int b = Math.round(B * 255f);\n\n return new RgbaColor(r, g, b, 1);\n }",
"public static String defaultString(final String str, final String fallback) {\n return isNullOrEmpty(str) ? fallback : str;\n }",
"public static ConstraintField getInstance(int value)\n {\n ConstraintField result = null;\n\n if (value >= 0 && value < FIELD_ARRAY.length)\n {\n result = FIELD_ARRAY[value];\n }\n\n return (result);\n }",
"public static FormValidation validateEmails(String emails) {\n if (!Strings.isNullOrEmpty(emails)) {\n String[] recipients = StringUtils.split(emails, \" \");\n for (String email : recipients) {\n FormValidation validation = validateInternetAddress(email);\n if (validation != FormValidation.ok()) {\n return validation;\n }\n }\n }\n return FormValidation.ok();\n }"
] |
That is, of size 6, which become 8, since HashMaps are powers of 2. Still, it's half the size | [
"private static String wordShapeChris2Long(String s, boolean omitIfInBoundary, int len, Collection<String> knownLCWords) {\r\n final char[] beginChars = new char[BOUNDARY_SIZE];\r\n final char[] endChars = new char[BOUNDARY_SIZE];\r\n int beginUpto = 0;\r\n int endUpto = 0;\r\n final Set<Character> seenSet = new TreeSet<Character>(); // TreeSet guarantees stable ordering; has no size parameter\r\n\r\n boolean nonLetters = false;\r\n\r\n for (int i = 0; i < len; i++) {\r\n int iIncr = 0;\r\n char c = s.charAt(i);\r\n char m = c;\r\n if (Character.isDigit(c)) {\r\n m = 'd';\r\n } else if (Character.isLowerCase(c)) {\r\n m = 'x';\r\n } else if (Character.isUpperCase(c) || Character.isTitleCase(c)) {\r\n m = 'X';\r\n }\r\n for (String gr : greek) {\r\n if (s.startsWith(gr, i)) {\r\n m = 'g';\r\n //System.out.println(s + \" :: \" + s.substring(i+1));\r\n iIncr = gr.length() - 1;\r\n break;\r\n }\r\n }\r\n if (m != 'x' && m != 'X') {\r\n nonLetters = true;\r\n }\r\n\r\n if (i < BOUNDARY_SIZE) {\r\n beginChars[beginUpto++] = m;\r\n } else if (i < len - BOUNDARY_SIZE) {\r\n seenSet.add(Character.valueOf(m));\r\n } else {\r\n endChars[endUpto++] = m;\r\n }\r\n i += iIncr;\r\n // System.out.println(\"Position skips to \" + i);\r\n }\r\n\r\n // Calculate size. This may be an upperbound, but is often correct\r\n int sbSize = beginUpto + endUpto + seenSet.size();\r\n if (knownLCWords != null) { sbSize++; }\r\n final StringBuilder sb = new StringBuilder(sbSize);\r\n // put in the beginning chars\r\n sb.append(beginChars, 0, beginUpto);\r\n // put in the stored ones sorted\r\n if (omitIfInBoundary) {\r\n for (Character chr : seenSet) {\r\n char ch = chr.charValue();\r\n boolean insert = true;\r\n for (int i = 0; i < beginUpto; i++) {\r\n if (beginChars[i] == ch) {\r\n insert = false;\r\n break;\r\n }\r\n }\r\n for (int i = 0; i < endUpto; i++) {\r\n if (endChars[i] == ch) {\r\n insert = false;\r\n break;\r\n }\r\n }\r\n if (insert) {\r\n sb.append(ch);\r\n }\r\n }\r\n } else {\r\n for (Character chr : seenSet) {\r\n sb.append(chr.charValue());\r\n }\r\n }\r\n // and add end ones\r\n sb.append(endChars, 0, endUpto);\r\n\r\n if (knownLCWords != null) {\r\n if (!nonLetters && knownLCWords.contains(s.toLowerCase())) {\r\n sb.append('k');\r\n }\r\n }\r\n // System.out.println(s + \" became \" + sb);\r\n return sb.toString();\r\n }"
] | [
"protected void checkProxyPrefetchingLimit(DefBase def, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n if (def.hasProperty(PropertyHelper.OJB_PROPERTY_PROXY_PREFETCHING_LIMIT))\r\n {\r\n if (!def.hasProperty(PropertyHelper.OJB_PROPERTY_PROXY))\r\n {\r\n if (def instanceof ClassDescriptorDef)\r\n {\r\n LogHelper.warn(true,\r\n ConstraintsBase.class,\r\n \"checkProxyPrefetchingLimit\",\r\n \"The class \"+def.getName()+\" has a proxy-prefetching-limit property but no proxy property\");\r\n }\r\n else\r\n { \r\n LogHelper.warn(true,\r\n ConstraintsBase.class,\r\n \"checkProxyPrefetchingLimit\",\r\n \"The feature \"+def.getName()+\" in class \"+def.getOwner().getName()+\" has a proxy-prefetching-limit property but no proxy property\");\r\n }\r\n }\r\n \r\n String propValue = def.getProperty(PropertyHelper.OJB_PROPERTY_PROXY_PREFETCHING_LIMIT);\r\n \r\n try\r\n {\r\n int value = Integer.parseInt(propValue);\r\n \r\n if (value < 0)\r\n {\r\n if (def instanceof ClassDescriptorDef)\r\n {\r\n throw new ConstraintException(\"The proxy-prefetching-limit value of class \"+def.getName()+\" must be a non-negative number\");\r\n }\r\n else\r\n { \r\n throw new ConstraintException(\"The proxy-prefetching-limit value of the feature \"+def.getName()+\" in class \"+def.getOwner().getName()+\" must be a non-negative number\");\r\n }\r\n }\r\n }\r\n catch (NumberFormatException ex)\r\n {\r\n if (def instanceof ClassDescriptorDef)\r\n {\r\n throw new ConstraintException(\"The proxy-prefetching-limit value of the class \"+def.getName()+\" is not a number\");\r\n }\r\n else\r\n { \r\n throw new ConstraintException(\"The proxy-prefetching-limit value of the feature \"+def.getName()+\" in class \"+def.getOwner().getName()+\" is not a number\");\r\n }\r\n }\r\n }\r\n }",
"public <T> T cached(String key) {\n H.Session sess = session();\n if (null != sess) {\n return sess.cached(key);\n } else {\n return app().cache().get(key);\n }\n }",
"public void replaceItem(@NonNull final T oldObject, @NonNull final T newObject) {\n synchronized (mLock) {\n final int position = getPosition(oldObject);\n if (position == -1) {\n // not found, don't replace\n return;\n }\n\n mObjects.remove(position);\n mObjects.add(position, newObject);\n\n if (isItemTheSame(oldObject, newObject)) {\n if (isContentTheSame(oldObject, newObject)) {\n // visible content hasn't changed, don't notify\n return;\n }\n\n // item with same stable id has changed\n notifyItemChanged(position, newObject);\n } else {\n // item replaced with another one with a different id\n notifyItemRemoved(position);\n notifyItemInserted(position);\n }\n }\n }",
"public static MatchInfo fromUri(final URI uri, final HttpMethod method) {\n int newPort = uri.getPort();\n if (newPort < 0) {\n try {\n newPort = uri.toURL().getDefaultPort();\n } catch (MalformedURLException | IllegalArgumentException e) {\n newPort = ANY_PORT;\n }\n }\n\n return new MatchInfo(uri.getScheme(), uri.getHost(), newPort, uri.getPath(), uri.getQuery(),\n uri.getFragment(), ANY_REALM, method);\n }",
"private int convertMoneyness(double moneyness) {\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\treturn (int) Math.round(moneyness * 100);\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\treturn - (int) Math.round(moneyness * 10000);\r\n\t\t} else {\r\n\t\t\treturn (int) Math.round(moneyness * 10000);\r\n\t\t}\r\n\t}",
"private void processWorkWeekDay(byte[] data, int offset, ProjectCalendarWeek week, Day day)\n {\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 60, false));\n\n int dayType = MPPUtility.getShort(data, offset + 0);\n if (dayType == 1)\n {\n week.setWorkingDay(day, DayType.DEFAULT);\n }\n else\n {\n ProjectCalendarHours hours = week.addCalendarHours(day);\n int rangeCount = MPPUtility.getShort(data, offset + 2);\n if (rangeCount == 0)\n {\n week.setWorkingDay(day, DayType.NON_WORKING);\n }\n else\n {\n week.setWorkingDay(day, DayType.WORKING);\n Calendar cal = DateHelper.popCalendar();\n for (int index = 0; index < rangeCount; index++)\n {\n Date startTime = DateHelper.getCanonicalTime(MPPUtility.getTime(data, offset + 8 + (index * 2)));\n int durationInSeconds = MPPUtility.getInt(data, offset + 20 + (index * 4)) * 6;\n cal.setTime(startTime);\n cal.add(Calendar.SECOND, durationInSeconds);\n Date finishTime = DateHelper.getCanonicalTime(cal.getTime());\n hours.addRange(new DateRange(startTime, finishTime));\n }\n DateHelper.pushCalendar(cal);\n }\n }\n }",
"public Date getCompleteThrough()\n {\n Date value = (Date) getCachedValue(TaskField.COMPLETE_THROUGH);\n if (value == null)\n {\n int percentComplete = NumberHelper.getInt(getPercentageComplete());\n switch (percentComplete)\n {\n case 0:\n {\n break;\n }\n\n case 100:\n {\n value = getActualFinish();\n break;\n }\n\n default:\n {\n Date actualStart = getActualStart();\n Duration duration = getDuration();\n if (actualStart != null && duration != null)\n {\n double durationValue = (duration.getDuration() * percentComplete) / 100d;\n duration = Duration.getInstance(durationValue, duration.getUnits());\n ProjectCalendar calendar = getEffectiveCalendar();\n value = calendar.getDate(actualStart, duration, true);\n }\n break;\n }\n }\n\n set(TaskField.COMPLETE_THROUGH, value);\n }\n return value;\n }",
"public void clear() {\n List<Widget> children = getChildren();\n Log.d(TAG, \"clear(%s): removing %d children\", getName(), children.size());\n for (Widget child : children) {\n removeChild(child, true);\n }\n requestLayout();\n }",
"public static Comment createComment(final String entityId,\n\t\t\t\t\t\t\t\t\t\tfinal String entityType,\n\t\t\t\t\t\t\t\t\t\tfinal String action,\n\t\t\t\t\t\t\t\t\t\tfinal String commentedText,\n\t\t\t\t\t\t\t\t\t\tfinal String user,\n\t\t\t\t\t\t\t\t\t\tfinal Date date) {\n\n\t\tfinal Comment comment = new Comment();\n\t\tcomment.setEntityId(entityId);\n\t\tcomment.setEntityType(entityType);\n\t\tcomment.setAction(action);\n\t\tcomment.setCommentText(commentedText);\n\t\tcomment.setCommentedBy(user);\n\t\tcomment.setCreatedDateTime(date);\n\t\treturn comment;\n\t}"
] |
Gets the UTF-8 sequence length of the code point.
@throws InvalidCodePointException if code point is not within a valid range | [
"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 }"
] | [
"private static void addProperties(EndpointReferenceType epr, SLProperties props) {\n MetadataType metadata = WSAEndpointReferenceUtils.getSetMetadata(epr);\n ServiceLocatorPropertiesType jaxbProps = SLPropertiesConverter.toServiceLocatorPropertiesType(props);\n\n JAXBElement<ServiceLocatorPropertiesType>\n slp = SL_OBJECT_FACTORY.createServiceLocatorProperties(jaxbProps);\n metadata.getAny().add(slp);\n }",
"private void init_jdbcTypes() throws SQLException\r\n {\r\n ReportQuery q = (ReportQuery) getQueryObject().getQuery();\r\n m_jdbcTypes = new int[m_attributeCount];\r\n \r\n // try to get jdbcTypes from Query\r\n if (q.getJdbcTypes() != null)\r\n {\r\n m_jdbcTypes = q.getJdbcTypes();\r\n }\r\n else\r\n {\r\n ResultSetMetaData rsMetaData = getRsAndStmt().m_rs.getMetaData();\r\n for (int i = 0; i < m_attributeCount; i++)\r\n {\r\n m_jdbcTypes[i] = rsMetaData.getColumnType(i + 1);\r\n }\r\n \r\n }\r\n }",
"public void performStep() {\n // check for zeros\n for( int i = helper.x2-1; i >= helper.x1; i-- ) {\n if( helper.isZero(i) ) {\n helper.splits[helper.numSplits++] = i;\n helper.x1 = i+1;\n return;\n }\n }\n\n double lambda;\n\n if( followingScript ) {\n if( helper.steps > 10 ) {\n followingScript = false;\n return;\n } else {\n // Using the true eigenvalues will in general lead to the fastest convergence\n // typically takes 1 or 2 steps\n lambda = eigenvalues[helper.x2];\n }\n } else {\n // the current eigenvalue isn't working so try something else\n lambda = helper.computeShift();\n }\n\n // similar transforms\n helper.performImplicitSingleStep(lambda,false);\n }",
"public static String getAggregatedResultHuman(Map<String, LinkedHashSet<String>> aggregateResultMap){\n\n StringBuilder res = new StringBuilder();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n LinkedHashSet<String> valueSet = entry.getValue(); \n res.append(\"[\" + entry.getKey() + \" COUNT: \" +valueSet.size() + \" ]:\\n\");\n for(String str: valueSet){\n res.append(\"\\t\" + str + \"\\n\");\n }\n res.append(\"###################################\\n\\n\");\n }\n \n return res.toString();\n \n }",
"private void fillWeekPanel() {\r\n\r\n addCheckBox(WeekOfMonth.FIRST.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_1_0);\r\n addCheckBox(WeekOfMonth.SECOND.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_2_0);\r\n addCheckBox(WeekOfMonth.THIRD.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_3_0);\r\n addCheckBox(WeekOfMonth.FOURTH.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_4_0);\r\n addCheckBox(WeekOfMonth.LAST.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_5_0);\r\n }",
"private void generateCopyingPart(WrappingHint.Builder builder) {\n ImmutableCollection<CopyMethod> copyMethods = ImmutableMultimap.<String, CopyMethod>builder()\n .putAll(configuration.FIELD_TYPE_TO_COPY_METHODS)\n .putAll(userDefinedCopyMethods)\n .build()\n .get(typeAssignedToField);\n \n if (copyMethods.isEmpty()) {\n throw new WrappingHintGenerationException();\n }\n \n CopyMethod firstSuitable = copyMethods.iterator().next();\n builder.setCopyMethodOwnerName(firstSuitable.owner.toString())\n .setCopyMethodName(firstSuitable.name);\n \n if (firstSuitable.isGeneric && typeSignature != null) {\n CollectionField withRemovedWildcards = CollectionField.from(typeAssignedToField, typeSignature)\n .transformGenericTree(GenericType::withoutWildcard);\n builder.setCopyTypeParameterName(formatTypeParameter(withRemovedWildcards.asSimpleString()));\n }\n }",
"private void digestInteger(MessageDigest digest, int value) {\n byte[] valueBytes = new byte[4];\n Util.numberToBytes(value, valueBytes, 0, 4);\n digest.update(valueBytes);\n }",
"public Set<RateType> getRateTypes() {\n @SuppressWarnings(\"unchecked\")\n Set<RateType> rateSet = get(KEY_RATE_TYPES, Set.class);\n if (rateSet == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(rateSet);\n }",
"public static String getEncoding(CmsObject cms, CmsResource file) {\n\n CmsProperty encodingProperty = CmsProperty.getNullProperty();\n try {\n encodingProperty = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true);\n } catch (CmsException e) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n return CmsEncoder.lookupEncoding(encodingProperty.getValue(\"\"), OpenCms.getSystemInfo().getDefaultEncoding());\n }"
] |
Set the replace of the uri and return the new URI.
@param initialUri the starting URI, the URI to update
@param path the path to set on the baeURI | [
"public static URI setPath(final URI initialUri, final String path) {\n String finalPath = path;\n if (!finalPath.startsWith(\"/\")) {\n finalPath = '/' + path;\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath,\n initialUri.getQuery(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n finalPath, initialUri.getQuery(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\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 E setById(final int id, final E element) {\n VListKey<K> key = new VListKey<K>(_key, id);\n UpdateElementById<K, E> updateElementAction = new UpdateElementById<K, E>(key, element);\n\n if(!_storeClient.applyUpdate(updateElementAction))\n throw new ObsoleteVersionException(\"update failed\");\n\n return updateElementAction.getResult();\n }",
"public static void write(BufferedWriter writer, DatabaseFieldConfig config, String tableName) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config, tableName);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}",
"public static final double round(double value, double precision)\n {\n precision = Math.pow(10, precision);\n return Math.round(value * precision) / precision;\n }",
"public static final BigDecimal printRate(Rate rate)\n {\n BigDecimal result = null;\n if (rate != null && rate.getAmount() != 0)\n {\n result = new BigDecimal(rate.getAmount());\n }\n return result;\n }",
"private List<String> getRotatedList(List<String> strings) {\n int index = RANDOM.nextInt(strings.size());\n List<String> rotated = new ArrayList<String>();\n for (int i = 0; i < strings.size(); i++) {\n rotated.add(strings.get(index));\n index = (index + 1) % strings.size();\n }\n return rotated;\n }",
"public int[] getIntArray(String attributeName)\n {\n int[] array = NativeVertexBuffer.getIntArray(getNative(), attributeName);\n if (array == null)\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return array;\n }",
"public boolean isRunning(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n return this.runningProcessors.containsKey(processorGraphNode.getProcessor());\n } finally {\n this.processorLock.unlock();\n }\n }",
"public static String read(final File file) throws IOException {\n final StringBuilder sb = new StringBuilder();\n\n try (\n final FileReader fr = new FileReader(file);\n final BufferedReader br = new BufferedReader(fr);\n ) {\n\n String sCurrentLine;\n\n while ((sCurrentLine = br.readLine()) != null) {\n sb.append(sCurrentLine);\n }\n }\n\n return sb.toString();\n }"
] |
Confirms that both clusters have the same number of nodes by comparing
set of node Ids between clusters.
@param lhs
@param rhs | [
"public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) {\n if(!lhs.getNodeIds().equals(rhs.getNodeIds())) {\n throw new VoldemortException(\"Node ids are not the same [ lhs cluster node ids (\"\n + lhs.getNodeIds()\n + \") not equal to rhs cluster node ids (\"\n + rhs.getNodeIds() + \") ]\");\n }\n }"
] | [
"public final Object getRealObject(Object objectOrProxy)\r\n {\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n return getIndirectionHandler(objectOrProxy).getRealSubject();\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for given Proxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n try\r\n {\r\n return ((VirtualProxy) objectOrProxy).getRealSubject();\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for VirtualProxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else\r\n {\r\n return objectOrProxy;\r\n }\r\n }",
"void throwCloudExceptionIfInFailedState() {\n if (this.isStatusFailed()) {\n if (this.errorBody() != null) {\n throw new CloudException(\"Async operation failed with provisioning state: \" + this.status(), this.response(), this.errorBody());\n } else {\n throw new CloudException(\"Async operation failed with provisioning state: \" + this.status(), this.response());\n }\n }\n }",
"public void processField(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n String defaultType = getDefaultJdbcTypeForCurrentMember();\r\n String defaultConversion = getDefaultJdbcConversionForCurrentMember();\r\n FieldDescriptorDef fieldDef = _curClassDef.getField(name);\r\n String attrName;\r\n\r\n if (fieldDef == null)\r\n {\r\n fieldDef = new FieldDescriptorDef(name);\r\n _curClassDef.addField(fieldDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processField\", \" Processing field \"+fieldDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n fieldDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n // storing additional info for later use\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE,\r\n OjbMemberTagsHandler.getMemberType().getQualifiedName());\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE, defaultType);\r\n if (defaultConversion != null)\r\n { \r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION, defaultConversion);\r\n }\r\n\r\n _curFieldDef = fieldDef;\r\n generate(template);\r\n _curFieldDef = null;\r\n }",
"public ItemRequest<Task> removeTag(String task) {\n \n String path = String.format(\"/tasks/%s/removeTag\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"private void verifyOrAddStore(String clusterURL,\n String keySchema,\n String valueSchema) {\n String newStoreDefXml = VoldemortUtils.getStoreDefXml(\n storeName,\n props.getInt(BUILD_REPLICATION_FACTOR, 2),\n props.getInt(BUILD_REQUIRED_READS, 1),\n props.getInt(BUILD_REQUIRED_WRITES, 1),\n props.getNullableInt(BUILD_PREFERRED_READS),\n props.getNullableInt(BUILD_PREFERRED_WRITES),\n props.getString(PUSH_FORCE_SCHEMA_KEY, keySchema),\n props.getString(PUSH_FORCE_SCHEMA_VALUE, valueSchema),\n description,\n owners);\n\n log.info(\"Verifying store against cluster URL: \" + clusterURL + \"\\n\" + newStoreDefXml.toString());\n StoreDefinition newStoreDef = VoldemortUtils.getStoreDef(newStoreDefXml);\n\n try {\n adminClientPerCluster.get(clusterURL).storeMgmtOps.verifyOrAddStore(newStoreDef, \"BnP config/data\",\n enableStoreCreation, this.storeVerificationExecutorService);\n } catch (UnreachableStoreException e) {\n log.info(\"verifyOrAddStore() failed on some nodes for clusterURL: \" + clusterURL + \" (this is harmless).\", e);\n // When we can't reach some node, we just skip it and won't create the store on it.\n // Next time BnP is run while the node is up, it will get the store created.\n } // Other exceptions need to bubble up!\n\n storeDef = newStoreDef;\n }",
"public 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 ByteArray readBytes(int size) throws IOException\n {\n byte[] data = new byte[size];\n m_stream.read(data);\n return new ByteArray(data);\n }",
"public 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}",
"public static java.sql.Date getDate(Object value) {\n try {\n return toDate(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }"
] |
Get a property as a float or throw an exception.
@param key the property name | [
"@Override\n public final float getFloat(final String key) {\n Float result = optFloat(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }"
] | [
"public Duration getFinishVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.FINISH_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineFinish(), getFinish(), format);\n set(AssignmentField.FINISH_VARIANCE, variance);\n }\n return (variance);\n }",
"protected void consumeChar(ImapRequestLineReader request, char expected)\n throws ProtocolException {\n char consumed = request.consume();\n if (consumed != expected) {\n throw new ProtocolException(\"Expected:'\" + expected + \"' found:'\" + consumed + '\\'');\n }\n }",
"public static 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 static RequiredConfigurationHolder populateHostResolutionContext(final HostInfo hostInfo, final Resource root, final ExtensionRegistry extensionRegistry) {\n final RequiredConfigurationHolder rc = new RequiredConfigurationHolder();\n for (IgnoredNonAffectedServerGroupsUtil.ServerConfigInfo info : hostInfo.getServerConfigInfos()) {\n processServerConfig(root, rc, info, extensionRegistry);\n }\n return rc;\n }",
"@Override\n\tpublic String getFirst(String headerName) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\treturn headerValues != null ? headerValues.get(0) : null;\n\t}",
"public void createEnablement() {\n GlobalEnablementBuilder builder = beanManager.getServices().get(GlobalEnablementBuilder.class);\n ModuleEnablement enablement = builder.createModuleEnablement(this);\n beanManager.setEnabled(enablement);\n\n if (BootstrapLogger.LOG.isDebugEnabled()) {\n BootstrapLogger.LOG.enabledAlternatives(this.beanManager, WeldCollections.toMultiRowString(enablement.getAllAlternatives()));\n BootstrapLogger.LOG.enabledDecorators(this.beanManager, WeldCollections.toMultiRowString(enablement.getDecorators()));\n BootstrapLogger.LOG.enabledInterceptors(this.beanManager, WeldCollections.toMultiRowString(enablement.getInterceptors()));\n }\n }",
"protected int readShort(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 16; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"@SuppressWarnings(\"deprecation\")\n @Deprecated\n public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException {\n validateOperation(operationObject);\n for (AttributeDefinition ad : this.parameters) {\n ad.validateAndSet(operationObject, model);\n }\n }",
"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 }"
] |
Guess whether given file is binary. Just checks for anything under 0x09. | [
"private static boolean isBinary(InputStream in) {\n try {\n int size = in.available();\n if (size > 1024) size = 1024;\n byte[] data = new byte[size];\n in.read(data);\n in.close();\n\n int ascii = 0;\n int other = 0;\n\n for (int i = 0; i < data.length; i++) {\n byte b = data[i];\n if (b < 0x09) return true;\n\n if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D) ascii++;\n else if (b >= 0x20 && b <= 0x7E) ascii++;\n else other++;\n }\n\n return other != 0 && 100 * other / (ascii + other) > 95;\n\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }"
] | [
"public synchronized void doneTask(int stealerId, int donorId) {\n removeNodesFromWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting--;\n doneSignal.countDown();\n // Try and schedule more tasks now that resources may be available to do\n // so.\n scheduleMoreTasks();\n }",
"public Class<?> getColumnType(int c) {\n\n for (int r = 0; r < m_data.size(); r++) {\n Object val = m_data.get(r).get(c);\n if (val != null) {\n return val.getClass();\n }\n }\n return Object.class;\n }",
"public double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\n\t}",
"private void readRoleDefinitions(Project gpProject)\n {\n m_roleDefinitions.put(\"Default:1\", \"project manager\");\n\n for (Roles roles : gpProject.getRoles())\n {\n if (\"Default\".equals(roles.getRolesetName()))\n {\n continue;\n }\n\n for (Role role : roles.getRole())\n {\n m_roleDefinitions.put(role.getId(), role.getName());\n }\n }\n }",
"public final void reset()\n {\n for (int i = 0; i < permutationIndices.length; i++)\n {\n permutationIndices[i] = i;\n }\n remainingPermutations = totalPermutations;\n }",
"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}",
"public void finished(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n this.runningProcessors.remove(processorGraphNode.getProcessor());\n this.executedProcessors.put(processorGraphNode.getProcessor(), null);\n } finally {\n this.processorLock.unlock();\n }\n }",
"public static final Long date2utc(Date date) {\n\n // use null for a null date\n if (date == null) return null;\n \n long time = date.getTime();\n \n // remove the timezone offset \n time -= timezoneOffsetMillis(date);\n \n return time;\n }",
"public static Type[] getActualTypeArguments(Type type) {\n Type resolvedType = Types.getCanonicalType(type);\n if (resolvedType instanceof ParameterizedType) {\n return ((ParameterizedType) resolvedType).getActualTypeArguments();\n } else {\n return EMPTY_TYPES;\n }\n }"
] |
Add a number of days to the supplied date.
@param date start date
@param days number of days to add
@return new date | [
"public static Date addDays(Date date, int days)\n {\n Calendar cal = popCalendar(date);\n cal.add(Calendar.DAY_OF_YEAR, days);\n Date result = cal.getTime();\n pushCalendar(cal);\n return result; \n }"
] | [
"private boolean isCacheable(PipelineContext context) throws GeomajasException {\n\t\tVectorLayer layer = context.get(PipelineCode.LAYER_KEY, VectorLayer.class);\n\t\treturn !(layer instanceof VectorLayerLazyFeatureConversionSupport &&\n\t\t\t\t((VectorLayerLazyFeatureConversionSupport) layer).useLazyFeatureConversion());\n\t}",
"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 }",
"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 }",
"public String getUserProfile(String userId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_USER_PROFILE);\r\n\r\n parameters.put(\"user_id\", userId);\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 return payload.getAttribute(\"url\");\r\n }",
"public static final String printExtendedAttributeCurrency(Number value)\n {\n return (value == null ? null : NUMBER_FORMAT.get().format(value.doubleValue() * 100));\n }",
"private void processDays(ProjectCalendar calendar) throws Exception\n {\n // Default all days to non-working\n for (Day day : Day.values())\n {\n calendar.setWorkingDay(day, false);\n }\n\n List<Row> rows = getRows(\"select * from zcalendarrule where zcalendar1=? and z_ent=?\", calendar.getUniqueID(), m_entityMap.get(\"CalendarWeekDayRule\"));\n for (Row row : rows)\n {\n Day day = row.getDay(\"ZWEEKDAY\");\n String timeIntervals = row.getString(\"ZTIMEINTERVALS\");\n if (timeIntervals == null)\n {\n calendar.setWorkingDay(day, false);\n }\n else\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n NodeList nodes = getNodeList(timeIntervals, m_dayTimeIntervals);\n calendar.setWorkingDay(day, nodes.getLength() > 0);\n\n for (int loop = 0; loop < nodes.getLength(); loop++)\n {\n NamedNodeMap attributes = nodes.item(loop).getAttributes();\n Date startTime = m_calendarTimeFormat.parse(attributes.getNamedItem(\"startTime\").getTextContent());\n Date endTime = m_calendarTimeFormat.parse(attributes.getNamedItem(\"endTime\").getTextContent());\n\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }",
"private void addHandlerInitializerMethod(ClassFile proxyClassType, ClassMethod staticConstructor) throws Exception {\n ClassMethod classMethod = proxyClassType.addMethod(AccessFlag.PRIVATE, INIT_MH_METHOD_NAME, BytecodeUtils.VOID_CLASS_DESCRIPTOR, LJAVA_LANG_OBJECT);\n final CodeAttribute b = classMethod.getCodeAttribute();\n b.aload(0);\n StaticMethodInformation methodInfo = new StaticMethodInformation(INIT_MH_METHOD_NAME, new Class[] { Object.class }, void.class,\n classMethod.getClassFile().getName());\n invokeMethodHandler(classMethod, methodInfo, false, DEFAULT_METHOD_RESOLVER, staticConstructor);\n b.checkcast(MethodHandler.class);\n b.putfield(classMethod.getClassFile().getName(), METHOD_HANDLER_FIELD_NAME, DescriptorUtils.makeDescriptor(MethodHandler.class));\n b.returnInstruction();\n BeanLogger.LOG.createdMethodHandlerInitializerForDecoratorProxy(getBeanType());\n\n }",
"private void tryRefreshAccessToken(final Long reqStartedAt) {\n authLock.writeLock().lock();\n try {\n if (!isLoggedIn()) {\n throw new StitchClientException(StitchClientErrorCode.LOGGED_OUT_DURING_REQUEST);\n }\n\n try {\n final Jwt jwt = Jwt.fromEncoded(getAuthInfo().getAccessToken());\n if (jwt.getIssuedAt() >= reqStartedAt) {\n return;\n }\n } catch (final IOException e) {\n // Swallow\n }\n\n // retry\n refreshAccessToken();\n } finally {\n authLock.writeLock().unlock();\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}"
] |
Helper to return the first item in the iterator or null.
@return T the first item or null. | [
"@Nullable\n public ResultT first() {\n final CoreRemoteMongoCursor<ResultT> cursor = iterator();\n if (!cursor.hasNext()) {\n return null;\n }\n return cursor.next();\n }"
] | [
"public static int ptb2Text(Reader ptbText, Writer w) throws IOException {\r\n int numTokens = 0;\r\n PTB2TextLexer lexer = new PTB2TextLexer(ptbText);\r\n for (String token; (token = lexer.next()) != null; ) {\r\n numTokens++;\r\n w.write(token);\r\n }\r\n return numTokens;\r\n }",
"private String getSymbolName(char c)\n {\n String result = null;\n\n switch (c)\n {\n case ',':\n {\n result = \"Comma\";\n break;\n }\n\n case '.':\n {\n result = \"Period\";\n break;\n }\n }\n\n return result;\n }",
"public String getStatement() throws SQLException {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendSql(null, sb, new ArrayList<ArgumentHolder>());\n\t\treturn sb.toString();\n\t}",
"private void setLanguageFilters(String filters) {\n\t\tthis.filterLanguages = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tCollections.addAll(this.filterLanguages, filters.split(\",\"));\n\t\t}\n\t}",
"public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) {\n return createEnterpriseUser(api, login, name, null);\n }",
"public static final PatchOperationTarget createHost(final String hostName, final ModelControllerClient client) {\n final PathElement host = PathElement.pathElement(HOST, hostName);\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(host, CORE_SERVICES);\n return new RemotePatchOperationTarget(address, client);\n }",
"private void addHours(ProjectCalendarDateRanges ranges, Record hoursRecord)\n {\n if (hoursRecord.getValue() != null)\n {\n String[] wh = hoursRecord.getValue().split(\"\\\\|\");\n try\n {\n String startText;\n String endText;\n\n if (wh[0].equals(\"s\"))\n {\n startText = wh[1];\n endText = wh[3];\n }\n else\n {\n startText = wh[3];\n endText = wh[1];\n }\n\n // for end time treat midnight as midnight next day\n if (endText.equals(\"00:00\"))\n {\n endText = \"24:00\";\n }\n Date start = m_calendarTimeFormat.parse(startText);\n Date end = m_calendarTimeFormat.parse(endText);\n\n ranges.addRange(new DateRange(start, end));\n }\n catch (ParseException e)\n {\n // silently ignore date parse exceptions\n }\n }\n }",
"public void sendLoadTrackCommand(int targetPlayer, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n final DeviceUpdate update = getLatestStatusFor(targetPlayer);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + targetPlayer + \" not found on network.\");\n }\n sendLoadTrackCommand(update, rekordboxId, sourcePlayer, sourceSlot, sourceType);\n }",
"public int[][] argb() {\n return Arrays.stream(points()).map(p -> argb(p.x, p.y)).toArray(int[][]::new);\n }"
] |
Bessel function of the second kind, of order 1.
@param x Value.
@return Y value. | [
"public static double Y(double x) {\r\n if (x < 8.0) {\r\n double y = x * x;\r\n double ans1 = x * (-0.4900604943e13 + y * (0.1275274390e13\r\n + y * (-0.5153438139e11 + y * (0.7349264551e9\r\n + y * (-0.4237922726e7 + y * 0.8511937935e4)))));\r\n double ans2 = 0.2499580570e14 + y * (0.4244419664e12\r\n + y * (0.3733650367e10 + y * (0.2245904002e8\r\n + y * (0.1020426050e6 + y * (0.3549632885e3 + y)))));\r\n return (ans1 / ans2) + 0.636619772 * (J(x) * Math.log(x) - 1.0 / x);\r\n } else {\r\n double z = 8.0 / x;\r\n double y = z * z;\r\n double xx = x - 2.356194491;\r\n double ans1 = 1.0 + y * (0.183105e-2 + y * (-0.3516396496e-4\r\n + y * (0.2457520174e-5 + y * (-0.240337019e-6))));\r\n double ans2 = 0.04687499995 + y * (-0.2002690873e-3\r\n + y * (0.8449199096e-5 + y * (-0.88228987e-6\r\n + y * 0.105787412e-6)));\r\n return Math.sqrt(0.636619772 / x) *\r\n (Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2);\r\n }\r\n }"
] | [
"private String convertOutputToHtml(String content) {\n\n if (content.length() == 0) {\n return \"\";\n }\n StringBuilder buffer = new StringBuilder();\n for (String line : content.split(\"\\n\")) {\n buffer.append(CmsEncoder.escapeXml(line) + \"<br>\");\n }\n return buffer.toString();\n }",
"public static void validate(final ArtifactQuery artifactQuery) {\n final Pattern invalidChars = Pattern.compile(\"[^A-Fa-f0-9]\");\n if(artifactQuery.getUser() == null ||\n \t\tartifactQuery.getUser().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [user] missing\")\n .build());\n }\n if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid [stage] value (supported 0 | 1)\")\n .build());\n }\n if(artifactQuery.getName() == null ||\n \t\tartifactQuery.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [name] missing, it should be the file name\")\n .build());\n }\n if(artifactQuery.getSha256() == null ||\n artifactQuery.getSha256().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [sha256] missing\")\n .build());\n }\n if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid file checksum value\")\n .build());\n }\n if(artifactQuery.getType() == null ||\n \t\tartifactQuery.getType().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [type] missing\")\n .build());\n }\n }",
"public int getCurrentMethodOrdinal(int overrideId, int pathId, String clientUUID, String[] filters) throws Exception {\n int currentOrdinal = 0;\n List<EnabledEndpoint> enabledEndpoints = getEnabledEndpoints(pathId, clientUUID, filters);\n for (EnabledEndpoint enabledEndpoint : enabledEndpoints) {\n if (enabledEndpoint.getOverrideId() == overrideId) {\n currentOrdinal++;\n }\n }\n return currentOrdinal;\n }",
"public void refreshBitmapShader()\n\t{\n\t\tshader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);\n\t}",
"public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, java.io.IOException\r\n {\r\n if (flavor.isMimeTypeEqual(OJBMETADATA_FLAVOR))\r\n return selectedDescriptors;\r\n else\r\n throw new UnsupportedFlavorException(flavor);\r\n }",
"public static base_responses add(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction addresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].profilename = resources[i].profilename;\n\t\t\t\taddresources[i].parameters = resources[i].parameters;\n\t\t\t\taddresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\taddresources[i].quiettime = resources[i].quiettime;\n\t\t\t\taddresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"@UiThread\n public void collapseParentRange(int startParentPosition, int parentCount) {\n int endParentPosition = startParentPosition + parentCount;\n for (int i = startParentPosition; i < endParentPosition; i++) {\n collapseParent(i);\n }\n }",
"protected float getLayoutOffset() {\n //final int offsetSign = getOffsetSign();\n final float axisSize = getViewPortSize(getOrientationAxis());\n float layoutOffset = - axisSize / 2;\n Log.d(LAYOUT, TAG, \"getLayoutOffset(): dimension: %5.2f, layoutOffset: %5.2f\",\n axisSize, layoutOffset);\n\n return layoutOffset;\n }",
"public Integer getIdFromName(String profileName) {\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.PROFILE_PROFILE_NAME + \" = ?\");\n query.setString(1, profileName);\n results = query.executeQuery();\n if (results.next()) {\n Object toReturn = results.getObject(Constants.GENERIC_ID);\n query.close();\n return (Integer) toReturn;\n }\n query.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }"
] |
Set the String-representation of size.
Like: Square, Thumbnail, Small, Medium, Large, Original.
@param label | [
"public void setLabel(String label) {\n\n int ix = lstSizes.indexOf(label);\n if (ix != -1) {\n setLabel(ix);\n }\n }"
] | [
"public void runOnInvariantViolationPlugins(Invariant invariant,\n\t\t\tCrawlerContext context) {\n\t\tLOGGER.debug(\"Running OnInvariantViolationPlugins...\");\n\t\tcounters.get(OnInvariantViolationPlugin.class).inc();\n\t\tfor (Plugin plugin : plugins.get(OnInvariantViolationPlugin.class)) {\n\t\t\tif (plugin instanceof OnInvariantViolationPlugin) {\n\t\t\t\ttry {\n\t\t\t\t\tLOGGER.debug(\"Calling plugin {}\", plugin);\n\t\t\t\t\t((OnInvariantViolationPlugin) plugin).onInvariantViolation(\n\t\t\t\t\t\t\tinvariant, context);\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\treportFailingPlugin(plugin, e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public AlbumArt requestArtworkFrom(final DataReference artReference, final CdjStatus.TrackType trackType) {\n ensureRunning();\n AlbumArt artwork = findArtInMemoryCaches(artReference); // First check the in-memory artwork caches.\n if (artwork == null) {\n artwork = requestArtworkInternal(artReference, trackType, false);\n }\n return artwork;\n }",
"public DataSetInfo create(int dataSet) throws InvalidDataSetException {\r\n\t\tDataSetInfo info = dataSets.get(createKey(dataSet));\r\n\t\tif (info == null) {\r\n\t\t\tint recordNumber = (dataSet >> 8) & 0xFF;\r\n\t\t\tint dataSetNumber = dataSet & 0xFF;\r\n\t\t\tthrow new UnsupportedDataSetException(recordNumber + \":\" + dataSetNumber);\r\n\t\t\t// info = super.create(dataSet);\r\n\t\t}\r\n\t\treturn info;\r\n\t}",
"@SuppressWarnings(\"unchecked\")\r\n\tpublic <T> T convertElement(ConversionContext context, Object source,\r\n\t\t\tTypeReference<T> destinationType) throws ConverterException {\r\n\t\treturn (T) elementConverter.convert(context, source, destinationType);\r\n\t}",
"public void addHiDpiImage(String factor, CmsJspImageBean image) {\n\n if (m_hiDpiImages == null) {\n m_hiDpiImages = CmsCollectionsGenericWrapper.createLazyMap(new CmsScaleHiDpiTransformer());\n }\n m_hiDpiImages.put(factor, image);\n }",
"public void register(Delta delta) {\n\t\tfinal IResourceDescription newDesc = delta.getNew();\n\t\tif (newDesc == null) {\n\t\t\tremoveDescription(delta.getUri());\n\t\t} else {\n\t\t\taddDescription(delta.getUri(), newDesc);\n\t\t}\n\t}",
"public static Session getSession(final ServerSetup setup, Properties mailProps) {\r\n Properties props = setup.configureJavaMailSessionProperties(mailProps, false);\r\n\r\n log.debug(\"Mail session properties are {}\", props);\r\n\r\n return Session.getInstance(props, null);\r\n }",
"protected void convertToHours(LinkedList<TimephasedWork> list)\n {\n for (TimephasedWork assignment : list)\n {\n Duration totalWork = assignment.getTotalAmount();\n Duration workPerDay = assignment.getAmountPerDay();\n totalWork = Duration.getInstance(totalWork.getDuration() / 60, TimeUnit.HOURS);\n workPerDay = Duration.getInstance(workPerDay.getDuration() / 60, TimeUnit.HOURS);\n assignment.setTotalAmount(totalWork);\n assignment.setAmountPerDay(workPerDay);\n }\n }",
"public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {\n DMatrixRMaj A = new DMatrixRMaj(length,length);\n\n symmetric(A,min,max,rand);\n\n return A;\n }"
] |
Use this API to fetch cachepolicylabel resource of given name . | [
"public static cachepolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel obj = new cachepolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel response = (cachepolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"private static Path resolveDockerDefinition(Path fullpath) {\n final Path ymlPath = fullpath.resolveSibling(fullpath.getFileName() + \".yml\");\n if (Files.exists(ymlPath)) {\n return ymlPath;\n } else {\n final Path yamlPath = fullpath.resolveSibling(fullpath.getFileName() + \".yaml\");\n if (Files.exists(yamlPath)) {\n return yamlPath;\n }\n }\n\n return null;\n }",
"public static base_response update(nitro_service client, vlan resource) throws Exception {\n\t\tvlan updateresource = new vlan();\n\t\tupdateresource.id = resource.id;\n\t\tupdateresource.aliasname = resource.aliasname;\n\t\tupdateresource.ipv6dynamicrouting = resource.ipv6dynamicrouting;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void afterCompletion(int status)\r\n {\r\n if(afterCompletionCall) return;\r\n\r\n log.info(\"Method afterCompletion was called\");\r\n try\r\n {\r\n switch(status)\r\n {\r\n case Status.STATUS_COMMITTED:\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Method afterCompletion: Do commit internal odmg-tx, status of JTA-tx is \" + TxUtil.getStatusString(status));\r\n }\r\n commit();\r\n break;\r\n default:\r\n log.error(\"Method afterCompletion: Do abort call on internal odmg-tx, status of JTA-tx is \" + TxUtil.getStatusString(status));\r\n abort();\r\n }\r\n }\r\n finally\r\n {\r\n afterCompletionCall = true;\r\n log.info(\"Method afterCompletion finished\");\r\n }\r\n }",
"public static <T> Class<T> loadClass(String className, ResourceLoader resourceLoader) {\n try {\n return cast(resourceLoader.classForName(className));\n } catch (ResourceLoadingException e) {\n return null;\n } catch (SecurityException e) {\n return null;\n }\n }",
"public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration(Properties properties,\n ClassLoader... classLoaders) {\n return FactoryServiceHolder.factoryService.newKnowledgeBuilderConfiguration( properties, classLoaders );\n }",
"public String getValueForDisplayValue(final String key) {\n if (mapDisplayValuesToValues.containsKey(key)) {\n return mapDisplayValuesToValues.get(key);\n }\n return key;\n }",
"public static BoxRetentionPolicyAssignment.Info createAssignmentToMetadata(BoxAPIConnection api,\r\n String policyID,\r\n String templateID,\r\n MetadataFieldFilter... filter) {\r\n JsonObject assignTo = new JsonObject().add(\"type\", TYPE_METADATA).add(\"id\", templateID);\r\n JsonArray filters = null;\r\n if (filter.length > 0) {\r\n filters = new JsonArray();\r\n for (MetadataFieldFilter f : filter) {\r\n filters.add(f.getJsonObject());\r\n }\r\n }\r\n return createAssignment(api, policyID, assignTo, filters);\r\n }",
"public JSONObject getPathFromEndpoint(String pathValue, String requestType) throws Exception {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n JSONObject response = new JSONObject(doGet(url, null));\n JSONArray paths = response.getJSONArray(\"paths\");\n for (int i = 0; i < paths.length(); i++) {\n JSONObject path = paths.getJSONObject(i);\n if (path.getString(\"path\").equals(pathValue) && path.getInt(\"requestType\") == type) {\n return path;\n }\n }\n return null;\n }",
"private static String getLogManagerLoggerName(final String name) {\n return (name.equals(RESOURCE_NAME) ? CommonAttributes.ROOT_LOGGER_NAME : name);\n }"
] |
Undo a prior removal using the supplied undo key.
@param removalKey - The key returned from the call to removeRoleMapping.
@return true if the undo was successful, false otherwise. | [
"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 addFilters(MpxjTreeNode parentNode, List<Filter> filters)\n {\n for (Filter field : filters)\n {\n final Filter f = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n return f.getName();\n }\n };\n parentNode.add(childNode);\n }\n }",
"public DefaultStreamingEndpoint languages(List<String> languages) {\n addPostParameter(Constants.LANGUAGE_PARAM, Joiner.on(',').join(languages));\n return this;\n }",
"public Collection<Tag> getListUser(String userId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_USER);\n\n parameters.put(\"user_id\", userId);\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 whoElement = response.getPayload();\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) whoElement.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.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n return tags;\n }",
"public static Info eye( final Variable A , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableMatrix ) {\n ret.op = new Operation(\"eye-m\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)A).matrix;\n output.matrix.reshape(mA.numRows,mA.numCols);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else if( A instanceof VariableInteger ) {\n ret.op = new Operation(\"eye-i\") {\n @Override\n public void process() {\n int N = ((VariableInteger)A).value;\n output.matrix.reshape(N,N);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable type \"+A);\n }\n\n return ret;\n }",
"public long addAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.sadd(getKey(), members);\n }\n });\n }",
"public static boolean isClosureDeclaration(ASTNode expression) {\r\n if (expression instanceof DeclarationExpression) {\r\n if (((DeclarationExpression) expression).getRightExpression() instanceof ClosureExpression) {\r\n return true;\r\n }\r\n }\r\n if (expression instanceof FieldNode) {\r\n ClassNode type = ((FieldNode) expression).getType();\r\n if (AstUtil.classNodeImplementsType(type, Closure.class)) {\r\n return true;\r\n } else if (((FieldNode) expression).getInitialValueExpression() instanceof ClosureExpression) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public void increasePriority(int overrideId, int ordinal, int pathId, String clientUUID) {\n logger.info(\"Increase priority\");\n\n int origPriority = -1;\n int newPriority = -1;\n int origId = 0;\n int newId = 0;\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n results = null;\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n statement.setInt(1, pathId);\n statement.setString(2, clientUUID);\n results = statement.executeQuery();\n\n int ordinalCount = 0;\n while (results.next()) {\n if (results.getInt(Constants.ENABLED_OVERRIDES_OVERRIDE_ID) == overrideId) {\n ordinalCount++;\n if (ordinalCount == ordinal) {\n origPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n origId = results.getInt(Constants.GENERIC_ID);\n break;\n }\n }\n newPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n newId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n // update priorities\n if (origPriority != -1 && newPriority != -1) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, origPriority);\n statement.setInt(2, newId);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, newPriority);\n statement.setInt(2, origId);\n statement.executeUpdate();\n }\n } catch (Exception e) {\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"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 void registerOgmExternalizers(SerializationConfigurationBuilder cfg) {\n\t\tfor ( AdvancedExternalizer<?> advancedExternalizer : ogmExternalizers.values() ) {\n\t\t\tcfg.addAdvancedExternalizer( advancedExternalizer );\n\t\t}\n\t}"
] |
Process dump file data from the given input stream. The method can
recover from an errors that occurred while processing an input stream,
which is assumed to contain the JSON serialization of a list of JSON
entities, with each entity serialization in one line. To recover from the
previous error, the first line is skipped.
@param inputStream
the stream to read from
@throws IOException
if there is a problem reading the stream | [
"private void processDumpFileContentsRecovery(InputStream inputStream)\n\t\t\tthrows IOException {\n\t\tJsonDumpFileProcessor.logger\n\t\t\t\t.warn(\"Entering recovery mode to parse rest of file. This might be slightly slower.\");\n\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(\n\t\t\t\tinputStream));\n\n\t\tString line = br.readLine();\n\t\tif (line == null) { // can happen if iterator already has consumed all\n\t\t\t\t\t\t\t// the stream\n\t\t\treturn;\n\t\t}\n\t\tif (line.length() >= 100) {\n\t\t\tline = line.substring(0, 100) + \"[...]\"\n\t\t\t\t\t+ line.substring(line.length() - 50);\n\t\t}\n\t\tJsonDumpFileProcessor.logger.warn(\"Skipping rest of current line: \"\n\t\t\t\t+ line);\n\n\t\tline = br.readLine();\n\t\twhile (line != null && line.length() > 1) {\n\t\t\ttry {\n\t\t\t\tEntityDocument document;\n\t\t\t\tif (line.charAt(line.length() - 1) == ',') {\n\t\t\t\t\tdocument = documentReader.readValue(line.substring(0,\n\t\t\t\t\t\t\tline.length() - 1));\n\t\t\t\t} else {\n\t\t\t\t\tdocument = documentReader.readValue(line);\n\t\t\t\t}\n\t\t\t\thandleDocument(document);\n\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\tlogJsonProcessingException(e);\n\t\t\t\tJsonDumpFileProcessor.logger.error(\"Problematic line was: \"\n\t\t\t\t\t\t+ line.substring(0, Math.min(50, line.length()))\n\t\t\t\t\t\t+ \"...\");\n\t\t\t}\n\n\t\t\tline = br.readLine();\n\t\t}\n\t}"
] | [
"public void addChildTask(Task child, int childOutlineLevel)\n {\n int outlineLevel = NumberHelper.getInt(getOutlineLevel());\n\n if ((outlineLevel + 1) == childOutlineLevel)\n {\n m_children.add(child);\n setSummary(true);\n }\n else\n {\n if (m_children.isEmpty() == false)\n {\n (m_children.get(m_children.size() - 1)).addChildTask(child, childOutlineLevel);\n }\n }\n }",
"public void setShowOutput(String mode) {\n try {\n this.outputMode = OutputMode.valueOf(mode.toUpperCase(Locale.ROOT));\n } catch (IllegalArgumentException e) {\n throw new IllegalArgumentException(\"showOutput accepts any of: \"\n + Arrays.toString(OutputMode.values()) + \", value is not valid: \" + mode);\n }\n }",
"public static StringTemplateGroup readStringTemplateGroup(InputStream stream) {\n\n try {\n return new StringTemplateGroup(\n new InputStreamReader(stream, \"UTF-8\"),\n DefaultTemplateLexer.class,\n new StringTemplateErrorListener() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void error(String arg0, Throwable arg1) {\n\n LOG.error(arg0 + \": \" + arg1.getMessage(), arg1);\n }\n\n @SuppressWarnings(\"synthetic-access\")\n public void warning(String arg0) {\n\n LOG.warn(arg0);\n\n }\n });\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return new StringTemplateGroup(\"dummy\");\n }\n }",
"public void show() {\n if (!(container instanceof RootPanel)) {\n if (!(container instanceof MaterialDialog)) {\n container.getElement().getStyle().setPosition(Style.Position.RELATIVE);\n }\n div.getElement().getStyle().setPosition(Style.Position.ABSOLUTE);\n }\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.HIDDEN);\n }\n if (type == LoaderType.CIRCULAR) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.LOADER_WRAPPER);\n div.add(preLoader);\n } else if (type == LoaderType.PROGRESS) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.PROGRESS_WRAPPER);\n progress.getElement().getStyle().setProperty(\"margin\", \"auto\");\n div.add(progress);\n }\n container.add(div);\n }",
"private YearWeek with(int newYear, int newWeek) {\n if (year == newYear && week == newWeek) {\n return this;\n }\n return of(newYear, newWeek);\n }",
"protected final void error(final HttpServletResponse httpServletResponse, final Throwable e) {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n LOGGER.error(\"Error while processing request\", e);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }",
"public static String resolveProxyUrl(String relativeUrl, TileMap tileMap, String baseTmsUrl) {\n\t\tTileCode tc = parseTileCode(relativeUrl);\n\t\treturn buildUrl(tc, tileMap, baseTmsUrl);\n\t}",
"public JsonNode wbSetLabel(String id, String site, String title,\n\t\t\tString newEntity, String language, String value,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(language,\n\t\t\t\t\"Language parameter cannot be null when setting a label\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"language\", language);\n\t\tif (value != null) {\n\t\t\tparameters.put(\"value\", value);\n\t\t}\n\t\t\n\t\tJsonNode response = performAPIAction(\"wbsetlabel\", id, site, title, newEntity,\n\t\t\t\tparameters, summary, baserevid, bot);\n\t\treturn response;\n\t}",
"public static void doEnqueue(final Jedis jedis, final String namespace, final String queue, final String jobJson) {\n jedis.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n jedis.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }"
] |
Returns a list of Elements form the DOM tree, matching the tag element. | [
"private ImmutableList<Element> getNodeListForTagElement(Document dom,\n\t\t\tCrawlElement crawlElement,\n\t\t\tEventableConditionChecker eventableConditionChecker) {\n\n\t\tBuilder<Element> result = ImmutableList.builder();\n\n\t\tif (crawlElement.getTagName() == null) {\n\t\t\treturn result.build();\n\t\t}\n\n\t\tEventableCondition eventableCondition =\n\t\t\t\teventableConditionChecker.getEventableCondition(crawlElement.getId());\n\t\t// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent\n\t\t// performance problems.\n\t\tImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);\n\n\t\tNodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());\n\n\t\tfor (int k = 0; k < nodeList.getLength(); k++) {\n\n\t\t\tElement element = (Element) nodeList.item(k);\n\t\t\tboolean matchesXpath =\n\t\t\t\t\telementMatchesXpath(eventableConditionChecker, eventableCondition,\n\t\t\t\t\t\t\texpressions, element);\n\t\t\tLOG.debug(\"Element {} matches Xpath={}\", DomUtils.getElementString(element),\n\t\t\t\t\tmatchesXpath);\n\t\t\t/*\n\t\t\t * TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return\n\t\t\t * false and when needed to add it can return true. / check if element is a candidate\n\t\t\t */\n\t\t\tString id = element.getNodeName() + \": \" + DomUtils.getAllElementAttributes(element);\n\t\t\tif (matchesXpath && !checkedElements.isChecked(id)\n\t\t\t\t\t&& !isExcluded(dom, element, eventableConditionChecker)) {\n\t\t\t\taddElement(element, result, crawlElement);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Element {} was not added\", element);\n\t\t\t}\n\t\t}\n\t\treturn result.build();\n\t}"
] | [
"public synchronized void removeAllSceneObjects() {\n final GVRCameraRig rig = getMainCameraRig();\n final GVRSceneObject head = rig.getOwnerObject();\n rig.removeAllChildren();\n\n NativeScene.removeAllSceneObjects(getNative());\n for (final GVRSceneObject child : mSceneRoot.getChildren()) {\n child.getParent().removeChildObject(child);\n }\n\n if (null != head) {\n mSceneRoot.addChildObject(head);\n }\n\n final int numControllers = getGVRContext().getInputManager().clear();\n if (numControllers > 0)\n {\n getGVRContext().getInputManager().selectController();\n }\n\n getGVRContext().runOnGlThread(new Runnable() {\n @Override\n public void run() {\n NativeScene.deleteLightsAndDepthTextureOnRenderThread(getNative());\n }\n });\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 Map<Integer, Integer>\n getMapOfContiguousPartitionRunLengths(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId);\n Map<Integer, Integer> runLengthToCount = Maps.newHashMap();\n\n if(idToRunLength.isEmpty()) {\n return runLengthToCount;\n }\n\n for(int runLength: idToRunLength.values()) {\n if(!runLengthToCount.containsKey(runLength)) {\n runLengthToCount.put(runLength, 0);\n }\n runLengthToCount.put(runLength, runLengthToCount.get(runLength) + 1);\n }\n\n return runLengthToCount;\n }",
"public static csvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cachepolicy_binding obj = new csvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cachepolicy_binding response[] = (csvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void pushDryRun() throws Exception {\n if (releaseAction.isCreateVcsTag()) {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), releaseAction.getTagUrl())) {\n throw new Exception(String.format(\"Tag with name '%s' already exists\", releaseAction.getTagUrl()));\n }\n }\n\n String testTagName = releaseAction.getTagUrl() + \"_test\";\n try {\n scmManager.testPush(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName);\n } catch (Exception e) {\n throw new Exception(String.format(\"Failed while attempting push dry-run: %s\", e.getMessage()), e);\n } finally {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName)) {\n scmManager.deleteLocalTag(testTagName);\n }\n }\n }",
"public static XClass getMemberType() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getType();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n XMethod method = getCurrentMethod();\r\n\r\n if (MethodTagsHandler.isGetterMethod(method)) {\r\n return method.getReturnType().getType();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getType();\r\n }\r\n }\r\n return null;\r\n }",
"public static base_response Import(nitro_service client, application resource) throws Exception {\n\t\tapplication Importresource = new application();\n\t\tImportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\tImportresource.appname = resource.appname;\n\t\tImportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"public Object invokeOperation(Map<String, String[]> parameterMap) throws JMException {\n MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature();\n\n Object[] values = new Object[parameterInfoArray.length];\n String[] types = new String[parameterInfoArray.length];\n\n MBeanValueConverter valueConverter = createMBeanValueConverter(parameterMap);\n\n for (int parameterNum = 0; parameterNum < parameterInfoArray.length; parameterNum++) {\n MBeanParameterInfo parameterInfo = parameterInfoArray[parameterNum];\n String type = parameterInfo.getType();\n types[parameterNum] = type;\n values[parameterNum] = valueConverter.convertParameterValue(parameterInfo.getName(), type);\n }\n\n return mBeanServer.invoke(objectName, operationInfo.getName(), values, types);\n }",
"public void updateIteratorPosition(int length) {\n if(length > 0) {\n //make sure we dont go OB\n if((length + character) > parsedLine.line().length())\n length = parsedLine.line().length() - character;\n\n //move word counter to the correct word\n while(hasNextWord() &&\n (length + character) >= parsedLine.words().get(word).lineIndex() +\n parsedLine.words().get(word).word().length())\n word++;\n\n character = length + character;\n }\n else\n throw new IllegalArgumentException(\"The length given must be > 0 and not exceed the boundary of the line (including the current position)\");\n }"
] |
Convenience method for retrieving an Object resource.
@param locale locale identifier
@param key resource key
@return resource value | [
"public static final Object getObject(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return (bundle.getObject(key));\n }"
] | [
"public void inverse(GVRPose src)\n {\n if (getSkeleton() != src.getSkeleton())\n throw new IllegalArgumentException(\"GVRPose.copy: input pose is incompatible with this pose\");\n src.sync();\n int numbones = getNumBones();\n Bone srcBone = src.mBones[0];\n Bone dstBone = mBones[0];\n\n mNeedSync = true;\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n srcBone.LocalMatrix.set(dstBone.WorldMatrix);\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(0), dstBone.toString());\n\n }\n for (int i = 1; i < numbones; ++i)\n {\n srcBone = src.mBones[i];\n dstBone = mBones[i];\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n dstBone.Changed = WORLD_ROT | WORLD_POS;\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(i), dstBone.toString());\n }\n }\n sync();\n }",
"public void sendMessageToAgents(String[] agent_name, String msgtype,\n Object message_content, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }",
"public static base_response clear(nitro_service client, bridgetable resource) throws Exception {\n\t\tbridgetable clearresource = new bridgetable();\n\t\tclearresource.vlan = resource.vlan;\n\t\tclearresource.ifnum = resource.ifnum;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"@Override\n public void onNewState(CrawlerContext context, StateVertex vertex) {\n LOG.debug(\"onNewState\");\n StateBuilder state = outModelCache.addStateIfAbsent(vertex);\n visitedStates.putIfAbsent(state.getName(), vertex);\n\n saveScreenshot(context.getBrowser(), state.getName(), vertex);\n\n outputBuilder.persistDom(state.getName(), context.getBrowser().getUnStrippedDom());\n }",
"public static String format(Flags flags) {\r\n StringBuilder buf = new StringBuilder();\r\n buf.append('(');\r\n if (flags.contains(Flags.Flag.ANSWERED)) {\r\n buf.append(\"\\\\Answered \");\r\n }\r\n if (flags.contains(Flags.Flag.DELETED)) {\r\n buf.append(\"\\\\Deleted \");\r\n }\r\n if (flags.contains(Flags.Flag.DRAFT)) {\r\n buf.append(\"\\\\Draft \");\r\n }\r\n if (flags.contains(Flags.Flag.FLAGGED)) {\r\n buf.append(\"\\\\Flagged \");\r\n }\r\n if (flags.contains(Flags.Flag.RECENT)) {\r\n buf.append(\"\\\\Recent \");\r\n }\r\n if (flags.contains(Flags.Flag.SEEN)) {\r\n buf.append(\"\\\\Seen \");\r\n }\r\n String[] userFlags = flags.getUserFlags();\r\n if(null!=userFlags) {\r\n for(String uf: userFlags) {\r\n buf.append(uf).append(' ');\r\n }\r\n }\r\n // Remove the trailing space, if necessary.\r\n if (buf.length() > 1) {\r\n buf.setLength(buf.length() - 1);\r\n }\r\n buf.append(')');\r\n return buf.toString();\r\n }",
"private void appendSubQuery(Query subQuery, StringBuffer buf)\r\n {\r\n buf.append(\" (\");\r\n buf.append(getSubQuerySQL(subQuery));\r\n buf.append(\") \");\r\n }",
"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 static vpnglobal_intranetip_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_intranetip_binding obj = new vpnglobal_intranetip_binding();\n\t\tvpnglobal_intranetip_binding response[] = (vpnglobal_intranetip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static java.util.Date toDateTime(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.util.Date) {\n return (java.util.Date) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return IN_DATETIME_FORMAT.parse((String) value);\n }\n\n return IN_DATETIME_FORMAT.parse(value.toString());\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.