query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Returns the value of the specified matrix element. Performs a bounds check to make sure the requested element is part of the matrix. @param row The row of the element. @param col The column of the element. @return The value of the element.
[ "@Override\n public double get( int row , int col ) {\n if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {\n throw new IllegalArgumentException(\"Specified element is out of bounds: \"+row+\" \"+col);\n }\n\n return data[ row * numCols + col ];\n }" ]
[ "public void clear() {\n valueBoxBase.setText(\"\");\n clearStatusText();\n\n if (getPlaceholder() == null || getPlaceholder().isEmpty()) {\n label.removeStyleName(CssName.ACTIVE);\n }\n }", "public static ResourceResolutionContext context(ResourceResolutionComponent[] components,\n Map<String, Object> messageParams) {\n return new ResourceResolutionContext(components, messageParams);\n }", "public void setModel(Database databaseModel, DescriptorRepository objModel)\r\n {\r\n _dbModel = databaseModel;\r\n _preparedModel = new PreparedModel(objModel, databaseModel);\r\n }", "public GVRAnimator animate(int animIndex, float timeInSec)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n anim.animate(timeInSec);\n return anim;\n }", "private static String guessPackaging(ProjectModel projectModel)\n {\n String projectType = projectModel.getProjectType();\n if (projectType != null)\n return projectType;\n\n LOG.warning(\"WINDUP-983 getProjectType() returned null for: \" + projectModel.getRootFileModel().getPrettyPath());\n\n String suffix = StringUtils.substringAfterLast(projectModel.getRootFileModel().getFileName(), \".\");\n if (\"jar war ear sar har \".contains(suffix+\" \")){\n projectModel.setProjectType(suffix); // FIXME: Remove when WINDUP-983 is fixed.\n return suffix;\n }\n\n // Should we try something more? Used APIs? What if it's a source?\n\n return \"unknown\";\n }", "public static void pushImage(String imageTag, String username, String password, String host) throws IOException {\n final AuthConfig authConfig = new AuthConfig();\n authConfig.withUsername(username);\n authConfig.withPassword(password);\n\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n dockerClient.pushImageCmd(imageTag).withAuthConfig(authConfig).exec(new PushImageResultCallback()).awaitSuccess();\n } finally {\n closeQuietly(dockerClient);\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 }", "public static ServiceController<DeploymentScanner> addService(final OperationContext context, final PathAddress resourceAddress, final String relativeTo, final String path,\n final int scanInterval, TimeUnit unit, final boolean autoDeployZip,\n final boolean autoDeployExploded, final boolean autoDeployXml, final boolean scanEnabled, final long deploymentTimeout, boolean rollbackOnRuntimeFailure,\n final FileSystemDeploymentService bootTimeService, final ScheduledExecutorService scheduledExecutorService) {\n final DeploymentScannerService service = new DeploymentScannerService(resourceAddress, relativeTo, path, scanInterval, unit, autoDeployZip,\n autoDeployExploded, autoDeployXml, scanEnabled, deploymentTimeout, rollbackOnRuntimeFailure, bootTimeService);\n final ServiceName serviceName = getServiceName(resourceAddress.getLastElement().getValue());\n service.scheduledExecutorValue.inject(scheduledExecutorService);\n final ServiceBuilder<DeploymentScanner> sb = context.getServiceTarget().addService(serviceName, service);\n sb.addDependency(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class), PathManager.class, service.pathManagerValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.notification-handler-registry\", null),\n NotificationHandlerRegistry.class, service.notificationRegistryValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.model-controller-client-factory\", null),\n ModelControllerClientFactory.class, service.clientFactoryValue);\n sb.requires(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_CHAINS);\n sb.addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.controlledProcessStateServiceValue);\n return sb.install();\n }", "public void rollback() throws GeomajasException {\n\t\ttry {\n\t\t\tsetConfigLocations(previousConfigLocations);\n\t\t\trefresh();\n\t\t} catch (Exception e) {\n\t\t\tthrow new GeomajasException(e, ExceptionCode.REFRESH_CONFIGURATION_FAILED);\n\t\t}\n\t}" ]
Can be overridden if you want to replace or supplement the debug handling for responses. @param responseCode @param inputStream
[ "protected void handleResponse(int responseCode, InputStream inputStream) {\n BufferedReader rd = null;\n try {\n // Buffer the result into a string\n rd = new BufferedReader(new InputStreamReader(inputStream));\n StringBuilder sb = new StringBuilder();\n String line;\n while((line = rd.readLine()) != null) {\n sb.append(line);\n }\n log.info(\"HttpHook [\" + hookName + \"] received \" + responseCode + \" response: \" + sb);\n } catch (IOException e) {\n log.error(\"Error while reading response for HttpHook [\" + hookName + \"]\", e);\n } finally {\n if (rd != null) {\n try {\n rd.close();\n } catch (IOException e) {\n // no-op\n }\n }\n }\n }" ]
[ "public static responderglobal_responderpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tresponderglobal_responderpolicy_binding obj = new responderglobal_responderpolicy_binding();\n\t\tresponderglobal_responderpolicy_binding response[] = (responderglobal_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public int getTotalCreatedConnections(){\r\n\t\tint total=0;\r\n\t\tfor (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){\r\n\t\t\ttotal+=this.partitions[i].getCreatedConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}", "public static int cudnnGetRNNDataDescriptor(\n cudnnRNNDataDescriptor RNNDataDesc, \n int[] dataType, \n int[] layout, \n int[] maxSeqLength, \n int[] batchSize, \n int[] vectorSize, \n int arrayLengthRequested, \n int[] seqLengthArray, \n Pointer paddingFill)\n {\n return checkResult(cudnnGetRNNDataDescriptorNative(RNNDataDesc, dataType, layout, maxSeqLength, batchSize, vectorSize, arrayLengthRequested, seqLengthArray, paddingFill));\n }", "protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\n }", "public HashMap<String, IndexInput> getIndexInputList() {\n HashMap<String, IndexInput> clonedIndexInputList = new HashMap<String, IndexInput>();\n for (Entry<String, IndexInput> entry : indexInputList.entrySet()) {\n clonedIndexInputList.put(entry.getKey(), entry.getValue().clone());\n }\n return clonedIndexInputList;\n }", "private Integer mapTaskID(Integer id)\n {\n Integer mappedID = m_clashMap.get(id);\n if (mappedID == null)\n {\n mappedID = id;\n }\n return (mappedID);\n }", "private List<DumpProcessingAction> handleArguments(String[] args) {\n\t\tCommandLine cmd;\n\t\tCommandLineParser parser = new GnuParser();\n\n\t\ttry {\n\t\t\tcmd = parser.parse(options, args);\n\t\t} catch (ParseException e) {\n\t\t\tlogger.error(\"Failed to parse arguments: \" + e.getMessage());\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\t// Stop processing if a help text is to be printed:\n\t\tif ((cmd.hasOption(CMD_OPTION_HELP)) || (args.length == 0)) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tList<DumpProcessingAction> configuration = new ArrayList<>();\n\n\t\thandleGlobalArguments(cmd);\n\n\t\tif (cmd.hasOption(CMD_OPTION_ACTION)) {\n\t\t\tDumpProcessingAction action = handleActionArguments(cmd);\n\t\t\tif (action != null) {\n\t\t\t\tconfiguration.add(action);\n\t\t\t}\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CONFIG_FILE)) {\n\t\t\ttry {\n\t\t\t\tList<DumpProcessingAction> configFile = readConfigFile(cmd\n\t\t\t\t\t\t.getOptionValue(CMD_OPTION_CONFIG_FILE));\n\t\t\t\tconfiguration.addAll(configFile);\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"Failed to read configuration file \\\"\"\n\t\t\t\t\t\t+ cmd.getOptionValue(CMD_OPTION_CONFIG_FILE) + \"\\\": \"\n\t\t\t\t\t\t+ e.toString());\n\t\t\t}\n\n\t\t}\n\n\t\treturn configuration;\n\n\t}", "private String GCMGetFreshToken(final String senderID) {\n getConfigLogger().verbose(getAccountId(), \"GcmManager: Requesting a GCM token for Sender ID - \" + senderID);\n String token = null;\n try {\n token = InstanceID.getInstance(context)\n .getToken(senderID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);\n getConfigLogger().info(getAccountId(), \"GCM token : \" + token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"GcmManager: Error requesting GCM token\", t);\n }\n return token;\n }", "public static base_response update(nitro_service client, cacheselector resource) throws Exception {\n\t\tcacheselector updateresource = new cacheselector();\n\t\tupdateresource.selectorname = resource.selectorname;\n\t\tupdateresource.rule = resource.rule;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Return a capitalized version of the specified property name. @param s The property name
[ "public static String capitalizePropertyName(String s) {\r\n\t\tif (s.length() == 0) {\r\n\t\t\treturn s;\r\n\t\t}\r\n\r\n\t\tchar[] chars = s.toCharArray();\r\n\t\tchars[0] = Character.toUpperCase(chars[0]);\r\n\t\treturn new String(chars);\r\n\t}" ]
[ "public int getCostRateTableIndex()\n {\n Integer value = (Integer) getCachedValue(AssignmentField.COST_RATE_TABLE);\n return value == null ? 0 : value.intValue();\n }", "public void stopServer() throws Exception {\n if (!externalDatabaseHost) {\n try (Connection sqlConnection = getConnection()) {\n sqlConnection.prepareStatement(\"SHUTDOWN\").execute();\n } catch (Exception e) {\n }\n\n try {\n server.stop();\n } catch (Exception e) {\n }\n }\n }", "private void disableTalkBack() {\n GVRSceneObject[] sceneObjects = mGvrContext.getMainScene().getWholeSceneObjects();\n for (GVRSceneObject sceneObject : sceneObjects) {\n if (sceneObject instanceof GVRAccessiblityObject)\n if (((GVRAccessiblityObject) sceneObject).getTalkBack() != null)\n ((GVRAccessiblityObject) sceneObject).getTalkBack().setActive(false);\n\n }\n }", "private void addToGraph(ClassDoc cd) {\n\t// avoid adding twice the same class, but don't rely on cg.getClassInfo\n\t// since there are other ways to add a classInfor than printing the class\n\tif (visited.contains(cd.toString()))\n\t return;\n\n\tvisited.add(cd.toString());\n\tcg.printClass(cd, false);\n\tcg.printRelations(cd);\n\tif (opt.inferRelationships)\n\t cg.printInferredRelations(cd);\n\tif (opt.inferDependencies)\n\t cg.printInferredDependencies(cd);\n }", "public static long getTxInfoCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(TX_INFO_CACHE_WEIGHT, TX_INFO_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\"Cache size must be positive for \" + TX_INFO_CACHE_WEIGHT);\n }\n return size;\n }", "private void checkModifications(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap features = new HashMap();\r\n FeatureDescriptorDef def;\r\n\r\n for (Iterator it = classDef.getFields(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getReferences(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getCollections(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n\r\n // now checking the modifications\r\n Properties mods;\r\n String modName;\r\n String propName;\r\n\r\n for (Iterator it = classDef.getModificationNames(); it.hasNext();)\r\n {\r\n modName = (String)it.next();\r\n if (!features.containsKey(modName))\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for an unknown feature \"+modName);\r\n }\r\n def = (FeatureDescriptorDef)features.get(modName);\r\n if (def.getOriginal() == null)\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for a feature \"+modName+\" that is not inherited but defined in the same class\");\r\n }\r\n // checking modification\r\n mods = classDef.getModification(modName);\r\n for (Iterator propIt = mods.keySet().iterator(); propIt.hasNext();)\r\n {\r\n propName = (String)propIt.next();\r\n if (!PropertyHelper.isPropertyAllowed(def.getClass(), propName))\r\n {\r\n throw new ConstraintException(\"The modification of attribute \"+propName+\" in class \"+classDef.getName()+\" is not applicable to the feature \"+modName);\r\n }\r\n }\r\n }\r\n }", "public Script getScript(int id) {\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE id = ?\"\n );\n statement.setInt(1, id);\n results = statement.executeQuery();\n if (results.next()) {\n return scriptFromSQLResult(results);\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return null;\n }", "public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{\n\t\tInputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream(\"/\"+baseName + \"_\"+locale.toString()+PROPERTIES_EXT);\n\t\tif(is != null){\n\t\t\treturn new PropertyResourceBundle(new InputStreamReader(is, \"UTF-8\"));\n\t\t}\n\t\treturn null;\n\t}", "public RedwoodConfiguration neatExit(){\r\n tasks.add(new Runnable() { public void run() {\r\n Runtime.getRuntime().addShutdownHook(new Thread(){\r\n @Override public void run(){ Redwood.stop(); }\r\n });\r\n }});\r\n return this;\r\n }" ]
Gets a SerialMessage with the SENSOR_ALARM_SUPPORTED_GET command @return the serial message, or null if the supported command is not supported.
[ "public SerialMessage getSupportedMessage() {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_SUPPORTED_GET for node {}\", this.getNode().getNodeId());\r\n\t\t\r\n\t\tif (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) {\r\n\t\t\tlogger.warn(\"Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET.\");\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\t\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t2, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) SENSOR_ALARM_SUPPORTED_GET };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}" ]
[ "synchronized boolean markReadMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n ContentValues cv = new ContentValues();\n cv.put(IS_READ,1);\n db.update(Table.INBOX_MESSAGES.getName(), cv,_ID + \" = ? AND \" + USER_ID + \" = ?\",new String[]{messageId,userId});\n return true;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }", "public String translatePath(String path) {\n String translated;\n // special character: ~ maps to the user's home directory\n if (path.startsWith(\"~\" + File.separator)) {\n translated = System.getProperty(\"user.home\") + path.substring(1);\n } else if (path.startsWith(\"~\")) {\n String userName = path.substring(1);\n translated = new File(new File(System.getProperty(\"user.home\")).getParent(),\n userName).getAbsolutePath();\n // Keep the path separator in translated or add one if no user home specified\n translated = userName.isEmpty() || path.endsWith(File.separator) ? translated + File.separator : translated;\n } else if (!new File(path).isAbsolute()) {\n translated = ctx.getCurrentDir().getAbsolutePath() + File.separator + path;\n } else {\n translated = path;\n }\n return translated;\n }", "public static base_response add(nitro_service client, dospolicy resource) throws Exception {\n\t\tdospolicy addresource = new dospolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.qdepth = resource.qdepth;\n\t\taddresource.cltdetectrate = resource.cltdetectrate;\n\t\treturn addresource.add_resource(client);\n\t}", "public int executeUpdate(String query) throws Exception {\n int returnVal = 0;\n Statement queryStatement = null;\n\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n returnVal = queryStatement.executeUpdate(query);\n } catch (Exception e) {\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnVal;\n }", "ValidationResult isRestrictedEventName(String name) {\n ValidationResult error = new ValidationResult();\n if (name == null) {\n error.setErrorCode(510);\n error.setErrorDesc(\"Event Name is null\");\n return error;\n }\n for (String x : restrictedNames)\n if (name.equalsIgnoreCase(x)) {\n // The event name is restricted\n\n error.setErrorCode(513);\n error.setErrorDesc(name + \" is a restricted event name. Last event aborted.\");\n Logger.v(name + \" is a restricted system event name. Last event aborted.\");\n return error;\n }\n return error;\n }", "public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) {\n return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }", "public BoxFile.Info uploadFile(InputStream fileContent, String name, long fileSize, ProgressListener listener) {\n FileUploadParams uploadInfo = new FileUploadParams()\n .setContent(fileContent)\n .setName(name)\n .setSize(fileSize)\n .setProgressListener(listener);\n return this.uploadFile(uploadInfo);\n }", "private void waitForOutstandingRequest() throws IOException {\n if (outstandingRequest == null) {\n return;\n }\n try {\n RetryHelper.runWithRetries(new Callable<Void>() {\n @Override\n public Void call() throws IOException, InterruptedException {\n if (RetryHelper.getContext().getAttemptNumber() > 1) {\n outstandingRequest.retry();\n }\n token = outstandingRequest.waitForNextToken();\n outstandingRequest = null;\n return null;\n }\n }, retryParams, GcsServiceImpl.exceptionHandler);\n } catch (RetryInterruptedException ex) {\n token = null;\n throw new ClosedByInterruptException();\n } catch (NonRetriableException e) {\n Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);\n throw e;\n }\n }", "private void processCalendarDays(ProjectCalendar calendar, Record root)\n {\n // Retrieve working hours ...\n Record daysOfWeek = root.getChild(\"DaysOfWeek\");\n if (daysOfWeek != null)\n {\n for (Record dayRecord : daysOfWeek.getChildren())\n {\n processCalendarHours(calendar, dayRecord);\n }\n }\n }" ]
Creates an operation to deploy existing deployment content to the runtime. @param deployment the deployment to deploy @return the deploy operation
[ "public static Operation createDeployOperation(final DeploymentDescription deployment) {\n Assert.checkNotNullParam(\"deployment\", deployment);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n addDeployOperationStep(builder, deployment);\n return builder.build();\n }" ]
[ "@Override\n\tpublic ProxyAuthenticationMethod getMethod() {\n\t\tswitch (authenticationMethod) {\n\t\tcase BASIC:\n\t\t\treturn ProxyAuthenticationMethod.BASIC;\n\t\tcase DIGEST:\n\t\t\treturn ProxyAuthenticationMethod.DIGEST;\n\t\tcase URL:\n\t\t\treturn ProxyAuthenticationMethod.URL;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "public static double elementSumSq( DMatrixD1 m ) {\n\n // minimize round off error\n double maxAbs = CommonOps_DDRM.elementMaxAbs(m);\n if( maxAbs == 0)\n return 0;\n\n double total = 0;\n \n int N = m.getNumElements();\n for( int i = 0; i < N; i++ ) {\n double d = m.data[i]/maxAbs;\n total += d*d;\n }\n\n return maxAbs*total*maxAbs;\n }", "public List<LogSegment> trunc(int newStart) {\n if (newStart < 0) {\n throw new IllegalArgumentException(\"Starting index must be positive.\");\n }\n while (true) {\n List<LogSegment> curr = contents.get();\n int newLength = Math.max(curr.size() - newStart, 0);\n List<LogSegment> updatedList = new ArrayList<LogSegment>(curr.subList(Math.min(newStart, curr.size() - 1),\n curr.size()));\n if (contents.compareAndSet(curr, updatedList)) {\n return curr.subList(0, curr.size() - newLength);\n }\n }\n }", "public ConfigBuilder withSentinels(final Set<String> sentinels) {\n if (sentinels == null || sentinels.size() < 1) {\n throw new IllegalArgumentException(\"sentinels is null or empty: \" + sentinels);\n }\n this.sentinels = sentinels;\n return this;\n }", "@PrefMetadata(type = CmsHiddenBuiltinPreference.class)\n public String getExplorerFileEntryOptions() {\n\n if (m_settings.getExplorerFileEntryOptions() == null) {\n return \"\";\n } else {\n return \"\" + m_settings.getExplorerFileEntryOptions();\n }\n }", "public static Credential getServiceAccountCredential(String serviceAccountId,\n String privateKeyFile, Collection<String> serviceAccountScopes)\n throws GeneralSecurityException, IOException {\n return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes)\n .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFile))\n .build();\n }", "public static DatabaseFieldConfig fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseFieldConfig config = new DatabaseFieldConfig();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseFieldConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseFieldConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}", "public void deleteModule(final String moduleId) {\n final DbModule module = getModule(moduleId);\n repositoryHandler.deleteModule(module.getId());\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n repositoryHandler.deleteArtifact(gavc);\n }\n }", "public void explore() {\n if (isLeaf) return;\n if (isGeneric) return;\n removeAllChildren();\n\n try {\n String addressPath = addressPath();\n ModelNode resourceDesc = executor.doCommand(addressPath + \":read-resource-description\");\n resourceDesc = resourceDesc.get(\"result\");\n ModelNode response = executor.doCommand(addressPath + \":read-resource(include-runtime=true,include-defaults=true)\");\n ModelNode result = response.get(\"result\");\n if (!result.isDefined()) return;\n\n List<String> childrenTypes = getChildrenTypes(addressPath);\n for (ModelNode node : result.asList()) {\n Property prop = node.asProperty();\n if (childrenTypes.contains(prop.getName())) { // resource node\n if (hasGenericOperations(addressPath, prop.getName())) {\n add(new ManagementModelNode(cliGuiCtx, new UserObject(node, prop.getName())));\n }\n if (prop.getValue().isDefined()) {\n for (ModelNode innerNode : prop.getValue().asList()) {\n UserObject usrObj = new UserObject(innerNode, prop.getName(), innerNode.asProperty().getName());\n add(new ManagementModelNode(cliGuiCtx, usrObj));\n }\n }\n } else { // attribute node\n UserObject usrObj = new UserObject(node, resourceDesc, prop.getName(), prop.getValue().asString());\n add(new ManagementModelNode(cliGuiCtx, usrObj));\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }" ]
Sets a request header with the given name and value. If a header with the specified name has already been set then the new value overwrites the current value. @param header the name of the header @param value the value of the header @throws NullPointerException if header or value are null @throws IllegalArgumentException if header or value are the empty string
[ "public void setHeader(String header, String value) {\n StringValidator.throwIfEmptyOrNull(\"header\", header);\n StringValidator.throwIfEmptyOrNull(\"value\", value);\n\n if (headers == null) {\n headers = new HashMap<String, String>();\n }\n\n headers.put(header, value);\n }" ]
[ "public void setMatrix(int[] matrix) {\n\t\tthis.matrix = matrix;\n\t\tsum = 0;\n\t\tfor (int i = 0; i < matrix.length; i++)\n\t\t\tsum += matrix[i];\n\t}", "private Integer getIntegerPropertyOverrideValue(String name, String key) {\n if (properties != null) {\n String propertyName = getPropertyName(name, key);\n\n String propertyOverrideValue = properties.getProperty(propertyName);\n\n if (propertyOverrideValue != null) {\n try {\n return Integer.parseInt(propertyOverrideValue);\n }\n catch (NumberFormatException e) {\n logger.error(\"Could not parse property override key={}, value={}\",\n key, propertyOverrideValue);\n }\n }\n }\n return null;\n }", "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 }", "public static final TimeUnit parseDurationTimeUnits(BigInteger value, TimeUnit defaultValue)\n {\n TimeUnit result = defaultValue;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 3:\n case 35:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 4:\n case 36:\n {\n result = TimeUnit.ELAPSED_MINUTES;\n break;\n }\n\n case 5:\n case 37:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 6:\n case 38:\n {\n result = TimeUnit.ELAPSED_HOURS;\n break;\n }\n\n case 7:\n case 39:\n case 53:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 8:\n case 40:\n {\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 9:\n case 41:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 10:\n case 42:\n {\n result = TimeUnit.ELAPSED_WEEKS;\n break;\n }\n\n case 11:\n case 43:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n case 44:\n {\n result = TimeUnit.ELAPSED_MONTHS;\n break;\n }\n\n case 19:\n case 51:\n {\n result = TimeUnit.PERCENT;\n break;\n }\n\n case 20:\n case 52:\n {\n result = TimeUnit.ELAPSED_PERCENT;\n break;\n }\n\n default:\n {\n result = PARENT_FILE.get().getProjectProperties().getDefaultDurationUnits();\n break;\n }\n }\n }\n\n return (result);\n }", "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 void addJobType(final String jobName, final Class<?> jobType) {\n checkJobType(jobName, jobType);\n this.jobTypes.put(jobName, jobType);\n }", "@Override\n public ImageSource apply(ImageSource input) {\n final int[][] pixelMatrix = new int[3][3];\n\n int w = input.getWidth();\n int h = input.getHeight();\n\n int[][] output = new int[h][w];\n\n for (int j = 1; j < h - 1; j++) {\n for (int i = 1; i < w - 1; i++) {\n pixelMatrix[0][0] = input.getR(i - 1, j - 1);\n pixelMatrix[0][1] = input.getRGB(i - 1, j);\n pixelMatrix[0][2] = input.getRGB(i - 1, j + 1);\n pixelMatrix[1][0] = input.getRGB(i, j - 1);\n pixelMatrix[1][2] = input.getRGB(i, j + 1);\n pixelMatrix[2][0] = input.getRGB(i + 1, j - 1);\n pixelMatrix[2][1] = input.getRGB(i + 1, j);\n pixelMatrix[2][2] = input.getRGB(i + 1, j + 1);\n\n int edge = (int) convolution(pixelMatrix);\n int rgb = (edge << 16 | edge << 8 | edge);\n output[j][i] = rgb;\n }\n }\n\n MatrixSource source = new MatrixSource(output);\n return source;\n }", "public static base_response delete(nitro_service client, lbroute resource) throws Exception {\n\t\tlbroute deleteresource = new lbroute();\n\t\tdeleteresource.network = resource.network;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "private void addOp(String op, String path, String value) {\n if (this.operations == null) {\n this.operations = new JsonArray();\n }\n\n this.operations.add(new JsonObject()\n .add(\"op\", op)\n .add(\"path\", path)\n .add(\"value\", value));\n }" ]
Revert all the working copy changes.
[ "public void revertWorkingCopy() throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new RevertWorkingCopyCallable(getLocation(), getSvnAuthenticationProvider(build), buildListener));\n }" ]
[ "public void forAllClassDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _model.getClasses(); it.hasNext(); )\r\n {\r\n _curClassDef = (ClassDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curClassDef = null;\r\n\r\n LogHelper.debug(true, OjbTagsHandler.class, \"forAllClassDefinitions\", \"Processed \"+_model.getNumClasses()+\" types\");\r\n }", "public static void writeUTF(@NotNull final OutputStream stream, @NotNull final String str) throws IOException {\n try (DataOutputStream dataStream = new DataOutputStream(stream)) {\n int len = str.length();\n if (len < SINGLE_UTF_CHUNK_SIZE) {\n dataStream.writeUTF(str);\n } else {\n int startIndex = 0;\n int endIndex;\n do {\n endIndex = startIndex + SINGLE_UTF_CHUNK_SIZE;\n if (endIndex > len) {\n endIndex = len;\n }\n dataStream.writeUTF(str.substring(startIndex, endIndex));\n startIndex += SINGLE_UTF_CHUNK_SIZE;\n } while (endIndex < len);\n }\n }\n }", "private void updateToNextWorkStart(Calendar cal)\n {\n Date originalDate = cal.getTime();\n\n //\n // Find the date ranges for the current day\n //\n ProjectCalendarDateRanges ranges = getRanges(originalDate, cal, null);\n\n if (ranges != null)\n {\n //\n // Do we have a start time today?\n //\n Date calTime = DateHelper.getCanonicalTime(cal.getTime());\n Date startTime = null;\n for (DateRange range : ranges)\n {\n Date rangeStart = DateHelper.getCanonicalTime(range.getStart());\n Date rangeEnd = DateHelper.getCanonicalTime(range.getEnd());\n Date rangeStartDay = DateHelper.getDayStartDate(range.getStart());\n Date rangeEndDay = DateHelper.getDayStartDate(range.getEnd());\n\n if (rangeStartDay.getTime() != rangeEndDay.getTime())\n {\n rangeEnd = DateHelper.addDays(rangeEnd, 1);\n }\n\n if (calTime.getTime() < rangeEnd.getTime())\n {\n if (calTime.getTime() > rangeStart.getTime())\n {\n startTime = calTime;\n }\n else\n {\n startTime = rangeStart;\n }\n break;\n }\n }\n\n //\n // If we don't have a start time today - find the next working day\n // then retrieve the start time.\n //\n if (startTime == null)\n {\n Day day;\n int nonWorkingDayCount = 0;\n do\n {\n cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1);\n day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n ++nonWorkingDayCount;\n if (nonWorkingDayCount > MAX_NONWORKING_DAYS)\n {\n cal.setTime(originalDate);\n break;\n }\n }\n while (!isWorkingDate(cal.getTime(), day));\n\n startTime = getStartTime(cal.getTime());\n }\n\n DateHelper.setTime(cal, startTime);\n }\n }", "private final boolean matchPattern(byte[][] patterns, int bufferIndex)\n {\n boolean match = false;\n for (byte[] pattern : patterns)\n {\n int index = 0;\n match = true;\n for (byte b : pattern)\n {\n if (b != m_buffer[bufferIndex + index])\n {\n match = false;\n break;\n }\n ++index;\n }\n if (match)\n {\n break;\n }\n }\n return match;\n }", "public String getArtifactLastVersion(final String gavc) {\n final List<String> versions = getArtifactVersions(gavc);\n\n final VersionsHandler versionHandler = new VersionsHandler(repositoryHandler);\n final String viaCompare = versionHandler.getLastVersion(versions);\n\n if (viaCompare != null) {\n return viaCompare;\n }\n\n //\n // These versions cannot be compared\n // Let's use the Collection.max() method by default, so goingo for a fallback\n // mechanism.\n //\n LOG.info(\"The versions cannot be compared\");\n return Collections.max(versions);\n\n }", "public static HashMap<String, JSONObject> flatRessources(JSONObject object) throws JSONException {\n HashMap<String, JSONObject> result = new HashMap<String, JSONObject>();\n\n // no cycle in hierarchies!!\n if (object.has(\"resourceId\") && object.has(\"childShapes\")) {\n result.put(object.getString(\"resourceId\"),\n object);\n JSONArray childShapes = object.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapes.length(); i++) {\n result.putAll(flatRessources(childShapes.getJSONObject(i)));\n }\n }\n ;\n\n return result;\n }", "private RgbaColor withHsl(int index, float value) {\n float[] HSL = convertToHsl();\n HSL[index] = value;\n return RgbaColor.fromHsl(HSL);\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 }", "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}" ]
Removes the specified object in index from the array. @param index The index to remove.
[ "public void removeAt(int index) {\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.remove(index);\n } else {\n mObjects.remove(index);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }" ]
[ "public void evictCache(String key) {\n H.Session sess = session();\n if (null != sess) {\n sess.evict(key);\n } else {\n app().cache().evict(key);\n }\n }", "private static String getBundle(String friendlyName, String className, int truncate)\r\n\t{\r\n\t\ttry {\r\n\t\t\tcl.loadClass(className);\r\n\t\t\tint start = className.length();\r\n\t\t\tfor (int i = 0; i < truncate; ++i)\r\n\t\t\t\tstart = className.lastIndexOf('.', start - 1);\r\n\t\t\tfinal String bundle = className.substring(0, start);\r\n\t\t\treturn \"+ \" + friendlyName + align(friendlyName) + \"- \" + bundle;\r\n\t\t}\r\n\t\tcatch (final ClassNotFoundException e) {}\r\n\t\tcatch (final NoClassDefFoundError e) {}\r\n\t\treturn \"- \" + friendlyName + align(friendlyName) + \"- not available\";\r\n\t}", "@Deprecated\n public ClientConfig setNodeBannagePeriod(int nodeBannagePeriod, TimeUnit unit) {\n this.failureDetectorBannagePeriod = unit.toMillis(nodeBannagePeriod);\n return this;\n }", "private void readHolidays()\n {\n for (MapRow row : m_tables.get(\"HOL\"))\n {\n ProjectCalendar calendar = m_calendarMap.get(row.getInteger(\"CALENDAR_ID\"));\n if (calendar != null)\n {\n Date date = row.getDate(\"DATE\");\n ProjectCalendarException exception = calendar.addCalendarException(date, date);\n if (row.getBoolean(\"ANNUAL\"))\n {\n RecurringData recurring = new RecurringData();\n recurring.setRecurrenceType(RecurrenceType.YEARLY);\n recurring.setYearlyAbsoluteFromDate(date);\n recurring.setStartDate(date);\n exception.setRecurring(recurring);\n // TODO set end date based on project end date\n }\n }\n }\n }", "public static List<TestSuiteResult> unmarshalSuites(File... directories) throws IOException {\n List<TestSuiteResult> results = new ArrayList<>();\n\n List<File> files = listTestSuiteFiles(directories);\n\n for (File file : files) {\n results.add(unmarshal(file));\n }\n return results;\n }", "public static base_response reset(nitro_service client, Interface resource) throws Exception {\n\t\tInterface resetresource = new Interface();\n\t\tresetresource.id = resource.id;\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}", "TrackMetadata queryMetadata(final DataReference track, final CdjStatus.TrackType trackType, final Client client)\n throws IOException, InterruptedException, TimeoutException {\n\n // Send the metadata menu request\n if (client.tryLockingForMenuOperations(20, TimeUnit.SECONDS)) {\n try {\n final Message.KnownType requestType = (trackType == CdjStatus.TrackType.REKORDBOX) ?\n Message.KnownType.REKORDBOX_METADATA_REQ : Message.KnownType.UNANALYZED_METADATA_REQ;\n final Message response = client.menuRequestTyped(requestType, Message.MenuIdentifier.MAIN_MENU,\n track.slot, trackType, new NumberField(track.rekordboxId));\n final long count = response.getMenuResultsCount();\n if (count == Message.NO_MENU_RESULTS_AVAILABLE) {\n return null;\n }\n\n // Gather the cue list and all the metadata menu items\n final List<Message> items = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, track.slot, trackType, response);\n final CueList cueList = getCueList(track.rekordboxId, track.slot, client);\n return new TrackMetadata(track, trackType, items, cueList);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock the player for menu operations\");\n }\n }", "public void each(int offset, int maxRows, Closure closure) throws SQLException {\n eachRow(getSql(), getParameters(), offset, maxRows, closure);\n }", "public static vpnvserver_authenticationsamlpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationsamlpolicy_binding obj = new vpnvserver_authenticationsamlpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationsamlpolicy_binding response[] = (vpnvserver_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Use this API to update transformpolicy.
[ "public static base_response update(nitro_service client, transformpolicy resource) throws Exception {\n\t\ttransformpolicy updateresource = new transformpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.logaction = resource.logaction;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "public void setBackgroundColor(int color) {\n colorUnpressed = color;\n\n if(!isSelected()) {\n if (rippleAnimationSupport()) {\n ripple.setRippleBackground(colorUnpressed);\n }\n else {\n view.setBackgroundColor(colorUnpressed);\n }\n }\n }", "public static StringBuffer leftShift(String self, Object value) {\n return new StringBuffer(self).append(value);\n }", "public static String getByteArrayDataAsString(String contentEncoding, byte[] bytes) {\n ByteArrayOutputStream byteout = null;\n if (contentEncoding != null &&\n contentEncoding.equals(\"gzip\")) {\n // GZIP\n ByteArrayInputStream bytein = null;\n GZIPInputStream zis = null;\n try {\n bytein = new ByteArrayInputStream(bytes);\n zis = new GZIPInputStream(bytein);\n byteout = new ByteArrayOutputStream();\n\n int res = 0;\n byte buf[] = new byte[1024];\n while (res >= 0) {\n res = zis.read(buf, 0, buf.length);\n if (res > 0) {\n byteout.write(buf, 0, res);\n }\n }\n\n zis.close();\n bytein.close();\n byteout.close();\n return byteout.toString();\n } catch (Exception e) {\n // No action to take\n }\n } else if (contentEncoding != null &&\n contentEncoding.equals(\"deflate\")) {\n try {\n // DEFLATE\n byte[] buffer = new byte[1024];\n Inflater decompresser = new Inflater();\n byteout = new ByteArrayOutputStream();\n decompresser.setInput(bytes);\n while (!decompresser.finished()) {\n int count = decompresser.inflate(buffer);\n byteout.write(buffer, 0, count);\n }\n byteout.close();\n decompresser.end();\n\n return byteout.toString();\n } catch (Exception e) {\n // No action to take\n }\n }\n\n return new String(bytes);\n }", "private String generatedBuilderSimpleName(TypeElement type) {\n String packageName = elements.getPackageOf(type).getQualifiedName().toString();\n String originalName = type.getQualifiedName().toString();\n checkState(originalName.startsWith(packageName + \".\"));\n String nameWithoutPackage = originalName.substring(packageName.length() + 1);\n return String.format(BUILDER_SIMPLE_NAME_TEMPLATE, nameWithoutPackage.replaceAll(\"\\\\.\", \"_\"));\n }", "private ResultAction getFailedResultAction(Throwable cause) {\n if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly()\n || (cause != null && !(cause instanceof OperationFailedException))) {\n return ResultAction.ROLLBACK;\n }\n return ResultAction.KEEP;\n }", "public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) {\r\n List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise);\n\r\n List<Map<String, String>> testCases = new ArrayList<>();\r\n for (Set<String> tuple : tuples) {\r\n testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains));\r\n }\n\r\n return testCases;\r\n }", "static void checkUpgradeConditions(final UpgradeCondition condition, final InstallationManager.MutablePatchingTarget target) throws PatchingException {\n // See if the prerequisites are met\n for (final String required : condition.getRequires()) {\n if (!target.isApplied(required)) {\n throw PatchLogger.ROOT_LOGGER.requiresPatch(required);\n }\n }\n // Check for incompatibilities\n for (final String incompatible : condition.getIncompatibleWith()) {\n if (target.isApplied(incompatible)) {\n throw PatchLogger.ROOT_LOGGER.incompatiblePatch(incompatible);\n }\n }\n }", "private <T extends ProgramElementDoc> List<T> filterByVisibility(T[] docs, Visibility visibility) {\n\tif (visibility == Visibility.PRIVATE)\n\t return Arrays.asList(docs);\n\n\tList<T> filtered = new ArrayList<T>();\n\tfor (T doc : docs) {\n\t if (Visibility.get(doc).compareTo(visibility) > 0)\n\t\tfiltered.add(doc);\n\t}\n\treturn filtered;\n }", "public ActionContext applyContentType(Result result) {\n if (!result.status().isError()) {\n return applyContentType();\n }\n return applyContentType(contentTypeForErrorResult(req()));\n }" ]
Obtains a local date in International Fixed calendar system from the era, year-of-era and day-of-year fields. @param era the International Fixed era, not null @param yearOfEra the year-of-era @param dayOfYear the day-of-year @return the International Fixed local date, not null @throws DateTimeException if unable to create the date @throws ClassCastException if the {@code era} is not a {@code InternationalFixedEra}
[ "@Override\n public InternationalFixedDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }" ]
[ "public static void main(String[] args) throws ParseException, IOException {\n\t\tClient client = new Client(\n\t\t\t\tnew DumpProcessingController(\"wikidatawiki\"), args);\n\t\tclient.performActions();\n\t}", "private boolean processQueue(K key) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key);\n if(requestQueue.isEmpty()) {\n return false;\n }\n\n // Attempt to get a resource.\n Pool<V> resourcePool = getResourcePoolForKey(key);\n V resource = null;\n Exception ex = null;\n try {\n // Must attempt non-blocking checkout to ensure resources are\n // created for the pool.\n resource = attemptNonBlockingCheckout(key, resourcePool);\n } catch(Exception e) {\n destroyResource(key, resourcePool, resource);\n ex = e;\n resource = null;\n }\n // Neither we got a resource, nor an exception. So no requests can be\n // processed return\n if(resource == null && ex == null) {\n return false;\n }\n\n // With resource in hand, process the resource requests\n AsyncResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue);\n if(resourceRequest == null) {\n if(resource != null) {\n // Did not use the resource! Directly check in via super to\n // avoid\n // circular call to processQueue().\n try {\n super.checkin(key, resource);\n } catch(Exception e) {\n logger.error(\"Exception checking in resource: \", e);\n }\n } else {\n // Poor exception, no request to tag this exception onto\n // drop it on the floor and continue as usual.\n }\n return false;\n } else {\n // We have a request here.\n if(resource != null) {\n resourceRequest.useResource(resource);\n } else {\n resourceRequest.handleException(ex);\n }\n return true;\n }\n }", "public Permissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element permissionsElement = response.getPayload();\r\n Permissions permissions = new Permissions();\r\n permissions.setId(permissionsElement.getAttribute(\"id\"));\r\n permissions.setPublicFlag(\"1\".equals(permissionsElement.getAttribute(\"ispublic\")));\r\n permissions.setFamilyFlag(\"1\".equals(permissionsElement.getAttribute(\"isfamily\")));\r\n permissions.setFriendFlag(\"1\".equals(permissionsElement.getAttribute(\"isfriend\")));\r\n permissions.setComment(permissionsElement.getAttribute(\"permcomment\"));\r\n permissions.setAddmeta(permissionsElement.getAttribute(\"permaddmeta\"));\r\n return permissions;\r\n }", "public static double ratioSmallestOverLargest( double []sv ) {\n if( sv.length == 0 )\n return Double.NaN;\n\n double min = sv[0];\n double max = min;\n\n for (int i = 1; i < sv.length; i++) {\n double v = sv[i];\n if( v > max )\n max = v;\n else if( v < min )\n min = v;\n }\n\n return min/max;\n }", "static String fromPackageName(String packageName) {\n List<String> tokens = tokenOf(packageName);\n return fromTokens(tokens);\n }", "public List<PossibleState> bfs(int min) throws ModelException {\r\n List<PossibleState> bootStrap = new LinkedList<>();\n\r\n TransitionTarget initial = model.getInitialTarget();\r\n PossibleState initialState = new PossibleState(initial, fillInitialVariables());\r\n bootStrap.add(initialState);\n\r\n while (bootStrap.size() < min) {\r\n PossibleState state = bootStrap.remove(0);\r\n TransitionTarget nextState = state.nextState;\n\r\n if (nextState.getId().equalsIgnoreCase(\"end\")) {\r\n throw new ModelException(\"Could not achieve required bootstrap without reaching end state\");\r\n }\n\r\n //run every action in series\r\n List<Map<String, String>> product = new LinkedList<>();\r\n product.add(new HashMap<>(state.variables));\n\r\n OnEntry entry = nextState.getOnEntry();\r\n List<Action> actions = entry.getActions();\n\r\n for (Action action : actions) {\r\n for (CustomTagExtension tagExtension : tagExtensionList) {\r\n if (tagExtension.getTagActionClass().isInstance(action)) {\r\n product = tagExtension.pipelinePossibleStates(action, product);\r\n }\r\n }\r\n }\n\r\n //go through every transition and see which of the products are valid, adding them to the list\r\n List<Transition> transitions = nextState.getTransitionsList();\n\r\n for (Transition transition : transitions) {\r\n String condition = transition.getCond();\r\n TransitionTarget target = ((List<TransitionTarget>) transition.getTargets()).get(0);\n\r\n for (Map<String, String> p : product) {\r\n Boolean pass;\n\r\n if (condition == null) {\r\n pass = true;\r\n } else {\r\n //scrub the context clean so we may use it to evaluate transition conditional\r\n Context context = this.getRootContext();\r\n context.reset();\n\r\n //set up new context\r\n for (Map.Entry<String, String> e : p.entrySet()) {\r\n context.set(e.getKey(), e.getValue());\r\n }\n\r\n //evaluate condition\r\n try {\r\n pass = (Boolean) this.getEvaluator().eval(context, condition);\r\n } catch (SCXMLExpressionException ex) {\r\n pass = false;\r\n }\r\n }\n\r\n //transition condition satisfied, add to bootstrap list\r\n if (pass) {\r\n PossibleState result = new PossibleState(target, p);\r\n bootStrap.add(result);\r\n }\r\n }\r\n }\r\n }\n\r\n return bootStrap;\r\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 ProjectFile read(POIFSFileSystem fs) throws MPXJException\n {\n try\n {\n ProjectFile projectFile = new ProjectFile();\n ProjectConfig config = projectFile.getProjectConfig();\n\n config.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoOutlineLevel(false);\n config.setAutoOutlineNumber(false);\n config.setAutoWBS(false);\n config.setAutoCalendarUniqueID(false);\n config.setAutoAssignmentUniqueID(false);\n\n projectFile.getEventManager().addProjectListeners(m_projectListeners);\n\n //\n // Open the file system and retrieve the root directory\n //\n DirectoryEntry root = fs.getRoot();\n\n //\n // Retrieve the CompObj data, validate the file format and process\n //\n CompObj compObj = new CompObj(new DocumentInputStream((DocumentEntry) root.getEntry(\"\\1CompObj\")));\n ProjectProperties projectProperties = projectFile.getProjectProperties();\n projectProperties.setFullApplicationName(compObj.getApplicationName());\n projectProperties.setApplicationVersion(compObj.getApplicationVersion());\n String format = compObj.getFileFormat();\n Class<? extends MPPVariantReader> readerClass = FILE_CLASS_MAP.get(format);\n if (readerClass == null)\n {\n throw new MPXJException(MPXJException.INVALID_FILE + \": \" + format);\n }\n MPPVariantReader reader = readerClass.newInstance();\n reader.process(this, projectFile, root);\n\n //\n // Update the internal structure. We'll take this opportunity to\n // generate outline numbers for the tasks as they don't appear to\n // be present in the MPP file.\n //\n config.setAutoOutlineNumber(true);\n projectFile.updateStructure();\n config.setAutoOutlineNumber(false);\n\n //\n // Perform post-processing to set the summary flag and clean\n // up any instances where a task has an empty splits list.\n //\n for (Task task : projectFile.getTasks())\n {\n task.setSummary(task.hasChildTasks());\n List<DateRange> splits = task.getSplits();\n if (splits != null && splits.isEmpty())\n {\n task.setSplits(null);\n }\n validationRelations(task);\n }\n\n //\n // Ensure that the unique ID counters are correct\n //\n config.updateUniqueCounters();\n\n //\n // Add some analytics\n //\n String projectFilePath = projectFile.getProjectProperties().getProjectFilePath();\n if (projectFilePath != null && projectFilePath.startsWith(\"<>\\\\\"))\n {\n projectProperties.setFileApplication(\"Microsoft Project Server\");\n }\n else\n {\n projectProperties.setFileApplication(\"Microsoft\");\n }\n projectProperties.setFileType(\"MPP\");\n\n return (projectFile);\n }\n\n catch (IOException ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR, ex);\n }\n\n catch (IllegalAccessException ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR, ex);\n }\n\n catch (InstantiationException ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR, ex);\n }\n }", "public void setFrustum(float[] frustum)\n {\n Matrix4f projMatrix = new Matrix4f();\n projMatrix.setFrustum(frustum[0], frustum[3], frustum[1], frustum[4], frustum[2], frustum[5]);\n setFrustum(projMatrix);\n }" ]
Use this API to fetch all the nssimpleacl resources that are configured on netscaler.
[ "public static nssimpleacl[] get(nitro_service service) throws Exception{\n\t\tnssimpleacl obj = new nssimpleacl();\n\t\tnssimpleacl[] response = (nssimpleacl[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public static void plotCharts(List<Chart> charts){\n\t\tint numRows =1;\n\t\tint numCols =1;\n\t\tif(charts.size()>1){\n\t\t\tnumRows = (int) Math.ceil(charts.size()/2.0);\n\t\t\tnumCols = 2;\n\t\t}\n\t\t\n\t final JFrame frame = new JFrame(\"\");\n\t frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);\n frame.getContentPane().setLayout(new GridLayout(numRows, numCols));\n\t for (Chart chart : charts) {\n\t if (chart != null) {\n\t JPanel chartPanel = new XChartPanel(chart);\n\t frame.add(chartPanel);\n\t }\n\t else {\n\t JPanel chartPanel = new JPanel();\n\t frame.getContentPane().add(chartPanel);\n\t }\n\n\t }\n\t // Display the window.\n frame.pack();\n frame.setVisible(true);\n\t}", "public static final String printFinishDateTime(Date value)\n {\n if (value != null)\n {\n value = DateHelper.addDays(value, 1);\n }\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }", "private String normalizePath(String scriptPath) {\n StringBuilder builder = new StringBuilder(scriptPath.length() + 1);\n if (scriptPath.startsWith(\"/\")) {\n builder.append(scriptPath.substring(1));\n } else {\n builder.append(scriptPath);\n }\n if (!scriptPath.endsWith(\"/\")) {\n builder.append(\"/\");\n }\n return builder.toString();\n }", "protected void notifyBufferChange(char[] newData, int numChars) {\n synchronized(bufferChangeLoggers) {\n Iterator<BufferChangeLogger> iterator = bufferChangeLoggers.iterator();\n while (iterator.hasNext()) {\n iterator.next().bufferChanged(newData, numChars);\n }\n }\n }", "public static base_response unset(nitro_service client, nsacl6 resource, String[] args) throws Exception{\n\t\tnsacl6 unsetresource = new nsacl6();\n\t\tunsetresource.acl6name = resource.acl6name;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private byte[] receiveBytes(InputStream is) throws IOException {\n byte[] buffer = new byte[8192];\n int len = (is.read(buffer));\n if (len < 1) {\n throw new IOException(\"receiveBytes read \" + len + \" bytes.\");\n }\n return Arrays.copyOf(buffer, len);\n }", "public static double Cosh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return 1 + (x * x) / 2D;\r\n } else {\r\n\r\n double mult = x * x;\r\n double fact = 2;\r\n int factS = 4;\r\n double result = 1 + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }", "private List<AssignmentField> getAllAssignmentExtendedAttributes()\n {\n ArrayList<AssignmentField> result = new ArrayList<AssignmentField>();\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_COST));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DATE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_DURATION));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_MULTI_VALUE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_RESOURCE_OUTLINE_CODE));\n result.addAll(Arrays.asList(AssignmentFieldLists.ENTERPRISE_TEXT));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FINISH));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_FLAG));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_NUMBER));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_START));\n result.addAll(Arrays.asList(AssignmentFieldLists.CUSTOM_TEXT));\n return result;\n }", "@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n String dir = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean verbose = false;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_GET);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_DIR)) {\n dir = (String) options.valueOf(AdminParserUtils.OPT_DIR);\n }\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n if(options.has(OPT_VERBOSE)) {\n verbose = true;\n }\n\n // execute command\n File directory = AdminToolUtils.createDir(dir);\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {\n metaKeys = Lists.newArrayList();\n for(Object key: MetadataStore.METADATA_KEYS) {\n metaKeys.add((String) key);\n }\n }\n\n doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose);\n }" ]
Tell a device to turn sync on or off. @param deviceNumber the device whose sync state is to be set @param synced {@code} true if sync should be turned on, else it will be turned off @throws IOException if there is a problem sending the command to the device @throws IllegalStateException if the {@code VirtualCdj} is not active @throws IllegalArgumentException if {@code deviceNumber} is not found on the network
[ "public void sendSyncModeCommand(int deviceNumber, boolean synced) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n sendSyncModeCommand(update, synced);\n }" ]
[ "public Triple<EObject, EReference, INode> decode(Resource res, String uriFragment) {\n\t\tif (isUseIndexFragment(res)) {\n\t\t\treturn getLazyProxyInformation(res, uriFragment);\n\t\t}\n\t\tList<String> split = Strings.split(uriFragment, SEP);\n\t\tEObject source = resolveShortFragment(res, split.get(1));\n\t\tEReference ref = fromShortExternalForm(source.eClass(), split.get(2));\n\t\tINode compositeNode = NodeModelUtils.getNode(source);\n\t\tif (compositeNode==null)\n\t\t\tthrow new IllegalStateException(\"Couldn't resolve lazy link, because no node model is attached.\");\n\t\tINode textNode = getNode(compositeNode, split.get(3));\n\t\treturn Tuples.create(source, ref, textNode);\n\t}", "private static void setFields(final Object from, final Object to,\r\n\t final Field[] fields, final boolean accessible,\r\n\t final Map objMap, final Map metadataMap)\r\n\t{\r\n\t\tfor (int f = 0, fieldsLength = fields.length; f < fieldsLength; ++f)\r\n\t\t{\r\n\t\t\tfinal Field field = fields[f];\r\n\t\t\tfinal int modifiers = field.getModifiers();\r\n\t\t\tif ((Modifier.STATIC & modifiers) != 0) continue;\r\n\t\t\tif ((Modifier.FINAL & modifiers) != 0)\r\n\t\t\t\tthrow new ObjectCopyException(\"cannot set final field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]\");\r\n\t\t\tif (!accessible && ((Modifier.PUBLIC & modifiers) == 0))\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tfield.setAccessible(true);\r\n\t\t\t\t}\r\n\t\t\t\tcatch (SecurityException e)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow new ObjectCopyException(\"cannot access field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]: \" + e.toString(), e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tcloneAndSetFieldValue(field, from, to, objMap, metadataMap);\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tthrow new ObjectCopyException(\"cannot set field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]: \" + e.toString(), e);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public void cmdProc(Interp interp, TclObject argv[])\n throws TclException {\n int currentObjIndex, len, i;\n int objc = argv.length - 1;\n boolean doBackslashes = true;\n boolean doCmds = true;\n boolean doVars = true;\n StringBuffer result = new StringBuffer();\n String s;\n char c;\n\n for (currentObjIndex = 1; currentObjIndex < objc; currentObjIndex++) {\n if (!argv[currentObjIndex].toString().startsWith(\"-\")) {\n break;\n }\n int opt = TclIndex.get(interp, argv[currentObjIndex],\n validCmds, \"switch\", 0);\n switch (opt) {\n case OPT_NOBACKSLASHES:\n doBackslashes = false;\n break;\n case OPT_NOCOMMANDS:\n doCmds = false;\n break;\n case OPT_NOVARS:\n doVars = false;\n break;\n default:\n throw new TclException(interp,\n \"SubstCrCmd.cmdProc: bad option \" + opt\n + \" index to cmds\");\n }\n }\n if (currentObjIndex != objc) {\n throw new TclNumArgsException(interp, currentObjIndex, argv,\n \"?-nobackslashes? ?-nocommands? ?-novariables? string\");\n }\n\n /*\n * Scan through the string one character at a time, performing\n * command, variable, and backslash substitutions.\n */\n\n s = argv[currentObjIndex].toString();\n len = s.length();\n i = 0;\n while (i < len) {\n c = s.charAt(i);\n\n if ((c == '[') && doCmds) {\n ParseResult res;\n try {\n interp.evalFlags = Parser.TCL_BRACKET_TERM;\n interp.eval(s.substring(i + 1, len));\n TclObject interp_result = interp.getResult();\n interp_result.preserve();\n res = new ParseResult(interp_result,\n i + interp.termOffset);\n } catch (TclException e) {\n i = e.errIndex + 1;\n throw e;\n }\n i = res.nextIndex + 2;\n result.append( res.value.toString() );\n res.release();\n /**\n * Removed\n (ToDo) may not be portable on Mac\n } else if (c == '\\r') {\n i++;\n */\n } else if ((c == '$') && doVars) {\n ParseResult vres = Parser.parseVar(interp,\n s.substring(i, len));\n i += vres.nextIndex;\n result.append( vres.value.toString() );\n vres.release();\n } else if ((c == '\\\\') && doBackslashes) {\n BackSlashResult bs = Interp.backslash(s, i, len);\n i = bs.nextIndex;\n if (bs.isWordSep) {\n break;\n } else {\n result.append( bs.c );\n }\n } else {\n result.append( c );\n i++;\n }\n }\n\n interp.setResult(result.toString());\n }", "@Override\n protected URL getDefinitionsURL() {\n try {\n URL url = CustomEPSGCodes.class.getResource(CUSTOM_EPSG_CODES_FILE);\n // quickly test url\n try (InputStream stream = url.openStream()) {\n //noinspection ResultOfMethodCallIgnored\n stream.read();\n }\n return url;\n } catch (Throwable e) {\n throw new AssertionError(\"Unable to load /epsg.properties file from root of classpath.\");\n }\n }", "public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) {\r\n for (String name : names) {\r\n if (hasAnnotation(node, name)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "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}", "public static CrashReport fromJson(String json) throws IllegalArgumentException {\n try {\n return new CrashReport(json);\n } catch (JSONException je) {\n throw new IllegalArgumentException(je.toString());\n }\n }", "public QueryBuilder useIndex(String designDocument, String indexName) {\n useIndex = new String[]{designDocument, indexName};\n return this;\n }", "protected void parseOperationsL(TokenList tokens, Sequence sequence) {\n\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n if( token.getType() != Type.VARIABLE )\n throw new ParseError(\"The first token in an equation needs to be a variable and not \"+token);\n\n while( token != null ) {\n if( token.getType() == Type.FUNCTION ) {\n throw new ParseError(\"Function encountered with no parentheses\");\n } else if( token.getType() == Type.SYMBOL && token.getSymbol() == Symbol.TRANSPOSE) {\n if( token.previous.getType() == Type.VARIABLE )\n token = insertTranspose(token.previous,tokens,sequence);\n else\n throw new ParseError(\"Expected variable before transpose\");\n }\n token = token.next;\n }\n }" ]
If there is a SubReport on a Group, we do the layout here @param columnsGroup @param jgroup
[ "protected void layoutGroupSubreports(DJGroup columnsGroup, JRDesignGroup jgroup) {\n\t\tlog.debug(\"Starting subreport layout...\");\n\t\tJRDesignBand footerBand = (JRDesignBand) ((JRDesignSection)jgroup.getGroupFooterSection()).getBandsList().get(0);\n\t\tJRDesignBand headerBand = (JRDesignBand) ((JRDesignSection)jgroup.getGroupHeaderSection()).getBandsList().get(0);\n\n\t\tlayOutSubReportInBand(columnsGroup, headerBand, DJConstants.HEADER);\n\t\tlayOutSubReportInBand(columnsGroup, footerBand, DJConstants.FOOTER);\n\n\t}" ]
[ "public boolean classifySentenceStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n while ((line = is.readLine()) != null) {\r\n \t\r\n if (line.trim().equals(\"\")) {\r\n \t text += sentence + eol;\r\n \t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n classifyAndWriteAnswers(documents, readerWriter);\r\n text = \"\";\r\n } else {\r\n \t text += line + eol;\r\n }\r\n }\r\n if (text.trim().equals(\"\")) {\r\n \treturn false;\r\n }\r\n return true;\r\n }", "private void addCalendarDay(MpxjTreeNode parentNode, ProjectCalendar calendar, final Day day)\n {\n MpxjTreeNode dayNode = new MpxjTreeNode(day)\n {\n @Override public String toString()\n {\n return day.name();\n }\n };\n parentNode.add(dayNode);\n addHours(dayNode, calendar.getHours(day));\n }", "public Date getTime(String fieldName) {\n\t\ttry {\n\t\t\tif (hasValue(fieldName)) {\n\t\t\t\treturn new Date(Long.valueOf(String.valueOf(resultMap.get(fieldName))) * 1000);\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a time.\", e);\n\t\t}\n\t}", "@RequestMapping(value = \"/api/plugins\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addPluginPath(Model model, Plugin add) throws Exception {\n PluginManager.getInstance().addPluginPath(add.getPath());\n\n return pluginInformation();\n }", "private void updateRemoveR() {\n for( int i = 1; i < n+1; i++ ) {\n for( int j = 0; j < n; j++ ) {\n double sum = 0;\n for( int k = i-1; k <= j; k++ ) {\n sum += U_tran.data[i*m+k] * R.data[k*n+j];\n }\n R.data[(i-1)*n+j] = sum;\n }\n }\n }", "public static void dumpMaterialProperty(AiMaterial.Property property) {\n System.out.print(property.getKey() + \" \" + property.getSemantic() + \n \" \" + property.getIndex() + \": \");\n Object data = property.getData();\n \n if (data instanceof ByteBuffer) {\n ByteBuffer buf = (ByteBuffer) data;\n for (int i = 0; i < buf.capacity(); i++) {\n System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + \" \");\n }\n \n System.out.println();\n }\n else {\n System.out.println(data.toString());\n }\n }", "private String formatRelationList(List<Relation> value)\n {\n String result = null;\n\n if (value != null && value.size() != 0)\n {\n StringBuilder sb = new StringBuilder();\n for (Relation relation : value)\n {\n if (sb.length() != 0)\n {\n sb.append(m_delimiter);\n }\n\n sb.append(formatRelation(relation));\n }\n\n result = sb.toString();\n }\n\n return (result);\n }", "public void sub(Vector3d v1, Vector3d v2) {\n x = v1.x - v2.x;\n y = v1.y - v2.y;\n z = v1.z - v2.z;\n }", "public static base_response unset(nitro_service client, systemuser resource, String[] args) throws Exception{\n\t\tsystemuser unsetresource = new systemuser();\n\t\tunsetresource.username = resource.username;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Returns an array of all endpoints @param profileId ID of profile @param clientUUID UUID of client @param filters filters to apply to endpoints @return Collection of endpoints @throws Exception exception
[ "public List<EndpointOverride> getPaths(int profileId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EndpointOverride> properties = new ArrayList<EndpointOverride>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_PROFILE_ID + \"=? \" +\n \" ORDER BY \" + Constants.PATH_PROFILE_PATH_ORDER + \" ASC\";\n\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n statement.setInt(2, profileId);\n\n results = statement.executeQuery();\n while (results.next()) {\n EndpointOverride endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\n properties.add(endpoint);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return properties;\n }" ]
[ "public void removeCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().remove(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.removeModulesOrganization(corporateGroupId, dbOrganization);\n }", "public Object assignIdValue(ConnectionSource connectionSource, Object data, Number val, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\tObject idVal = dataPersister.convertIdNumber(val);\n\t\tif (idVal == null) {\n\t\t\tthrow new SQLException(\"Invalid class \" + dataPersister + \" for sequence-id \" + this);\n\t\t} else {\n\t\t\tassignField(connectionSource, data, idVal, false, objectCache);\n\t\t\treturn idVal;\n\t\t}\n\t}", "public static AppDescriptor deserializeFrom(byte[] bytes) {\n try {\n ByteArrayInputStream bais = new ByteArrayInputStream(bytes);\n ObjectInputStream ois = new ObjectInputStream(bais);\n return (AppDescriptor) ois.readObject();\n } catch (IOException e) {\n throw E.ioException(e);\n } catch (ClassNotFoundException e) {\n throw E.unexpected(e);\n }\n }", "public void combine(CRFClassifier<IN> crf, double weight) {\r\n Timing timer = new Timing();\r\n\r\n // Check the CRFClassifiers are compatible\r\n if (!this.pad.equals(crf.pad)) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: pad does not match\");\r\n }\r\n if (this.windowSize != crf.windowSize) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: windowSize does not match\");\r\n }\r\n if (this.labelIndices.length != crf.labelIndices.length) {\r\n // Should match since this should be same as the windowSize\r\n throw new RuntimeException(\"Incompatible CRFClassifier: labelIndices length does not match\");\r\n }\r\n this.classIndex.addAll(crf.classIndex.objectsList());\r\n\r\n // Combine weights of the other classifier with this classifier,\r\n // weighing the other classifier's weights by weight\r\n // First merge the feature indicies\r\n int oldNumFeatures1 = this.featureIndex.size();\r\n int oldNumFeatures2 = crf.featureIndex.size();\r\n int oldNumWeights1 = this.getNumWeights();\r\n int oldNumWeights2 = crf.getNumWeights();\r\n this.featureIndex.addAll(crf.featureIndex.objectsList());\r\n this.knownLCWords.addAll(crf.knownLCWords);\r\n assert (weights.length == oldNumFeatures1);\r\n\r\n // Combine weights of this classifier with other classifier\r\n for (int i = 0; i < labelIndices.length; i++) {\r\n this.labelIndices[i].addAll(crf.labelIndices[i].objectsList());\r\n }\r\n System.err.println(\"Combining weights: will automatically match labelIndices\");\r\n combineWeights(crf, weight);\r\n\r\n int numFeatures = featureIndex.size();\r\n int numWeights = getNumWeights();\r\n long elapsedMs = timer.stop();\r\n System.err.println(\"numFeatures: orig1=\" + oldNumFeatures1 + \", orig2=\" + oldNumFeatures2 + \", combined=\"\r\n + numFeatures);\r\n System.err\r\n .println(\"numWeights: orig1=\" + oldNumWeights1 + \", orig2=\" + oldNumWeights2 + \", combined=\" + numWeights);\r\n System.err.println(\"Time to combine CRFClassifier: \" + Timing.toSecondsString(elapsedMs) + \" seconds\");\r\n }", "@Override\n protected void onLoad() {\n\tsuper.onLoad();\n\n\t// these styles need to be the same for the box and shadow so\n\t// that we can measure properly\n\tmatchStyles(\"display\");\n\tmatchStyles(\"fontSize\");\n\tmatchStyles(\"fontFamily\");\n\tmatchStyles(\"fontWeight\");\n\tmatchStyles(\"lineHeight\");\n\tmatchStyles(\"paddingTop\");\n\tmatchStyles(\"paddingRight\");\n\tmatchStyles(\"paddingBottom\");\n\tmatchStyles(\"paddingLeft\");\n\n\tadjustSize();\n }", "private List<Rule> getStyleRules(final String styleProperty) {\n final List<Rule> styleRules = new ArrayList<>(this.json.size());\n\n for (Iterator<String> iterator = this.json.keys(); iterator.hasNext(); ) {\n String styleKey = iterator.next();\n if (styleKey.equals(JSON_STYLE_PROPERTY) ||\n styleKey.equals(MapfishStyleParserPlugin.JSON_VERSION)) {\n continue;\n }\n PJsonObject styleJson = this.json.getJSONObject(styleKey);\n final List<Rule> currentRules = createStyleRule(styleKey, styleJson, styleProperty);\n for (Rule currentRule: currentRules) {\n if (currentRule != null) {\n styleRules.add(currentRule);\n }\n }\n }\n\n return styleRules;\n }", "private String GCMGetFreshToken(final String senderID) {\n getConfigLogger().verbose(getAccountId(), \"GcmManager: Requesting a GCM token for Sender ID - \" + senderID);\n String token = null;\n try {\n token = InstanceID.getInstance(context)\n .getToken(senderID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);\n getConfigLogger().info(getAccountId(), \"GCM token : \" + token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"GcmManager: Error requesting GCM token\", t);\n }\n return token;\n }", "public static final char getChar(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return (bundle.getString(key).charAt(0));\n }", "public QueryBuilder<T, ID> groupBy(String columnName) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't groupBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddGroupBy(ColumnNameOrRawSql.withColumnName(columnName));\n\t\treturn this;\n\t}" ]
This method lists all tasks defined in the file. @param file MPX file
[ "private static void listTasks(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n\n for (Task task : file.getTasks())\n {\n Date date = task.getStart();\n String text = task.getStartText();\n String startDate = text != null ? text : (date != null ? df.format(date) : \"(no start date supplied)\");\n\n date = task.getFinish();\n text = task.getFinishText();\n String finishDate = text != null ? text : (date != null ? df.format(date) : \"(no finish date supplied)\");\n\n Duration dur = task.getDuration();\n text = task.getDurationText();\n String duration = text != null ? text : (dur != null ? dur.toString() : \"(no duration supplied)\");\n\n dur = task.getActualDuration();\n String actualDuration = dur != null ? dur.toString() : \"(no actual duration supplied)\";\n\n String baselineDuration = task.getBaselineDurationText();\n if (baselineDuration == null)\n {\n dur = task.getBaselineDuration();\n if (dur != null)\n {\n baselineDuration = dur.toString();\n }\n else\n {\n baselineDuration = \"(no duration supplied)\";\n }\n }\n\n System.out.println(\"Task: \" + task.getName() + \" ID=\" + task.getID() + \" Unique ID=\" + task.getUniqueID() + \" (Start Date=\" + startDate + \" Finish Date=\" + finishDate + \" Duration=\" + duration + \" Actual Duration\" + actualDuration + \" Baseline Duration=\" + baselineDuration + \" Outline Level=\" + task.getOutlineLevel() + \" Outline Number=\" + task.getOutlineNumber() + \" Recurring=\" + task.getRecurring() + \")\");\n }\n System.out.println();\n }" ]
[ "public final void debug(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.DEBUG, pObject, null);\r\n\t}", "private String escapeString(String value)\n {\n m_buffer.setLength(0);\n m_buffer.append('\"');\n for (int index = 0; index < value.length(); index++)\n {\n char c = value.charAt(index);\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\\\\\"\");\n break;\n }\n\n case '\\\\':\n {\n m_buffer.append(\"\\\\\\\\\");\n break;\n }\n\n case '/':\n {\n m_buffer.append(\"\\\\/\");\n break;\n }\n\n case '\\b':\n {\n m_buffer.append(\"\\\\b\");\n break;\n }\n\n case '\\f':\n {\n m_buffer.append(\"\\\\f\");\n break;\n }\n\n case '\\n':\n {\n m_buffer.append(\"\\\\n\");\n break;\n }\n\n case '\\r':\n {\n m_buffer.append(\"\\\\r\");\n break;\n }\n\n case '\\t':\n {\n m_buffer.append(\"\\\\t\");\n break;\n }\n\n default:\n {\n // Append if it's not a control character (0x00 to 0x1f)\n if (c > 0x1f)\n {\n m_buffer.append(c);\n }\n break;\n }\n }\n }\n m_buffer.append('\"');\n return m_buffer.toString();\n }", "public static base_response export(nitro_service client, application resource) throws Exception {\n\t\tapplication exportresource = new application();\n\t\texportresource.appname = resource.appname;\n\t\texportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\texportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}", "public void processDefaultCurrency(Row row)\n {\n ProjectProperties properties = m_project.getProjectProperties();\n properties.setCurrencySymbol(row.getString(\"curr_symbol\"));\n properties.setSymbolPosition(CURRENCY_SYMBOL_POSITION_MAP.get(row.getString(\"pos_curr_fmt_type\")));\n properties.setCurrencyDigits(row.getInteger(\"decimal_digit_cnt\"));\n properties.setThousandsSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n properties.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n }", "public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() {\n\n if (null == m_resourceCategories) {\n m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object resourceName) {\n\n try {\n CmsResource resource = m_cms.readResource(\n getRequestContext().removeSiteRoot((String)resourceName));\n return new CmsJspCategoryAccessBean(m_cms, resource);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n });\n }\n return m_resourceCategories;\n }", "public Flags flagList(ImapRequestLineReader request) throws ProtocolException {\n Flags flags = new Flags();\n request.nextWordChar();\n consumeChar(request, '(');\n CharacterValidator validator = new NoopCharValidator();\n String nextWord = consumeWord(request, validator);\n while (!nextWord.endsWith(\")\")) {\n setFlag(nextWord, flags);\n nextWord = consumeWord(request, validator);\n }\n // Got the closing \")\", may be attached to a word.\n if (nextWord.length() > 1) {\n setFlag(nextWord.substring(0, nextWord.length() - 1), flags);\n }\n\n return flags;\n }", "private void validationRelations(Task task)\n {\n List<Relation> predecessors = task.getPredecessors();\n if (!predecessors.isEmpty())\n {\n ArrayList<Relation> invalid = new ArrayList<Relation>();\n for (Relation relation : predecessors)\n {\n Task sourceTask = relation.getSourceTask();\n Task targetTask = relation.getTargetTask();\n\n String sourceOutlineNumber = sourceTask.getOutlineNumber();\n String targetOutlineNumber = targetTask.getOutlineNumber();\n\n if (sourceOutlineNumber != null && targetOutlineNumber != null && sourceOutlineNumber.startsWith(targetOutlineNumber + '.'))\n {\n invalid.add(relation);\n }\n }\n\n for (Relation relation : invalid)\n {\n relation.getSourceTask().removePredecessor(relation.getTargetTask(), relation.getType(), relation.getLag());\n }\n }\n }", "public static MapBounds adjustBoundsToScaleAndMapSize(\n final GenericMapAttributeValues mapValues,\n final Rectangle paintArea,\n final MapBounds bounds,\n final double dpi) {\n MapBounds newBounds = bounds;\n if (mapValues.isUseNearestScale()) {\n newBounds = newBounds.adjustBoundsToNearestScale(\n mapValues.getZoomLevels(),\n mapValues.getZoomSnapTolerance(),\n mapValues.getZoomLevelSnapStrategy(),\n mapValues.getZoomSnapGeodetic(),\n paintArea, dpi);\n }\n\n newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));\n\n if (mapValues.isUseAdjustBounds()) {\n newBounds = newBounds.adjustedEnvelope(paintArea);\n }\n return newBounds;\n }", "public static boolean queryHasResult(Statement stmt, String sql) {\n try {\n ResultSet rs = stmt.executeQuery(sql);\n try {\n return rs.next();\n } finally {\n rs.close();\n }\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }" ]
Returns server group by ID @param id ID of server group @return ServerGroup @throws Exception exception
[ "public ServerGroup getServerGroup(int id, int profileId) throws Exception {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n if (id == 0) {\n return new ServerGroup(0, \"Default\", profileId);\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, id);\n results = queryStatement.executeQuery();\n if (results.next()) {\n ServerGroup curGroup = new ServerGroup(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.GENERIC_NAME),\n results.getInt(Constants.GENERIC_PROFILE_ID));\n return curGroup;\n }\n logger.info(\"Did not find the ID: {}\", id);\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }" ]
[ "public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.InputStream\",\"java.io.OutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n try {\n T result = closure.call(new Object[]{input, output});\n\n InputStream temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(input);\n closeWithWarning(output);\n }\n }", "private int[] changeColor() {\n int[] changedPixels = new int[pixels.length];\n double frequenz = 2 * Math.PI / 1020;\n\n for (int i = 0; i < pixels.length; i++) {\n int argb = pixels[i];\n int a = (argb >> 24) & 0xff;\n int r = (argb >> 16) & 0xff;\n int g = (argb >> 8) & 0xff;\n int b = argb & 0xff;\n\n r = (int) (255 * Math.sin(frequenz * r));\n b = (int) (-255 * Math.cos(frequenz * b) + 255);\n\n changedPixels[i] = (a << 24) | (r << 16) | (g << 8) | b;\n }\n\n return changedPixels;\n }", "public final static int readMdLinkId(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n boolean endReached = false;\n switch (ch)\n {\n case '\\n':\n out.append(' ');\n break;\n case '[':\n counter++;\n out.append(ch);\n break;\n case ']':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n else\n {\n out.append(ch);\n }\n break;\n default:\n out.append(ch);\n break;\n }\n if (endReached)\n {\n break;\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }", "public final File getJasperCompilation(final Configuration configuration) {\n File jasperCompilation = new File(getWorking(configuration), \"jasper-bin\");\n createIfMissing(jasperCompilation, \"Jasper Compilation\");\n return jasperCompilation;\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 static Method findGetter(final Object object, final String fieldName) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t}\n\t\t\n\t\tfinal Class<?> clazz = object.getClass();\n\t\t\n\t\t// find a standard getter\n\t\tfinal String standardGetterName = getMethodNameForField(GET_PREFIX, fieldName);\n\t\tMethod getter = findGetterWithCompatibleReturnType(standardGetterName, clazz, false);\n\t\t\n\t\t// if that fails, try for an isX() style boolean getter\n\t\tif( getter == null ) {\n\t\t\tfinal String booleanGetterName = getMethodNameForField(IS_PREFIX, fieldName);\n\t\t\tgetter = findGetterWithCompatibleReturnType(booleanGetterName, clazz, true);\n\t\t}\n\t\t\n\t\tif( getter == null ) {\n\t\t\tthrow new SuperCsvReflectionException(\n\t\t\t\tString\n\t\t\t\t\t.format(\n\t\t\t\t\t\t\"unable to find getter for field %s in class %s - check that the corresponding nameMapping element matches the field name in the bean\",\n\t\t\t\t\t\tfieldName, clazz.getName()));\n\t\t}\n\t\t\n\t\treturn getter;\n\t}", "public static transformpolicy[] get(nitro_service service) throws Exception{\n\t\ttransformpolicy obj = new transformpolicy();\n\t\ttransformpolicy[] response = (transformpolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void shutdownDomain(final ModelControllerClient client, final int timeout) throws IOException, OperationExecutionException {\n // Note the following two operations used to shutdown a domain don't seem to work well in a composite operation.\n // The operation occasionally sees a java.util.concurrent.CancellationException because the operation client\n // is likely closed before the AsyncFuture.get() is complete. Using a non-composite operation doesn't seem to\n // have this issue.\n\n // First shutdown the servers\n final ModelNode stopServersOp = Operations.createOperation(\"stop-servers\");\n stopServersOp.get(\"blocking\").set(true);\n stopServersOp.get(\"timeout\").set(timeout);\n ModelNode response = client.execute(stopServersOp);\n if (!Operations.isSuccessfulOutcome(response)) {\n throw new OperationExecutionException(\"Failed to stop servers.\", stopServersOp, response);\n }\n\n // Now shutdown the host\n final ModelNode address = determineHostAddress(client);\n final ModelNode shutdownOp = Operations.createOperation(\"shutdown\", address);\n response = client.execute(shutdownOp);\n if (Operations.isSuccessfulOutcome(response)) {\n // Wait until the process has died\n while (true) {\n if (isDomainRunning(client, true)) {\n try {\n TimeUnit.MILLISECONDS.sleep(20L);\n } catch (InterruptedException e) {\n LOGGER.trace(\"Interrupted during sleep\", e);\n }\n } else {\n break;\n }\n }\n } else {\n throw new OperationExecutionException(\"Failed to shutdown host.\", shutdownOp, response);\n }\n }", "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Creatable<? extends Indexable> creatable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatable;\n return this.addPostRunDependent(dependency);\n }" ]
Appends the indentation string at the current position of the parent and adds a new composite node, indicating the same indentation for subsequent lines. @return an indentation node, using the given indentString, appended as a child on the given parent
[ "public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) {\n final IndentNode indent = new IndentNode(indentString);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(indent);\n return indent;\n }" ]
[ "private static Version getDockerVersion(String serverUrl) {\n try {\n DockerClient client = DockerClientBuilder.getInstance(serverUrl).build();\n return client.versionCmd().exec();\n } catch (Exception e) {\n return null;\n }\n }", "public static IndexableTaskItem create(final FunctionalTaskItem taskItem) {\n return new IndexableTaskItem() {\n @Override\n protected Observable<Indexable> invokeTaskAsync(TaskGroup.InvocationContext context) {\n FunctionalTaskItem.Context fContext = new FunctionalTaskItem.Context(this);\n fContext.setInnerContext(context);\n return taskItem.call(fContext);\n }\n };\n }", "public Try<R,Throwable> execute(T input){\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)));\n\t\t \n\t}", "public static Object unmarshal(String message, Class<?> childClass) {\n try {\n Class<?>[] reverseAndToArray = Iterables.toArray(Lists.reverse(getAllSuperTypes(childClass)), Class.class);\n JAXBContext jaxbCtx = JAXBContext.newInstance(reverseAndToArray);\n Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();\n\n return unmarshaller.unmarshal(new StringReader(message));\n } catch (Exception e) {\n }\n\n return null;\n }", "public static void setDefaultHostName(String hostName) {\n if (hostName == null || hostName.contains(\":\")) {\n return;\n }\n DEFAULT_BASE_URL = \"http://\" + hostName + \":\" + DEFAULT_API_PORT + \"/\" + API_BASE + \"/\";\n }", "public static AnnotationNode getAnnotation(AnnotatedNode node, String name) {\r\n List<AnnotationNode> annotations = node.getAnnotations();\r\n for (AnnotationNode annot : annotations) {\r\n if (annot.getClassNode().getName().equals(name)) {\r\n return annot;\r\n }\r\n }\r\n return null;\r\n }", "public static MetadataTemplate getMetadataTemplateByID(BoxAPIConnection api, String templateID) {\n\n URL url = METADATA_TEMPLATE_BY_ID_URL_TEMPLATE.build(api.getBaseURL(), templateID);\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new MetadataTemplate(response.getJSON());\n }", "public Where<T, ID> rawComparison(String columnName, String rawOperator, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value, rawOperator));\n\t\treturn this;\n\t}", "protected void update(float scale) {\n GVRSceneObject owner = getOwnerObject();\n if (isEnabled() && (owner != null) && owner.isEnabled())\n {\n float w = getWidth();\n float h = getHeight();\n mPose.update(mARPlane.getCenterPose(), scale);\n Matrix4f m = new Matrix4f();\n m.set(mPose.getPoseMatrix());\n m.scaleLocal(w * 0.95f, h * 0.95f, 1.0f);\n owner.getTransform().setModelMatrix(m);\n }\n }" ]
Merges a list of local and online dumps. For dumps available both online and locally, only the local version is included. The list is order with most recent dump date first. @return a merged list of dump files
[ "List<MwDumpFile> mergeDumpLists(List<MwDumpFile> localDumps,\n\t\t\tList<MwDumpFile> onlineDumps) {\n\t\tList<MwDumpFile> result = new ArrayList<>(localDumps);\n\n\t\tHashSet<String> localDateStamps = new HashSet<>();\n\t\tfor (MwDumpFile dumpFile : localDumps) {\n\t\t\tlocalDateStamps.add(dumpFile.getDateStamp());\n\t\t}\n\t\tfor (MwDumpFile dumpFile : onlineDumps) {\n\t\t\tif (!localDateStamps.contains(dumpFile.getDateStamp())) {\n\t\t\t\tresult.add(dumpFile);\n\t\t\t}\n\t\t}\n\t\tresult.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));\n\t\treturn result;\n\t}" ]
[ "@Override\n public void preStateCrawling(CrawlerContext context,\n ImmutableList<CandidateElement> candidateElements, StateVertex state) {\n LOG.debug(\"preStateCrawling\");\n List<CandidateElementPosition> newElements = Lists.newLinkedList();\n LOG.info(\"Prestate found new state {} with {} candidates\", state.getName(),\n candidateElements.size());\n for (CandidateElement element : candidateElements) {\n try {\n WebElement webElement = getWebElement(context.getBrowser(), element);\n if (webElement != null) {\n newElements.add(findElement(webElement, element));\n }\n } catch (WebDriverException e) {\n LOG.info(\"Could not get position for {}\", element, e);\n }\n }\n\n StateBuilder stateOut = outModelCache.addStateIfAbsent(state);\n stateOut.addCandidates(newElements);\n LOG.trace(\"preState finished, elements added to state\");\n }", "protected Integer getCorrectIndex(Integer index) {\n Integer size = jsonNode.size();\n Integer newIndex = index;\n\n // reverse walking through the array\n if(index < 0) {\n newIndex = size + index;\n }\n\n // the negative index would be greater than the size a second time!\n if(newIndex < 0) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n // the index is greater as the actual size\n if(index > size) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n return newIndex;\n }", "public static base_response unset(nitro_service client, inatparam resource, String[] args) throws Exception{\n\t\tinatparam unsetresource = new inatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private <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 }", "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 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 }", "private static Dimension adaptTileDimensions(\n final Dimension pixels, final int maxWidth, final int maxHeight) {\n return new Dimension(adaptTileDimension(pixels.width, maxWidth),\n adaptTileDimension(pixels.height, maxHeight));\n }", "public Diff compare(File f1, File f2) throws Exception {\n\t\treturn this.compare(getCtType(f1), getCtType(f2));\n\t}", "private static Constraint loadConstraint(Annotation context) {\n Constraint constraint = null;\n final ServiceLoader<Constraint> constraints = ServiceLoader.load(Constraint.class);\n\n for (Constraint aConstraint : constraints) {\n try {\n aConstraint.getClass().getDeclaredMethod(\"check\", context.annotationType());\n constraint = aConstraint;\n break;\n } catch (NoSuchMethodException e) {\n // Look for next implementation if method not found with required signature.\n }\n }\n\n if (constraint == null) {\n throw new IllegalStateException(\"Couldn't found any implementation of \" + Constraint.class.getName());\n }\n return constraint;\n }" ]
Main method of the class, which handles the process of creating the tests @param requirementsFolder , it is the folder where the plain text given by the client is stored @param platformName , to choose the MAS platform (JADE, JADEX, etc.) @param src_test_dir , the folder where our classes are created @param tests_package , the name of the package where the stories are created @param casemanager_package , the path where casemanager must be created @param loggingPropFile , properties file @throws Exception , if any error is found in the configuration
[ "public static void generateJavaFiles(String requirementsFolder,\n String platformName, String src_test_dir, String tests_package,\n String casemanager_package, String loggingPropFile)\n throws Exception {\n\n File reqFolder = new File(requirementsFolder);\n if (reqFolder.isDirectory()) {\n for (File f : reqFolder.listFiles()) {\n if (f.getName().endsWith(\".story\")) {\n try {\n SystemReader.generateJavaFilesForOneStory(\n f.getCanonicalPath(), platformName,\n src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } catch (IOException e) {\n String message = \"ERROR: \" + e.getMessage();\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n }\n for (File f : reqFolder.listFiles()) {\n if (f.isDirectory()) {\n SystemReader.generateJavaFiles(requirementsFolder\n + File.separator + f.getName(), platformName,\n src_test_dir, tests_package + \".\" + f.getName(),\n casemanager_package, loggingPropFile);\n }\n }\n } else if (reqFolder.getName().endsWith(\".story\")) {\n SystemReader.generateJavaFilesForOneStory(requirementsFolder,\n platformName, src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } else {\n String message = \"No story file found in \" + requirementsFolder;\n logger.severe(message);\n throw new BeastException(message);\n }\n\n }" ]
[ "public static Duration getDuration(ProjectProperties properties, Integer durationValue, Integer unitsValue)\n {\n Duration result;\n if (durationValue == null)\n {\n result = null;\n }\n else\n {\n result = Duration.getInstance(durationValue.intValue(), TimeUnit.MINUTES);\n TimeUnit units = getDurationUnits(unitsValue);\n if (result.getUnits() != units)\n {\n result = result.convertUnits(units, properties);\n }\n }\n return (result);\n }", "public Rectangle toRelative(Rectangle rect) {\n\t\treturn new Rectangle(rect.getLeft() - origX, rect.getBottom() - origY, rect.getRight() - origX, rect.getTop()\n\t\t\t\t- origY);\n\t}", "public int consume(Map<String, String> initialVars) {\r\n this.dataPipe = new DataPipe(this);\n\r\n // Set initial variables\r\n for (Map.Entry<String, String> ent : initialVars.entrySet()) {\r\n dataPipe.getDataMap().put(ent.getKey(), ent.getValue());\r\n }\n\r\n // Call transformers\r\n for (DataTransformer dc : dataTransformers) {\r\n dc.transform(dataPipe);\r\n }\n\r\n // Call writers\r\n for (DataWriter oneOw : dataWriters) {\r\n try {\r\n oneOw.writeOutput(dataPipe);\r\n } catch (Exception e) { //NOPMD\r\n log.error(\"Exception in DataWriter\", e);\r\n }\r\n }\n\r\n return 1;\r\n }", "public static void extractHouseholderColumn( ZMatrixRMaj A ,\n int row0 , int row1 ,\n int col , double u[], int offsetU )\n {\n int indexU = (row0+offsetU)*2;\n u[indexU++] = 1;\n u[indexU++] = 0;\n\n for (int row = row0+1; row < row1; row++) {\n int indexA = A.getIndex(row,col);\n u[indexU++] = A.data[indexA];\n u[indexU++] = A.data[indexA+1];\n }\n }", "private SortedSet<Date> calculateDates() {\n\n if (null == m_allDates) {\n SortedSet<Date> result = new TreeSet<>();\n if (isAnyDatePossible()) {\n Calendar date = getFirstDate();\n int previousOccurrences = 0;\n while (showMoreEntries(date, previousOccurrences)) {\n result.add(date.getTime());\n toNextDate(date);\n previousOccurrences++;\n }\n }\n m_allDates = result;\n }\n return m_allDates;\n }", "public String getUuidFromResponse(ResponseOnSingeRequest myResponse) {\n\n String uuid = PcConstants.NA;\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(getJobIdRegex());\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n uuid = matcher.group(1);\n }\n\n return uuid;\n }", "public static policydataset get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset obj = new policydataset();\n\t\tobj.set_name(name);\n\t\tpolicydataset response = (policydataset) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setAlias(String alias)\r\n\t{\r\n\t\tif (alias == null || alias.trim().equals(\"\"))\r\n\t\t{\r\n\t\t\tm_alias = null;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tm_alias = alias;\r\n\t\t}\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(m_alias);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "@SuppressWarnings(\"unchecked\") private Object formatType(DataType type, Object value)\n {\n switch (type)\n {\n case DATE:\n {\n value = formatDateTime(value);\n break;\n }\n\n case CURRENCY:\n {\n value = formatCurrency((Number) value);\n break;\n }\n\n case UNITS:\n {\n value = formatUnits((Number) value);\n break;\n }\n\n case PERCENTAGE:\n {\n value = formatPercentage((Number) value);\n break;\n }\n\n case ACCRUE:\n {\n value = formatAccrueType((AccrueType) value);\n break;\n }\n\n case CONSTRAINT:\n {\n value = formatConstraintType((ConstraintType) value);\n break;\n }\n\n case WORK:\n case DURATION:\n {\n value = formatDuration(value);\n break;\n }\n\n case RATE:\n {\n value = formatRate((Rate) value);\n break;\n }\n\n case PRIORITY:\n {\n value = formatPriority((Priority) value);\n break;\n }\n\n case RELATION_LIST:\n {\n value = formatRelationList((List<Relation>) value);\n break;\n }\n\n case TASK_TYPE:\n {\n value = formatTaskType((TaskType) value);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return (value);\n }" ]
Normalizes elements in 'u' by dividing by max and computes the norm2 of the normalized array u. Adjust the sign of the returned value depending on the size of the first element in 'u'. Normalization is done to avoid overflow. <pre> for i=j:numRows u[i] = u[i] / max tau = tau + u[i]*u[i] end tau = sqrt(tau) if( u[j] &lt; 0 ) tau = -tau; </pre> @param j Element in 'u' that it starts at. @param numRows Element in 'u' that it stops at. @param u Array @param max Max value in 'u' that is used to normalize it. @return norm2 of 'u'
[ "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 }" ]
[ "@Override\n\tpublic Result getResult() throws Exception {\n\t\tResult returnResult = result;\n\n\t\t// If we've chained to other Actions, we need to find the last result\n\t\twhile (returnResult instanceof ActionChainResult) {\n\t\t\tActionProxy aProxy = ((ActionChainResult) returnResult).getProxy();\n\n\t\t\tif (aProxy != null) {\n\t\t\t\tResult proxyResult = aProxy.getInvocation().getResult();\n\n\t\t\t\tif ((proxyResult != null) && (aProxy.getExecuteResult())) {\n\t\t\t\t\treturnResult = proxyResult;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn returnResult;\n\t}", "public static int checkVlen(int i) {\n int count = 0;\n if (i >= -112 && i <= 127) {\n return 1;\n } else {\n int len = -112;\n if (i < 0) {\n i ^= -1L; // take one's complement'\n len = -120;\n }\n\n long tmp = i;\n while (tmp != 0) {\n tmp = tmp >> 8;\n len--;\n }\n\n count++;\n\n len = (len < -120) ? -(len + 120) : -(len + 112);\n\n while (len != 0) {\n count++;\n len--;\n }\n\n return count;\n }\n }", "public DiscreteInterval plus(DiscreteInterval other) {\n return new DiscreteInterval(this.min + other.min, this.max + other.max);\n }", "public <V> V attach(final AttachmentKey<V> key, final V value) {\n assert key != null;\n return key.cast(contextAttachments.put(key, value));\n }", "private void stream(InputStream is, File destFile) throws IOException {\n try {\n startProgress();\n OutputStream os = new FileOutputStream(destFile);\n \n boolean finished = false;\n try {\n byte[] buf = new byte[1024 * 10];\n int read;\n while ((read = is.read(buf)) >= 0) {\n os.write(buf, 0, read);\n processedBytes += read;\n logProgress();\n }\n \n os.flush();\n finished = true;\n } finally {\n os.close();\n if (!finished) {\n destFile.delete();\n }\n }\n } finally {\n is.close();\n completeProgress();\n }\n }", "public List<AssignmentRow> getAssignmentRows(VariableType varType) {\n List<AssignmentRow> rows = new ArrayList<AssignmentRow>();\n List<Variable> handledVariables = new ArrayList<Variable>();\n // Create an AssignmentRow for each Assignment\n for (Assignment assignment : assignments) {\n if (assignment.getVariableType() == varType) {\n String dataType = getDisplayNameFromDataType(assignment.getDataType());\n AssignmentRow row = new AssignmentRow(assignment.getName(),\n assignment.getVariableType(),\n dataType,\n assignment.getCustomDataType(),\n assignment.getProcessVarName(),\n assignment.getConstant());\n rows.add(row);\n handledVariables.add(assignment.getVariable());\n }\n }\n List<Variable> vars = null;\n if (varType == VariableType.INPUT) {\n vars = inputVariables;\n } else {\n vars = outputVariables;\n }\n // Create an AssignmentRow for each Variable that doesn't have an Assignment\n for (Variable var : vars) {\n if (!handledVariables.contains(var)) {\n AssignmentRow row = new AssignmentRow(var.getName(),\n var.getVariableType(),\n var.getDataType(),\n var.getCustomDataType(),\n null,\n null);\n rows.add(row);\n }\n }\n\n return rows;\n }", "public static Observable<Void> mapToVoid(Observable<?> fromObservable) {\n if (fromObservable != null) {\n return fromObservable.subscribeOn(Schedulers.io())\n .map(new RXMapper<Void>());\n } else {\n return Observable.empty();\n }\n }", "public Object get(String name, ObjectFactory<?> factory) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\n\t\tObject result = context.getBean(name);\n\t\tif (null == result) {\n\t\t\tresult = factory.getObject();\n\t\t\tcontext.setBean(name, result);\n\t\t}\n\t\treturn result;\n\t}", "public final static int readMdLink(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n boolean endReached = false;\n switch (ch)\n {\n case '(':\n counter++;\n break;\n case ' ':\n if (counter == 1)\n {\n endReached = true;\n }\n break;\n case ')':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n break;\n }\n if (endReached)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }" ]
append human message to JsonRtn class @param jsonRtn @return
[ "private static JsonRtn appendErrorHumanMsg(JsonRtn jsonRtn) {\n if (bundle == null || jsonRtn == null || StringUtils.isEmpty(jsonRtn.getErrCode())) {\n return null;\n }\n\n try {\n jsonRtn.setErrHumanMsg(bundle.getString(jsonRtn.getErrCode()));\n return jsonRtn;\n } catch (Exception e) {\n return null;\n }\n }" ]
[ "private Task readTask(ChildTaskContainer parent, Integer id)\n {\n Table a0 = getTable(\"A0TAB\");\n Table a1 = getTable(\"A1TAB\");\n Table a2 = getTable(\"A2TAB\");\n Table a3 = getTable(\"A3TAB\");\n Table a4 = getTable(\"A4TAB\");\n\n Task task = parent.addTask();\n MapRow a1Row = a1.find(id);\n MapRow a2Row = a2.find(id);\n\n setFields(A0TAB_FIELDS, a0.find(id), task);\n setFields(A1TAB_FIELDS, a1Row, task);\n setFields(A2TAB_FIELDS, a2Row, task);\n setFields(A3TAB_FIELDS, a3.find(id), task);\n setFields(A5TAB_FIELDS, a4.find(id), task);\n\n task.setStart(task.getEarlyStart());\n task.setFinish(task.getEarlyFinish());\n if (task.getName() == null)\n {\n task.setName(task.getText(1));\n }\n\n m_eventManager.fireTaskReadEvent(task);\n\n return task;\n }", "private ProjectFile handleOleCompoundDocument(InputStream stream) throws Exception\n {\n POIFSFileSystem fs = new POIFSFileSystem(POIFSFileSystem.createNonClosingInputStream(stream));\n String fileFormat = MPPReader.getFileFormat(fs);\n if (fileFormat != null && fileFormat.startsWith(\"MSProject\"))\n {\n MPPReader reader = new MPPReader();\n addListeners(reader);\n return reader.read(fs);\n }\n return null;\n }", "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 bridgegroup_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_nsip_binding obj = new bridgegroup_nsip_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_nsip_binding response[] = (bridgegroup_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected void createBulge( int x1 , double p , boolean byAngle ) {\n double a11 = diag[x1];\n double a22 = diag[x1+1];\n double a12 = off[x1];\n double a23 = off[x1+1];\n\n if( byAngle ) {\n c = Math.cos(p);\n s = Math.sin(p);\n\n c2 = c*c;\n s2 = s*s;\n cs = c*s;\n } else {\n computeRotation(a11-p, a12);\n }\n\n // multiply the rotator on the top left.\n diag[x1] = c2*a11 + 2.0*cs*a12 + s2*a22;\n diag[x1+1] = c2*a22 - 2.0*cs*a12 + s2*a11;\n off[x1] = a12*(c2-s2) + cs*(a22 - a11);\n off[x1+1] = c*a23;\n bulge = s*a23;\n\n if( Q != null )\n updateQ(x1,x1+1,c,s);\n }", "public <T> void setState(HttpConnectionInterceptor interceptor, String stateName, T\n stateObjectToStore) {\n Map<String, Object> state = interceptorStates.get(interceptor);\n if (state == null) {\n interceptorStates.put(interceptor, (state = new ConcurrentHashMap<String, Object>()));\n }\n state.put(stateName, stateObjectToStore);\n }", "private static String clearPath(String path) {\n try {\n ExpressionBaseState state = new ExpressionBaseState(\"EXPR\", true, false);\n if (Util.isWindows()) {\n // to not require escaping FS name separator\n state.setDefaultHandler(WordCharacterHandler.IGNORE_LB_ESCAPE_OFF);\n } else {\n state.setDefaultHandler(WordCharacterHandler.IGNORE_LB_ESCAPE_ON);\n }\n // Remove escaping characters\n path = ArgumentWithValue.resolveValue(path, state);\n } catch (CommandFormatException ex) {\n // XXX OK, continue translation\n }\n // Remove quote to retrieve candidates.\n if (path.startsWith(\"\\\"\")) {\n path = path.substring(1);\n }\n // Could be an escaped \" character. We don't take into account this corner case.\n // concider it the end of the quoted part.\n if (path.endsWith(\"\\\"\")) {\n path = path.substring(0, path.length() - 1);\n }\n return path;\n }", "public 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 void signOff(WebSocketConnection connection) {\n for (ConcurrentMap<WebSocketConnection, WebSocketConnection> connections : registry.values()) {\n connections.remove(connection);\n }\n }" ]
Set the state of an individual day in a weekly recurrence. @param day Day instance @param value true if this day is included in the recurrence
[ "public void setWeeklyDay(Day day, boolean value)\n {\n if (value)\n {\n m_days.add(day);\n }\n else\n {\n m_days.remove(day);\n }\n }" ]
[ "private static void updateSniffingLoggersLevel(Logger logger) {\n\n\t\tInputStream settingIS = FoundationLogger.class\n\t\t\t\t.getResourceAsStream(\"/sniffingLogger.xml\");\n\t\tif (settingIS == null) {\n\t\t\tlogger.debug(\"file sniffingLogger.xml not found in classpath\");\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tSAXBuilder builder = new SAXBuilder();\n\t\t\t\tDocument document = builder.build(settingIS);\n\t\t\t\tsettingIS.close();\n\t\t\t\tElement rootElement = document.getRootElement();\n\t\t\t\tList<Element> sniffingloggers = rootElement\n\t\t\t\t\t\t.getChildren(\"sniffingLogger\");\n\t\t\t\tfor (Element sniffinglogger : sniffingloggers) {\n\t\t\t\t\tString loggerName = sniffinglogger.getAttributeValue(\"id\");\n\t\t\t\t\tLogger.getLogger(loggerName).setLevel(Level.TRACE);\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(\n\t\t\t\t\t\t\"cannot load the sniffing logger configuration file. error is: \"\n\t\t\t\t\t\t\t\t+ e, e);\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Problem parsing sniffingLogger.xml\", e);\n\t\t\t}\n\t\t}\n\n\t}", "public static String renderJson(Object o) {\n\n Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()\n .create();\n return gson.toJson(o);\n }", "@Override\n public EthiopicDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public boolean hasUser(String userId) {\r\n String normalized = normalizerUserName(userId);\r\n return loginToUser.containsKey(normalized) || emailToUser.containsKey(normalized);\r\n }", "public Where<T, ID> le(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LESS_THAN_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "public synchronized void addRoleMapping(final String roleName) {\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n if (newRoles.containsKey(roleName) == false) {\n newRoles.put(roleName, new RoleMappingImpl(roleName));\n roleMappings = Collections.unmodifiableMap(newRoles);\n }\n }", "public boolean matches(HostName host) {\n\t\tif(this == host) {\n\t\t\treturn true;\n\t\t}\n\t\tif(isValid()) {\n\t\t\tif(host.isValid()) {\n\t\t\t\tif(isAddressString()) {\n\t\t\t\t\treturn host.isAddressString()\n\t\t\t\t\t\t\t&& asAddressString().equals(host.asAddressString())\n\t\t\t\t\t\t\t&& Objects.equals(getPort(), host.getPort())\n\t\t\t\t\t\t\t&& Objects.equals(getService(), host.getService());\n\t\t\t\t}\n\t\t\t\tif(host.isAddressString()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tString thisHost = parsedHost.getHost();\n\t\t\t\tString otherHost = host.parsedHost.getHost();\n\t\t\t\tif(!thisHost.equals(otherHost)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn Objects.equals(parsedHost.getEquivalentPrefixLength(), host.parsedHost.getEquivalentPrefixLength()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getMask(), host.parsedHost.getMask()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getPort(), host.parsedHost.getPort()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getService(), host.parsedHost.getService());\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\treturn !host.isValid() && toString().equals(host.toString());\n\t}", "private void handleChange(Object propertyId) {\n\n if (!m_saveBtn.isEnabled()) {\n m_saveBtn.setEnabled(true);\n m_saveExitBtn.setEnabled(true);\n }\n m_model.handleChange(propertyId);\n\n }", "public static boolean oracleExists(CuratorFramework curator) {\n boolean exists = false;\n try {\n exists = curator.checkExists().forPath(ZookeeperPath.ORACLE_SERVER) != null\n && !curator.getChildren().forPath(ZookeeperPath.ORACLE_SERVER).isEmpty();\n } catch (Exception nne) {\n if (nne instanceof KeeperException.NoNodeException) {\n // you'll do nothing\n } else {\n throw new RuntimeException(nne);\n }\n }\n return exists;\n }" ]
Constructs a list of items with given separators. @param sql StringBuilder to which the constructed string will be appended. @param list List of objects (usually strings) to join. @param init String to be added to the start of the list, before any of the items. @param sep Separator string to be added between items in the list.
[ "protected void appendList(StringBuilder sql, List<?> list, String init, String sep) {\n\n boolean first = true;\n\n for (Object s : list) {\n if (first) {\n sql.append(init);\n } else {\n sql.append(sep);\n }\n sql.append(s);\n first = false;\n }\n }" ]
[ "public ItemRequest<Section> delete(String section) {\n \n String path = String.format(\"/sections/%s\", section);\n return new ItemRequest<Section>(this, Section.class, path, \"DELETE\");\n }", "void writeBestRankTriples() {\n\t\tfor (Resource resource : this.rankBuffer.getBestRankedStatements()) {\n\t\t\ttry {\n\t\t\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\t\t\tRdfWriter.RDF_TYPE, RdfWriter.WB_BEST_RANK.toString());\n\t\t\t} catch (RDFHandlerException e) {\n\t\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t\tthis.rankBuffer.clear();\n\t}", "private void createSimpleCubeSixMeshes(GVRContext gvrContext,\n boolean facingOut, String vertexDesc, ArrayList<GVRTexture> textureList)\n {\n GVRSceneObject[] children = new GVRSceneObject[6];\n GVRMesh[] meshes = new GVRMesh[6];\n GVRVertexBuffer vbuf = new GVRVertexBuffer(gvrContext, vertexDesc, SIMPLE_VERTICES.length / 3);\n\n if (facingOut)\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_OUTWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_OUTWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_OUTWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_OUTWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_OUTWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_OUTWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_OUTWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_OUTWARD_BOTTOM_INDICES);\n }\n else\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_INWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_INWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_INWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_INWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_INWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_INWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_INWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_INWARD_BOTTOM_INDICES);\n }\n\n for (int i = 0; i < 6; i++)\n {\n children[i] = new GVRSceneObject(gvrContext, meshes[i], textureList.get(i));\n addChildObject(children[i]);\n }\n\n // attached an empty renderData for parent object, so that we can set some common properties\n GVRRenderData renderData = new GVRRenderData(gvrContext);\n attachRenderData(renderData);\n }", "public static lbvserver[] get(nitro_service service) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\tlbvserver[] response = (lbvserver[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private static String convertPathToResource(String path) {\n File file = new File(path);\n List<String> parts = new ArrayList<String>();\n do {\n parts.add(file.getName());\n file = file.getParentFile();\n }\n while (file != null);\n\n StringBuffer sb = new StringBuffer();\n int size = parts.size();\n for (int a = size - 1; a >= 0; a--) {\n if (sb.length() > 0) {\n sb.append(\"_\");\n }\n sb.append(parts.get(a));\n }\n\n // TODO: Better regex replacement\n return sb.toString().replace('-', '_').replace(\"+\", \"plus\").toLowerCase(Locale.US);\n }", "public void classifyAndWriteViterbiSearchGraph(String testFile, String searchGraphPrefix, DocumentReaderAndWriter<IN> readerAndWriter) throws IOException {\r\n Timing timer = new Timing();\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromFile(testFile, readerAndWriter);\r\n int numWords = 0;\r\n int numSentences = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n DFSA<String, Integer> tagLattice = getViterbiSearchGraph(doc, AnswerAnnotation.class);\r\n numWords += doc.size();\r\n PrintWriter latticeWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences\r\n + \".wlattice\"));\r\n PrintWriter vsgWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences + \".lattice\"));\r\n if (readerAndWriter instanceof LatticeWriter)\r\n ((LatticeWriter) readerAndWriter).printLattice(tagLattice, doc, latticeWriter);\r\n tagLattice.printAttFsmFormat(vsgWriter);\r\n latticeWriter.close();\r\n vsgWriter.close();\r\n numSentences++;\r\n }\r\n\r\n long millis = timer.stop();\r\n double wordspersec = numWords / (((double) millis) / 1000);\r\n NumberFormat nf = new DecimalFormat(\"0.00\"); // easier way!\r\n System.err.println(this.getClass().getName() + \" tagged \" + numWords + \" words in \" + numSentences\r\n + \" documents at \" + nf.format(wordspersec) + \" words per second.\");\r\n }", "public Integer getEnd() {\n if (mtasPositionType.equals(POSITION_RANGE)\n || mtasPositionType.equals(POSITION_SET)) {\n return mtasPositionEnd;\n } else if (mtasPositionType.equals(POSITION_SINGLE)) {\n return mtasPositionStart;\n } else {\n return null;\n }\n }", "@Subscribe\n public void onEnd(AggregatedQuitEvent e) {\n try {\n writeHints(hintsFile, hints);\n } catch (IOException exception) {\n outer.log(\"Could not write back the hints file.\", exception, Project.MSG_ERR);\n }\n }", "public String getVertexString() {\n if (tail() != null) {\n return \"\" + tail().index + \"-\" + head().index;\n } else {\n return \"?-\" + head().index;\n }\n }" ]
Use this API to add dnsaaaarec.
[ "public static base_response add(nitro_service client, dnsaaaarec resource) throws Exception {\n\t\tdnsaaaarec addresource = new dnsaaaarec();\n\t\taddresource.hostname = resource.hostname;\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.ttl = resource.ttl;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final ResourceRoot deploymentRoot = phaseContext.getDeploymentUnit().getAttachment(Attachments.DEPLOYMENT_ROOT);\n final ModuleSpecification moduleSpecification = phaseContext.getDeploymentUnit().getAttachment(\n Attachments.MODULE_SPECIFICATION);\n if(deploymentRoot == null)\n return;\n final ServicesAttachment servicesAttachments = phaseContext.getDeploymentUnit().getAttachment(Attachments.SERVICES);\n if(servicesAttachments != null && !servicesAttachments.getServiceImplementations(ServiceActivator.class.getName()).isEmpty()) {\n moduleSpecification.addSystemDependency(MSC_DEP);\n }\n }", "@Override\n\tpublic void clear() {\n\t\tif (dao == null) {\n\t\t\treturn;\n\t\t}\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\titerator.next();\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}", "public IntervalFrequency getRefreshFrequency() {\n switch (mRefreshInterval) {\n case REALTIME_REFRESH_INTERVAL:\n return IntervalFrequency.REALTIME;\n case HIGH_REFRESH_INTERVAL:\n return IntervalFrequency.HIGH;\n case LOW_REFRESH_INTERVAL:\n return IntervalFrequency.LOW;\n case MEDIUM_REFRESH_INTERVAL:\n return IntervalFrequency.MEDIUM;\n default:\n return IntervalFrequency.NONE;\n }\n }", "public static <IN extends CoreMap> CRFClassifier<IN> getClassifier(File file) throws IOException, ClassCastException,\r\n ClassNotFoundException {\r\n CRFClassifier<IN> crf = new CRFClassifier<IN>();\r\n crf.loadClassifier(file);\r\n return crf;\r\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 }", "public void addRow(Component component) {\n\n Component actualComponent = component == null ? m_newComponentFactory.get() : component;\n I_CmsEditableGroupRow row = m_rowBuilder.buildRow(this, actualComponent);\n m_container.addComponent(row);\n updatePlaceholder();\n updateButtonBars();\n updateGroupValidation();\n }", "protected final StringBuilder getBaseUrl(final HttpServletRequest httpServletRequest) {\n StringBuilder baseURL = new StringBuilder();\n if (httpServletRequest.getContextPath() != null && !httpServletRequest.getContextPath().isEmpty()) {\n baseURL.append(httpServletRequest.getContextPath());\n }\n if (httpServletRequest.getServletPath() != null && !httpServletRequest.getServletPath().isEmpty()) {\n baseURL.append(httpServletRequest.getServletPath());\n }\n return baseURL;\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 }", "private int calcItemWidth(RecyclerView rvCategories) {\n if (itemWidth == null || itemWidth == 0) {\n for (int i = 0; i < rvCategories.getChildCount(); i++) {\n itemWidth = rvCategories.getChildAt(i).getWidth();\n if (itemWidth != 0) {\n break;\n }\n }\n }\n // in case of call before view was created\n if (itemWidth == null) {\n itemWidth = 0;\n }\n return itemWidth;\n }" ]
Use this API to disable snmpalarm resources of given names.
[ "public static base_responses disable(nitro_service client, String trapname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm disableresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tdisableresources[i] = new snmpalarm();\n\t\t\t\tdisableresources[i].trapname = trapname[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, disableresources,\"disable\");\n\t\t}\n\t\treturn result;\n\t}" ]
[ "public static <T> DatabaseTableConfig<T> fromClass(DatabaseType databaseType, Class<T> clazz) throws SQLException {\n\t\tString tableName = extractTableName(databaseType, clazz);\n\t\tif (databaseType.isEntityNamesMustBeUpCase()) {\n\t\t\ttableName = databaseType.upCaseEntityName(tableName);\n\t\t}\n\t\treturn new DatabaseTableConfig<T>(databaseType, clazz, tableName,\n\t\t\t\textractFieldTypes(databaseType, clazz, tableName));\n\t}", "public double[] getTenors(double moneyness, double maturity) {\r\n\t\tint maturityInMonths\t= (int) Math.round(maturity * 12);\r\n\t\tint[] tenorsInMonths\t= getTenors(convertMoneyness(moneyness), maturityInMonths);\r\n\t\tdouble[] tenors\t\t\t= new double[tenorsInMonths.length];\r\n\r\n\t\tfor(int index = 0; index < tenors.length; index++) {\r\n\t\t\ttenors[index] = convertTenor(maturityInMonths, tenorsInMonths[index]);\r\n\t\t}\r\n\t\treturn tenors;\r\n\t}", "public static base_response update(nitro_service client, sslocspresponder resource) throws Exception {\n\t\tsslocspresponder updateresource = new sslocspresponder();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.cache = resource.cache;\n\t\tupdateresource.cachetimeout = resource.cachetimeout;\n\t\tupdateresource.batchingdepth = resource.batchingdepth;\n\t\tupdateresource.batchingdelay = resource.batchingdelay;\n\t\tupdateresource.resptimeout = resource.resptimeout;\n\t\tupdateresource.respondercert = resource.respondercert;\n\t\tupdateresource.trustresponder = resource.trustresponder;\n\t\tupdateresource.producedattimeskew = resource.producedattimeskew;\n\t\tupdateresource.signingcert = resource.signingcert;\n\t\tupdateresource.usenonce = resource.usenonce;\n\t\tupdateresource.insertclientcert = resource.insertclientcert;\n\t\treturn updateresource.update_resource(client);\n\t}", "private String getPropertyValue(String level, String name)\r\n {\r\n return getDefForLevel(level).getProperty(name);\r\n }", "@UiHandler(\"m_currentTillEndCheckBox\")\n void onCurrentTillEndChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setCurrentTillEnd(event.getValue());\n }\n }", "public static String getVersionString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.version\");\n\t\t}\n\t\treturn versionString;\n\t}", "@Override\n public Future<GcsFileMetadata> readObjectAsync(final ByteBuffer dst, final GcsFilename filename,\n long startOffsetBytes, long timeoutMillis) {\n Preconditions.checkArgument(startOffsetBytes >= 0, \"%s: offset must be non-negative: %s\", this,\n startOffsetBytes);\n final int n = dst.remaining();\n Preconditions.checkArgument(n > 0, \"%s: dst full: %s\", this, dst);\n final int want = Math.min(READ_LIMIT_BYTES, n);\n\n final HTTPRequest req = makeRequest(filename, null, GET, timeoutMillis);\n req.setHeader(\n new HTTPHeader(RANGE, \"bytes=\" + startOffsetBytes + \"-\" + (startOffsetBytes + want - 1)));\n final HTTPRequestInfo info = new HTTPRequestInfo(req);\n return new FutureWrapper<HTTPResponse, GcsFileMetadata>(urlfetch.fetchAsync(req)) {\n @Override\n protected GcsFileMetadata wrap(HTTPResponse resp) throws IOException {\n long totalLength;\n switch (resp.getResponseCode()) {\n case 200:\n totalLength = getLengthFromHeader(resp, X_GOOG_CONTENT_LENGTH);\n break;\n case 206:\n totalLength = getLengthFromContentRange(resp);\n break;\n case 404:\n throw new FileNotFoundException(\"Could not find: \" + filename);\n case 416:\n throw new BadRangeException(\"Requested Range not satisfiable; perhaps read past EOF? \"\n + URLFetchUtils.describeRequestAndResponse(info, resp));\n default:\n throw HttpErrorHandler.error(info, resp);\n }\n byte[] content = resp.getContent();\n Preconditions.checkState(content.length <= want, \"%s: got %s > wanted %s\", this,\n content.length, want);\n dst.put(content);\n return getMetadataFromResponse(filename, resp, totalLength);\n }\n\n @Override\n protected Throwable convertException(Throwable e) {\n return OauthRawGcsService.convertException(info, e);\n }\n };\n }", "public static base_responses update(nitro_service client, nsrpcnode resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsrpcnode updateresources[] = new nsrpcnode[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsrpcnode();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].srcip = resources[i].srcip;\n\t\t\t\tupdateresources[i].secure = resources[i].secure;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private void setMaxMin(IntervalRBTreeNode<T> n) {\n n.min = n.left;\n n.max = n.right;\n if (n.leftChild != null) {\n n.min = Math.min(n.min, n.leftChild.min);\n n.max = Math.max(n.max, n.leftChild.max);\n }\n if (n.rightChild != null) {\n n.min = Math.min(n.min, n.rightChild.min);\n n.max = Math.max(n.max, n.rightChild.max);\n }\n }" ]
Create a random permutation of the numbers 0, ..., size - 1. see Algorithm P, D.E. Knuth: The Art of Computer Programming, Vol. 2, p. 145
[ "public static int[] randomPermutation(int size) {\n Random r = new Random();\n int[] result = new int[size];\n\n for (int j = 0; j < size; j++) {\n result[j] = j;\n }\n \n for (int j = size - 1; j > 0; j--) {\n int k = r.nextInt(j);\n int temp = result[j];\n result[j] = result[k];\n result[k] = temp;\n }\n\n return result;\n }" ]
[ "public static void requireNamespace(final XMLExtendedStreamReader reader, final Namespace requiredNs) throws XMLStreamException {\n Namespace actualNs = Namespace.forUri(reader.getNamespaceURI());\n if (actualNs != requiredNs) {\n throw unexpectedElement(reader);\n }\n }", "protected Element createLineElement(float x1, float y1, float x2, float y2)\n {\n HtmlDivLine line = new HtmlDivLine(x1, y1, x2, y2);\n String color = colorString(getGraphicsState().getStrokingColor());\n\n StringBuilder pstyle = new StringBuilder(50);\n pstyle.append(\"left:\").append(style.formatLength(line.getLeft())).append(';');\n pstyle.append(\"top:\").append(style.formatLength(line.getTop())).append(';');\n pstyle.append(\"width:\").append(style.formatLength(line.getWidth())).append(';');\n pstyle.append(\"height:\").append(style.formatLength(line.getHeight())).append(';');\n pstyle.append(line.getBorderSide()).append(':').append(style.formatLength(line.getLineStrokeWidth())).append(\" solid \").append(color).append(';');\n if (line.getAngleDegrees() != 0)\n pstyle.append(\"transform:\").append(\"rotate(\").append(line.getAngleDegrees()).append(\"deg);\");\n\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"class\", \"r\");\n el.setAttribute(\"style\", pstyle.toString());\n el.appendChild(doc.createEntityReference(\"nbsp\"));\n return el;\n }", "private void recurseAndAddFiles(GraphRewrite event, EvaluationContext context,\n Path tempFolder,\n FileService fileService, ArchiveModel archiveModel,\n FileModel parentFileModel, boolean subArchivesOnly)\n {\n checkCancelled(event);\n\n int numberAdded = 0;\n\n FileFilter filter = TrueFileFilter.TRUE;\n if (archiveModel instanceof IdentifiedArchiveModel)\n {\n filter = new IdentifiedArchiveFileFilter(archiveModel);\n }\n\n File fileReference;\n if (parentFileModel instanceof ArchiveModel)\n fileReference = new File(((ArchiveModel) parentFileModel).getUnzippedDirectory());\n else\n fileReference = parentFileModel.asFile();\n\n WindupJavaConfigurationService windupJavaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n File[] subFiles = fileReference.listFiles();\n if (subFiles == null)\n return;\n\n for (File subFile : subFiles)\n {\n if (!filter.accept(subFile))\n continue;\n\n if (subArchivesOnly && !ZipUtil.endsWithZipExtension(subFile.getAbsolutePath()))\n continue;\n\n FileModel subFileModel = fileService.createByFilePath(parentFileModel, subFile.getAbsolutePath());\n\n // check if this file should be ignored\n if (windupJavaConfigurationService.checkIfIgnored(event, subFileModel))\n continue;\n\n numberAdded++;\n if (numberAdded % 250 == 0)\n event.getGraphContext().commit();\n\n if (subFile.isFile() && ZipUtil.endsWithZipExtension(subFileModel.getFilePath()))\n {\n File newZipFile = subFileModel.asFile();\n ArchiveModel newArchiveModel = GraphService.addTypeToModel(event.getGraphContext(), subFileModel, ArchiveModel.class);\n newArchiveModel.setParentArchive(archiveModel);\n newArchiveModel.setArchiveName(newZipFile.getName());\n\n /*\n * New archive must be reloaded in case the archive should be ignored\n */\n newArchiveModel = GraphService.refresh(event.getGraphContext(), newArchiveModel);\n\n ArchiveModel canonicalArchiveModel = null;\n for (FileModel otherMatches : fileService.findAllByProperty(FileModel.SHA1_HASH, newArchiveModel.getSHA1Hash()))\n {\n if (otherMatches instanceof ArchiveModel && !otherMatches.equals(newArchiveModel) && !(otherMatches instanceof DuplicateArchiveModel))\n {\n canonicalArchiveModel = (ArchiveModel)otherMatches;\n break;\n }\n }\n\n if (canonicalArchiveModel != null)\n {\n // handle as duplicate\n DuplicateArchiveModel duplicateArchive = GraphService.addTypeToModel(event.getGraphContext(), newArchiveModel, DuplicateArchiveModel.class);\n duplicateArchive.setCanonicalArchive(canonicalArchiveModel);\n\n // create dupes for child archives\n unzipToTempDirectory(event, context, tempFolder, newZipFile, duplicateArchive, true);\n } else\n {\n unzipToTempDirectory(event, context, tempFolder, newZipFile, newArchiveModel, false);\n }\n } else if (subFile.isDirectory())\n {\n recurseAndAddFiles(event, context, tempFolder, fileService, archiveModel, subFileModel, false);\n }\n }\n }", "public void onAttach(GVRSceneObject sceneObj)\n {\n super.onAttach(sceneObj);\n GVRComponent comp = getComponent(GVRRenderData.getComponentType());\n\n if (comp == null)\n {\n throw new IllegalStateException(\"Cannot attach a morph to a scene object without a base mesh\");\n }\n\n GVRMesh mesh = ((GVRRenderData) comp).getMesh();\n if (mesh == null)\n {\n throw new IllegalStateException(\"Cannot attach a morph to a scene object without a base mesh\");\n }\n GVRShaderData mtl = getMaterial();\n\n if ((mtl == null) ||\n !mtl.getTextureDescriptor().contains(\"blendshapeTexture\"))\n {\n throw new IllegalStateException(\"Scene object shader does not support morphing\");\n }\n copyBaseShape(mesh.getVertexBuffer());\n mtl.setInt(\"u_numblendshapes\", mNumBlendShapes);\n mtl.setFloatArray(\"u_blendweights\", mWeights);\n }", "public WebMBeanAdapter createWebMBeanAdapter(String mBeanName, String encoding)\n throws JMException, UnsupportedEncodingException {\n return new WebMBeanAdapter(mBeanServer, mBeanName, encoding);\n }", "private void processUpdate(DeviceUpdate update) {\n updates.put(update.getAddress(), update);\n\n // Keep track of the largest sync number we see.\n if (update instanceof CdjStatus) {\n int syncNumber = ((CdjStatus)update).getSyncNumber();\n if (syncNumber > this.largestSyncCounter.get()) {\n this.largestSyncCounter.set(syncNumber);\n }\n }\n\n // Deal with the tempo master complexities, including handoff to/from us.\n if (update.isTempoMaster()) {\n final Integer packetYieldingTo = update.getDeviceMasterIsBeingYieldedTo();\n if (packetYieldingTo == null) {\n // This is a normal, non-yielding master packet. Update our notion of the current master, and,\n // if we were yielding, finish that process, updating our sync number appropriately.\n if (master.get()) {\n if (nextMaster.get() == update.deviceNumber) {\n syncCounter.set(largestSyncCounter.get() + 1);\n } else {\n if (nextMaster.get() == 0xff) {\n logger.warn(\"Saw master asserted by player \" + update.deviceNumber +\n \" when we were not yielding it.\");\n } else {\n logger.warn(\"Expected to yield master role to player \" + nextMaster.get() +\n \" but saw master asserted by player \" + update.deviceNumber);\n }\n }\n }\n master.set(false);\n nextMaster.set(0xff);\n setTempoMaster(update);\n setMasterTempo(update.getEffectiveTempo());\n } else {\n // This is a yielding master packet. If it is us that is being yielded to, take over master.\n // Log a message if it was unsolicited, and a warning if it's coming from a different player than\n // we asked.\n if (packetYieldingTo == getDeviceNumber()) {\n if (update.deviceNumber != masterYieldedFrom.get()) {\n if (masterYieldedFrom.get() == 0) {\n logger.info(\"Accepting unsolicited Master yield; we must be the only synced device playing.\");\n } else {\n logger.warn(\"Expected player \" + masterYieldedFrom.get() + \" to yield master to us, but player \" +\n update.deviceNumber + \" did.\");\n }\n }\n master.set(true);\n masterYieldedFrom.set(0);\n setTempoMaster(null);\n setMasterTempo(getTempo());\n }\n }\n } else {\n // This update was not acting as a tempo master; if we thought it should be, update our records.\n DeviceUpdate oldMaster = getTempoMaster();\n if (oldMaster != null && oldMaster.getAddress().equals(update.getAddress())) {\n // This device has resigned master status, and nobody else has claimed it so far\n setTempoMaster(null);\n }\n }\n deliverDeviceUpdate(update);\n }", "private void solveInternalL() {\n // This takes advantage of the diagonal elements always being real numbers\n\n // solve L*y=b storing y in x\n TriangularSolver_ZDRM.solveL_diagReal(t, vv, n);\n\n // solve L^T*x=y\n TriangularSolver_ZDRM.solveConjTranL_diagReal(t, vv, n);\n }", "public static base_response delete(nitro_service client, String labelname) throws Exception {\n\t\tdnspolicylabel deleteresource = new dnspolicylabel();\n\t\tdeleteresource.labelname = labelname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "protected Connection obtainInternalConnection(ConnectionHandle connectionHandle) throws SQLException {\r\n\t\tboolean tryAgain = false;\r\n\t\tConnection result = null;\r\n\t\tConnection oldRawConnection = connectionHandle.getInternalConnection();\r\n\t\tString url = this.getConfig().getJdbcUrl();\r\n\t\t\r\n\t\tint acquireRetryAttempts = this.getConfig().getAcquireRetryAttempts();\r\n\t\tlong acquireRetryDelayInMs = this.getConfig().getAcquireRetryDelayInMs();\r\n\t\tAcquireFailConfig acquireConfig = new AcquireFailConfig();\r\n\t\tacquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts));\r\n\t\tacquireConfig.setAcquireRetryDelayInMs(acquireRetryDelayInMs);\r\n\t\tacquireConfig.setLogMessage(\"Failed to acquire connection to \"+url);\r\n\t\tConnectionHook connectionHook = this.getConfig().getConnectionHook();\r\n\t\tdo{ \r\n\t\t\tresult = null;\r\n\t\t\ttry { \r\n\t\t\t\t// keep track of this hook.\r\n\t\t\t\tresult = this.obtainRawInternalConnection();\r\n\t\t\t\ttryAgain = false;\r\n\r\n\t\t\t\tif (acquireRetryAttempts != this.getConfig().getAcquireRetryAttempts()){\r\n\t\t\t\t\tlogger.info(\"Successfully re-established connection to \"+url);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tthis.getDbIsDown().set(false);\r\n\t\t\t\t\r\n\t\t\t\tconnectionHandle.setInternalConnection(result);\r\n\t\t\t\t\r\n\t\t\t\t// call the hook, if available.\r\n\t\t\t\tif (connectionHook != null){\r\n\t\t\t\t\tconnectionHook.onAcquire(connectionHandle);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\r\n\t\t\t\tConnectionHandle.sendInitSQL(result, this.getConfig().getInitSQL());\r\n\t\t\t} catch (SQLException e) {\r\n\t\t\t\t// call the hook, if available.\r\n\t\t\t\tif (connectionHook != null){\r\n\t\t\t\t\ttryAgain = connectionHook.onAcquireFail(e, acquireConfig);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlogger.error(String.format(\"Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d\", url, acquireRetryDelayInMs, acquireRetryAttempts), e);\r\n\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tif (acquireRetryAttempts > 0){\r\n\t\t\t\t\t\t\tThread.sleep(acquireRetryDelayInMs);\r\n\t \t\t\t\t\t}\r\n\t\t\t\t\t\ttryAgain = (acquireRetryAttempts--) > 0;\r\n\t\t\t\t\t} catch (InterruptedException e1) {\r\n\t\t\t\t\t\ttryAgain=false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (!tryAgain){\r\n\t\t\t\t\tif (oldRawConnection != null) {\r\n\t\t\t\t\t\toldRawConnection.close();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (result != null) {\r\n\t\t\t\t\t\tresult.close();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tconnectionHandle.setInternalConnection(oldRawConnection);\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} while (tryAgain);\r\n\r\n\t\treturn result;\r\n\r\n\t}" ]
Returns a new AWT BufferedImage from this image. @param type the type of buffered image to create, if not specified then defaults to the current image type @return a new, non-shared, BufferedImage with the same data as this Image.
[ "public BufferedImage toNewBufferedImage(int type) {\n BufferedImage target = new BufferedImage(width, height, type);\n Graphics2D g2 = (Graphics2D) target.getGraphics();\n g2.drawImage(awt, 0, 0, null);\n g2.dispose();\n return target;\n }" ]
[ "public static base_responses add(nitro_service client, snmpuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpuser addresources[] = new snmpuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new snmpuser();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].group = resources[i].group;\n\t\t\t\taddresources[i].authtype = resources[i].authtype;\n\t\t\t\taddresources[i].authpasswd = resources[i].authpasswd;\n\t\t\t\taddresources[i].privtype = resources[i].privtype;\n\t\t\t\taddresources[i].privpasswd = resources[i].privpasswd;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static appfwpolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_csvserver_binding obj = new appfwpolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_csvserver_binding response[] = (appfwpolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public <T> T callFunction(\n final String name,\n final List<?> args,\n final @Nullable Long requestTimeout,\n final Class<T> resultClass,\n final CodecRegistry codecRegistry\n ) {\n return this.functionService\n .withCodecRegistry(codecRegistry)\n .callFunction(name, args, requestTimeout, resultClass);\n }", "private void disableTalkBack() {\n GVRSceneObject[] sceneObjects = mGvrContext.getMainScene().getWholeSceneObjects();\n for (GVRSceneObject sceneObject : sceneObjects) {\n if (sceneObject instanceof GVRAccessiblityObject)\n if (((GVRAccessiblityObject) sceneObject).getTalkBack() != null)\n ((GVRAccessiblityObject) sceneObject).getTalkBack().setActive(false);\n\n }\n }", "public static boolean isBigInteger(CharSequence self) {\n try {\n new BigInteger(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "public static DatabaseFieldConfig fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseFieldConfig config = new DatabaseFieldConfig();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseFieldConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseFieldConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}", "private void increaseBeliefCount(String bName) {\n Object belief = this.getBelief(bName);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n this.setBelief(bName, count + 1);\n }", "public static final String printResourceType(ResourceType value)\n {\n return (Integer.toString(value == null ? ResourceType.WORK.getValue() : value.getValue()));\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}" ]
Encodes the given URI path with the given encoding. @param path the path to be encoded @param encoding the character encoding to encode to @return the encoded path @throws UnsupportedEncodingException when the given encoding parameter is not supported
[ "public static String encodePath(String path, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(path, encoding, HierarchicalUriComponents.Type.PATH);\n\t}" ]
[ "public void removeWorstFit() {\n // find the observation with the most error\n int worstIndex=-1;\n double worstError = -1;\n\n for( int i = 0; i < y.numRows; i++ ) {\n double predictedObs = 0;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n predictedObs += A.get(i,j)*coef.get(j,0);\n }\n\n double error = Math.abs(predictedObs- y.get(i,0));\n\n if( error > worstError ) {\n worstError = error;\n worstIndex = i;\n }\n }\n\n // nothing left to remove, so just return\n if( worstIndex == -1 )\n return;\n\n // remove that observation\n removeObservation(worstIndex);\n\n // update A\n solver.removeRowFromA(worstIndex);\n\n // solve for the parameters again\n solver.solve(y,coef);\n }", "protected void convertSearchResults(final Collection<CmsSearchResource> searchResults) {\n\n m_foundResources = new ArrayList<I_CmsSearchResourceBean>();\n for (final CmsSearchResource searchResult : searchResults) {\n m_foundResources.add(new CmsSearchResourceBean(searchResult, m_cmsObject));\n }\n }", "public static float smoothPulse(float a1, float a2, float b1, float b2, float x) {\n\t\tif (x < a1 || x >= b2)\n\t\t\treturn 0;\n\t\tif (x >= a2) {\n\t\t\tif (x < b1)\n\t\t\t\treturn 1.0f;\n\t\t\tx = (x - b1) / (b2 - b1);\n\t\t\treturn 1.0f - (x*x * (3.0f - 2.0f*x));\n\t\t}\n\t\tx = (x - a1) / (a2 - a1);\n\t\treturn x*x * (3.0f - 2.0f*x);\n\t}", "private void processProperties() {\n state = true;\n try {\n importerServiceFilter = getFilter(importerServiceFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_IMPORTERSERVICE_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n\n try {\n importDeclarationFilter = getFilter(importDeclarationFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_IMPORTDECLARATION_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n }", "public String getGroup(String groupId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GROUP);\r\n\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\r\n Element payload = response.getPayload();\r\n return payload.getAttribute(\"url\");\r\n }", "private void reply(final String response, final boolean error,\n final String errorMessage, final String stackTrace,\n final String statusCode, final int statusCodeInt) {\n\n \n if (!sentReply) {\n \n //must update sentReply first to avoid duplicated msg.\n sentReply = true;\n // Close the connection. Make sure the close operation ends because\n // all I/O operations are asynchronous in Netty.\n if(channel!=null && channel.isOpen())\n channel.close().awaitUninterruptibly();\n final ResponseOnSingeRequest res = new ResponseOnSingeRequest(\n response, error, errorMessage, stackTrace, statusCode,\n statusCodeInt, PcDateUtils.getNowDateTimeStrStandard(), null);\n if (!getContext().system().deadLetters().equals(sender)) {\n sender.tell(res, getSelf());\n }\n if (getContext() != null) {\n getContext().stop(getSelf());\n }\n }\n\n }", "private boolean hasPrimaryKey(T entity) {\n Object pk = getPrimaryKey(entity);\n if (pk == null) {\n return false;\n } else {\n if (pk instanceof Number && ((Number) pk).longValue() == 0) {\n return false;\n }\n }\n return true;\n }", "public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n return getModuleDependencies(module, filters, 1, new ArrayList<String>());\n }", "protected NodeData createRectangleStyle(float x, float y, float width, float height, boolean stroke, boolean fill)\n {\n float lineWidth = transformLength((float) getGraphicsState().getLineWidth());\n float lw = (lineWidth < 1f) ? 1f : lineWidth;\n float wcor = stroke ? lw : 0.0f;\n \n NodeData ret = CSSFactory.createNodeData();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"absolute\")));\n ret.push(createDeclaration(\"left\", tf.createLength(x, unit)));\n ret.push(createDeclaration(\"top\", tf.createLength(y, unit)));\n ret.push(createDeclaration(\"width\", tf.createLength(width - wcor, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(height - wcor, unit)));\n \n if (stroke)\n {\n ret.push(createDeclaration(\"border-width\", tf.createLength(lw, unit)));\n ret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n String color = colorString(getGraphicsState().getStrokingColor());\n ret.push(createDeclaration(\"border-color\", tf.createColor(color)));\n }\n \n if (fill)\n {\n String color = colorString(getGraphicsState().getNonStrokingColor());\n if (color != null)\n ret.push(createDeclaration(\"background-color\", tf.createColor(color)));\n }\n\n return ret;\n }" ]
Count the total number of queued resource requests for all queues. The result is "approximate" in the face of concurrency since individual queues can change size during the aggregate count. @return The (approximate) aggregate count of queued resource requests.
[ "public int getRegisteredResourceRequestCount() {\n int count = 0;\n for(Entry<K, Queue<AsyncResourceRequest<V>>> entry: this.requestQueueMap.entrySet()) {\n // FYI: .size() is not constant time in the next call. ;)\n count += entry.getValue().size();\n }\n return count;\n }" ]
[ "public void prepareServer() {\n try {\n server = new Server(0);\n jettyHandler = new AbstractHandler() {\n public void handle(String target, Request req, HttpServletRequest request,\n HttpServletResponse response) throws IOException, ServletException {\n response.setContentType(\"text/plain\");\n\n String[] operands = request.getRequestURI().split(\"/\");\n\n String name = \"\";\n String command = \"\";\n String value = \"\";\n\n //operands[0] = \"\", request starts with a \"/\"\n\n if (operands.length >= 2) {\n name = operands[1];\n }\n\n if (operands.length >= 3) {\n command = operands[2];\n }\n\n if (operands.length >= 4) {\n value = operands[3];\n }\n\n if (command.equals(\"report\")) { //report a number of lines written\n response.getWriter().write(makeReport(name, value));\n } else if (command.equals(\"request\") && value.equals(\"block\")) { //request a new block of work\n response.getWriter().write(requestBlock(name));\n } else if (command.equals(\"request\") && value.equals(\"name\")) { //request a new name to report with\n response.getWriter().write(requestName());\n } else { //non recognized response\n response.getWriter().write(\"exit\");\n }\n\n ((Request) request).setHandled(true);\n }\n };\n\n server.setHandler(jettyHandler);\n\n // Select any available port\n server.start();\n Connector[] connectors = server.getConnectors();\n NetworkConnector nc = (NetworkConnector) connectors[0];\n listeningPort = nc.getLocalPort();\n hostName = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "public PagedList<V> convert(final PagedList<U> uList) {\n if (uList == null || uList.isEmpty()) {\n return new PagedList<V>() {\n @Override\n public Page<V> nextPage(String s) throws RestException, IOException {\n return null;\n }\n };\n }\n Page<U> uPage = uList.currentPage();\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return new PagedList<V>(vPage) {\n @Override\n public Page<V> nextPage(String nextPageLink) throws RestException, IOException {\n Page<U> uPage = uList.nextPage(nextPageLink);\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return vPage;\n }\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}", "@SuppressWarnings(\"unchecked\")\n\t/* @Nullable */\n\tpublic <T> T get(Object receiver, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\t\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\treturn (T) f.get(receiver);\n\t}", "public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) {\n\t\tthis.connectionTimeoutInMs = TimeUnit.MILLISECONDS.convert(connectionTimeout, timeUnit);\n\t}", "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 void afterMaterialization(IndirectionHandler handler, Object materializedObject)\r\n {\r\n try\r\n {\r\n Identity oid = handler.getIdentity();\r\n if (log.isDebugEnabled())\r\n log.debug(\"deferred registration: \" + oid);\r\n if(!isOpen())\r\n {\r\n log.error(\"Proxy object materialization outside of a running tx, obj=\" + oid);\r\n try{throw new Exception(\"Proxy object materialization outside of a running tx, obj=\" + oid);}catch(Exception e)\r\n {\r\n e.printStackTrace();\r\n }\r\n }\r\n ClassDescriptor cld = getBroker().getClassDescriptor(materializedObject.getClass());\r\n RuntimeObject rt = new RuntimeObject(materializedObject, oid, cld, false, false);\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n catch (Throwable t)\r\n {\r\n log.error(\"Register materialized object with this tx failed\", t);\r\n throw new LockNotGrantedException(t.getMessage());\r\n }\r\n unregisterFromIndirectionHandler(handler);\r\n }", "private static String guessPackaging(ProjectModel projectModel)\n {\n String projectType = projectModel.getProjectType();\n if (projectType != null)\n return projectType;\n\n LOG.warning(\"WINDUP-983 getProjectType() returned null for: \" + projectModel.getRootFileModel().getPrettyPath());\n\n String suffix = StringUtils.substringAfterLast(projectModel.getRootFileModel().getFileName(), \".\");\n if (\"jar war ear sar har \".contains(suffix+\" \")){\n projectModel.setProjectType(suffix); // FIXME: Remove when WINDUP-983 is fixed.\n return suffix;\n }\n\n // Should we try something more? Used APIs? What if it's a source?\n\n return \"unknown\";\n }", "public boolean hasChanged(MediaDetails originalMedia) {\n if (!hashKey().equals(originalMedia.hashKey())) {\n throw new IllegalArgumentException(\"Can't compare media details with different hashKey values\");\n }\n return playlistCount != originalMedia.playlistCount || trackCount != originalMedia.trackCount;\n }" ]
Draw a rounded rectangular boundary. @param rect rectangle @param color colour @param linewidth line width @param r radius for rounded corners
[ "public void strokeRoundRectangle(Rectangle rect, Color color, float linewidth, float r) {\n\t\ttemplate.saveState();\n\t\tsetStroke(color, linewidth, null);\n\t\ttemplate.roundRectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight(), r);\n\t\ttemplate.stroke();\n\t\ttemplate.restoreState();\n\t}" ]
[ "private void merge(ExecutionStatistics otherStatistics) {\n for (String s : otherStatistics.executionInfo.keySet())\n {\n TimingData thisStats = this.executionInfo.get(s);\n TimingData otherStats = otherStatistics.executionInfo.get(s);\n if(thisStats == null) {\n this.executionInfo.put(s,otherStats);\n } else {\n thisStats.merge(otherStats);\n }\n\n }\n }", "@Override\n public void map(GenericData.Record record,\n AvroCollector<Pair<ByteBuffer, ByteBuffer>> collector,\n Reporter reporter) throws IOException {\n\n byte[] keyBytes = null;\n byte[] valBytes = null;\n Object keyRecord = null;\n Object valRecord = null;\n try {\n keyRecord = record.get(keyField);\n valRecord = record.get(valField);\n keyBytes = keySerializer.toBytes(keyRecord);\n valBytes = valueSerializer.toBytes(valRecord);\n\n this.collectorWrapper.setCollector(collector);\n this.mapper.map(keyBytes, valBytes, this.collectorWrapper);\n\n recordCounter++;\n } catch (OutOfMemoryError oom) {\n logger.error(oomErrorMessage(reporter));\n if (keyBytes == null) {\n logger.error(\"keyRecord caused OOM!\");\n } else {\n logger.error(\"keyRecord: \" + keyRecord);\n logger.error(\"valRecord: \" + (valBytes == null ? \"caused OOM\" : valRecord));\n }\n throw new VoldemortException(oomErrorMessage(reporter), oom);\n }\n }", "public static void addTTLIndex(DBCollection collection, String field, int ttl) {\n if (ttl <= 0) {\n throw new IllegalArgumentException(\"TTL must be positive\");\n }\n collection.createIndex(new BasicDBObject(field, 1), new BasicDBObject(\"expireAfterSeconds\", ttl));\n }", "public 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 Method getMethod(Method method) {\n return getMethod(method.getReturnType(), method.getName(), method.getParameterTypes());\n }", "@RequestMapping(value = \"api/edit/repeatNumber\", method = RequestMethod.POST)\n public\n @ResponseBody\n String updateRepeatNumber(Model model, int newNum, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n logger.info(\"want to update repeat number of path_id={}, to newNum={}\", path_id, newNum);\n editService.updateRepeatNumber(newNum, path_id, clientUUID);\n return null;\n }", "public static Collection<String> getFormatProviderNames() {\n Collection<String> providers = Optional.ofNullable(getMonetaryFormatsSpi()).orElseThrow(\n () -> new MonetaryException(\n \"No MonetaryFormatsSingletonSpi loaded, query functionality is not available.\"))\n .getProviderNames();\n if (Objects.isNull(providers)) {\n Logger.getLogger(MonetaryFormats.class.getName()).warning(\n \"No supported rate/conversion providers returned by SPI: \" +\n getMonetaryFormatsSpi().getClass().getName());\n return Collections.emptySet();\n }\n return providers;\n }", "private void writeAssignments()\n {\n Allocations allocations = m_factory.createAllocations();\n m_plannerProject.setAllocations(allocations);\n\n List<Allocation> allocationList = allocations.getAllocation();\n for (ResourceAssignment mpxjAssignment : m_projectFile.getResourceAssignments())\n {\n Allocation plannerAllocation = m_factory.createAllocation();\n allocationList.add(plannerAllocation);\n\n plannerAllocation.setTaskId(getIntegerString(mpxjAssignment.getTask().getUniqueID()));\n plannerAllocation.setResourceId(getIntegerString(mpxjAssignment.getResourceUniqueID()));\n plannerAllocation.setUnits(getIntegerString(mpxjAssignment.getUnits()));\n\n m_eventManager.fireAssignmentWrittenEvent(mpxjAssignment);\n }\n }", "protected void processDurationField(Row row)\n {\n processField(row, \"DUR_FIELD_ID\", \"DUR_REF_UID\", MPDUtility.getAdjustedDuration(m_project, row.getInt(\"DUR_VALUE\"), MPDUtility.getDurationTimeUnits(row.getInt(\"DUR_FMT\"))));\n }" ]
Use this API to count bridgegroup_vlan_binding resources configued on NetScaler.
[ "public static long count(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_vlan_binding obj = new bridgegroup_vlan_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tbridgegroup_vlan_binding response[] = (bridgegroup_vlan_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}" ]
[ "public User getLimits() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIMITS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n NodeList photoNodes = userElement.getElementsByTagName(\"photos\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element plElement = (Element) photoNodes.item(i);\r\n PhotoLimits pl = new PhotoLimits();\r\n user.setPhotoLimits(pl);\r\n pl.setMaxDisplay(plElement.getAttribute(\"maxdisplaypx\"));\r\n pl.setMaxUpload(plElement.getAttribute(\"maxupload\"));\r\n }\r\n NodeList videoNodes = userElement.getElementsByTagName(\"videos\");\r\n for (int i = 0; i < videoNodes.getLength(); i++) {\r\n Element vlElement = (Element) videoNodes.item(i);\r\n VideoLimits vl = new VideoLimits();\r\n user.setPhotoLimits(vl);\r\n vl.setMaxDuration(vlElement.getAttribute(\"maxduration\"));\r\n vl.setMaxUpload(vlElement.getAttribute(\"maxupload\"));\r\n }\r\n return user;\r\n }", "private boolean exceedsScreenDimensions(InternalFeature f, double scale) {\n\t\tEnvelope env = f.getBounds();\n\t\treturn (env.getWidth() * scale > MAXIMUM_TILE_COORDINATE) ||\n\t\t\t\t(env.getHeight() * scale > MAXIMUM_TILE_COORDINATE);\n\t}", "public ItemRequest<Task> removeDependencies(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public RuntimeParameter addParameter(String key, String value)\n {\n RuntimeParameter jp = new RuntimeParameter();\n jp.setJi(this.getId());\n jp.setKey(key);\n jp.setValue(value);\n return jp;\n }", "private boolean isAbandoned(final SubmittedPrintJob printJob) {\n final long duration = ThreadPoolJobManager.this.jobQueue.timeSinceLastStatusCheck(\n printJob.getEntry().getReferenceId());\n final boolean abandoned =\n duration > TimeUnit.SECONDS.toMillis(ThreadPoolJobManager.this.abandonedTimeout);\n if (abandoned) {\n LOGGER.info(\"Job {} is abandoned (no status check within the last {} seconds)\",\n printJob.getEntry().getReferenceId(), ThreadPoolJobManager.this.abandonedTimeout);\n }\n return abandoned;\n }", "public static void setEnabled(Element element, boolean enabled) {\n element.setPropertyBoolean(\"disabled\", !enabled);\n\tsetStyleName(element, \"disabled\", !enabled);\n }", "public static sslpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tsslpolicy_lbvserver_binding obj = new sslpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tsslpolicy_lbvserver_binding response[] = (sslpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static BoxRetentionPolicy.Info createFinitePolicy(BoxAPIConnection api, String name, int length,\r\n String action, RetentionPolicyParams optionalParams) {\r\n return createRetentionPolicy(api, name, TYPE_FINITE, length, action, optionalParams);\r\n }", "private void setMaxMin(IntervalRBTreeNode<T> n) {\n n.min = n.left;\n n.max = n.right;\n if (n.leftChild != null) {\n n.min = Math.min(n.min, n.leftChild.min);\n n.max = Math.max(n.max, n.leftChild.max);\n }\n if (n.rightChild != null) {\n n.min = Math.min(n.min, n.rightChild.min);\n n.max = Math.max(n.max, n.rightChild.max);\n }\n }" ]
Parses values out of the header text. @param header header text
[ "private void parse(String header)\n {\n ArrayList<String> list = new ArrayList<String>(4);\n StringBuilder sb = new StringBuilder();\n int index = 1;\n while (index < header.length())\n {\n char c = header.charAt(index++);\n if (Character.isDigit(c))\n {\n sb.append(c);\n }\n else\n {\n if (sb.length() != 0)\n {\n list.add(sb.toString());\n sb.setLength(0);\n }\n }\n }\n\n if (sb.length() != 0)\n {\n list.add(sb.toString());\n }\n\n m_id = list.get(0);\n m_sequence = Integer.parseInt(list.get(1));\n m_type = Integer.valueOf(list.get(2));\n if (list.size() > 3)\n {\n m_subtype = Integer.parseInt(list.get(3));\n }\n }" ]
[ "public static csparameter get(nitro_service service) throws Exception{\n\t\tcsparameter obj = new csparameter();\n\t\tcsparameter[] response = (csparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static <T> T[] concat(T firstElement, T... array) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( firstElement.getClass(), 1 + array.length );\n\t\tresult[0] = firstElement;\n\t\tSystem.arraycopy( array, 0, result, 1, array.length );\n\n\t\treturn result;\n\t}", "public static lbvserver_filterpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_filterpolicy_binding obj = new lbvserver_filterpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_filterpolicy_binding response[] = (lbvserver_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void removeNodeMetaData(Object key) {\n if (key==null) throw new GroovyBugError(\"Tried to remove meta data with null key \"+this+\".\");\n if (metaDataMap == null) {\n return;\n }\n metaDataMap.remove(key);\n }", "public FluoKeyValueGenerator set(RowColumnValue rcv) {\n setRow(rcv.getRow());\n setColumn(rcv.getColumn());\n setValue(rcv.getValue());\n return this;\n }", "public static synchronized List<Class< ? >> locateAll(final String serviceName) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n List<Class< ? >> classes = new ArrayList<Class< ? >>();\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null ) {\n for ( Callable<Class< ? >> c : l ) {\n try {\n classes.add( c.call() );\n } catch ( Exception e ) {\n }\n }\n }\n }\n return classes;\n }", "private Map<Integer, List<Row>> createWorkPatternAssignmentMap(List<Row> rows) throws ParseException\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"ID\");\n String workPatterns = row.getString(\"WORK_PATTERNS\");\n map.put(calendarID, createWorkPatternAssignmentRowList(workPatterns));\n }\n return map;\n }", "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 Map<String, Object> introspect(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {\n\t\tMap<String, Object> result = new HashMap<>();\n\t\tBeanInfo info = Introspector.getBeanInfo( obj.getClass() );\n\t\tfor ( PropertyDescriptor pd : info.getPropertyDescriptors() ) {\n\t\t\tMethod reader = pd.getReadMethod();\n\t\t\tString name = pd.getName();\n\t\t\tif ( reader != null && !\"class\".equals( name ) ) {\n\t\t\t\tresult.put( name, reader.invoke( obj ) );\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}" ]
Converts the http entity to string. If entity is null, returns empty string. @param entity @return @throws IOException
[ "public static String entityToString(HttpEntity entity) throws IOException {\n if (entity != null) {\n InputStream is = entity.getContent();\n return IOUtils.toString(is, \"UTF-8\");\n }\n return \"\";\n }" ]
[ "public RendererBuilder<T> withPrototype(Renderer<? extends T> renderer) {\n if (renderer == null) {\n throw new NeedsPrototypesException(\n \"RendererBuilder can't use a null Renderer<T> instance as prototype\");\n }\n this.prototypes.add(renderer);\n return this;\n }", "public static String formatAsStackTraceElement(InjectionPoint ij) {\n Member member;\n if (ij.getAnnotated() instanceof AnnotatedField) {\n AnnotatedField<?> annotatedField = (AnnotatedField<?>) ij.getAnnotated();\n member = annotatedField.getJavaMember();\n } else if (ij.getAnnotated() instanceof AnnotatedParameter<?>) {\n AnnotatedParameter<?> annotatedParameter = (AnnotatedParameter<?>) ij.getAnnotated();\n member = annotatedParameter.getDeclaringCallable().getJavaMember();\n } else {\n // Not throwing an exception, because this method is invoked when an exception is already being thrown.\n // Throwing an exception here would hide the original exception.\n return \"-\";\n }\n return formatAsStackTraceElement(member);\n }", "public static MediaType binary( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, true );\n }", "@Override\n synchronized public V put(K key, V value) {\n V oldValue = this.get(key);\n try {\n super.put(key, value);\n writeBack(key, value);\n return oldValue;\n } catch(Exception e) {\n super.put(key, oldValue);\n writeBack(key, oldValue);\n throw new VoldemortException(\"Failed to put(\" + key + \", \" + value\n + \") in write through cache\", e);\n }\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 }", "public static void invert( final int blockLength ,\n final boolean upper ,\n final DSubmatrixD1 T ,\n final DSubmatrixD1 T_inv ,\n final double temp[] )\n {\n if( upper )\n throw new IllegalArgumentException(\"Upper triangular matrices not supported yet\");\n\n if( temp.length < blockLength*blockLength )\n throw new IllegalArgumentException(\"Temp must be at least blockLength*blockLength long.\");\n\n if( T.row0 != T_inv.row0 || T.row1 != T_inv.row1 || T.col0 != T_inv.col0 || T.col1 != T_inv.col1)\n throw new IllegalArgumentException(\"T and T_inv must be at the same elements in the matrix\");\n\n final int M = T.row1-T.row0;\n\n final double dataT[] = T.original.data;\n final double dataX[] = T_inv.original.data;\n\n final int offsetT = T.row0*T.original.numCols+M*T.col0;\n\n for( int i = 0; i < M; i += blockLength ) {\n int heightT = Math.min(T.row1-(i+T.row0),blockLength);\n\n int indexII = offsetT + T.original.numCols*(i+T.row0) + heightT*(i+T.col0);\n\n for( int j = 0; j < i; j += blockLength ) {\n int widthX = Math.min(T.col1-(j+T.col0),blockLength);\n\n for( int w = 0; w < temp.length; w++ ) {\n temp[w] = 0;\n }\n\n for( int k = j; k < i; k += blockLength ) {\n int widthT = Math.min(T.col1-(k+T.col0),blockLength);\n\n int indexL = offsetT + T.original.numCols*(i+T.row0) + heightT*(k+T.col0);\n int indexX = offsetT + T.original.numCols*(k+T.row0) + widthT*(j+T.col0);\n\n blockMultMinus(dataT,dataX,temp,indexL,indexX,0,heightT,widthT,widthX);\n }\n\n int indexX = offsetT + T.original.numCols*(i+T.row0) + heightT*(j+T.col0);\n\n InnerTriangularSolver_DDRB.solveL(dataT,temp,heightT,widthX,heightT,indexII,0);\n System.arraycopy(temp,0,dataX,indexX,widthX*heightT);\n }\n InnerTriangularSolver_DDRB.invertLower(dataT,dataX,heightT,indexII,indexII);\n }\n }", "public static String packageNameOf(Class<?> clazz) {\n String name = clazz.getName();\n int pos = name.lastIndexOf('.');\n E.unexpectedIf(pos < 0, \"Class does not have package: \" + name);\n return name.substring(0, pos);\n }", "public void install(@Observes(precedence = 90) CubeDockerConfiguration configuration,\n ArquillianDescriptor arquillianDescriptor) {\n\n DockerCompositions cubes = configuration.getDockerContainersContent();\n\n final SeleniumContainers seleniumContainers =\n SeleniumContainers.create(getBrowser(arquillianDescriptor), cubeDroneConfigurationInstance.get());\n cubes.add(seleniumContainers.getSeleniumContainerName(), seleniumContainers.getSeleniumContainer());\n\n final boolean recording = cubeDroneConfigurationInstance.get().isRecording();\n if (recording) {\n cubes.add(seleniumContainers.getVncContainerName(), seleniumContainers.getVncContainer());\n cubes.add(seleniumContainers.getVideoConverterContainerName(),\n seleniumContainers.getVideoConverterContainer());\n }\n\n seleniumContainersInstanceProducer.set(seleniumContainers);\n\n System.out.println(\"SELENIUM INSTALLED\");\n System.out.println(ConfigUtil.dump(cubes));\n }", "private void deliverWaveformPreviewUpdate(final int player, final WaveformPreview preview) {\n final Set<WaveformListener> listeners = getWaveformListeners();\n if (!listeners.isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformPreviewUpdate update = new WaveformPreviewUpdate(player, preview);\n for (final WaveformListener listener : listeners) {\n try {\n listener.previewChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform preview update to listener\", t);\n }\n }\n }\n });\n }\n }" ]
Gets the time warp. @return the time warp
[ "@PrefMetadata(type = CmsTimeWarpPreference.class)\n public String getTimeWarp() {\n\n long warp = m_settings.getTimeWarp();\n return warp < 0 ? \"\" : \"\" + warp; // if timewarp < 0 (i.e. time warp is not set), use the empty string because we don't want the date selector widget to interpret the negative value\n }" ]
[ "public static final String getString(byte[] data, int offset)\n {\n return getString(data, offset, data.length - offset);\n }", "private void WebPageCloseOnClick(GVRViewSceneObject gvrWebViewSceneObject, GVRSceneObject gvrSceneObjectAnchor, String url) {\n final String urlFinal = url;\n\n webPagePlusUISceneObject = new GVRSceneObject(gvrContext);\n webPagePlusUISceneObject.getTransform().setPosition(webPagePlusUIPosition[0], webPagePlusUIPosition[1], webPagePlusUIPosition[2]);\n\n GVRScene mainScene = gvrContext.getMainScene();\n\n Sensor webPageSensor = new Sensor(urlFinal, Sensor.Type.TOUCH, gvrWebViewSceneObject, true);\n final GVRSceneObject gvrSceneObjectAnchorFinal = gvrSceneObjectAnchor;\n final GVRSceneObject gvrWebViewSceneObjectFinal = gvrWebViewSceneObject;\n final GVRSceneObject webPagePlusUISceneObjectFinal = webPagePlusUISceneObject;\n\n webPagePlusUISceneObjectFinal.addChildObject(gvrWebViewSceneObjectFinal);\n gvrSceneObjectAnchorFinal.addChildObject(webPagePlusUISceneObjectFinal);\n\n\n webPageSensor.addISensorEvents(new ISensorEvents() {\n boolean uiObjectIsActive = false;\n boolean clickDown = true;\n\n @Override\n public void onSensorEvent(SensorEvent event) {\n if (event.isActive()) {\n clickDown = !clickDown;\n if (clickDown) {\n // Delete the WebView page\n gvrSceneObjectAnchorFinal.removeChildObject(webPagePlusUISceneObjectFinal);\n webPageActive = false;\n webPagePlusUISceneObject = null;\n webPageClosed = true; // Make sure click up doesn't open web page behind it\n }\n }\n }\n });\n }", "boolean isUserPasswordReset(CmsUser user) {\n\n if (USER_PASSWORD_STATUS.containsKey(user.getId())) { //Check if user was checked before\n if (!USER_PASSWORD_STATUS.get(user.getId()).booleanValue()) { // was false before, false->true is never done without changing map\n return false;\n }\n if (m_checkedUserPasswordReset.contains(user.getId())) { //was true before, true->false happens when user resets password. Only check one time per table load.\n return true; //Set gets flushed on reloading table\n }\n }\n CmsUser currentUser = user;\n if (user.getAdditionalInfo().size() < 3) {\n\n try {\n currentUser = m_cms.readUser(user.getId());\n } catch (CmsException e) {\n LOG.error(\"Can not read user\", e);\n }\n }\n if (currentUser.getAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET) != null) {\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(true));\n m_checkedUserPasswordReset.add(currentUser.getId());\n return true;\n }\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(false));\n return false;\n }", "private void readVersion(InputStream is) throws IOException\n {\n BytesReadInputStream bytesReadStream = new BytesReadInputStream(is);\n String version = DatatypeConverter.getString(bytesReadStream);\n m_offset += bytesReadStream.getBytesRead();\n SynchroLogger.log(\"VERSION\", version);\n \n String[] versionArray = version.split(\"\\\\.\");\n m_majorVersion = Integer.parseInt(versionArray[0]);\n }", "public static String createFolderPath(String path) {\n\n String[] pathParts = path.split(\"\\\\.\");\n String path2 = \"\";\n for (String part : pathParts) {\n if (path2.equals(\"\")) {\n path2 = part;\n } else {\n path2 = path2 + File.separator\n + changeFirstLetterToLowerCase(createClassName(part));\n }\n }\n\n return path2;\n }", "public void racRent() {\n\t\tpos = pos - 1;\n\t\tString userName = CarSearch.getLastSearchParams()[0];\n\t\tString pickupDate = CarSearch.getLastSearchParams()[1];\n\t\tString returnDate = CarSearch.getLastSearchParams()[2];\n\t\tthis.searcher.search(userName, pickupDate, returnDate);\n\t\tif (searcher!=null && searcher.getCars()!= null && pos < searcher.getCars().size() && searcher.getCars().get(pos) != null) {\n\t\t\tRESStatusType resStatus = reserver.reserveCar(searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\t\t\tConfirmationType confirm = reserver.getConfirmation(resStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\n\t\t\tRESCarType car = confirm.getCar();\n\t\t\tCustomerDetailsType customer = confirm.getCustomer();\n\t\t\t\n\t\t\tSystem.out.println(MessageFormat.format(CONFIRMATION\n\t\t\t\t\t, confirm.getDescription()\n\t\t\t\t\t, confirm.getReservationId()\n\t\t\t\t\t, customer.getName()\n\t\t\t\t\t, customer.getEmail()\n\t\t\t\t\t, customer.getCity()\n\t\t\t\t\t, customer.getStatus()\n\t\t\t\t\t, car.getBrand()\n\t\t\t\t\t, car.getDesignModel()\n\t\t\t\t\t, confirm.getFromDate()\n\t\t\t\t\t, confirm.getToDate()\n\t\t\t\t\t, padl(car.getRateDay(), 10)\n\t\t\t\t\t, padl(car.getRateWeekend(), 10)\n\t\t\t\t\t, padl(confirm.getCreditPoints().toString(), 7)));\n\t\t} else {\n\t\t\tSystem.out.println(\"Invalid selection: \" + (pos+1)); //$NON-NLS-1$\n\t\t}\n\t}", "public void merge() {\n Thread currentThread = Thread.currentThread();\n if(!stats.get(currentThread).equals(this) || currentThread instanceof WindupChildThread) {\n throw new IllegalArgumentException(\"Trying to merge executionstatistics from a \"\n + \"different thread that is not registered as main thread of application run\");\n }\n\n for (Thread thread : stats.keySet())\n {\n if(thread instanceof WindupChildThread && ((WindupChildThread) thread).getParentThread().equals(currentThread)) {\n merge(stats.get(thread));\n }\n }\n }", "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 String readOptionalString(JSONObject json, String key, String defaultValue) {\n\n try {\n String str = json.getString(key);\n if (str != null) {\n return str;\n }\n\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON string failed. Default to provided default value.\", e);\n }\n return defaultValue;\n }" ]
Creates a new Box Developer Edition connection with enterprise token leveraging an access token cache. @param enterpriseId the enterprise ID to use for requesting access token. @param clientId the client ID to use when exchanging the JWT assertion for an access token. @param clientSecret the client secret to use when exchanging the JWT assertion for an access token. @param encryptionPref the encryption preferences for signing the JWT. @param accessTokenCache the cache for storing access token information (to minimize fetching new tokens) @return a new instance of BoxAPIConnection.
[ "public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(String enterpriseId, String clientId,\n String clientSecret, JWTEncryptionPreferences encryptionPref, IAccessTokenCache accessTokenCache) {\n\n BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection(enterpriseId,\n DeveloperEditionEntityType.ENTERPRISE, clientId, clientSecret, encryptionPref, accessTokenCache);\n\n connection.tryRestoreUsingAccessTokenCache();\n\n return connection;\n }" ]
[ "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}", "public static linkset[] get(nitro_service service) throws Exception{\n\t\tlinkset obj = new linkset();\n\t\tlinkset[] response = (linkset[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) {\n int cursor = destOffset;\n for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) {\n int bbSize = bb.remaining();\n if ((cursor + bbSize) > destArray.length)\n throw new ArrayIndexOutOfBoundsException(String.format(\"cursor + bbSize = %,d\", cursor + bbSize));\n bb.get(destArray, cursor, bbSize);\n cursor += bbSize;\n }\n }", "void portForward(final Patch patch, IdentityPatchContext context) throws PatchingException, IOException, XMLStreamException {\n assert patch.getIdentity().getPatchType() == Patch.PatchType.CUMULATIVE;\n\n final PatchingHistory history = context.getHistory();\n for (final PatchElement element : patch.getElements()) {\n\n final PatchElementProvider provider = element.getProvider();\n final String name = provider.getName();\n final boolean addOn = provider.isAddOn();\n\n final IdentityPatchContext.PatchEntry target = context.resolveForElement(element);\n final String cumulativePatchID = target.getCumulativePatchID();\n if (Constants.BASE.equals(cumulativePatchID)) {\n reenableRolledBackInBase(target);\n continue;\n }\n\n boolean found = false;\n final PatchingHistory.Iterator iterator = history.iterator();\n while (iterator.hasNextCP()) {\n final PatchingHistory.Entry entry = iterator.nextCP();\n final String patchId = addOn ? entry.getAddOnPatches().get(name) : entry.getLayerPatches().get(name);\n\n if (patchId != null && patchId.equals(cumulativePatchID)) {\n final Patch original = loadPatchInformation(entry.getPatchId(), installedImage);\n for (final PatchElement originalElement : original.getElements()) {\n if (name.equals(originalElement.getProvider().getName())\n && addOn == originalElement.getProvider().isAddOn()) {\n PatchingTasks.addMissingModifications(target, originalElement.getModifications(), ContentItemFilter.ALL_BUT_MISC);\n }\n }\n // Record a loader to have access to the current modules\n final DirectoryStructure structure = target.getDirectoryStructure();\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(null, bundlesRoot, modulesRoot);\n context.recordContentLoader(patchId, loader);\n found = true;\n break;\n }\n }\n if (!found) {\n throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(cumulativePatchID);\n }\n\n reenableRolledBackInBase(target);\n }\n }", "private void saveLocalization() {\n\n SortedProperties localization = new SortedProperties();\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n String value = item.getItemProperty(TableProperty.TRANSLATION).getValue().toString();\n if (!(key.isEmpty() || value.isEmpty())) {\n localization.put(key, value);\n }\n }\n m_keyset.updateKeySet(m_localizations.get(m_locale).keySet(), localization.keySet());\n m_localizations.put(m_locale, localization);\n\n }", "public static base_response delete(nitro_service client, String viewname) throws Exception {\n\t\tdnsview deleteresource = new dnsview();\n\t\tdeleteresource.viewname = viewname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "private void readResourceAssignments()\n {\n for (MapRow row : getTable(\"USGTAB\"))\n {\n Task task = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID\"));\n Resource resource = m_projectFile.getResourceByUniqueID(row.getInteger(\"RESOURCE_ID\"));\n if (task != null && resource != null)\n {\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n m_eventManager.fireAssignmentReadEvent(assignment);\n }\n }\n }", "public SqlStatement getPreparedUpdateStatement(ClassDescriptor cld)\r\n {\r\n SqlForClass sfc = getSqlForClass(cld);\r\n SqlStatement result = sfc.getUpdateSql();\r\n if(result == null)\r\n {\r\n ProcedureDescriptor pd = cld.getUpdateProcedure();\r\n\r\n if(pd == null)\r\n {\r\n result = new SqlUpdateStatement(cld, logger);\r\n }\r\n else\r\n {\r\n result = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setUpdateSql(result);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + result.getStatement());\r\n }\r\n }\r\n return result;\r\n }", "public void setEnterpriseText(int index, String value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_TEXT, index), value);\n }" ]
Reads color table as 256 RGB integer values. @param ncolors int number of colors to read. @return int array containing 256 colors (packed ARGB with full alpha).
[ "private int[] readColorTable(int ncolors) {\n int nbytes = 3 * ncolors;\n int[] tab = null;\n byte[] c = new byte[nbytes];\n\n try {\n rawData.get(c);\n\n // Max size to avoid bounds checks.\n tab = new int[MAX_BLOCK_SIZE];\n int i = 0;\n int j = 0;\n while (i < ncolors) {\n int r = ((int) c[j++]) & 0xff;\n int g = ((int) c[j++]) & 0xff;\n int b = ((int) c[j++]) & 0xff;\n tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;\n }\n } catch (BufferUnderflowException e) {\n //if (Log.isLoggable(TAG, Log.DEBUG)) {\n Logger.d(TAG, \"Format Error Reading Color Table\", e);\n //}\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n\n return tab;\n }" ]
[ "@Override\n\tpublic T next() {\n\t\tSQLException sqlException = null;\n\t\ttry {\n\t\t\tT result = nextThrow();\n\t\t\tif (result != null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\tsqlException = e;\n\t\t}\n\t\t// we have to throw if there is no next or on a SQLException\n\t\tlast = null;\n\t\tcloseQuietly();\n\t\tthrow new IllegalStateException(\"Could not get next result for \" + dataClass, sqlException);\n\t}", "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}", "private static Set<ProjectModel> getAllApplications(GraphContext graphContext)\n {\n Set<ProjectModel> apps = new HashSet<>();\n Iterable<ProjectModel> appProjects = graphContext.findAll(ProjectModel.class);\n for (ProjectModel appProject : appProjects)\n apps.add(appProject);\n return apps;\n }", "public static appfwpolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_policybinding_binding obj = new appfwpolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_policybinding_binding response[] = (appfwpolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Nullable\n @SuppressWarnings(\"unchecked\")\n protected <T extends JavaElement> ActiveElements<T> popIfActive() {\n return (ActiveElements<T>) (!activations.isEmpty() && activations.peek().depth == depth ? activations.pop() :\n null);\n }", "private Envelope getMaxScreenEnvelope(InternalTile tile, Coordinate panOrigin) {\n\t\tint nrOfTilesX = Math.max(1, MAXIMUM_TILE_COORDINATE / tile.getScreenWidth());\n\t\tint nrOfTilesY = Math.max(1, MAXIMUM_TILE_COORDINATE / tile.getScreenHeight());\n\n\t\tdouble x1 = panOrigin.x - nrOfTilesX * tile.getTileWidth();\n\t\t// double x2 = x1 + (nrOfTilesX * tileWidth * 2);\n\t\tdouble x2 = panOrigin.x + nrOfTilesX * tile.getTileWidth();\n\t\tdouble y1 = panOrigin.y - nrOfTilesY * tile.getTileHeight();\n\t\t// double y2 = y1 + (nrOfTilesY * tileHeight * 2);\n\t\tdouble y2 = panOrigin.y + nrOfTilesY * tile.getTileHeight();\n\t\treturn new Envelope(x1, x2, y1, y2);\n\t}", "public void deleteModule(final String moduleId) {\n final DbModule module = getModule(moduleId);\n repositoryHandler.deleteModule(module.getId());\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n repositoryHandler.deleteArtifact(gavc);\n }\n }", "@Override\n public Iterator<BoxItem.Info> iterator() {\n URL url = GET_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxFolder.this.getID());\n return new BoxItemIterator(BoxFolder.this.getAPI(), url);\n }", "@Override\n public InternationalFixedDate date(int prolepticYear, int month, int dayOfMonth) {\n return InternationalFixedDate.of(prolepticYear, month, dayOfMonth);\n }" ]
This method returns the installed identity with the requested name and version. If the product name is null, the default identity will be returned. If the product name was recognized and the requested version was not null, the version comparison will take place. If the version of the currently installed product doesn't match the requested one, the exception will be thrown. If the requested version is null, the currently installed identity with the requested name will be returned. If the product name was not recognized among the registered ones, a new installed identity with the requested name will be created and returned. (This is because the patching system is not aware of how many and what the patching streams there are expected). @param productName @param productVersion @return @throws PatchingException
[ "@Override\n public InstalledIdentity getInstalledIdentity(String productName, String productVersion) throws PatchingException {\n final String defaultIdentityName = defaultIdentity.getIdentity().getName();\n if(productName == null) {\n productName = defaultIdentityName;\n }\n\n final File productConf = new File(installedImage.getInstallationMetadata(), productName + Constants.DOT_CONF);\n final String recordedProductVersion;\n if(!productConf.exists()) {\n recordedProductVersion = null;\n } else {\n final Properties props = loadProductConf(productConf);\n recordedProductVersion = props.getProperty(Constants.CURRENT_VERSION);\n }\n\n if(defaultIdentityName.equals(productName)) {\n if(recordedProductVersion != null && !recordedProductVersion.equals(defaultIdentity.getIdentity().getVersion())) {\n // this means the patching history indicates that the current version is different from the one specified in the server's version module,\n // which could happen in case:\n // - the last applied CP didn't include the new version module or\n // - the version module version included in the last CP didn't match the version specified in the CP's metadata, or\n // - the version module was updated from a one-off, or\n // - the patching history was edited somehow\n // In any case, here I decided to rely on the patching history.\n defaultIdentity = loadIdentity(productName, recordedProductVersion);\n }\n if(productVersion != null && !defaultIdentity.getIdentity().getVersion().equals(productVersion)) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.productVersionDidNotMatchInstalled(\n productName, productVersion, defaultIdentity.getIdentity().getVersion()));\n }\n return defaultIdentity;\n }\n\n if(recordedProductVersion != null && !Constants.UNKNOWN.equals(recordedProductVersion)) {\n if(productVersion != null) {\n if (!productVersion.equals(recordedProductVersion)) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.productVersionDidNotMatchInstalled(productName, productVersion, recordedProductVersion));\n }\n } else {\n productVersion = recordedProductVersion;\n }\n }\n\n return loadIdentity(productName, productVersion);\n }" ]
[ "public void printMinors(int matrix[], int N, PrintStream stream) {\n this.N = N;\n this.stream = stream;\n\n // compute all the minors\n int index = 0;\n for( int i = 1; i <= N; i++ ) {\n for( int j = 1; j <= N; j++ , index++) {\n stream.print(\" double m\"+i+\"\"+j+\" = \");\n if( (i+j) % 2 == 1 )\n stream.print(\"-( \");\n printTopMinor(matrix,i-1,j-1,N);\n if( (i+j) % 2 == 1 )\n stream.print(\")\");\n stream.print(\";\\n\");\n }\n }\n\n stream.println();\n // compute the determinant\n stream.print(\" double det = (a11*m11\");\n for( int i = 2; i <= N; i++ ) {\n stream.print(\" + \"+a(i-1)+\"*m\"+1+\"\"+i);\n }\n stream.println(\")/scale;\");\n\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void setOffline(boolean value){\n offline = value;\n if (offline) {\n getConfigLogger().debug(getAccountId(), \"CleverTap Instance has been set to offline, won't send events queue\");\n } else {\n getConfigLogger().debug(getAccountId(), \"CleverTap Instance has been set to online, sending events queue\");\n flush();\n }\n }", "public static List<DomainControllerData> domainControllerDataFromByteBuffer(byte[] buffer) throws Exception {\n List<DomainControllerData> retval = new ArrayList<DomainControllerData>();\n if (buffer == null) {\n return retval;\n }\n ByteArrayInputStream in_stream = new ByteArrayInputStream(buffer);\n DataInputStream in = new DataInputStream(in_stream);\n String content = SEPARATOR;\n while (SEPARATOR.equals(content)) {\n DomainControllerData data = new DomainControllerData();\n data.readFrom(in);\n retval.add(data);\n try {\n content = readString(in);\n } catch (EOFException ex) {\n content = null;\n }\n }\n in.close();\n return retval;\n }", "public final void save(final PrintJobStatusExtImpl entry) {\n getSession().merge(entry);\n getSession().flush();\n getSession().evict(entry);\n }", "private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {\n List<T> indexesOfType = new ArrayList<T>();\n Gson g = new Gson();\n for (JsonElement index : indexes) {\n if (index.isJsonObject()) {\n JsonObject indexDefinition = index.getAsJsonObject();\n JsonElement indexType = indexDefinition.get(\"type\");\n if (indexType != null && indexType.isJsonPrimitive()) {\n JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();\n if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive\n .getAsString().equals(type))) {\n indexesOfType.add(g.fromJson(indexDefinition, modelType));\n }\n }\n }\n }\n return indexesOfType;\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 }", "private Entry getEntry(Object key)\r\n {\r\n if (key == null) return null;\r\n int hash = hashCode(key);\r\n int index = indexFor(hash);\r\n for (Entry entry = table[index]; entry != null; entry = entry.next)\r\n {\r\n if ((entry.hash == hash) && equals(key, entry.getKey()))\r\n {\r\n return entry;\r\n }\r\n }\r\n return null;\r\n }", "public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster,\n zoneId);\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"[\");\n boolean first = true;\n Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet());\n for(int initPartitionId: sortedInitPartitionIds) {\n if(!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n\n int runLength = idToRunLength.get(initPartitionId);\n if(runLength == 1) {\n sb.append(initPartitionId);\n } else {\n int endPartitionId = (initPartitionId + runLength - 1)\n % cluster.getNumberOfPartitions();\n sb.append(initPartitionId).append(\"-\").append(endPartitionId);\n }\n }\n sb.append(\"]\");\n\n return sb.toString();\n }", "public static Resource getSetupPage(I_SetupUiContext context, String name) {\n\n String path = CmsStringUtil.joinPaths(context.getSetupBean().getContextPath(), CmsSetupBean.FOLDER_SETUP, name);\n Resource resource = new ExternalResource(path);\n return resource;\n }" ]
Given a directory, determine if it contains a multi-file database whose format we can process. @param directory directory to process @return ProjectFile instance if we can process anything, or null
[ "private ProjectFile handleDatabaseInDirectory(File directory) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n if (file.isDirectory())\n {\n continue;\n }\n\n FileInputStream fis = new FileInputStream(file);\n int bytesRead = fis.read(buffer);\n fis.close();\n\n //\n // If the file is smaller than the buffer we are peeking into,\n // it's probably not a valid schedule file.\n //\n if (bytesRead != BUFFER_SIZE)\n {\n continue;\n }\n\n if (matchesFingerprint(buffer, BTRIEVE_FINGERPRINT))\n {\n return handleP3BtrieveDatabase(directory);\n }\n\n if (matchesFingerprint(buffer, STW_FINGERPRINT))\n {\n return handleSureTrakDatabase(directory);\n }\n }\n }\n return null;\n }" ]
[ "public AppMsg setLayoutGravity(int gravity) {\n mLayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, gravity);\n return this;\n }", "public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context, final Procedure1<? super ContentAssistEntry> init) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, init);\n }", "public List<Collaborator> listCollaborators(String appName) {\n return connection.execute(new CollabList(appName), apiKey);\n }", "public Object copy(final Object obj, final PersistenceBroker broker)\r\n {\r\n return clone(obj, IdentityMapFactory.getIdentityMap(), broker);\r\n }", "public static base_response delete(nitro_service client, String selectorname) throws Exception {\n\t\tcacheselector deleteresource = new cacheselector();\n\t\tdeleteresource.selectorname = selectorname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "static void endInitialization(WeldContainer container, boolean isShutdownHookEnabled) {\n container.complete();\n // If needed, register one shutdown hook for all containers\n if (shutdownHook == null && isShutdownHookEnabled) {\n synchronized (LOCK) {\n if (shutdownHook == null) {\n shutdownHook = new ShutdownHook();\n SecurityActions.addShutdownHook(shutdownHook);\n }\n }\n }\n container.fireContainerInitializedEvent();\n }", "private void readCalendars(Project project, HashMap<BigInteger, ProjectCalendar> map)\n {\n Project.Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n LinkedList<Pair<ProjectCalendar, BigInteger>> baseCalendars = new LinkedList<Pair<ProjectCalendar, BigInteger>>();\n for (Project.Calendars.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, map, baseCalendars);\n }\n updateBaseCalendarNames(baseCalendars, map);\n }\n\n try\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n BigInteger calendarID = new BigInteger(properties.getDefaultCalendarName());\n ProjectCalendar calendar = map.get(calendarID);\n m_projectFile.setDefaultCalendar(calendar);\n }\n\n catch (Exception ex)\n {\n // Ignore exceptions\n }\n }", "public SourceBuilder add(String fmt, Object... args) {\n TemplateApplier.withParams(args).onText(source::append).onParam(this::add).parse(fmt);\n return this;\n }", "private static ClassLoader getParentCl()\n {\n try\n {\n Method m = ClassLoader.class.getMethod(\"getPlatformClassLoader\");\n return (ClassLoader) m.invoke(null);\n }\n catch (NoSuchMethodException e)\n {\n // Java < 9, just use the bootstrap CL.\n return null;\n }\n catch (Exception e)\n {\n throw new JqmInitError(\"Could not fetch Platform Class Loader\", e);\n }\n }" ]
Refresh's this connection's access token using its refresh token. @throws IllegalStateException if this connection's access token cannot be refreshed.
[ "public void refresh() {\n this.refreshLock.writeLock().lock();\n\n if (!this.canRefresh()) {\n this.refreshLock.writeLock().unlock();\n throw new IllegalStateException(\"The BoxAPIConnection cannot be refreshed because it doesn't have a \"\n + \"refresh token.\");\n }\n\n URL url = null;\n try {\n url = new URL(this.tokenURL);\n } catch (MalformedURLException e) {\n this.refreshLock.writeLock().unlock();\n assert false : \"An invalid refresh URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid refresh URL indicates a bug in the SDK.\", e);\n }\n\n String urlParameters = String.format(\"grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s\",\n this.refreshToken, this.clientID, this.clientSecret);\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n this.refreshLock.writeLock().unlock();\n throw e;\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n this.accessToken = jsonObject.get(\"access_token\").asString();\n this.refreshToken = jsonObject.get(\"refresh_token\").asString();\n this.lastRefresh = System.currentTimeMillis();\n this.expires = jsonObject.get(\"expires_in\").asLong() * 1000;\n\n this.notifyRefresh();\n\n this.refreshLock.writeLock().unlock();\n }" ]
[ "public Operation.Info create( Symbol op , Variable left , Variable right ) {\n switch( op ) {\n case PLUS:\n return Operation.add(left, right, managerTemp);\n\n case MINUS:\n return Operation.subtract(left, right, managerTemp);\n\n case TIMES:\n return Operation.multiply(left, right, managerTemp);\n\n case RDIVIDE:\n return Operation.divide(left, right, managerTemp);\n\n case LDIVIDE:\n return Operation.divide(right, left, managerTemp);\n\n case POWER:\n return Operation.pow(left, right, managerTemp);\n\n case ELEMENT_DIVIDE:\n return Operation.elementDivision(left, right, managerTemp);\n\n case ELEMENT_TIMES:\n return Operation.elementMult(left, right, managerTemp);\n\n case ELEMENT_POWER:\n return Operation.elementPow(left, right, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }", "public static void writeFlowId(Message message, String flowId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage)message;\n Header hdFlowId = soapMessage.getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n LOG.warning(\"FlowId already existing in soap header, need not to write FlowId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(FLOW_ID_QNAME, flowId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored flowId '\" + flowId + \"' in soap header: \" + FLOW_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create flowId header.\", e);\n }\n\n }", "public static Key toKey(RowColumn rc) {\n if ((rc == null) || (rc.getRow().equals(Bytes.EMPTY))) {\n return null;\n }\n Text row = ByteUtil.toText(rc.getRow());\n if ((rc.getColumn().equals(Column.EMPTY)) || !rc.getColumn().isFamilySet()) {\n return new Key(row);\n }\n Text cf = ByteUtil.toText(rc.getColumn().getFamily());\n if (!rc.getColumn().isQualifierSet()) {\n return new Key(row, cf);\n }\n Text cq = ByteUtil.toText(rc.getColumn().getQualifier());\n if (!rc.getColumn().isVisibilitySet()) {\n return new Key(row, cf, cq);\n }\n Text cv = ByteUtil.toText(rc.getColumn().getVisibility());\n return new Key(row, cf, cq, cv);\n }", "public void merge(final ResourceRoot additionalResourceRoot) {\n if(!additionalResourceRoot.getRoot().equals(root)) {\n throw ServerLogger.ROOT_LOGGER.cannotMergeResourceRoot(root, additionalResourceRoot.getRoot());\n }\n usePhysicalCodeSource = additionalResourceRoot.usePhysicalCodeSource;\n if(additionalResourceRoot.getExportFilters().isEmpty()) {\n //new root has no filters, so we don't want our existing filters to break anything\n //see WFLY-1527\n this.exportFilters.clear();\n } else {\n this.exportFilters.addAll(additionalResourceRoot.getExportFilters());\n }\n }", "public ConfigOptionBuilder setCommandLineOptionWithArgument( CommandLineOption commandLineOption, StringConverter converter ) {\n co.setCommandLineOption( commandLineOption );\n return setStringConverter( converter );\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 }", "public List<ResourceRequestType.ResourceRequestCriterion> getResourceRequestCriterion()\n {\n if (resourceRequestCriterion == null)\n {\n resourceRequestCriterion = new ArrayList<ResourceRequestType.ResourceRequestCriterion>();\n }\n return this.resourceRequestCriterion;\n }", "public String genId() {\n S.Buffer sb = S.newBuffer();\n sb.a(longEncoder.longToStr(nodeIdProvider.nodeId()))\n .a(longEncoder.longToStr(startIdProvider.startId()))\n .a(longEncoder.longToStr(sequenceProvider.seqId()));\n return sb.toString();\n }", "@Override\r\n public synchronized long skip(final long length) throws IOException {\r\n final long skip = super.skip(length);\r\n this.count += skip;\r\n return skip;\r\n }" ]
Store the data of a print job in the registry. @param printJobStatus the print job status
[ "private void store(final PrintJobStatus printJobStatus) throws JSONException {\n JSONObject metadata = new JSONObject();\n metadata.put(JSON_REQUEST_DATA, printJobStatus.getEntry().getRequestData().getInternalObj());\n metadata.put(JSON_STATUS, printJobStatus.getStatus().toString());\n metadata.put(JSON_START_DATE, printJobStatus.getStartTime());\n metadata.put(JSON_REQUEST_COUNT, printJobStatus.getRequestCount());\n if (printJobStatus.getCompletionDate() != null) {\n metadata.put(JSON_COMPLETION_DATE, printJobStatus.getCompletionTime());\n }\n metadata.put(JSON_ACCESS_ASSERTION, this.assertionPersister.marshal(printJobStatus.getAccess()));\n if (printJobStatus.getError() != null) {\n metadata.put(JSON_ERROR, printJobStatus.getError());\n }\n if (printJobStatus.getResult() != null) {\n metadata.put(JSON_REPORT_URI, printJobStatus.getResult().getReportURIString());\n metadata.put(JSON_FILENAME, printJobStatus.getResult().getFileName());\n metadata.put(JSON_FILE_EXT, printJobStatus.getResult().getFileExtension());\n metadata.put(JSON_MIME_TYPE, printJobStatus.getResult().getMimeType());\n }\n this.registry.put(RESULT_METADATA + printJobStatus.getReferenceId(), metadata);\n }" ]
[ "public synchronized void becomeTempoMaster() throws IOException {\n logger.debug(\"Trying to become master.\");\n if (!isSendingStatus()) {\n throw new IllegalStateException(\"Must be sending status updates to become the tempo master.\");\n }\n\n // Is there someone we need to ask to yield to us?\n final DeviceUpdate currentMaster = getTempoMaster();\n if (currentMaster != null) {\n // Send the yield request; we will become master when we get a successful response.\n byte[] payload = new byte[MASTER_HANDOFF_REQUEST_PAYLOAD.length];\n System.arraycopy(MASTER_HANDOFF_REQUEST_PAYLOAD, 0, payload, 0, MASTER_HANDOFF_REQUEST_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n payload[8] = getDeviceNumber();\n if (logger.isDebugEnabled()) {\n logger.debug(\"Sending master yield request to player \" + currentMaster);\n }\n requestingMasterRoleFromPlayer.set(currentMaster.deviceNumber);\n assembleAndSendPacket(Util.PacketType.MASTER_HANDOFF_REQUEST, payload, currentMaster.address, BeatFinder.BEAT_PORT);\n } else if (!master.get()) {\n // There is no other master, we can just become it immediately.\n requestingMasterRoleFromPlayer.set(0);\n setMasterTempo(getTempo());\n master.set(true);\n }\n }", "public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url,\n String fileName, long fileSize) throws InterruptedException, IOException {\n //Create a upload session\n BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize);\n return this.uploadHelper(session, stream, fileSize);\n }", "public float getLayoutSize(final Layout.Axis axis) {\n float size = 0;\n for (Layout layout : mLayouts) {\n size = Math.max(size, layout.getSize(axis));\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getLayoutSize [%s] axis [%s] size [%f]\", getName(), axis, size);\n return size;\n }", "public static boolean setCustomRequestForDefaultProfile(String pathName, String customData) {\n try {\n return setCustomForDefaultProfile(pathName, false, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public void verifyMessageSize(int maxMessageSize) {\n Iterator<MessageAndOffset> shallowIter = internalIterator(true);\n while(shallowIter.hasNext()) {\n MessageAndOffset messageAndOffset = shallowIter.next();\n int payloadSize = messageAndOffset.message.payloadSize();\n if(payloadSize > maxMessageSize) {\n throw new MessageSizeTooLargeException(\"payload size of \" + payloadSize + \" larger than \" + maxMessageSize);\n }\n }\n }", "public T mapRow(ResultSet rs) throws SQLException {\n Map<String, Object> map = new HashMap<String, Object>();\n ResultSetMetaData metadata = rs.getMetaData();\n\n for (int i = 1; i <= metadata.getColumnCount(); ++i) {\n String label = metadata.getColumnLabel(i);\n\n final Object value;\n // calling getObject on a BLOB/CLOB produces weird results\n switch (metadata.getColumnType(i)) {\n case Types.BLOB:\n value = rs.getBytes(i);\n break;\n case Types.CLOB:\n value = rs.getString(i);\n break;\n default:\n value = rs.getObject(i);\n }\n\n // don't use table name extractor because we don't want aliased table name\n boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i));\n String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i);\n if (tableName != null && !tableName.isEmpty()) {\n String qualifiedName = tableName + \".\" + metadata.getColumnName(i);\n add(map, qualifiedName, value, overwrite);\n }\n\n add(map, label, value, overwrite);\n }\n\n return objectMapper.convertValue(map, type);\n }", "public String getAuthorizationUri(final String redirectUri, final Set<String> scopes, final String state) {\n if (account == null)\n throw new IllegalArgumentException(\"Auth is not set\");\n if (account.getClientId() == null)\n throw new IllegalArgumentException(\"client_id is not set\");\n StringBuilder builder = new StringBuilder();\n builder.append(URI_AUTHENTICATION);\n builder.append(\"?\");\n builder.append(\"response_type=\");\n builder.append(encode(\"code\"));\n builder.append(\"&redirect_uri=\");\n builder.append(encode(redirectUri));\n builder.append(\"&client_id=\");\n builder.append(encode(account.getClientId()));\n builder.append(\"&scope=\");\n builder.append(encode(getScopesString(scopes)));\n builder.append(\"&state=\");\n builder.append(encode(state));\n builder.append(\"&code_challenge\");\n builder.append(getCodeChallenge()); // Already url encoded\n builder.append(\"&code_challenge_method=\");\n builder.append(encode(\"S256\"));\n return builder.toString();\n }", "public PersonTagList<PersonTag> getList(String photoId) throws FlickrException {\r\n\r\n // Delegating this to photos.people.PeopleInterface - Naming standard would be to use PeopleInterface but having 2 the same name can cause issues\r\n com.flickr4java.flickr.photos.people.PeopleInterface pi = new com.flickr4java.flickr.photos.people.PeopleInterface(apiKey, sharedSecret, transportAPI);\r\n return pi.getList(photoId);\r\n }", "public static List<Dependency> getAllDependencies(final Module module) {\n final Set<Dependency> dependencies = new HashSet<Dependency>();\n final List<String> producedArtifacts = new ArrayList<String>();\n for(final Artifact artifact: getAllArtifacts(module)){\n producedArtifacts.add(artifact.getGavc());\n }\n\n dependencies.addAll(getAllDependencies(module, producedArtifacts));\n\n return new ArrayList<Dependency>(dependencies);\n }" ]
This method writes predecessor data to an MSPDI file. We have to deal with a slight anomaly in this method that is introduced by the MPX file format. It would be possible for someone to create an MPX file with both the predecessor list and the unique ID predecessor list populated... which means that we must process both and avoid adding duplicate predecessors. Also interesting to note is that MSP98 populates the predecessor list, not the unique ID predecessor list, as you might expect. @param xml MSPDI task data @param mpx MPX task data
[ "private void writePredecessors(Project.Tasks.Task xml, Task mpx)\n {\n List<Project.Tasks.Task.PredecessorLink> list = xml.getPredecessorLink();\n\n List<Relation> predecessors = mpx.getPredecessors();\n for (Relation rel : predecessors)\n {\n Integer taskUniqueID = rel.getTargetTask().getUniqueID();\n list.add(writePredecessor(taskUniqueID, rel.getType(), rel.getLag()));\n m_eventManager.fireRelationWrittenEvent(rel);\n }\n }" ]
[ "public static String expandLine(CharSequence self, int tabStop) {\n String s = self.toString();\n int index;\n while ((index = s.indexOf('\\t')) != -1) {\n StringBuilder builder = new StringBuilder(s);\n int count = tabStop - index % tabStop;\n builder.deleteCharAt(index);\n for (int i = 0; i < count; i++) builder.insert(index, \" \");\n s = builder.toString();\n }\n return s;\n }", "public void setChildren(List<PrintComponent<?>> children) {\n\t\tthis.children = children;\n\t\t// needed for Json unmarshall !!!!\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.setParent(this);\n\t\t}\n\t}", "public void setLabels(Collection<LabelType> labels) {\r\n this.labels.clear();\r\n if (labels != null) {\r\n this.labels.addAll(labels);\r\n }\r\n }", "public static void log(byte[] data)\n {\n if (LOG != null)\n {\n LOG.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n LOG.flush();\n }\n }", "public void addChildTask(Task child)\n {\n child.m_parent = this;\n m_children.add(child);\n setSummary(true);\n\n if (getParentFile().getProjectConfig().getAutoOutlineLevel() == true)\n {\n child.setOutlineLevel(Integer.valueOf(NumberHelper.getInt(getOutlineLevel()) + 1));\n }\n }", "public static DMatrixSparseCSC rectangle(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n\n nz_total = Math.min(numCols*numRows,nz_total);\n int[] selected = UtilEjml.shuffled(numRows*numCols, nz_total, rand);\n Arrays.sort(selected,0,nz_total);\n\n DMatrixSparseCSC ret = new DMatrixSparseCSC(numRows,numCols,nz_total);\n ret.indicesSorted = true;\n\n // compute the number of elements in each column\n int hist[] = new int[ numCols ];\n for (int i = 0; i < nz_total; i++) {\n hist[selected[i]/numRows]++;\n }\n\n // define col_idx\n ret.histogramToStructure(hist);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]%numRows;\n\n ret.nz_rows[i] = row;\n ret.nz_values[i] = rand.nextDouble()*(max-min)+min;\n }\n\n return ret;\n }", "public IPv6Address getIPv6Address(IPv6AddressSegment segs[]) {\n\t\tIPv6AddressCreator creator = getIPv6Network().getAddressCreator();\n\t\treturn creator.createAddress(IPv6AddressSection.createSection(creator, segs, this)); /* address creation */\n\t}", "public int compareTo(InternalFeature o) {\n\t\tif (null == o) {\n\t\t\treturn -1; // avoid NPE, put null objects at the end\n\t\t}\n\t\tif (null != styleDefinition && null != o.getStyleInfo()) {\n\t\t\tif (styleDefinition.getIndex() > o.getStyleInfo().getIndex()) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (styleDefinition.getIndex() < o.getStyleInfo().getIndex()) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}", "private boolean isRedeployAfterRemoval(ModelNode operation) {\n return operation.hasDefined(DEPLOYMENT_OVERLAY_LINK_REMOVAL) &&\n operation.get(DEPLOYMENT_OVERLAY_LINK_REMOVAL).asBoolean();\n }" ]
Creates builder for passed path element @param elementName name of xml element that is used as decorator @return PersistentResourceXMLBuilder @deprecated decorator element support is currently considered as preview @since 4.0
[ "@Deprecated\n public static PersistentResourceXMLBuilder decorator(final String elementName) {\n return new PersistentResourceXMLBuilder(PathElement.pathElement(elementName), null).setDecoratorGroup(elementName);\n }" ]
[ "private SearchableItem buildSearchableItem(Message menuItem) {\n return new SearchableItem((int) ((NumberField) menuItem.arguments.get(1)).getValue(),\n ((StringField) menuItem.arguments.get(3)).getValue());\n }", "protected Collection provideStateManagers(Collection pojos)\r\n {\r\n \tPersistenceCapable pc;\r\n \tint [] fieldNums;\r\n \tIterator iter = pojos.iterator();\r\n \tCollection result = new ArrayList();\r\n \t\r\n \twhile (iter.hasNext())\r\n \t{\r\n \t\t// obtain a StateManager\r\n \t\tpc = (PersistenceCapable) iter.next();\r\n \t\tIdentity oid = new Identity(pc, broker);\r\n \t\tStateManagerInternal smi = pmi.getStateManager(oid, pc.getClass()); \r\n \t\t\r\n \t\t// fetch attributes into StateManager\r\n\t\t\tJDOClass jdoClass = Helper.getJDOClass(pc.getClass());\r\n\t\t\tfieldNums = jdoClass.getManagedFieldNumbers();\r\n\r\n\t\t\tFieldManager fm = new OjbFieldManager(pc, broker);\r\n\t\t\tsmi.replaceFields(fieldNums, fm);\r\n\t\t\tsmi.retrieve();\r\n\t\t\t\r\n\t\t\t// get JDO PersistencecCapable instance from SM and add it to result collection\r\n\t\t\tObject instance = smi.getObject();\r\n\t\t\tresult.add(instance);\r\n \t}\r\n \treturn result; \r\n\t}", "@Override public void onBindViewHolder(RendererViewHolder viewHolder, int position) {\n T content = getItem(position);\n Renderer<T> renderer = viewHolder.getRenderer();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null renderer\");\n }\n renderer.setContent(content);\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n }", "private void setRawDirection(SwipyRefreshLayoutDirection direction) {\n if (mDirection == direction) {\n return;\n }\n\n mDirection = direction;\n switch (mDirection) {\n case BOTTOM:\n mCurrentTargetOffsetTop = mOriginalOffsetTop = getMeasuredHeight();\n break;\n case TOP:\n default:\n mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();\n break;\n }\n }", "public List<String> parseMethodList(String methods) {\n\n String[] methodArray = StringUtils.delimitedListToStringArray(methods, \",\");\n\n List<String> methodList = new ArrayList<String>();\n\n for (String methodName : methodArray) {\n methodList.add(methodName.trim());\n }\n return methodList;\n }", "String escapeValue(Object value) {\n return HtmlUtils.htmlEscape(value != null ? value.toString() : \"<null>\");\n }", "private FieldType getActivityIDField(Map<FieldType, String> map)\n {\n FieldType result = null;\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n if (entry.getValue().equals(\"task_code\"))\n {\n result = entry.getKey();\n break;\n }\n }\n return result;\n }", "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }", "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 }" ]
Entry point for this example Uses HDFS ToolRunner to wrap processing of @param args Command-line arguments for HDFS example
[ "public static void main(String[] args) {\n CmdLine cmd = new CmdLine();\n Configuration conf = new Configuration();\n int res = 0;\n try {\n res = ToolRunner.run(conf, cmd, args);\n } catch (Exception e) {\n System.err.println(\"Error while running MR job\");\n e.printStackTrace();\n }\n System.exit(res);\n }" ]
[ "private void getYearlyDates(Calendar calendar, List<Date> dates)\n {\n if (m_relative)\n {\n getYearlyRelativeDates(calendar, dates);\n }\n else\n {\n getYearlyAbsoluteDates(calendar, dates);\n }\n }", "private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {\n List<T> indexesOfType = new ArrayList<T>();\n Gson g = new Gson();\n for (JsonElement index : indexes) {\n if (index.isJsonObject()) {\n JsonObject indexDefinition = index.getAsJsonObject();\n JsonElement indexType = indexDefinition.get(\"type\");\n if (indexType != null && indexType.isJsonPrimitive()) {\n JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();\n if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive\n .getAsString().equals(type))) {\n indexesOfType.add(g.fromJson(indexDefinition, modelType));\n }\n }\n }\n }\n return indexesOfType;\n }", "public void set(Object receiver, String fieldName, /* @Nullable */ Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\tf.set(receiver, value);\n\t}", "@Nonnull\n public BufferedImage createBufferedImage(final int imageWidth, final int imageHeight) {\n return new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);\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}", "public CollectionDescriptor getCollectionDescriptorByName(String name)\r\n {\r\n if (name == null)\r\n {\r\n return null;\r\n }\r\n\r\n CollectionDescriptor cod = (CollectionDescriptor) getCollectionDescriptorNameMap().get(name);\r\n\r\n //\r\n // BRJ: if the CollectionDescriptor is not found\r\n // look in the ClassDescriptor referenced by 'super' for it\r\n //\r\n if (cod == null)\r\n {\r\n ClassDescriptor superCld = getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n cod = superCld.getCollectionDescriptorByName(name);\r\n }\r\n }\r\n\r\n return cod;\r\n }", "private static String toColumnName(String fieldName) {\n int lastDot = fieldName.indexOf('.');\n if (lastDot > -1) {\n return fieldName.substring(lastDot + 1);\n } else {\n return fieldName;\n }\n }", "private boolean ignoreMethod(String name)\n {\n boolean result = false;\n\n for (String ignoredName : IGNORED_METHODS)\n {\n if (name.matches(ignoredName))\n {\n result = true;\n break;\n }\n }\n\n return result;\n }", "public void setGlobal(int pathId, Boolean global) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_GLOBAL + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setBoolean(1, global);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
Mbeans for FETCH_ENTRIES
[ "@JmxGetter(name = \"avgFetchEntriesNetworkTimeMs\", description = \"average time spent on network, for streaming operations\")\n public double getAvgFetchEntriesNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.FETCH_ENTRIES).getAvgEventValue()\n / Time.NS_PER_MS;\n }" ]
[ "public static <R extends Resource<?>, U extends PaginatedResponse<R>> Flux<R> getResources(U response) {\n return Flux.fromIterable(response.getResources());\n }", "protected void addPoint(double time, RandomVariable value, boolean isParameter) {\n\t\tsynchronized (rationalFunctionInterpolationLazyInitLock) {\n\t\t\tif(interpolationEntity == InterpolationEntity.LOG_OF_VALUE_PER_TIME && time == 0) {\n\t\t\t\tboolean containsOne = false; int index=0;\n\t\t\t\tfor(int i = 0; i< value.size(); i++){if(value.get(i)==1.0) {containsOne = true; index=i; break;}}\n\t\t\t\tif(containsOne && isParameter == false) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new IllegalArgumentException(\"The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index\" + index + \").\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tRandomVariable interpolationEntityValue = interpolationEntityFromValue(value, time);\n\n\t\t\tint index = getTimeIndex(time);\n\t\t\tif(index >= 0) {\n\t\t\t\tif(points.get(index).value == interpolationEntityValue) {\n\t\t\t\t\treturn;\t\t\t// Already in list\n\t\t\t\t} else if(isParameter) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new RuntimeException(\"Trying to add a value for a time for which another value already exists.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Insert the new point, retain ordering.\n\t\t\t\tPoint point = new Point(time, interpolationEntityValue, isParameter);\n\t\t\t\tpoints.add(-index-1, point);\n\n\t\t\t\tif(isParameter) {\n\t\t\t\t\t// Add this point also to the list of parameters\n\t\t\t\t\tint parameterIndex = getParameterIndex(time);\n\t\t\t\t\tif(parameterIndex >= 0) {\n\t\t\t\t\t\tnew RuntimeException(\"CurveFromInterpolationPoints inconsistent.\");\n\t\t\t\t\t}\n\t\t\t\t\tpointsBeingParameters.add(-parameterIndex-1, point);\n\t\t\t\t}\n\t\t\t}\n\t\t\trationalFunctionInterpolation = null;\n\t\t\tcurveCacheReference = null;\n\t\t}\n\t}", "private static OkHttpClient getUnsafeOkHttpClient() {\n try {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] {\n new X509TrustManager() {\n @Override\n public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public java.security.cert.X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n }\n };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new java.security.SecureRandom());\n // Create an ssl socket factory with our all-trusting manager\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n\n OkHttpClient okHttpClient = new OkHttpClient();\n okHttpClient.setSslSocketFactory(sslSocketFactory);\n okHttpClient.setHostnameVerifier(new HostnameVerifier() {\n @Override\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n });\n\n return okHttpClient;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public static BoxDeveloperEditionAPIConnection getAppUserConnection(String userId, BoxConfig boxConfig) {\n return getAppUserConnection(userId, boxConfig.getClientId(), boxConfig.getClientSecret(),\n boxConfig.getJWTEncryptionPreferences());\n }", "@RequestMapping(value = \"api/edit/disableAll\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableAll(Model model, int profileID,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) {\n editService.disableAll(profileID, clientUUID);\n return null;\n }", "protected Transformer getTransformer() {\n TransformerFactory transformerFactory = domXmlDataFormat.getTransformerFactory();\n try {\n Transformer transformer = transformerFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.ENCODING, \"UTF-8\");\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n return transformer;\n }\n catch (TransformerConfigurationException e) {\n throw LOG.unableToCreateTransformer(e);\n }\n }", "public void createAssignmentFieldMap(Props props)\n {\n //System.out.println(\"ASSIGN\");\n byte[] fieldMapData = null;\n for (Integer key : ASSIGNMENT_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultAssignmentData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }", "public static authenticationtacacspolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_authenticationvserver_binding obj = new authenticationtacacspolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_authenticationvserver_binding response[] = (authenticationtacacspolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "void commitTempFile(File temp) throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n if (!interactionPolicy.isReadOnly()) {\n FilePersistenceUtils.moveTempFileToMain(temp, mainFile);\n } else {\n FilePersistenceUtils.moveTempFileToMain(temp, lastFile);\n }\n }" ]
Determine the target type for the generic return type of the given method, where formal type variables are declared on the given class. @param method the method to introspect @param clazz the class to resolve type variables against @return the corresponding generic parameter or return type @see #resolveReturnTypeForGenericMethod
[ "public static Class<?> resolveReturnType(Method method, Class<?> clazz) {\n\t\tAssert.notNull(method, \"Method must not be null\");\n\t\tType genericType = method.getGenericReturnType();\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tMap<TypeVariable, Type> typeVariableMap = getTypeVariableMap(clazz);\n\t\tType rawType = getRawType(genericType, typeVariableMap);\n\t\treturn (rawType instanceof Class ? (Class<?>) rawType : method.getReturnType());\n\t}" ]
[ "private Object getColumnValue(String table, String column, String data, int type, boolean epochDateFormat) throws MPXJException\n {\n try\n {\n Object value = null;\n\n switch (type)\n {\n case Types.BIT:\n {\n value = DatatypeConverter.parseBoolean(data);\n break;\n }\n\n case Types.VARCHAR:\n case Types.LONGVARCHAR:\n {\n value = DatatypeConverter.parseString(data);\n break;\n }\n\n case Types.TIME:\n {\n value = DatatypeConverter.parseBasicTime(data);\n break;\n }\n\n case Types.TIMESTAMP:\n {\n if (epochDateFormat)\n {\n value = DatatypeConverter.parseEpochTimestamp(data);\n }\n else\n {\n value = DatatypeConverter.parseBasicTimestamp(data);\n }\n break;\n }\n\n case Types.DOUBLE:\n {\n value = DatatypeConverter.parseDouble(data);\n break;\n }\n\n case Types.INTEGER:\n {\n value = DatatypeConverter.parseInteger(data);\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported SQL type: \" + type);\n }\n }\n\n return value;\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to parse \" + table + \".\" + column + \" (data=\" + data + \", type=\" + type + \")\", ex);\n }\n }", "public void setJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n checkJobTypes(jobTypes);\n this.jobTypes.clear();\n this.jobTypes.putAll(jobTypes);\n }", "public <U> CoreRemoteMongoIterable<U> map(final Function<ResultT, U> mapper) {\n return new CoreRemoteMappingIterable<>(this, mapper);\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 void update(int width, int height, byte[] grayscaleData)\n {\n NativeBitmapImage.updateFromMemory(getNative(), width, height, grayscaleData);\n }", "public Metadata createMetadata(String templateName, String scope, Metadata metadata) {\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"POST\");\n request.addHeader(\"Content-Type\", \"application/json\");\n request.setBody(metadata.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }", "public static gslbdomain_stats[] get(nitro_service service) throws Exception{\n\t\tgslbdomain_stats obj = new gslbdomain_stats();\n\t\tgslbdomain_stats[] response = (gslbdomain_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public void setDirectory(final String directory) {\n this.directory = new File(this.configuration.getDirectory(), directory);\n if (!this.directory.exists()) {\n throw new IllegalArgumentException(String.format(\n \"Directory does not exist: %s.\\n\" +\n \"Configuration contained value %s which is supposed to be relative to \" +\n \"configuration directory.\",\n this.directory, directory));\n }\n\n if (!this.directory.getAbsolutePath()\n .startsWith(this.configuration.getDirectory().getAbsolutePath())) {\n throw new IllegalArgumentException(String.format(\n \"All files and directories must be contained in the configuration directory the \" +\n \"directory provided in the configuration breaks that contract: %s in config \" +\n \"file resolved to %s.\",\n directory, this.directory));\n }\n }", "@SuppressForbidden(\"legitimate sysstreams.\")\n private Execute forkProcess(ForkedJvmInfo slaveInfo, EventBus eventBus, \n CommandlineJava commandline, \n TailInputStream eventStream, OutputStream sysout, OutputStream syserr, RandomAccessFile streamsBuffer) {\n try {\n String tempDir = commandline.getSystemProperties().getVariablesVector().stream()\n .filter(v -> v.getKey().equals(\"java.io.tmpdir\"))\n .map(v -> v.getValue())\n .findAny()\n .orElse(null);\n\n final LocalSlaveStreamHandler streamHandler = \n new LocalSlaveStreamHandler(\n eventBus, testsClassLoader, System.err, eventStream, \n sysout, syserr, heartbeat, streamsBuffer);\n\n // Add certain properties to allow identification of the forked JVM from within\n // the subprocess. This can be used for policy files etc.\n final Path cwd = getWorkingDirectory(slaveInfo, tempDir);\n\n Variable v = new Variable();\n v.setKey(CHILDVM_SYSPROP_CWD);\n v.setFile(cwd.toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SYSPROP_TEMPDIR);\n v.setFile(getTempDir().toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_ID);\n v.setValue(Integer.toString(slaveInfo.id));\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT);\n v.setValue(Integer.toString(slaveInfo.slaves));\n commandline.addSysproperty(v);\n\n // Emit command line before -stdin to avoid confusion.\n slaveInfo.slaveCommandLine = escapeAndJoin(commandline.getCommandline());\n log(\"Forked child JVM at '\" + cwd.toAbsolutePath().normalize() + \n \"', command (may need escape sequences for your shell):\\n\" + \n slaveInfo.slaveCommandLine, Project.MSG_VERBOSE);\n\n final Execute execute = new Execute();\n execute.setCommandline(commandline.getCommandline());\n execute.setVMLauncher(true);\n execute.setWorkingDirectory(cwd.toFile());\n execute.setStreamHandler(streamHandler);\n execute.setNewenvironment(newEnvironment);\n if (env.getVariables() != null)\n execute.setEnvironment(env.getVariables());\n log(\"Starting JVM J\" + slaveInfo.id, Project.MSG_DEBUG);\n execute.execute();\n return execute;\n } catch (IOException e) {\n throw new BuildException(\"Could not start the child process. Run ant with -verbose to get\" +\n \t\t\" the execution details.\", e);\n }\n }" ]
Use this API to fetch sslservicegroup_sslcertkey_binding resources of given name .
[ "public static sslservicegroup_sslcertkey_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tsslservicegroup_sslcertkey_binding obj = new sslservicegroup_sslcertkey_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tsslservicegroup_sslcertkey_binding response[] = (sslservicegroup_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public void rollback() throws GitAPIException {\n try (Git git = getGit()) {\n git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();\n }\n }", "private void ensureFields(ClassDescriptorDef classDef, Collection fields) throws ConstraintException\r\n {\r\n boolean forceVirtual = !classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true);\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next();\r\n\r\n // First we check whether this field is already present in the class\r\n FieldDescriptorDef foundFieldDef = classDef.getField(fieldDef.getName());\r\n\r\n if (foundFieldDef != null)\r\n {\r\n if (isEqual(fieldDef, foundFieldDef))\r\n {\r\n if (forceVirtual)\r\n {\r\n foundFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n continue;\r\n }\r\n else\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a different field of the same name\");\r\n }\r\n }\r\n\r\n // perhaps a reference or collection ?\r\n if (classDef.getCollection(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a collection of the same name\");\r\n }\r\n if (classDef.getReference(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a reference of the same name\");\r\n }\r\n classDef.addFieldClone(fieldDef);\r\n classDef.getField(fieldDef.getName()).setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\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 }", "public boolean isValid() {\n\t\tif(parsedHost != null) {\n\t\t\treturn true;\n\t\t}\n\t\tif(validationException != null) {\n\t\t\treturn false;\n\t\t}\n\t\ttry {\n\t\t\tvalidate();\n\t\t\treturn true;\n\t\t} catch(HostNameException e) {\n\t\t\treturn false;\n\t\t}\n\t}", "public static final String getSelectedText(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getItemText(index) : null;\n }", "void killAll()\n {\n for (RjiRegistration reg : this.instancesById.values().toArray(new RjiRegistration[] {}))\n {\n reg.rji.handleInstruction(Instruction.KILL);\n }\n }", "public void merge(GVRSkeleton newSkel)\n {\n int numBones = getNumBones();\n List<Integer> parentBoneIds = new ArrayList<Integer>(numBones + newSkel.getNumBones());\n List<String> newBoneNames = new ArrayList<String>(newSkel.getNumBones());\n List<Matrix4f> newMatrices = new ArrayList<Matrix4f>(newSkel.getNumBones());\n GVRPose oldBindPose = getBindPose();\n GVRPose curPose = getPose();\n\n for (int i = 0; i < numBones; ++i)\n {\n parentBoneIds.add(mParentBones[i]);\n }\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n String boneName = newSkel.getBoneName(j);\n int boneId = getBoneIndex(boneName);\n if (boneId < 0)\n {\n int parentId = newSkel.getParentBoneIndex(j);\n Matrix4f m = new Matrix4f();\n\n newSkel.getBindPose().getLocalMatrix(j, m);\n newMatrices.add(m);\n newBoneNames.add(boneName);\n if (parentId >= 0)\n {\n boneName = newSkel.getBoneName(parentId);\n parentId = getBoneIndex(boneName);\n }\n parentBoneIds.add(parentId);\n }\n }\n if (parentBoneIds.size() == numBones)\n {\n return;\n }\n int n = numBones + parentBoneIds.size();\n int[] parentIds = Arrays.copyOf(mParentBones, n);\n int[] boneOptions = Arrays.copyOf(mBoneOptions, n);\n String[] boneNames = Arrays.copyOf(mBoneNames, n);\n\n mBones = Arrays.copyOf(mBones, n);\n mPoseMatrices = new float[n * 16];\n for (int i = 0; i < parentBoneIds.size(); ++i)\n {\n n = numBones + i;\n parentIds[n] = parentBoneIds.get(i);\n boneNames[n] = newBoneNames.get(i);\n boneOptions[n] = BONE_ANIMATE;\n }\n mBoneOptions = boneOptions;\n mBoneNames = boneNames;\n mParentBones = parentIds;\n mPose = new GVRPose(this);\n mBindPose = new GVRPose(this);\n mBindPose.copy(oldBindPose);\n mPose.copy(curPose);\n mBindPose.sync();\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n mBindPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n mPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n }\n setBindPose(mBindPose);\n mPose.sync();\n updateBonePose();\n }", "public static final Boolean parseExtendedAttributeBoolean(String value)\n {\n return ((value.equals(\"1\") ? Boolean.TRUE : Boolean.FALSE));\n }", "private GenericCriteriaPrompt getPromptValue(FieldType field, byte[] block)\n {\n int textOffset = getPromptOffset(block);\n String value = MPPUtility.getUnicodeString(m_criteriaData, m_criteriaTextStart + textOffset);\n GenericCriteriaPrompt prompt = new GenericCriteriaPrompt(field.getDataType(), value);\n if (m_prompts != null)\n {\n m_prompts.add(prompt);\n }\n return prompt;\n }" ]
Checks whether given class descriptor has a primary key. @param classDef The class descriptor @param checkLevel The current check level (this constraint is only checked in strict) @exception ConstraintException If the constraint has been violated
[ "private void checkPrimaryKey(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n classDef.getPrimaryKeys().isEmpty())\r\n {\r\n LogHelper.warn(true,\r\n getClass(),\r\n \"checkPrimaryKey\",\r\n \"The class \"+classDef.getName()+\" has no primary key\");\r\n }\r\n }" ]
[ "public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {\n final CopyOption[] options;\n if (overwrite) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};\n } else {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.walkFileTree(source, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n Files.copy(dir, target.resolve(source.relativize(dir)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.copy(file, target.resolve(source.relativize(file)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }", "public E get(int i) {\r\n if (i < 0 || i >= objects.size())\r\n throw new ArrayIndexOutOfBoundsException(\"Index \" + i + \r\n \" outside the bounds [0,\" + \r\n size() + \")\");\r\n return objects.get(i);\r\n }", "private JSONArray toJsonStringArray(Collection<? extends Object> collection) {\n\n if (null != collection) {\n JSONArray array = new JSONArray();\n for (Object o : collection) {\n array.put(\"\" + o);\n }\n return array;\n } else {\n return null;\n }\n }", "protected String getIsolationLevelAsString()\r\n {\r\n if (defaultIsolationLevel == IL_READ_UNCOMMITTED)\r\n {\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_READ_COMMITTED)\r\n {\r\n return LITERAL_IL_READ_COMMITTED;\r\n }\r\n else if (defaultIsolationLevel == IL_REPEATABLE_READ)\r\n {\r\n return LITERAL_IL_REPEATABLE_READ;\r\n }\r\n else if (defaultIsolationLevel == IL_SERIALIZABLE)\r\n {\r\n return LITERAL_IL_SERIALIZABLE;\r\n }\r\n else if (defaultIsolationLevel == IL_OPTIMISTIC)\r\n {\r\n return LITERAL_IL_OPTIMISTIC;\r\n }\r\n return LITERAL_IL_READ_UNCOMMITTED;\r\n }", "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 static int[] getTileScreenSize(double[] worldSize, double scale) {\n\t\tint screenWidth = (int) Math.round(scale * worldSize[0]);\n\t\tint screenHeight = (int) Math.round(scale * worldSize[1]);\n\t\treturn new int[] { screenWidth, screenHeight };\n\t}", "public void setPattern(String patternType) {\r\n\r\n final PatternType type = PatternType.valueOf(patternType);\r\n if (type != m_model.getPatternType()) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n EndType oldEndType = m_model.getEndType();\r\n m_model.setPatternType(type);\r\n m_model.setIndividualDates(null);\r\n m_model.setInterval(getPatternDefaultValues().getInterval());\r\n m_model.setEveryWorkingDay(Boolean.FALSE);\r\n m_model.clearWeekDays();\r\n m_model.clearIndividualDates();\r\n m_model.clearWeeksOfMonth();\r\n m_model.clearExceptions();\r\n if (type.equals(PatternType.NONE) || type.equals(PatternType.INDIVIDUAL)) {\r\n m_model.setEndType(EndType.SINGLE);\r\n } else if (oldEndType.equals(EndType.SINGLE)) {\r\n m_model.setEndType(EndType.TIMES);\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n }\r\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\r\n m_model.setMonth(getPatternDefaultValues().getMonth());\r\n if (type.equals(PatternType.WEEKLY)) {\r\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\r\n }\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }", "public static <IN> PaddedList<IN> valueOf(List<IN> list, IN padding) {\r\n return new PaddedList<IN>(list, padding);\r\n }", "private boolean isOrdinal(int paramType) {\n\t\tswitch ( paramType ) {\n\t\t\tcase Types.INTEGER:\n\t\t\tcase Types.NUMERIC:\n\t\t\tcase Types.SMALLINT:\n\t\t\tcase Types.TINYINT:\n\t\t\tcase Types.BIGINT:\n\t\t\tcase Types.DECIMAL: //for Oracle Driver\n\t\t\tcase Types.DOUBLE: //for Oracle Driver\n\t\t\tcase Types.FLOAT: //for Oracle Driver\n\t\t\t\treturn true;\n\t\t\tcase Types.CHAR:\n\t\t\tcase Types.LONGVARCHAR:\n\t\t\tcase Types.VARCHAR:\n\t\t\t\treturn false;\n\t\t\tdefault:\n\t\t\t\tthrow new HibernateException( \"Unable to persist an Enum in a column of SQL Type: \" + paramType );\n\t\t}\n\t}" ]
Returns true if this Bytes object equals another. This method checks it's arguments. @since 1.2.0
[ "public boolean contentEquals(byte[] bytes, int offset, int len) {\n Preconditions.checkArgument(len >= 0 && offset >= 0 && offset + len <= bytes.length);\n return contentEqualsUnchecked(bytes, offset, len);\n }" ]
[ "private void checkSequenceName(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String autoIncr = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT);\r\n String seqName = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_SEQUENCE_NAME);\r\n\r\n if ((seqName != null) && (seqName.length() > 0))\r\n {\r\n if (!\"ojb\".equals(autoIncr) && !\"database\".equals(autoIncr))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has sequence-name set though it's autoincrement value is not set to 'ojb'\");\r\n }\r\n }\r\n }", "private static void listTasks(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n\n for (Task task : file.getTasks())\n {\n Date date = task.getStart();\n String text = task.getStartText();\n String startDate = text != null ? text : (date != null ? df.format(date) : \"(no start date supplied)\");\n\n date = task.getFinish();\n text = task.getFinishText();\n String finishDate = text != null ? text : (date != null ? df.format(date) : \"(no finish date supplied)\");\n\n Duration dur = task.getDuration();\n text = task.getDurationText();\n String duration = text != null ? text : (dur != null ? dur.toString() : \"(no duration supplied)\");\n\n dur = task.getActualDuration();\n String actualDuration = dur != null ? dur.toString() : \"(no actual duration supplied)\";\n\n String baselineDuration = task.getBaselineDurationText();\n if (baselineDuration == null)\n {\n dur = task.getBaselineDuration();\n if (dur != null)\n {\n baselineDuration = dur.toString();\n }\n else\n {\n baselineDuration = \"(no duration supplied)\";\n }\n }\n\n System.out.println(\"Task: \" + task.getName() + \" ID=\" + task.getID() + \" Unique ID=\" + task.getUniqueID() + \" (Start Date=\" + startDate + \" Finish Date=\" + finishDate + \" Duration=\" + duration + \" Actual Duration\" + actualDuration + \" Baseline Duration=\" + baselineDuration + \" Outline Level=\" + task.getOutlineLevel() + \" Outline Number=\" + task.getOutlineNumber() + \" Recurring=\" + task.getRecurring() + \")\");\n }\n System.out.println();\n }", "public Point measureImage(Resources resources) {\n BitmapFactory.Options justBoundsOptions = new BitmapFactory.Options();\n justBoundsOptions.inJustDecodeBounds = true;\n\n if (bitmap != null) {\n return new Point(bitmap.getWidth(), bitmap.getHeight());\n } else if (resId != null) {\n BitmapFactory.decodeResource(resources, resId, justBoundsOptions);\n float scale = (float) justBoundsOptions.inTargetDensity / justBoundsOptions.inDensity;\n return new Point((int) (justBoundsOptions.outWidth * scale + 0.5f), (int) (justBoundsOptions.outHeight * scale + 0.5f));\n } else if (fileToBitmap != null) {\n BitmapFactory.decodeFile(fileToBitmap.getAbsolutePath(), justBoundsOptions);\n } else if (inputStream != null) {\n BitmapFactory.decodeStream(inputStream, null, justBoundsOptions);\n try {\n inputStream.reset();\n } catch (IOException ignored) {\n }\n } else if (view != null) {\n return new Point(view.getWidth(), view.getHeight());\n }\n return new Point(justBoundsOptions.outWidth, justBoundsOptions.outHeight);\n }", "public static appfwprofile get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile obj = new appfwprofile();\n\t\tobj.set_name(name);\n\t\tappfwprofile response = (appfwprofile) obj.get_resource(service);\n\t\treturn response;\n\t}", "public Release rollback(String appName, String releaseUuid) {\n return connection.execute(new Rollback(appName, releaseUuid), apiKey);\n }", "public static int count(CharSequence self, CharSequence text) {\n int answer = 0;\n for (int idx = 0; true; idx++) {\n idx = self.toString().indexOf(text.toString(), idx);\n // break once idx goes to -1 or for case of empty string once\n // we get to the end to avoid JDK library bug (see GROOVY-5858)\n if (idx < answer) break;\n ++answer;\n }\n return answer;\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public UTMDetail getUTMDetails() {\n UTMDetail ud = new UTMDetail();\n ud.setSource(source);\n ud.setMedium(medium);\n ud.setCampaign(campaign);\n return ud;\n }", "public BoxGroupMembership.Info addMembership(BoxUser user, Role role) {\n BoxAPIConnection api = this.getAPI();\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"user\", new JsonObject().add(\"id\", user.getID()));\n requestJSON.add(\"group\", new JsonObject().add(\"id\", this.getID()));\n if (role != null) {\n requestJSON.add(\"role\", role.toJSONString());\n }\n\n URL url = ADD_MEMBERSHIP_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 BoxGroupMembership membership = new BoxGroupMembership(api, responseJSON.get(\"id\").asString());\n return membership.new Info(responseJSON);\n }", "public void fireEvent(final WorkerEvent event, final Worker worker, final String queue, final Job job, \n final Object runner, final Object result, final Throwable t) {\n final ConcurrentSet<WorkerListener> listeners = this.eventListenerMap.get(event);\n if (listeners != null) {\n for (final WorkerListener listener : listeners) {\n if (listener != null) {\n try {\n listener.onEvent(event, worker, queue, job, runner, result, t);\n } catch (Exception e) {\n log.error(\"Failure executing listener \" + listener + \" for event \" + event \n + \" from queue \" + queue + \" on worker \" + worker, e);\n }\n }\n }\n }\n }" ]
Get HttpResourceModel which matches the HttpMethod of the request. @param routableDestinations List of ResourceModels. @param targetHttpMethod HttpMethod. @param requestUri request URI. @return RoutableDestination that matches httpMethod that needs to be handled. null if there are no matches.
[ "private PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>\n getMatchedDestination(List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations,\n HttpMethod targetHttpMethod, String requestUri) {\n\n LOG.trace(\"Routable destinations for request {}: {}\", requestUri, routableDestinations);\n Iterable<String> requestUriParts = splitAndOmitEmpty(requestUri, '/');\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations = new ArrayList<>();\n long maxScore = 0;\n\n for (PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> destination : routableDestinations) {\n HttpResourceModel resourceModel = destination.getDestination();\n\n for (HttpMethod httpMethod : resourceModel.getHttpMethod()) {\n if (targetHttpMethod.equals(httpMethod)) {\n long score = getWeightedMatchScore(requestUriParts, splitAndOmitEmpty(resourceModel.getPath(), '/'));\n LOG.trace(\"Max score = {}. Weighted score for {} is {}. \", maxScore, destination, score);\n if (score > maxScore) {\n maxScore = score;\n matchedDestinations.clear();\n matchedDestinations.add(destination);\n } else if (score == maxScore) {\n matchedDestinations.add(destination);\n }\n }\n }\n }\n\n if (matchedDestinations.size() > 1) {\n throw new IllegalStateException(String.format(\"Multiple matched handlers found for request uri %s: %s\",\n requestUri, matchedDestinations));\n } else if (matchedDestinations.size() == 1) {\n return matchedDestinations.get(0);\n }\n return null;\n }" ]
[ "public static base_responses delete(nitro_service client, clusterinstance resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusterinstance deleteresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new clusterinstance();\n\t\t\t\tdeleteresources[i].clid = resources[i].clid;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public Duration getFinishSlack()\n {\n Duration finishSlack = (Duration) getCachedValue(TaskField.FINISH_SLACK);\n if (finishSlack == null)\n {\n Duration duration = getDuration();\n if (duration != null)\n {\n finishSlack = DateHelper.getVariance(this, getEarlyFinish(), getLateFinish(), duration.getUnits());\n set(TaskField.FINISH_SLACK, finishSlack);\n }\n }\n return (finishSlack);\n }", "private void populateMilestone(Row row, Task task)\n {\n task.setMilestone(true);\n //PROJID\n task.setUniqueID(row.getInteger(\"MILESTONEID\"));\n task.setStart(row.getDate(\"GIVEN_DATE_TIME\"));\n task.setFinish(row.getDate(\"GIVEN_DATE_TIME\"));\n //PROGREST_PERIOD\n //SYMBOL_APPEARANCE\n //MILESTONE_TYPE\n //PLACEMENU\n task.setPercentageComplete(row.getBoolean(\"COMPLETED\") ? COMPLETE : INCOMPLETE);\n //INTERRUPTIBLE_X\n //ACTUAL_DURATIONTYPF\n //ACTUAL_DURATIONELA_MONTHS\n //ACTUAL_DURATIONHOURS\n task.setEarlyStart(row.getDate(\"EARLY_START_DATE\"));\n task.setLateStart(row.getDate(\"LATE_START_DATE\"));\n //FREE_START_DATE\n //START_CONSTRAINT_DATE\n //END_CONSTRAINT_DATE\n //EFFORT_BUDGET\n //NATURAO_ORDER\n //LOGICAL_PRECEDENCE\n //SPAVE_INTEGER\n //SWIM_LANE\n //USER_PERCENT_COMPLETE\n //OVERALL_PERCENV_COMPLETE\n //OVERALL_PERCENT_COMPL_WEIGHT\n task.setName(row.getString(\"NARE\"));\n //NOTET\n task.setText(1, row.getString(\"UNIQUE_TASK_ID\"));\n task.setCalendar(m_project.getCalendarByUniqueID(row.getInteger(\"CALENDAU\")));\n //EFFORT_TIMI_UNIT\n //WORL_UNIT\n //LATEST_ALLOC_PROGRESS_PERIOD\n //WORN\n //CONSTRAINU\n //PRIORITB\n //CRITICAM\n //USE_PARENU_CALENDAR\n //BUFFER_TASK\n //MARK_FOS_HIDING\n //OWNED_BY_TIMESHEEV_X\n //START_ON_NEX_DAY\n //LONGEST_PATH\n //DURATIOTTYPF\n //DURATIOTELA_MONTHS\n //DURATIOTHOURS\n //STARZ\n //ENJ\n //DURATION_TIMJ_UNIT\n //UNSCHEDULABLG\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n task.setDuration(Duration.getInstance(0, TimeUnit.HOURS));\n }", "public void copyTo(int start, int end, byte[] dest, int destPos) {\n // this.subSequence(start, end).copyTo(dest, destPos) would allocate another Bytes object\n arraycopy(start, dest, destPos, end - start);\n }", "private void registerRows() {\n\t\tfor (int i = 0; i < rows.length; i++) {\n\t\t\tDJCrosstabRow crosstabRow = rows[i];\n\n\t\t\tJRDesignCrosstabRowGroup ctRowGroup = new JRDesignCrosstabRowGroup();\n\n\t\t\tctRowGroup.setWidth(crosstabRow.getHeaderWidth());\n\n\t\t\tctRowGroup.setName(crosstabRow.getProperty().getProperty());\n\n\t\t\tJRDesignCrosstabBucket rowBucket = new JRDesignCrosstabBucket();\n\n //New in JR 4.1+\n rowBucket.setValueClassName(crosstabRow.getProperty().getValueClassName());\n\n\t\t\tctRowGroup.setBucket(rowBucket);\n\n\t\t\tJRDesignExpression bucketExp = ExpressionUtils.createExpression(\"$F{\"+crosstabRow.getProperty().getProperty()+\"}\", crosstabRow.getProperty().getValueClassName());\n\t\t\trowBucket.setExpression(bucketExp);\n\n\n\t\t\tJRDesignCellContents rowHeaderContents = new JRDesignCellContents();\n\t\t\tJRDesignTextField rowTitle = new JRDesignTextField();\n\n\t\t\tJRDesignExpression rowTitExp = new JRDesignExpression();\n\t\t\trowTitExp.setValueClassName(crosstabRow.getProperty().getValueClassName());\n\t\t\trowTitExp.setText(\"$V{\"+crosstabRow.getProperty().getProperty()+\"}\");\n\n\t\t\trowTitle.setExpression(rowTitExp);\n\t\t\trowTitle.setWidth(crosstabRow.getHeaderWidth());\n\n\t\t\t//The width can be the sum of the with of all the rows starting from the current one, up to the inner most one.\n\t\t\tint auxHeight = getRowHeaderMaxHeight(crosstabRow);\n//\t\t\tint auxHeight = crosstabRow.getHeight(); //FIXME getRowHeaderMaxHeight() must be FIXED because it breaks when 1rs row shows total and 2nd doesn't\n\t\t\trowTitle.setHeight(auxHeight);\n\n\t\t\tStyle headerstyle = crosstabRow.getHeaderStyle() == null ? this.djcross.getRowHeaderStyle(): crosstabRow.getHeaderStyle();\n\n\t\t\tif (headerstyle != null){\n\t\t\t\tlayoutManager.applyStyleToElement(headerstyle, rowTitle);\n\t\t\t\trowHeaderContents.setBackcolor(headerstyle.getBackgroundColor());\n\t\t\t}\n\n\t\t\trowHeaderContents.addElement(rowTitle);\n\t\t\trowHeaderContents.setMode( ModeEnum.OPAQUE );\n\n\t\t\tboolean fullBorder = i <= 0; //Only outer most will have full border\n\t\t\tapplyCellBorder(rowHeaderContents, false, fullBorder);\n\n\t\t\tctRowGroup.setHeader(rowHeaderContents );\n\n\t\t\tif (crosstabRow.isShowTotals())\n\t\t\t\tcreateRowTotalHeader(ctRowGroup,crosstabRow,fullBorder);\n\n\n\t\t\ttry {\n\t\t\t\tjrcross.addRowGroup(ctRowGroup);\n\t\t\t} catch (JRException e) {\n\t\t\t\tlog.error(e.getMessage(),e);\n\t\t\t}\n\n\t\t}\n\t}", "public static void main(String[] args) {\n try {\n new StartMain(args).go();\n } catch(Throwable t) {\n WeldSELogger.LOG.error(\"Application exited with an exception\", t);\n System.exit(1);\n }\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public static NotificationInfo getNotificationInfo(final Bundle extras) {\n if (extras == null) return new NotificationInfo(false, false);\n\n boolean fromCleverTap = extras.containsKey(Constants.NOTIFICATION_TAG);\n boolean shouldRender = fromCleverTap && extras.containsKey(\"nm\");\n return new NotificationInfo(fromCleverTap, shouldRender);\n }", "private void sendEmptyRequest(String path, String method) throws DatastoreEmulatorException {\n HttpURLConnection connection = null;\n try {\n URL url = new URL(this.host + path);\n connection = (HttpURLConnection) url.openConnection();\n connection.setDoOutput(true);\n connection.setRequestMethod(method);\n connection.getOutputStream().close();\n if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {\n throw new DatastoreEmulatorException(\n String.format(\n \"%s request to %s returned HTTP status %s\",\n method, path, connection.getResponseCode()));\n }\n } catch (IOException e) {\n throw new DatastoreEmulatorException(\n String.format(\"Exception connecting to emulator on %s request to %s\", method, path), e);\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n }", "protected String calculateNextVersion(String fromVersion) {\n // first turn it to release version\n fromVersion = calculateReleaseVersion(fromVersion);\n String nextVersion;\n int lastDotIndex = fromVersion.lastIndexOf('.');\n try {\n if (lastDotIndex != -1) {\n // probably a major minor version e.g., 2.1.1\n String minorVersionToken = fromVersion.substring(lastDotIndex + 1);\n String nextMinorVersion;\n int lastDashIndex = minorVersionToken.lastIndexOf('-');\n if (lastDashIndex != -1) {\n // probably a minor-buildNum e.g., 2.1.1-4 (should change to 2.1.1-5)\n String buildNumber = minorVersionToken.substring(lastDashIndex + 1);\n int nextBuildNumber = Integer.parseInt(buildNumber) + 1;\n nextMinorVersion = minorVersionToken.substring(0, lastDashIndex + 1) + nextBuildNumber;\n } else {\n nextMinorVersion = Integer.parseInt(minorVersionToken) + 1 + \"\";\n }\n nextVersion = fromVersion.substring(0, lastDotIndex + 1) + nextMinorVersion;\n } else {\n // maybe it's just a major version; try to parse as an int\n int nextMajorVersion = Integer.parseInt(fromVersion) + 1;\n nextVersion = nextMajorVersion + \"\";\n }\n } catch (NumberFormatException e) {\n return fromVersion;\n }\n return nextVersion + \"-SNAPSHOT\";\n }" ]
Determines whether the current object on the specified level has a specific property, and if so, processes the template @param template The template @param attributes The attributes of the tag @exception XDocletException If an error occurs @doc.tag type="block" @doc.param name="level" optional="false" description="The level for the current object" values="class,field,reference,collection" @doc.param name="name" optional="false" description="The name of the property"
[ "public void ifHasProperty(String template, Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n\r\n if (value != null)\r\n {\r\n generate(template);\r\n }\r\n }" ]
[ "public static List<File> listFilesByRegex(String regex, File... directories) {\n return listFiles(directories,\n new RegexFileFilter(regex),\n CanReadFileFilter.CAN_READ);\n }", "public ParallelTaskBuilder setReplaceVarMapToSingleTargetFromMap(\n Map<String, StrStrMap> replacementVarMapNodeSpecific,\n String uniformTargetHost) {\n setReplacementVarMapNodeSpecific(replacementVarMapNodeSpecific);\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skip setting.\");\n return this;\n }\n for (Entry<String, StrStrMap> entry : replacementVarMapNodeSpecific\n .entrySet()) {\n\n if (entry.getValue() != null) {\n entry.getValue().addPair(PcConstants.UNIFORM_TARGET_HOST_VAR,\n uniformTargetHost);\n }\n }\n return this;\n }", "public static boolean containsAllQualifiers(Set<QualifierInstance> requiredQualifiers, Set<QualifierInstance> qualifiers) {\n return qualifiers.containsAll(requiredQualifiers);\n }", "public TimephasedWorkContainer getBaselineWork(ResourceAssignment assignment, ProjectCalendar calendar, TimephasedWorkNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedWorkContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedWork> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 8; // 8 byte header\n int blockSize = 40;\n double previousCumulativeWorkPerformedInMinutes = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n TimephasedWork work = null;\n\n while (index + blockSize <= data.length)\n {\n double cumulativeWorkInMinutes = (double) ((long) MPPUtility.getDouble(data, index + 20)) / 1000;\n if (!Duration.durationValueEquals(cumulativeWorkInMinutes, previousCumulativeWorkPerformedInMinutes))\n {\n //double unknownWorkThisPeriodInMinutes = ((long) MPPUtility.getDouble(data, index + 0)) / 1000;\n double normalActualWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 8)) / 10;\n double normalRemainingWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 28)) / 10;\n double workThisPeriodInMinutes = cumulativeWorkInMinutes - previousCumulativeWorkPerformedInMinutes;\n double overtimeWorkThisPeriodInMinutes = workThisPeriodInMinutes - (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n double overtimeFactor = overtimeWorkThisPeriodInMinutes / (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n\n double normalWorkPerDayInMinutes = 480;\n double overtimeWorkPerDayInMinutes = normalWorkPerDayInMinutes * overtimeFactor;\n\n work = new TimephasedWork();\n work.setFinish(MPPUtility.getTimestampFromTenths(data, index + 16));\n work.setStart(blockStartDate);\n work.setTotalAmount(Duration.getInstance(workThisPeriodInMinutes, TimeUnit.MINUTES));\n work.setAmountPerDay(Duration.getInstance(normalWorkPerDayInMinutes + overtimeWorkPerDayInMinutes, TimeUnit.MINUTES));\n\n previousCumulativeWorkPerformedInMinutes = cumulativeWorkInMinutes;\n\n if (list == null)\n {\n list = new LinkedList<TimephasedWork>();\n }\n list.add(work);\n //System.out.println(work);\n }\n blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n }\n\n if (list != null)\n {\n if (work != null)\n {\n work.setFinish(assignment.getFinish());\n }\n result = new DefaultTimephasedWorkContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }", "public void setRowReader(String newReaderClassName)\r\n {\r\n try\r\n {\r\n m_rowReader =\r\n (RowReader) ClassHelper.newInstance(\r\n newReaderClassName,\r\n ClassDescriptor.class,\r\n this);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Instantiating of current set RowReader failed\", e);\r\n }\r\n }", "public static String renderJson(Object o) {\n\n Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()\n .create();\n return gson.toJson(o);\n }", "public B set(String key, int value) {\n this.data.put(key, value);\n return (B) this;\n }", "private void handleChange(Object propertyId) {\n\n if (!m_saveBtn.isEnabled()) {\n m_saveBtn.setEnabled(true);\n m_saveExitBtn.setEnabled(true);\n }\n m_model.handleChange(propertyId);\n\n }", "public static void main(String[] args) throws ParseException, IOException {\n\t\tClient client = new Client(\n\t\t\t\tnew DumpProcessingController(\"wikidatawiki\"), args);\n\t\tclient.performActions();\n\t}" ]
Appends the given string to the given StringBuilder, replacing '&amp;', '&lt;' and '&gt;' by their respective HTML entities. @param out The StringBuilder to append to. @param value The string to append. @param offset The character offset into value from where to start
[ "public final static void codeEncode(final StringBuilder out, final String value, final int offset)\n {\n for (int i = offset; i < value.length(); i++)\n {\n final char c = value.charAt(i);\n switch (c)\n {\n case '&':\n out.append(\"&amp;\");\n break;\n case '<':\n out.append(\"&lt;\");\n break;\n case '>':\n out.append(\"&gt;\");\n break;\n default:\n out.append(c);\n }\n }\n }" ]
[ "private String getCurrencyFormat(CurrencySymbolPosition position)\n {\n String result;\n\n switch (position)\n {\n case AFTER:\n {\n result = \"1.1#\";\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n result = \"1.1 #\";\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n result = \"# 1.1\";\n break;\n }\n\n default:\n case BEFORE:\n {\n result = \"#1.1\";\n break;\n }\n }\n\n return result;\n }", "protected void parseLinks(CmsObject cms) throws CmsException {\n\n List<CmsResource> linkParseables = new ArrayList<>();\n for (CmsResourceImportData resData : m_moduleData.getResourceData()) {\n CmsResource importRes = resData.getImportResource();\n if ((importRes != null) && m_importIds.contains(importRes.getStructureId()) && isLinkParsable(importRes)) {\n linkParseables.add(importRes);\n }\n }\n m_report.println(Messages.get().container(Messages.RPT_START_PARSE_LINKS_0), I_CmsReport.FORMAT_HEADLINE);\n CmsImportVersion10.parseLinks(cms, linkParseables, m_report);\n m_report.println(Messages.get().container(Messages.RPT_END_PARSE_LINKS_0), I_CmsReport.FORMAT_HEADLINE);\n }", "public static Node removePartitionFromNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition));\n }", "public static String getTokenText(INode node) {\n\t\tif (node instanceof ILeafNode)\n\t\t\treturn ((ILeafNode) node).getText();\n\t\telse {\n\t\t\tStringBuilder builder = new StringBuilder(Math.max(node.getTotalLength(), 1));\n\t\t\tboolean hiddenSeen = false;\n\t\t\tfor (ILeafNode leaf : node.getLeafNodes()) {\n\t\t\t\tif (!leaf.isHidden()) {\n\t\t\t\t\tif (hiddenSeen && builder.length() > 0)\n\t\t\t\t\t\tbuilder.append(' ');\n\t\t\t\t\tbuilder.append(leaf.getText());\n\t\t\t\t\thiddenSeen = false;\n\t\t\t\t} else {\n\t\t\t\t\thiddenSeen = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn builder.toString();\n\t\t}\n\t}", "public ServerGroup addServerGroup(String groupName) {\n ServerGroup group = new ServerGroup();\n\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", groupName),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP, params));\n group = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return group;\n }", "public static DataPersister lookupForField(Field field) {\n\n\t\t// see if the any of the registered persisters are valid first\n\t\tif (registeredPersisters != null) {\n\t\t\tfor (DataPersister persister : registeredPersisters) {\n\t\t\t\tif (persister.isValidForField(field)) {\n\t\t\t\t\treturn persister;\n\t\t\t\t}\n\t\t\t\t// check the classes instead\n\t\t\t\tfor (Class<?> clazz : persister.getAssociatedClasses()) {\n\t\t\t\t\tif (field.getType() == clazz) {\n\t\t\t\t\t\treturn persister;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// look it up in our built-in map by class\n\t\tDataPersister dataPersister = builtInMap.get(field.getType().getName());\n\t\tif (dataPersister != null) {\n\t\t\treturn dataPersister;\n\t\t}\n\n\t\t/*\n\t\t * Special case for enum types. We can't put this in the registered persisters because we want people to be able\n\t\t * to override it.\n\t\t */\n\t\tif (field.getType().isEnum()) {\n\t\t\treturn DEFAULT_ENUM_PERSISTER;\n\t\t} else {\n\t\t\t/*\n\t\t\t * Serializable classes return null here because we don't want them to be automatically configured for\n\t\t\t * forwards compatibility with future field types that happen to be Serializable.\n\t\t\t */\n\t\t\treturn null;\n\t\t}\n\t}", "public static String determineAccessorName(@Nonnull final AccessorPrefix prefix, @Nonnull final String fieldName) {\n\t\tCheck.notNull(prefix, \"prefix\");\n\t\tCheck.notEmpty(fieldName, \"fieldName\");\n\t\tfinal Matcher m = PATTERN.matcher(fieldName);\n\t\tCheck.stateIsTrue(m.find(), \"passed field name '%s' is not applicable\", fieldName);\n\t\tfinal String name = m.group();\n\t\treturn prefix.getPrefix() + name.substring(0, 1).toUpperCase() + name.substring(1);\n\t}", "public static ModelMBeanOperationInfo[] extractOperationInfo(Object object) {\n ArrayList<ModelMBeanOperationInfo> infos = new ArrayList<ModelMBeanOperationInfo>();\n for(Method m: object.getClass().getMethods()) {\n JmxOperation jmxOperation = m.getAnnotation(JmxOperation.class);\n JmxGetter jmxGetter = m.getAnnotation(JmxGetter.class);\n JmxSetter jmxSetter = m.getAnnotation(JmxSetter.class);\n if(jmxOperation != null || jmxGetter != null || jmxSetter != null) {\n String description = \"\";\n int visibility = 1;\n int impact = MBeanOperationInfo.UNKNOWN;\n if(jmxOperation != null) {\n description = jmxOperation.description();\n impact = jmxOperation.impact();\n } else if(jmxGetter != null) {\n description = jmxGetter.description();\n impact = MBeanOperationInfo.INFO;\n visibility = 4;\n } else if(jmxSetter != null) {\n description = jmxSetter.description();\n impact = MBeanOperationInfo.ACTION;\n visibility = 4;\n }\n ModelMBeanOperationInfo info = new ModelMBeanOperationInfo(m.getName(),\n description,\n extractParameterInfo(m),\n m.getReturnType()\n .getName(), impact);\n info.getDescriptor().setField(\"visibility\", Integer.toString(visibility));\n infos.add(info);\n }\n }\n\n return infos.toArray(new ModelMBeanOperationInfo[infos.size()]);\n }", "public IntBuffer getIntVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n IntBuffer data = buffer.asIntBuffer();\n if (!NativeVertexBuffer.getIntVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }" ]
Filter that's either negated or normal as specified.
[ "public static <E> Filter<E> switchedFilter(Filter<E> filter, boolean negated) {\r\n return (new NegatedFilter<E>(filter, negated));\r\n }" ]
[ "public static sslocspresponder get(nitro_service service, String name) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tobj.set_name(name);\n\t\tsslocspresponder response = (sslocspresponder) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void parseResponse(InputStream inputStream) {\n\n try {\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(inputStream);\n doc.getDocumentElement().normalize();\n\n NodeList nodes = doc.getElementsByTagName(\"place\");\n\n for (int i = 0; i < nodes.getLength(); i++) {\n Node node = nodes.item(i);\n\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element element = (Element) node;\n _woeid = getValue(\"woeid\", element);\n }\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }", "private String getProjectName() {\n String pName = Strings.emptyToNull(projectName);\n if (pName == null) { \n pName = Strings.emptyToNull(junit4.getProject().getName());\n }\n if (pName == null) {\n pName = \"(unnamed project)\"; \n }\n return pName;\n }", "protected void updateModel(final ModelNode operation, final Resource resource) throws OperationFailedException {\n updateModel(operation, resource.getModel());\n }", "void backupConfiguration() throws IOException {\n\n final String configuration = Constants.CONFIGURATION;\n\n final File a = new File(installedImage.getAppClientDir(), configuration);\n final File d = new File(installedImage.getDomainDir(), configuration);\n final File s = new File(installedImage.getStandaloneDir(), configuration);\n\n if (a.exists()) {\n final File ab = new File(configBackup, Constants.APP_CLIENT);\n backupDirectory(a, ab);\n }\n if (d.exists()) {\n final File db = new File(configBackup, Constants.DOMAIN);\n backupDirectory(d, db);\n }\n if (s.exists()) {\n final File sb = new File(configBackup, Constants.STANDALONE);\n backupDirectory(s, sb);\n }\n\n }", "public static nsrpcnode[] get(nitro_service service, String ipaddress[]) throws Exception{\n\t\tif (ipaddress !=null && ipaddress.length>0) {\n\t\t\tnsrpcnode response[] = new nsrpcnode[ipaddress.length];\n\t\t\tnsrpcnode obj[] = new nsrpcnode[ipaddress.length];\n\t\t\tfor (int i=0;i<ipaddress.length;i++) {\n\t\t\t\tobj[i] = new nsrpcnode();\n\t\t\t\tobj[i].set_ipaddress(ipaddress[i]);\n\t\t\t\tresponse[i] = (nsrpcnode) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public InsertIntoTable set(String name, Object value) {\n builder.set(name, value);\n return this;\n }", "protected synchronized ResourceRoot getSeamIntResourceRoot() throws DeploymentUnitProcessingException {\n try {\n if (seamIntResourceRoot == null) {\n final ModuleLoader moduleLoader = Module.getBootModuleLoader();\n Module extModule = moduleLoader.loadModule(EXT_CONTENT_MODULE);\n URL url = extModule.getExportedResource(SEAM_INT_JAR);\n if (url == null)\n throw ServerLogger.ROOT_LOGGER.noSeamIntegrationJarPresent(extModule);\n\n File file = new File(url.toURI());\n VirtualFile vf = VFS.getChild(file.toURI());\n final Closeable mountHandle = VFS.mountZip(file, vf, TempFileProviderService.provider());\n Service<Closeable> mountHandleService = new Service<Closeable>() {\n public void start(StartContext startContext) throws StartException {\n }\n\n public void stop(StopContext stopContext) {\n VFSUtils.safeClose(mountHandle);\n }\n\n public Closeable getValue() throws IllegalStateException, IllegalArgumentException {\n return mountHandle;\n }\n };\n ServiceBuilder<Closeable> builder = serviceTarget.addService(ServiceName.JBOSS.append(SEAM_INT_JAR),\n mountHandleService);\n builder.setInitialMode(ServiceController.Mode.ACTIVE).install();\n serviceTarget = null; // our cleanup service install work is done\n\n MountHandle dummy = MountHandle.create(null); // actual close is done by the MSC service above\n seamIntResourceRoot = new ResourceRoot(vf, dummy);\n }\n return seamIntResourceRoot;\n } catch (Exception e) {\n throw new DeploymentUnitProcessingException(e);\n }\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public synchronized void pushInstallReferrer(String source, String medium, String campaign) {\n if (source == null && medium == null && campaign == null) return;\n try {\n // If already pushed, don't send it again\n int status = StorageHelper.getInt(context, \"app_install_status\", 0);\n if (status != 0) {\n Logger.d(\"Install referrer has already been set. Will not override it\");\n return;\n }\n StorageHelper.putInt(context, \"app_install_status\", 1);\n\n if (source != null) source = Uri.encode(source);\n if (medium != null) medium = Uri.encode(medium);\n if (campaign != null) campaign = Uri.encode(campaign);\n\n String uriStr = \"wzrk://track?install=true\";\n if (source != null) uriStr += \"&utm_source=\" + source;\n if (medium != null) uriStr += \"&utm_medium=\" + medium;\n if (campaign != null) uriStr += \"&utm_campaign=\" + campaign;\n\n Uri uri = Uri.parse(uriStr);\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n Logger.v(\"Failed to push install referrer\", t);\n }\n }" ]
Return the factor loading for a given time and a given component. The factor loading is the vector <i>f<sub>i</sub></i> such that the scalar product <br> <i>f<sub>j</sub>f<sub>k</sub> = f<sub>j,1</sub>f<sub>k,1</sub> + ... + f<sub>j,m</sub>f<sub>k,m</sub></i> <br> is the instantaneous covariance of the component <i>j</i> and <i>k</i>. With respect to simulation time <i>t</i>, this method uses a piece wise constant interpolation, i.e., it calculates <i>t_<sub>i</sub></i> such that <i>t_<sub>i</sub></i> is the largest point in <code>getTimeDiscretization</code> such that <i>t_<sub>i</sub> &le; t </i>. The component here, it given via a double <i>T</i> which may be associated with the LIBOR fixing date. With respect to component time <i>T</i>, this method uses a piece wise constant interpolation, i.e., it calculates <i>T_<sub>j</sub></i> such that <i>T_<sub>j</sub></i> is the largest point in <code>getTimeDiscretization</code> such that <i>T_<sub>j</sub> &le; T </i>. @param time The time <i>t</i> at which factor loading is requested. @param component The component time (as a double associated with the fixing of the forward rate) <i>T<sub>i</sub></i>. @param realizationAtTimeIndex The realization of the stochastic process (may be used to implement local volatility/covariance/correlation models). @return The factor loading <i>f<sub>i</sub>(t)</i>.
[ "public\tRandomVariableInterface[]\tgetFactorLoading(double time, double component, RandomVariableInterface[] realizationAtTimeIndex) {\n\t\tint componentIndex = liborPeriodDiscretization.getTimeIndex(component);\n\t\tif(componentIndex < 0) {\n\t\t\tcomponentIndex = -componentIndex - 2;\n\t\t}\n\t\treturn getFactorLoading(time, componentIndex, realizationAtTimeIndex);\n\t}" ]
[ "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 }", "public static void popShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.size() > 0) {\n shells.remove(shells.size() - 1);\n }\n\n }", "private List<TokenStream> collectTokenStreams(TokenStream stream) {\n \n // walk through the token stream and build a collection \n // of sub token streams that represent possible date locations\n List<Token> currentGroup = null;\n List<List<Token>> groups = new ArrayList<List<Token>>();\n Token currentToken;\n int currentTokenType;\n StringBuilder tokenString = new StringBuilder();\n while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) {\n currentTokenType = currentToken.getType();\n tokenString.append(DateParser.tokenNames[currentTokenType]).append(\" \");\n\n // we're currently NOT collecting for a possible date group\n if(currentGroup == null) {\n // skip over white space and known tokens that cannot be the start of a date\n if(currentTokenType != DateLexer.WHITE_SPACE &&\n DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) {\n\n currentGroup = new ArrayList<Token>();\n currentGroup.add(currentToken);\n }\n }\n\n // we're currently collecting\n else {\n // preserve white space\n if(currentTokenType == DateLexer.WHITE_SPACE) {\n currentGroup.add(currentToken);\n }\n\n else {\n // if this is an unknown token, we'll close out the current group\n if(currentTokenType == DateLexer.UNKNOWN) {\n addGroup(currentGroup, groups);\n currentGroup = null;\n }\n // otherwise, the token is known and we're currently collecting for\n // a group, so we'll add it to the current group\n else {\n currentGroup.add(currentToken);\n }\n }\n }\n }\n\n if(currentGroup != null) {\n addGroup(currentGroup, groups);\n }\n \n _logger.info(\"STREAM: \" + tokenString.toString());\n List<TokenStream> streams = new ArrayList<TokenStream>();\n for(List<Token> group:groups) {\n if(!group.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"GROUP: \");\n for (Token token : group) {\n builder.append(DateParser.tokenNames[token.getType()]).append(\" \");\n }\n _logger.info(builder.toString());\n\n streams.add(new CommonTokenStream(new NattyTokenSource(group)));\n }\n }\n\n return streams;\n }", "public void registerDestructionCallback(String name, Runnable callback) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\tbean = new Bean();\n\t\t\tbeans.put(name, bean);\n\t\t}\n\t\tbean.destructionCallback = callback;\n\t}", "public <T extends OutputStream> T write(T os) throws IOException {\n close();\n\n if (!(this.os instanceof ByteArrayOutputStream))\n throw new IllegalStateException(\"Cannot write to another target if setOutputStream has been called\");\n final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray();\n\n if (packer != null)\n packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os);\n else\n os.write(content);\n\n os.close();\n return os;\n }", "private void addMembersInclSupertypes(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n addMembers(memberNames, members, type, tagName, paramName, paramValue);\r\n if (type.getInterfaces() != null) {\r\n for (Iterator it = type.getInterfaces().iterator(); it.hasNext(); ) {\r\n addMembersInclSupertypes(memberNames, members, (XClass)it.next(), tagName, paramName, paramValue);\r\n }\r\n }\r\n if (!type.isInterface() && (type.getSuperclass() != null)) {\r\n addMembersInclSupertypes(memberNames, members, type.getSuperclass(), tagName, paramName, paramValue);\r\n }\r\n }", "public void addItem(T value, String text, boolean reload) {\n values.add(value);\n listBox.addItem(text, keyFactory.generateKey(value));\n\n if (reload) {\n reload();\n }\n }", "public DbOrganization getMatchingOrganization(final DbModule dbModule) {\n if(dbModule.getOrganization() != null\n && !dbModule.getOrganization().isEmpty()){\n return getOrganization(dbModule.getOrganization());\n }\n\n for(final DbOrganization organization: repositoryHandler.getAllOrganizations()){\n final CorporateFilter corporateFilter = new CorporateFilter(organization);\n if(corporateFilter.matches(dbModule)){\n return organization;\n }\n }\n\n return null;\n }", "public AutomatonInstance doClone() {\n\t\tAutomatonInstance clone = new AutomatonInstance(this.automatonEng, this.current, this.instanceId, this.safeGuard);\n\t\tclone.failed = this.failed;\n\t\tclone.transitionCount = this.transitionCount;\n\t\tclone.failCount = this.failCount;\n\t\tclone.iterateCount = this.iterateCount;\n\t\tclone.backtrackCount = this.backtrackCount;\n\t\tclone.trace = new LinkedList<>();\n\t\tfor(StateExploration se:this.trace) {\n\t\t\tclone.trace.add(se.doClone());\n\t\t}\n\t\treturn clone;\n\t}" ]
If the burst mode is on, emit the particles only once. @param particlePositions @param particleVelocities @param particleTimeStamps
[ "protected void emitWithBurstCheck(float[] particlePositions, float[] particleVelocities,\n float[] particleTimeStamps)\n {\n if ( burstMode )\n {\n if ( executeOnce )\n {\n emit(particlePositions, particleVelocities, particleTimeStamps);\n executeOnce = false;\n }\n }\n else\n {\n emit(particlePositions, particleVelocities, particleTimeStamps);\n }\n\n }" ]
[ "public OJBLock atomicGetOrCreateLock(Object resourceId, Object isolationId)\r\n {\r\n synchronized(globalLocks)\r\n {\r\n MultiLevelLock lock = getLock(resourceId);\r\n if(lock == null)\r\n {\r\n lock = createLock(resourceId, isolationId);\r\n }\r\n return (OJBLock) lock;\r\n }\r\n }", "public static InstalledIdentity load(final InstalledImage installedImage, final ProductConfig productConfig, List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n return LayersFactory.load(installedImage, productConfig, moduleRoots, bundleRoots);\n }", "protected void switchTab() {\n\n Component tab = m_tab.getSelectedTab();\n int pos = m_tab.getTabPosition(m_tab.getTab(tab));\n if (m_isWebOU) {\n if (pos == 0) {\n pos = 1;\n }\n }\n m_tab.setSelectedTab(pos + 1);\n }", "public static base_response clear(nitro_service client) throws Exception {\n\t\tnspbr6 clearresource = new nspbr6();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public void setWorkingDay(Day day, DayType working)\n {\n DayType value;\n\n if (working == null)\n {\n if (isDerived())\n {\n value = DayType.DEFAULT;\n }\n else\n {\n value = DayType.WORKING;\n }\n }\n else\n {\n value = working;\n }\n\n m_days[day.getValue() - 1] = value;\n }", "@Override\n\tpublic void add(String headerName, String headerValue) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\tif (headerValues == null) {\n\t\t\theaderValues = new LinkedList<String>();\n\t\t\tthis.headers.put(headerName, headerValues);\n\t\t}\n\t\theaderValues.add(headerValue);\n\t}", "public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = _table.getColumn((String)objA).getProperty(\"id\");\r\n String idBStr = _table.getColumn((String)objB).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex) {\r\n return 1;\r\n }\r\n try {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex) {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }", "public void setNearClippingDistance(float near) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near);\n centerCamera.setNearClippingDistance(near);\n ((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near);\n }\n }", "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 }" ]
refresh all deliveries dependencies for a particular product
[ "public void work(RepositoryHandler repoHandler, DbProduct product) {\n if (!product.getDeliveries().isEmpty()) {\n\n product.getDeliveries().forEach(delivery -> {\n\n final Set<Artifact> artifacts = new HashSet<>();\n\n final DataFetchingUtils utils = new DataFetchingUtils();\n final DependencyHandler depHandler = new DependencyHandler(repoHandler);\n final Set<String> deliveryDependencies = utils.getDeliveryDependencies(repoHandler, depHandler, delivery);\n\n final Set<String> fullGAVCSet = deliveryDependencies.stream().filter(DataUtils::isFullGAVC).collect(Collectors.toSet());\n final Set<String> shortIdentiferSet = deliveryDependencies.stream().filter(entry -> !DataUtils.isFullGAVC(entry)).collect(Collectors.toSet());\n\n\n processDependencySet(repoHandler,\n shortIdentiferSet,\n batch -> String.format(BATCH_TEMPLATE_REGEX, StringUtils.join(batch, '|')),\n 1,\n artifacts::add\n );\n\n processDependencySet(repoHandler,\n fullGAVCSet,\n batch -> QueryUtils.quoteIds(batch, BATCH_TEMPLATE),\n 10,\n artifacts::add\n );\n\n if (!artifacts.isEmpty()) {\n delivery.setAllArtifactDependencies(new ArrayList<>(artifacts));\n }\n });\n\n repoHandler.store(product);\n }\n }" ]
[ "private <T> MongoCollection<T> getLocalCollection(\n final MongoNamespace namespace,\n final Class<T> resultClass,\n final CodecRegistry codecRegistry\n ) {\n return localClient\n .getDatabase(String.format(\"sync_user_%s\", namespace.getDatabaseName()))\n .getCollection(namespace.getCollectionName(), resultClass)\n .withCodecRegistry(codecRegistry);\n }", "protected void processAliases(List<MonolingualTextValue> addAliases, List<MonolingualTextValue> deleteAliases) {\n for(MonolingualTextValue val : addAliases) {\n addAlias(val);\n }\n for(MonolingualTextValue val : deleteAliases) {\n deleteAlias(val);\n }\n }", "public V get(K key) {\n ManagedReference<V> ref = internalMap.get(key);\n if (ref!=null) return ref.get();\n return null;\n }", "public int evaluate(FieldContainer container)\n {\n //\n // First step - determine the list of criteria we are should use\n //\n List<GraphicalIndicatorCriteria> criteria;\n if (container instanceof Task)\n {\n Task task = (Task) container;\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n if (m_projectSummaryInheritsFromSummaryRows == false)\n {\n criteria = m_projectSummaryCriteria;\n }\n else\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n if (task.getSummary() == true)\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n // It is possible to have a resource summary row, but at the moment\n // I can't see how you can determine this.\n criteria = m_nonSummaryRowCriteria;\n }\n\n //\n // Now we have the criteria, evaluate each one until we get a result\n //\n int result = -1;\n for (GraphicalIndicatorCriteria gic : criteria)\n {\n result = gic.evaluate(container);\n if (result != -1)\n {\n break;\n }\n }\n\n //\n // If we still don't have a result at the end, return the\n // default value, which is 0\n //\n if (result == -1)\n {\n result = 0;\n }\n\n return (result);\n }", "private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName,\r\n\t\t\tDayCountConvention daycountConvention) {\r\n\r\n\t\tboolean isFixed = leg.getElementsByTagName(\"interestType\").item(0).getTextContent().equalsIgnoreCase(\"FIX\");\r\n\r\n\t\tArrayList<Period> periods \t\t= new ArrayList<>();\r\n\t\tArrayList<Double> notionalsList\t= new ArrayList<>();\r\n\t\tArrayList<Double> rates\t\t\t= new ArrayList<>();\r\n\r\n\t\t//extracting data for each period\r\n\t\tNodeList periodsXML = leg.getElementsByTagName(\"incomePayment\");\r\n\t\tfor(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) {\r\n\r\n\t\t\tElement periodXML = (Element) periodsXML.item(periodIndex);\r\n\r\n\t\t\tLocalDate startDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"startDate\").item(0).getTextContent());\r\n\t\t\tLocalDate endDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"endDate\").item(0).getTextContent());\r\n\r\n\t\t\tLocalDate fixingDate\t= startDate;\r\n\t\t\tLocalDate paymentDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"payDate\").item(0).getTextContent());\r\n\r\n\t\t\tif(! isFixed) {\r\n\t\t\t\tfixingDate = LocalDate.parse(periodXML.getElementsByTagName(\"fixingDate\").item(0).getTextContent());\r\n\t\t\t}\r\n\r\n\t\t\tperiods.add(new Period(fixingDate, paymentDate, startDate, endDate));\r\n\r\n\t\t\tdouble notional\t\t= Double.parseDouble(periodXML.getElementsByTagName(\"nominal\").item(0).getTextContent());\r\n\t\t\tnotionalsList.add(new Double(notional));\r\n\r\n\t\t\tif(isFixed) {\r\n\t\t\t\tdouble fixedRate\t= Double.parseDouble(periodXML.getElementsByTagName(\"fixedRate\").item(0).getTextContent());\r\n\t\t\t\trates.add(new Double(fixedRate));\r\n\t\t\t} else {\r\n\t\t\t\trates.add(new Double(0));\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention);\r\n\t\tdouble[] notionals\t= notionalsList.stream().mapToDouble(Double::doubleValue).toArray();\r\n\t\tdouble[] spreads\t= rates.stream().mapToDouble(Double::doubleValue).toArray();\r\n\r\n\t\treturn new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false);\r\n\t}", "private static Point findMidnormalPoint(Point center, Point a, Point b, Rect area, int radius) {\n if (a.y == b.y) {\n //top\n if (a.y < center.y) {\n return new Point((a.x + b.x) / 2, center.y + radius);\n }\n //bottom\n return new Point((a.x + b.x) / 2, center.y - radius);\n }\n if (a.x == b.x) {\n //left\n if (a.x < center.x) {\n return new Point(center.x + radius, (a.y + b.y) / 2);\n }\n //right\n return new Point(center.x - radius, (a.y + b.y) / 2);\n }\n //slope of line ab\n double abSlope = (a.y - b.y) / (a.x - b.x * 1.0);\n //slope of midnormal\n double midnormalSlope = -1.0 / abSlope;\n\n double radian = Math.tan(midnormalSlope);\n int dy = (int) (radius * Math.sin(radian));\n int dx = (int) (radius * Math.cos(radian));\n Point point = new Point(center.x + dx, center.y + dy);\n if (!inArea(point, area, 0)) {\n point = new Point(center.x - dx, center.y - dy);\n }\n return point;\n }", "public OperationTransformerEntry resolveOperationTransformer(final PathAddress address, final String operationName, PlaceholderResolver placeholderResolver) {\n final Iterator<PathElement> iterator = address.iterator();\n final OperationTransformerEntry entry = resolveOperationTransformer(iterator, operationName, placeholderResolver);\n if(entry != null) {\n return entry;\n }\n // Default is forward unchanged\n return FORWARD;\n }", "public static <T> void callInitializers(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends MethodInjectionPoint<?, ?>> initializerMethods) {\n for (MethodInjectionPoint<?, ?> initializer : initializerMethods) {\n initializer.invoke(instance, null, manager, creationalContext, CreationException.class);\n }\n }", "public static void initialize(final Context context) {\n if (!initialized.compareAndSet(false, true)) {\n return;\n }\n\n applicationContext = context.getApplicationContext();\n\n final String packageName = applicationContext.getPackageName();\n localAppName = packageName;\n\n final PackageManager manager = applicationContext.getPackageManager();\n try {\n final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);\n localAppVersion = pkgInfo.versionName;\n } catch (final NameNotFoundException e) {\n Log.d(TAG, \"Failed to get version of application, will not send in device info.\");\n }\n\n Log.d(TAG, \"Initialized android SDK\");\n }" ]
Gets the registration point that been associated with the registration for the longest period. @return the initial registration point, or {@code null} if there are no longer any registration points
[ "public synchronized RegistrationPoint getOldestRegistrationPoint() {\n return registrationPoints.size() == 0 ? null : registrationPoints.values().iterator().next().get(0);\n }" ]
[ "private static BufferedImage scale(BufferedImage imageToScale, int dWidth, int dHeight, double fWidth, double fHeight) {\n BufferedImage dbi = null;\n // Needed to create a new BufferedImage object\n int imageType = imageToScale.getType();\n if (imageToScale != null) {\n dbi = new BufferedImage(dWidth, dHeight, imageType);\n Graphics2D g = dbi.createGraphics();\n AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight);\n g.drawRenderedImage(imageToScale, at);\n }\n return dbi;\n }", "public Set<ConstraintViolation> validate(DataSetInfo info) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\ttry {\r\n\t\t\tif (info.isMandatory() && get(info.getDataSetNumber()) == null) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.MANDATORY_MISSING));\r\n\t\t\t}\r\n\t\t\tif (!info.isRepeatable() && getAll(info.getDataSetNumber()).size() > 1) {\r\n\t\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.REPEATABLE_REPEATED));\r\n\t\t\t}\r\n\t\t} catch (SerializationException e) {\r\n\t\t\terrors.add(new ConstraintViolation(info, ConstraintViolation.INVALID_VALUE));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}", "public static void clear() {\n JobContext ctx = current_.get();\n if (null != ctx) {\n ctx.bag_.clear();\n JobContext parent = ctx.parent;\n if (null != parent) {\n current_.set(parent);\n ctx.parent = null;\n } else {\n current_.remove();\n Act.eventBus().trigger(new JobContextDestroyed(ctx));\n }\n }\n }", "protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }", "SimpleJsonEncoder appendToJSON(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n if (value instanceof Number) {\n sb.append(value.toString());\n } else {\n sb.append(QUOTE).append(escapeString(value.toString())).append(QUOTE);\n }\n }\n return this;\n }", "public ArrayList<Duration> segmentBaselineWork(ProjectFile file, List<TimephasedWork> work, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n return segmentWork(file.getBaselineCalendar(), work, rangeUnits, dateList);\n }", "public static gslbservice_stats[] get(nitro_service service) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tgslbservice_stats[] response = (gslbservice_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public MaterializeBuilder withActivity(Activity activity) {\n this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content);\n this.mActivity = activity;\n return this;\n }", "public static String nameFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).name() : null;\n }" ]
Look for the closing parenthesis corresponding to the one at position represented by the opening index. @param text input expression @param opening opening parenthesis index @return closing parenthesis index
[ "private int getClosingParenthesisPosition(String text, int opening)\n {\n if (text.charAt(opening) != '(')\n {\n return -1;\n }\n\n int count = 0;\n for (int i = opening; i < text.length(); i++)\n {\n char c = text.charAt(i);\n switch (c)\n {\n case '(':\n {\n ++count;\n break;\n }\n\n case ')':\n {\n --count;\n if (count == 0)\n {\n return i;\n }\n break;\n }\n }\n }\n\n return -1;\n }" ]
[ "public String getRelativePath() {\n final StringBuilder builder = new StringBuilder();\n for(final String p : path) {\n builder.append(p).append(\"/\");\n }\n builder.append(getName());\n return builder.toString();\n }", "public void insertValue(int index, float[] newValue) {\n if ( newValue.length == 2) {\n try {\n value.add( index, new SFVec2f(newValue[0], newValue[1]) );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFVec2f get1Value(index) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFVec2f get1Value(index) exception \" + e);\n }\n }\n else {\n Log.e(TAG, \"X3D MFVec2f insertValue set with array length not equal to 2\");\n }\n }", "public static String getJsonDatatypeFromDatatypeIri(String datatypeIri) {\n\t\tswitch (datatypeIri) {\n\t\t\tcase DatatypeIdValue.DT_ITEM:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_ITEM;\n\t\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_GLOBE_COORDINATES;\n\t\t\tcase DatatypeIdValue.DT_URL:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_URL;\n\t\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_COMMONS_MEDIA;\n\t\t\tcase DatatypeIdValue.DT_TIME:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_TIME;\n\t\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_QUANTITY;\n\t\t\tcase DatatypeIdValue.DT_STRING:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_STRING;\n\t\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_MONOLINGUAL_TEXT;\n\t\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_PROPERTY;\n\t\t\tdefault:\n\t\t\t\t//We apply the reverse algorithm of JacksonDatatypeId::getDatatypeIriFromJsonDatatype\n\t\t\t\tMatcher matcher = DATATYPE_ID_PATTERN.matcher(datatypeIri);\n\t\t\t\tif(!matcher.matches()) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Unknown datatype: \" + datatypeIri);\n\t\t\t\t}\n\t\t\n\t\t\t\tStringBuilder jsonDatatypeBuilder = new StringBuilder();\n\t\t\t\tfor(char ch : StringUtils.uncapitalize(matcher.group(1)).toCharArray()) {\n\t\t\t\t\tif(Character.isUpperCase(ch)) {\n\t\t\t\t\t\tjsonDatatypeBuilder\n\t\t\t\t\t\t\t\t.append('-')\n\t\t\t\t\t\t\t\t.append(Character.toLowerCase(ch));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjsonDatatypeBuilder.append(ch);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn jsonDatatypeBuilder.toString();\n\t\t}\n\t}", "private long getTime(Date start, Date end, long target, boolean after)\n {\n long total = 0;\n if (start != null && end != null)\n {\n Date startTime = DateHelper.getCanonicalTime(start);\n Date endTime = DateHelper.getCanonicalTime(end);\n\n Date startDay = DateHelper.getDayStartDate(start);\n Date finishDay = DateHelper.getDayStartDate(end);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n int diff = DateHelper.compare(startTime, endTime, target);\n if (diff == 0)\n {\n if (after == true)\n {\n total = (endTime.getTime() - target);\n }\n else\n {\n total = (target - startTime.getTime());\n }\n }\n else\n {\n if ((after == true && diff < 0) || (after == false && diff > 0))\n {\n total = (endTime.getTime() - startTime.getTime());\n }\n }\n }\n return (total);\n }", "public ItemRequest<Project> removeMembers(String project) {\n \n String path = String.format(\"/projects/%s/removeMembers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "public static ModelNode createListDeploymentsOperation() {\n final ModelNode op = createOperation(READ_CHILDREN_NAMES);\n op.get(CHILD_TYPE).set(DEPLOYMENT);\n return op;\n }", "@Deprecated\r\n private InputStream getImageAsStream(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImageAsStream(buffer.toString());\r\n }", "public static ModelNode createRemoveOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createRemoveOperation(address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }", "public static void printResults(Counter<String> entityTP, Counter<String> entityFP,\r\n Counter<String> entityFN) {\r\n Set<String> entities = new TreeSet<String>();\r\n entities.addAll(entityTP.keySet());\r\n entities.addAll(entityFP.keySet());\r\n entities.addAll(entityFN.keySet());\r\n boolean printedHeader = false;\r\n for (String entity : entities) {\r\n double tp = entityTP.getCount(entity);\r\n double fp = entityFP.getCount(entity);\r\n double fn = entityFN.getCount(entity);\r\n printedHeader = printPRLine(entity, tp, fp, fn, printedHeader);\r\n }\r\n double tp = entityTP.totalCount();\r\n double fp = entityFP.totalCount();\r\n double fn = entityFN.totalCount();\r\n printedHeader = printPRLine(\"Totals\", tp, fp, fn, printedHeader);\r\n }" ]
Extracts baseline cost from the MPP file for a specific baseline. Returns null if no baseline cost is present, otherwise returns a list of timephased work items. @param calendar baseline calendar @param normaliser normaliser associated with this data @param data timephased baseline work data block @param raw flag indicating if this data is to be treated as raw @return timephased work
[ "public TimephasedCostContainer getBaselineCost(ProjectCalendar calendar, TimephasedCostNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedCostContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedCost> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 16; // 16 byte header\n int blockSize = 20;\n double previousTotalCost = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n index += blockSize;\n\n while (index + blockSize <= data.length)\n {\n Date blockEndDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n double currentTotalCost = (double) ((long) MPPUtility.getDouble(data, index + 8)) / 100;\n if (!costEquals(previousTotalCost, currentTotalCost))\n {\n TimephasedCost cost = new TimephasedCost();\n cost.setStart(blockStartDate);\n cost.setFinish(blockEndDate);\n cost.setTotalAmount(Double.valueOf(currentTotalCost - previousTotalCost));\n\n if (list == null)\n {\n list = new LinkedList<TimephasedCost>();\n }\n list.add(cost);\n //System.out.println(cost);\n\n previousTotalCost = currentTotalCost;\n }\n\n blockStartDate = blockEndDate;\n index += blockSize;\n }\n\n if (list != null)\n {\n result = new DefaultTimephasedCostContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }" ]
[ "public void addChannel(String boneName, GVRAnimationChannel channel)\n {\n int boneId = mSkeleton.getBoneIndex(boneName);\n if (boneId >= 0)\n {\n mBoneChannels[boneId] = channel;\n mSkeleton.setBoneOptions(boneId, GVRSkeleton.BONE_ANIMATE);\n Log.d(\"BONE\", \"Adding animation channel %d %s \", boneId, boneName);\n }\n }", "private int checkInInternal() {\n\n m_logStream.println(\"[\" + new Date() + \"] STARTING Git task\");\n m_logStream.println(\"=========================\");\n m_logStream.println();\n\n if (m_checkout) {\n m_logStream.println(\"Running checkout script\");\n\n } else if (!(m_resetHead || m_resetRemoteHead)) {\n m_logStream.println(\"Exporting relevant modules\");\n m_logStream.println(\"--------------------------\");\n m_logStream.println();\n\n exportModules();\n\n m_logStream.println();\n m_logStream.println(\"Calling script to check in the exports\");\n m_logStream.println(\"--------------------------------------\");\n m_logStream.println();\n\n } else {\n\n m_logStream.println();\n m_logStream.println(\"Calling script to reset the repository\");\n m_logStream.println(\"--------------------------------------\");\n m_logStream.println();\n\n }\n\n int exitCode = runCommitScript();\n if (exitCode != 0) {\n m_logStream.println();\n m_logStream.println(\"ERROR: Something went wrong. The script got exitcode \" + exitCode + \".\");\n m_logStream.println();\n }\n if ((exitCode == 0) && m_checkout) {\n boolean importOk = importModules();\n if (!importOk) {\n return -1;\n }\n }\n m_logStream.println(\"[\" + new Date() + \"] FINISHED Git task\");\n m_logStream.println();\n m_logStream.close();\n\n return exitCode;\n }", "public int[] next()\n {\n boolean hasNewPerm = false;\n\n escape:while( level >= 0) {\n// boolean foundZero = false;\n for( int i = iter[level]; i < data.length; i = iter[level] ) {\n iter[level]++;\n\n if( data[i] == -1 ) {\n level++;\n data[i] = level-1;\n\n if( level >= data.length ) {\n // a new permutation has been created return the results.\n hasNewPerm = true;\n System.arraycopy(data,0,ret,0,ret.length);\n level = level-1;\n data[i] = -1;\n break escape;\n } else {\n valk[level] = i;\n }\n }\n }\n\n data[valk[level]] = -1;\n iter[level] = 0;\n level = level-1;\n\n }\n\n if( hasNewPerm )\n return ret;\n return null;\n }", "public static base_responses add(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver addresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new ntpserver();\n\t\t\t\taddresources[i].serverip = resources[i].serverip;\n\t\t\t\taddresources[i].servername = resources[i].servername;\n\t\t\t\taddresources[i].minpoll = resources[i].minpoll;\n\t\t\t\taddresources[i].maxpoll = resources[i].maxpoll;\n\t\t\t\taddresources[i].autokey = resources[i].autokey;\n\t\t\t\taddresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "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 static File copyResourceToLocalFile(String sourceResource, String destFileName) throws Exception {\n try {\n Resource keystoreFile = new ClassPathResource(sourceResource);\n InputStream in = keystoreFile.getInputStream();\n\n File outKeyStoreFile = new File(destFileName);\n FileOutputStream fop = new FileOutputStream(outKeyStoreFile);\n byte[] buf = new byte[512];\n int num;\n while ((num = in.read(buf)) != -1) {\n fop.write(buf, 0, num);\n }\n fop.flush();\n fop.close();\n in.close();\n return outKeyStoreFile;\n } catch (IOException ioe) {\n throw new Exception(\"Could not copy keystore file: \" + ioe.getMessage());\n }\n }", "private void ensureNoTableInfoIfNoRepositoryInfo(ClassDescriptorDef classDef, String checkLevel)\r\n {\r\n if (!classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))\r\n {\r\n classDef.setProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, \"false\");\r\n }\r\n }", "public HashMap<K2, HashMap<K3, V>> get(final K1 firstKey) {\n\t\treturn map.get(firstKey);\n\t}", "public final OutputFormat getOutputFormat(final PJsonObject specJson) {\n final String format = specJson.getString(MapPrinterServlet.JSON_OUTPUT_FORMAT);\n final boolean mapExport =\n this.configuration.getTemplate(specJson.getString(Constants.JSON_LAYOUT_KEY)).isMapExport();\n final String beanName =\n format + (mapExport ? MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING : OUTPUT_FORMAT_BEAN_NAME_ENDING);\n\n if (!this.outputFormat.containsKey(beanName)) {\n throw new RuntimeException(\"Format '\" + format + \"' with mapExport '\" + mapExport\n + \"' is not supported.\");\n }\n\n return this.outputFormat.get(beanName);\n }" ]
Returns the z-coordinate of a vertex normal. @param vertex the vertex index @return the z coordinate
[ "public float getNormalZ(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }" ]
[ "private void addUDFValue(FieldTypeClass fieldType, FieldContainer container, Row row)\n {\n Integer fieldId = row.getInteger(\"udf_type_id\");\n String fieldName = m_udfFields.get(fieldId);\n\n Object value = null;\n FieldType field = m_project.getCustomFields().getFieldByAlias(fieldType, fieldName);\n if (field != null)\n {\n DataType fieldDataType = field.getDataType();\n\n switch (fieldDataType)\n {\n case DATE:\n {\n value = row.getDate(\"udf_date\");\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n {\n value = row.getDouble(\"udf_number\");\n break;\n }\n\n case GUID:\n case INTEGER:\n {\n value = row.getInteger(\"udf_code_id\");\n break;\n }\n\n case BOOLEAN:\n {\n String text = row.getString(\"udf_text\");\n if (text != null)\n {\n // before a normal boolean parse, we try to lookup the text as a P6 static type indicator UDF\n value = STATICTYPE_UDF_MAP.get(text);\n if (value == null)\n {\n value = Boolean.valueOf(row.getBoolean(\"udf_text\"));\n }\n }\n else\n {\n value = Boolean.valueOf(row.getBoolean(\"udf_number\"));\n }\n break;\n }\n\n default:\n {\n value = row.getString(\"udf_text\");\n break;\n }\n }\n\n container.set(field, value);\n }\n }", "private int combineSubsetBlocks(Mode[] mode_type, int[] mode_length, int index_point) {\n /* bring together same type blocks */\n if (index_point > 1) {\n for (int i = 1; i < index_point; i++) {\n if (mode_type[i - 1] == mode_type[i]) {\n /* bring together */\n mode_length[i - 1] = mode_length[i - 1] + mode_length[i];\n /* decrease the list */\n for (int j = i + 1; j < index_point; j++) {\n mode_length[j - 1] = mode_length[j];\n mode_type[j - 1] = mode_type[j];\n }\n index_point--;\n i--;\n }\n }\n }\n return index_point;\n }", "public Archetype parse(String adl) {\n try {\n return parse(new StringReader(adl));\n } catch (IOException e) {\n // StringReader should never throw an IOException\n throw new AssertionError(e);\n }\n }", "public void setNearClippingDistance(float near) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near);\n centerCamera.setNearClippingDistance(near);\n ((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near);\n }\n }", "public static policydataset get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset obj = new policydataset();\n\t\tobj.set_name(name);\n\t\tpolicydataset response = (policydataset) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void logMigration(DbMigration migration, boolean wasSuccessful) {\n BoundStatement boundStatement = logMigrationStatement.bind(wasSuccessful, migration.getVersion(),\n migration.getScriptName(), migration.getMigrationScript(), new Date());\n session.execute(boundStatement);\n }", "private static void setFields(final Object from, final Object to,\r\n\t final Field[] fields, final boolean accessible,\r\n\t final Map objMap, final Map metadataMap)\r\n\t{\r\n\t\tfor (int f = 0, fieldsLength = fields.length; f < fieldsLength; ++f)\r\n\t\t{\r\n\t\t\tfinal Field field = fields[f];\r\n\t\t\tfinal int modifiers = field.getModifiers();\r\n\t\t\tif ((Modifier.STATIC & modifiers) != 0) continue;\r\n\t\t\tif ((Modifier.FINAL & modifiers) != 0)\r\n\t\t\t\tthrow new ObjectCopyException(\"cannot set final field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]\");\r\n\t\t\tif (!accessible && ((Modifier.PUBLIC & modifiers) == 0))\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tfield.setAccessible(true);\r\n\t\t\t\t}\r\n\t\t\t\tcatch (SecurityException e)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow new ObjectCopyException(\"cannot access field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]: \" + e.toString(), e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tcloneAndSetFieldValue(field, from, to, objMap, metadataMap);\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tthrow new ObjectCopyException(\"cannot set field [\" + field.getName() + \"] of class [\" + from.getClass().getName() + \"]: \" + e.toString(), e);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "private static Map<String, Set<String>> expand(Map<String, Set<String>> viewToPropNames) {\n\n Set<String> baseProps = viewToPropNames.get(PropertyView.BASE_VIEW);\n\n if (baseProps == null) {\n baseProps = ImmutableSet.of();\n }\n\n if (!SquigglyConfig.isFilterImplicitlyIncludeBaseFieldsInView()) {\n\n // make an exception for full view\n Set<String> fullView = viewToPropNames.get(PropertyView.FULL_VIEW);\n\n if (fullView != null) {\n fullView.addAll(baseProps);\n }\n\n return viewToPropNames;\n }\n\n for (Map.Entry<String, Set<String>> entry : viewToPropNames.entrySet()) {\n String viewName = entry.getKey();\n Set<String> propNames = entry.getValue();\n\n if (!PropertyView.BASE_VIEW.equals(viewName)) {\n propNames.addAll(baseProps);\n }\n }\n\n return viewToPropNames;\n }", "public Where<T, ID> and() {\n\t\tManyClause clause = new ManyClause(pop(\"AND\"), ManyClause.AND_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}" ]
Returns the shared prefix of these columns. Null otherwise. @param associationKeyColumns the columns sharing a prefix @return the shared prefix of these columns. {@code null} otherwise.
[ "public static String getColumnSharedPrefix(String[] associationKeyColumns) {\n\t\tString prefix = null;\n\t\tfor ( String column : associationKeyColumns ) {\n\t\t\tString newPrefix = getPrefix( column );\n\t\t\tif ( prefix == null ) { // first iteration\n\t\t\t\tprefix = newPrefix;\n\t\t\t\tif ( prefix == null ) { // no prefix, quit\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { // subsequent iterations\n\t\t\t\tif ( ! equals( prefix, newPrefix ) ) { // different prefixes\n\t\t\t\t\tprefix = null;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn prefix;\n\t}" ]
[ "private Filter getFilter(String layerFilter, String[] featureIds) throws GeomajasException {\n\t\tFilter filter = null;\n\t\tif (null != layerFilter) {\n\t\t\tfilter = filterService.parseFilter(layerFilter);\n\t\t}\n\t\tif (null != featureIds) {\n\t\t\tFilter fidFilter = filterService.createFidFilter(featureIds);\n\t\t\tif (null == filter) {\n\t\t\t\tfilter = fidFilter;\n\t\t\t} else {\n\t\t\t\tfilter = filterService.createAndFilter(filter, fidFilter);\n\t\t\t}\n\t\t}\n\t\treturn filter;\n\t}", "private void parseJSON(JsonObject jsonObject) {\n for (JsonObject.Member member : jsonObject) {\n JsonValue value = member.getValue();\n if (value.isNull()) {\n continue;\n }\n\n try {\n String memberName = member.getName();\n if (memberName.equals(\"id\")) {\n this.versionID = value.asString();\n } else if (memberName.equals(\"sha1\")) {\n this.sha1 = value.asString();\n } else if (memberName.equals(\"name\")) {\n this.name = value.asString();\n } else if (memberName.equals(\"size\")) {\n this.size = Double.valueOf(value.toString()).longValue();\n } else if (memberName.equals(\"created_at\")) {\n this.createdAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"modified_at\")) {\n this.modifiedAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"trashed_at\")) {\n this.trashedAt = BoxDateFormat.parse(value.asString());\n } else if (memberName.equals(\"modified_by\")) {\n JsonObject userJSON = value.asObject();\n String userID = userJSON.get(\"id\").asString();\n BoxUser user = new BoxUser(getAPI(), userID);\n this.modifiedBy = user.new Info(userJSON);\n }\n } catch (ParseException e) {\n assert false : \"A ParseException indicates a bug in the SDK.\";\n }\n }\n }", "public boolean hasCachedValue(Key key) {\n\t\ttry {\n\t\t\treadLock.lock();\n\t\t\treturn content.containsKey(key);\n\t\t} finally {\n\t\t\treadLock.unlock();\n\t\t}\n\t}", "public CollectionRequest<ProjectMembership> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/project_memberships\", project);\n return new CollectionRequest<ProjectMembership>(this, ProjectMembership.class, path, \"GET\");\n }", "public String getValueSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String valueSchema = schema.getField(valueFieldName).schema().toString();\n return valueSchema;\n }", "public RandomVariable[] getGradient(){\r\n\r\n\t\t// for now let us take the case for output-dimension equal to one!\r\n\t\tint numberOfVariables = getNumberOfVariablesInList();\r\n\t\tint numberOfCalculationSteps = factory.getNumberOfEntriesInList();\r\n\r\n\t\tRandomVariable[] omega_hat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\t// first entry gets initialized\r\n\t\tomega_hat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\t/*\r\n\t\t * TODO: Find way that calculations form here on are not 'recorded' by the factory\r\n\t\t * IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down!\r\n\t\t * */\r\n\r\n\t\tfor(int functionIndex = numberOfCalculationSteps - 2; functionIndex > 0; functionIndex--){\r\n\t\t\t// apply chain rule\r\n\t\t\tomega_hat[functionIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\t/*TODO: save all D_{i,j}*\\omega_j in vector and sum up later */\r\n\t\t\tfor(RandomVariableUniqueVariable parent:parentsVariables){\r\n\r\n\t\t\t\tint variableIndex = parent.getVariableID();\r\n\r\n\t\t\t\tomega_hat[functionIndex] = omega_hat[functionIndex].add(getPartialDerivative(functionIndex, variableIndex).mult(omega_hat[variableIndex]));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices!\r\n\t\t * Thus save the indices of the true variables and recover them after finalizing all the calculations\r\n\t\t * IDEA: quit calculation after minimal true variable index is reached */\r\n\t\tRandomVariable[] gradient = new RandomVariable[numberOfVariables];\r\n\r\n\t\t/* TODO: sort array in correct manner! */\r\n\t\tint[] indicesOfVariables = getIDsOfVariablesInList();\r\n\r\n\t\tfor(int i = 0; i < numberOfVariables; i++){\r\n\t\t\tgradient[i] = omega_hat[numberOfCalculationSteps - numberOfVariables + indicesOfVariables[i]];\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}", "public static long getMaxIdForClass(\r\n PersistenceBroker brokerForClass, ClassDescriptor cldForOriginalOrExtent, FieldDescriptor original)\r\n throws PersistenceBrokerException\r\n {\r\n FieldDescriptor field = null;\r\n if (!original.getClassDescriptor().equals(cldForOriginalOrExtent))\r\n {\r\n // check if extent match not the same table\r\n if (!original.getClassDescriptor().getFullTableName().equals(\r\n cldForOriginalOrExtent.getFullTableName()))\r\n {\r\n // we have to look for id's in extent class table\r\n field = cldForOriginalOrExtent.getFieldDescriptorByName(original.getAttributeName());\r\n }\r\n }\r\n else\r\n {\r\n field = original;\r\n }\r\n if (field == null)\r\n {\r\n // if null skip this call\r\n return 0;\r\n }\r\n\r\n String column = field.getColumnName();\r\n long result = 0;\r\n ResultSet rs = null;\r\n Statement stmt = null;\r\n StatementManagerIF sm = brokerForClass.serviceStatementManager();\r\n String table = cldForOriginalOrExtent.getFullTableName();\r\n // String column = cld.getFieldDescriptorByName(fieldName).getColumnName();\r\n String sql = SM_SELECT_MAX + column + SM_FROM + table;\r\n try\r\n {\r\n //lookup max id for the current class\r\n stmt = sm.getGenericStatement(cldForOriginalOrExtent, Query.NOT_SCROLLABLE);\r\n rs = stmt.executeQuery(sql);\r\n rs.next();\r\n result = rs.getLong(1);\r\n }\r\n catch (Exception e)\r\n {\r\n log.warn(\"Cannot lookup max value from table \" + table + \" for column \" + column +\r\n \", PB was \" + brokerForClass + \", using jdbc-descriptor \" +\r\n brokerForClass.serviceConnectionManager().getConnectionDescriptor(), e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n sm.closeResources(stmt, rs);\r\n }\r\n catch (Exception ignore)\r\n {\r\n // ignore it\r\n }\r\n }\r\n return result;\r\n }", "public static int getId(Context context, String id, String defType) {\n String type = \"R.\" + defType + \".\";\n if (id.startsWith(type)) {\n id = id.substring(type.length());\n }\n\n Resources r = context.getResources();\n int resId = r.getIdentifier(id, defType,\n context.getPackageName());\n if (resId > 0) {\n return resId;\n } else {\n throw new RuntimeAssertion(\"Specified resource '%s' could not be found\", id);\n }\n }", "public void syncInternalStateFromFileSystem(boolean alsoSyncRemoteState) {\n // Make sure versions missing from the file-system are cleaned up from the internal state\n for (Long version: versionToEnabledMap.keySet()) {\n File[] existingVersionDirs = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (existingVersionDirs.length == 0) {\n removeVersion(version, alsoSyncRemoteState);\n }\n }\n\n // Make sure we have all versions on the file-system in the internal state\n File[] versionDirs = ReadOnlyUtils.getVersionDirs(rootDir);\n if (versionDirs != null) {\n for (File versionDir: versionDirs) {\n long versionNumber = ReadOnlyUtils.getVersionId(versionDir);\n boolean versionEnabled = isVersionEnabled(versionDir);\n versionToEnabledMap.put(versionNumber, versionEnabled);\n }\n }\n\n // Identify the current version (based on a symlink in the file-system)\n File currentVersionDir = ReadOnlyUtils.getCurrentVersion(rootDir);\n if (currentVersionDir != null) {\n currentVersion = ReadOnlyUtils.getVersionId(currentVersionDir);\n } else {\n currentVersion = -1; // Should we throw instead?\n }\n\n logger.info(\"Successfully synced internal state from local file-system: \" + this.toString());\n }" ]
Removes a design document using the id and rev from the database. @param id the document id (optionally prefixed with "_design/") @param rev the document revision @return {@link DesignDocument}
[ "public Response remove(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.remove(ensureDesignPrefix(id), rev);\r\n\r\n }" ]
[ "private boolean addonDependsOnReporting(Addon addon)\n {\n for (AddonDependency dep : addon.getDependencies())\n {\n if (dep.getDependency().equals(this.addon))\n {\n return true;\n }\n boolean subDep = addonDependsOnReporting(dep.getDependency());\n if (subDep)\n {\n return true;\n }\n }\n return false;\n }", "public Conditionals addIfMatch(Tag tag) {\n Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE));\n Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH));\n List<Tag> match = new ArrayList<>(this.match);\n\n if (tag == null) {\n tag = Tag.ALL;\n }\n if (Tag.ALL.equals(tag)) {\n match.clear();\n }\n if (!match.contains(Tag.ALL)) {\n if (!match.contains(tag)) {\n match.add(tag);\n }\n }\n else {\n throw new IllegalArgumentException(\"Tag ALL already in the list\");\n }\n return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince);\n }", "public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) {\n return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf);\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}", "public void setReadTimeout(int readTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.readTimeout(readTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}", "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 double[] eigenToSampleSpace( double[] eigenData ) {\n if( eigenData.length != numComponents )\n throw new IllegalArgumentException(\"Unexpected sample length\");\n\n DMatrixRMaj s = new DMatrixRMaj(A.getNumCols(),1);\n DMatrixRMaj r = DMatrixRMaj.wrap(numComponents,1,eigenData);\n \n CommonOps_DDRM.multTransA(V_t,r,s);\n\n DMatrixRMaj mean = DMatrixRMaj.wrap(A.getNumCols(),1,this.mean);\n CommonOps_DDRM.add(s,mean,s);\n\n return s.data;\n }", "public void setPlaying(boolean playing) {\n\n if (this.playing.get() == playing) {\n return;\n }\n\n this.playing.set(playing);\n\n if (playing) {\n metronome.jumpToBeat(whereStopped.get().getBeat());\n if (isSendingStatus()) { // Need to also start the beat sender.\n beatSender.set(new BeatSender(metronome));\n }\n } else {\n final BeatSender activeSender = beatSender.get();\n if (activeSender != null) { // We have a beat sender we need to stop.\n activeSender.shutDown();\n beatSender.set(null);\n }\n whereStopped.set(metronome.getSnapshot());\n }\n }", "private void renderAsLI(Writer writer, ProjectModel project, Iterator<Link> links, boolean wrap) throws IOException\n {\n if (!links.hasNext())\n return;\n\n if (wrap)\n writer.append(\"<ul>\");\n while (links.hasNext())\n {\n Link link = links.next();\n writer.append(\"<li>\");\n renderLink(writer, project, link);\n writer.append(\"</li>\");\n }\n if (wrap)\n writer.append(\"</ul>\");\n }" ]
Read all of the fields information from the configuration file.
[ "private static <T> void readFields(BufferedReader reader, DatabaseTableConfig<T> config) throws SQLException {\n\t\tList<DatabaseFieldConfig> fields = new ArrayList<DatabaseFieldConfig>();\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read next field from config file\", e);\n\t\t\t}\n\t\t\tif (line == null || line.equals(CONFIG_FILE_FIELDS_END)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tDatabaseFieldConfig fieldConfig = DatabaseFieldConfigLoader.fromReader(reader);\n\t\t\tif (fieldConfig == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfields.add(fieldConfig);\n\t\t}\n\t\tconfig.setFieldConfigs(fields);\n\t}" ]
[ "@NonNull\n @SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher reset() {\n lastResponsePage = 0;\n lastRequestPage = 0;\n lastResponseId = 0;\n endReached = false;\n clearFacetRefinements();\n cancelPendingRequests();\n numericRefinements.clear();\n return this;\n }", "protected PersistenceBrokerInternal createNewBrokerInstance(PBKey key) throws PBFactoryException\r\n {\r\n if (key == null) throw new PBFactoryException(\"Could not create new broker with PBkey argument 'null'\");\r\n // check if the given key really exists\r\n if (MetadataManager.getInstance().connectionRepository().getDescriptor(key) == null)\r\n {\r\n throw new PBFactoryException(\"Given PBKey \" + key + \" does not match in metadata configuration\");\r\n }\r\n if (log.isEnabledFor(Logger.INFO))\r\n {\r\n // only count created instances when INFO-Log-Level\r\n log.info(\"Create new PB instance for PBKey \" + key +\r\n \", already created persistence broker instances: \" + instanceCount);\r\n // useful for testing\r\n ++this.instanceCount;\r\n }\r\n\r\n PersistenceBrokerInternal instance = null;\r\n Class[] types = {PBKey.class, PersistenceBrokerFactoryIF.class};\r\n Object[] args = {key, this};\r\n try\r\n {\r\n instance = (PersistenceBrokerInternal) ClassHelper.newInstance(implementationClass, types, args);\r\n OjbConfigurator.getInstance().configure(instance);\r\n instance = (PersistenceBrokerInternal) InterceptorFactory.getInstance().createInterceptorFor(instance);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Creation of a new PB instance failed\", e);\r\n throw new PBFactoryException(\"Creation of a new PB instance failed\", e);\r\n }\r\n return instance;\r\n }", "public void removeFile(String name) {\n if(files.containsKey(name)) {\n files.remove(name);\n }\n\n if(fileStreams.containsKey(name)) {\n fileStreams.remove(name);\n }\n }", "public static Properties getProps(Properties props, String name, Properties defaultProperties) {\n final String propString = props.getProperty(name);\n if (propString == null) return defaultProperties;\n String[] propValues = propString.split(\",\");\n if (propValues.length < 1) {\n throw new IllegalArgumentException(\"Illegal format of specifying properties '\" + propString + \"'\");\n }\n Properties properties = new Properties();\n for (int i = 0; i < propValues.length; i++) {\n String[] prop = propValues[i].split(\"=\");\n if (prop.length != 2) throw new IllegalArgumentException(\"Illegal format of specifying properties '\" + propValues[i] + \"'\");\n properties.put(prop[0], prop[1]);\n }\n return properties;\n }", "public void spawnThread(DukeController controller, int check_interval) {\n this.controller = controller;\n timer = mgr.schedule(this, 0, check_interval * 1000); // convert to ms\n }", "public static BoxDeveloperEditionAPIConnection getAppUserConnection(String userId, BoxConfig boxConfig) {\n return getAppUserConnection(userId, boxConfig.getClientId(), boxConfig.getClientSecret(),\n boxConfig.getJWTEncryptionPreferences());\n }", "public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = true;\n if (m_criteria != null)\n {\n result = m_criteria.evaluate(container, promptValues);\n\n //\n // If this row has failed, but it is a summary row, and we are\n // including related summary rows, then we need to recursively test\n // its children\n //\n if (!result && m_showRelatedSummaryRows && container instanceof Task)\n {\n for (Task task : ((Task) container).getChildTasks())\n {\n if (evaluate(task, promptValues))\n {\n result = true;\n break;\n }\n }\n }\n }\n\n return (result);\n }", "public ItemRequest<Task> findById(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }", "public static <ObjType, Hashable> Collection<ObjType> uniqueNonhashableObjects(Collection<ObjType> objects, Function<ObjType, Hashable> customHasher) {\r\n Map<Hashable, ObjType> hashesToObjects = new HashMap<Hashable, ObjType>();\r\n for (ObjType object : objects) {\r\n hashesToObjects.put(customHasher.apply(object), object);\r\n }\r\n return hashesToObjects.values();\r\n }" ]
Remove a key for all language versions. If a descriptor is present, the key is only removed in the descriptor. @param key the key to remove. @return <code>true</code> if removing was successful, <code>false</code> otherwise.
[ "private boolean removeKeyForAllLanguages(String key) {\n\n try {\n if (hasDescriptor()) {\n lockDescriptor();\n }\n loadAllRemainingLocalizations();\n lockAllLocalizations(key);\n } catch (CmsException | IOException e) {\n LOG.warn(\"Not able lock all localications for bundle.\", e);\n return false;\n }\n if (!hasDescriptor()) {\n\n for (Entry<Locale, SortedProperties> entry : m_localizations.entrySet()) {\n SortedProperties localization = entry.getValue();\n if (localization.containsKey(key)) {\n localization.remove(key);\n m_changedTranslations.add(entry.getKey());\n }\n }\n }\n return true;\n }" ]
[ "public static String printUUID(UUID guid)\n {\n return guid == null ? null : \"{\" + guid.toString().toUpperCase() + \"}\";\n }", "public void process(AvailabilityTable table, byte[] data)\n {\n if (data != null)\n {\n Calendar cal = DateHelper.popCalendar();\n int items = MPPUtility.getShort(data, 0);\n int offset = 12;\n\n for (int loop = 0; loop < items; loop++)\n {\n double unitsValue = MPPUtility.getDouble(data, offset + 4);\n if (unitsValue != 0)\n {\n Date startDate = MPPUtility.getTimestampFromTenths(data, offset);\n Date endDate = MPPUtility.getTimestampFromTenths(data, offset + 20);\n cal.setTime(endDate);\n cal.add(Calendar.MINUTE, -1);\n endDate = cal.getTime();\n Double units = NumberHelper.getDouble(unitsValue / 100);\n Availability item = new Availability(startDate, endDate, units);\n table.add(item);\n }\n offset += 20;\n }\n DateHelper.pushCalendar(cal);\n Collections.sort(table);\n }\n }", "public static <T> DecoratorImpl<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new DecoratorImpl<T>(attributes, clazz, beanManager);\n }", "private ServerDetails createInitialResolveDetailsFromDeployDetails(ServerDetails deployerDetails) {\n RepositoryConf oldResolveRepositoryConfig = deployerDetails.getResolveReleaseRepository();\n RepositoryConf oldSnapshotResolveRepositoryConfig = deployerDetails.getResolveSnapshotRepository();\n RepositoryConf resolverReleaseRepos = oldResolveRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldResolveRepositoryConfig;\n RepositoryConf resolveSnapshotRepos = oldSnapshotResolveRepositoryConfig == null ? RepositoryConf.emptyRepositoryConfig : oldSnapshotResolveRepositoryConfig;\n return new ServerDetails(deployerDetails.getArtifactoryName(), deployerDetails.getArtifactoryUrl(),\n null, null, resolverReleaseRepos, resolveSnapshotRepos, null, null);\n }", "public static int getJSONColor(final JSONObject json, String elementName) throws JSONException {\n Object raw = json.get(elementName);\n return convertJSONColor(raw);\n }", "@Override\n public void solve(DMatrixRBlock B, DMatrixRBlock X) {\n if( B.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in B.\");\n\n DSubmatrixD1 L = new DSubmatrixD1(decomposer.getT(null));\n\n if( X != null ) {\n if( X.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in X.\");\n if( X.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in X\");\n }\n \n if( B.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in B\");\n\n // L * L^T*X = B\n\n // Solve for Y: L*Y = B\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),false);\n\n // L^T * X = Y\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),true);\n\n if( X != null ) {\n // copy the solution from B into X\n MatrixOps_DDRB.extractAligned(B,X);\n }\n\n }", "public static PipelineConfiguration.Builder parse(ModelNode json) {\n ModelNode analyzerIncludeNode = json.get(\"analyzers\").get(\"include\");\n ModelNode analyzerExcludeNode = json.get(\"analyzers\").get(\"exclude\");\n ModelNode filterIncludeNode = json.get(\"filters\").get(\"include\");\n ModelNode filterExcludeNode = json.get(\"filters\").get(\"exclude\");\n ModelNode transformIncludeNode = json.get(\"transforms\").get(\"include\");\n ModelNode transformExcludeNode = json.get(\"transforms\").get(\"exclude\");\n ModelNode reporterIncludeNode = json.get(\"reporters\").get(\"include\");\n ModelNode reporterExcludeNode = json.get(\"reporters\").get(\"exclude\");\n\n return builder()\n .withTransformationBlocks(json.get(\"transformBlocks\"))\n .withAnalyzerExtensionIdsInclude(asStringList(analyzerIncludeNode))\n .withAnalyzerExtensionIdsExclude(asStringList(analyzerExcludeNode))\n .withFilterExtensionIdsInclude(asStringList(filterIncludeNode))\n .withFilterExtensionIdsExclude(asStringList(filterExcludeNode))\n .withTransformExtensionIdsInclude(asStringList(transformIncludeNode))\n .withTransformExtensionIdsExclude(asStringList(transformExcludeNode))\n .withReporterExtensionIdsInclude(asStringList(reporterIncludeNode))\n .withReporterExtensionIdsExclude(asStringList(reporterExcludeNode));\n }", "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 }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<CopticDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<CopticDate>) super.zonedDateTime(temporal);\n }" ]
Register a new SingleServiceWrapperInterceptor for the bean being wrapped, associate it with the PerformanceMonitor and tell it which methods to intercept. @param source An Attribute node from the spring configuration @param beanName The name of the bean that this performance monitor is wrapped around @param registry The registry where all the spring beans are registered
[ "private void registerInterceptor(Node source,\n String beanName,\n BeanDefinitionRegistry registry) {\n List<String> methodList = buildMethodList(source);\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(SingleServiceWrapperInterceptor.class);\n initializer.addPropertyValue(\"methods\", methodList);\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n initializer.addPropertyReference(\"serviceWrapper\", perfMonitorName);\n\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n registry.registerBeanDefinition(interceptorName, initializer.getBeanDefinition());\n }" ]
[ "public static <T> Observable<T> delayedEmitAsync(T event, int milliseconds) {\n return delayProvider.delayedEmitAsync(event, milliseconds);\n }", "public static Integer convertPathIdentifier(String identifier, Integer profileId) throws Exception {\n Integer pathId = -1;\n try {\n pathId = Integer.parseInt(identifier);\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n if (profileId == null)\n throw new Exception(\"A profileId must be specified\");\n\n pathId = PathOverrideService.getInstance().getPathId(identifier, profileId);\n }\n\n return pathId;\n }", "@PreDestroy\n public final void shutdown() {\n this.timer.shutdownNow();\n this.executor.shutdownNow();\n if (this.cleanUpTimer != null) {\n this.cleanUpTimer.shutdownNow();\n }\n }", "public List<Message> requestTrackMenuFrom(final SlotReference slotReference, final int sortOrder)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n return MetadataFinder.getInstance().getFullTrackList(slotReference.slot, client, sortOrder);\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting track menu\");\n }", "public static base_response update(nitro_service client, cmpparameter resource) throws Exception {\n\t\tcmpparameter updateresource = new cmpparameter();\n\t\tupdateresource.cmplevel = resource.cmplevel;\n\t\tupdateresource.quantumsize = resource.quantumsize;\n\t\tupdateresource.servercmp = resource.servercmp;\n\t\tupdateresource.heurexpiry = resource.heurexpiry;\n\t\tupdateresource.heurexpirythres = resource.heurexpirythres;\n\t\tupdateresource.heurexpiryhistwt = resource.heurexpiryhistwt;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.cmpbypasspct = resource.cmpbypasspct;\n\t\tupdateresource.cmponpush = resource.cmponpush;\n\t\tupdateresource.policytype = resource.policytype;\n\t\tupdateresource.addvaryheader = resource.addvaryheader;\n\t\tupdateresource.externalcache = resource.externalcache;\n\t\treturn updateresource.update_resource(client);\n\t}", "public EventsRequest<Event> get(String resource, String sync) {\n return new EventsRequest<Event>(this, Event.class, \"/events\", \"GET\")\n .query(\"resource\", resource)\n .query(\"sync\", sync);\n }", "public QueryBuilder<T, ID> join(QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException {\n\t\taddJoinInfo(JoinType.INNER, null, null, joinedQueryBuilder, JoinWhereOperation.AND);\n\t\treturn this;\n\t}", "public VectorClock incremented(int nodeId, long time) {\n VectorClock copyClock = this.clone();\n copyClock.incrementVersion(nodeId, time);\n return copyClock;\n }", "public static base_responses delete(nitro_service client, String selectorname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (selectorname != null && selectorname.length > 0) {\n\t\t\tcacheselector deleteresources[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++){\n\t\t\t\tdeleteresources[i] = new cacheselector();\n\t\t\t\tdeleteresources[i].selectorname = selectorname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Returns the parsed story from the given path @param configuration the Configuration used to run story @param storyPath the story path @return The parsed Story
[ "public Story storyOfPath(Configuration configuration, String storyPath) {\n String storyAsText = configuration.storyLoader().loadStoryAsText(storyPath);\n return configuration.storyParser().parseStory(storyAsText, storyPath);\n }" ]
[ "public void configure(@Observes(precedence = -10) ArquillianDescriptor arquillianDescriptor) {\n Map<String, String> config = arquillianDescriptor.extension(EXTENSION_NAME).getExtensionProperties();\n CubeConfiguration cubeConfiguration = CubeConfiguration.fromMap(config);\n configurationProducer.set(cubeConfiguration);\n }", "public static void stopService() {\n DaemonStarter.currentPhase.set(LifecyclePhase.STOPPING);\n final CountDownLatch cdl = new CountDownLatch(1);\n Executors.newSingleThreadExecutor().execute(() -> {\n DaemonStarter.getLifecycleListener().stopping();\n DaemonStarter.daemon.stop();\n cdl.countDown();\n });\n\n try {\n int timeout = DaemonStarter.lifecycleListener.get().getShutdownTimeoutSeconds();\n if (!cdl.await(timeout, TimeUnit.SECONDS)) {\n DaemonStarter.rlog.error(\"Failed to stop gracefully\");\n DaemonStarter.abortSystem();\n }\n } catch (InterruptedException e) {\n DaemonStarter.rlog.error(\"Failure awaiting stop\", e);\n Thread.currentThread().interrupt();\n }\n\n }", "@SafeVarargs\n public static void registerFilterTypes(final Class<? extends DynamicFilter>... types) {\n FILTER_TYPES.addAll(Arrays.asList(types));\n }", "public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }", "public static STSClient createSTSX509Client(Bus bus, Map<String, String> stsProps) {\r\n final STSClient stsClient = createClient(bus, stsProps);\r\n\r\n stsClient.setWsdlLocation(stsProps.get(STS_X509_WSDL_LOCATION));\r\n stsClient.setEndpointQName(new QName(stsProps.get(STS_NAMESPACE), stsProps.get(STS_X509_ENDPOINT_NAME)));\r\n\r\n return stsClient;\r\n }", "private void executeResult() throws Exception {\n\t\tresult = createResult();\n\n\t\tString timerKey = \"executeResult: \" + getResultCode();\n\t\ttry {\n\t\t\tUtilTimerStack.push(timerKey);\n\t\t\tif (result != null) {\n\t\t\t\tresult.execute(this);\n\t\t\t} else if (resultCode != null && !Action.NONE.equals(resultCode)) {\n\t\t\t\tthrow new ConfigurationException(\"No result defined for action \" + getAction().getClass().getName()\n\t\t\t\t\t\t+ \" and result \" + getResultCode(), proxy.getConfig());\n\t\t\t} else {\n\t\t\t\tif (LOG.isDebugEnabled()) {\n\t\t\t\t\tLOG.debug(\"No result returned for action \" + getAction().getClass().getName() + \" at \"\n\t\t\t\t\t\t\t+ proxy.getConfig().getLocation());\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tUtilTimerStack.pop(timerKey);\n\t\t}\n\t}", "public void setWeekDay(String weekDayStr) {\n\n final WeekDay weekDay = WeekDay.valueOf(weekDayStr);\n if ((m_model.getWeekDay() != null) || !m_model.getWeekDay().equals(weekDay)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDay(weekDay);\n onValueChange();\n }\n });\n\n }\n\n }", "public boolean isPrivate() {\n\t\t// refer to RFC 1918\n // 10/8 prefix\n // 172.16/12 prefix (172.16.0.0 – 172.31.255.255)\n // 192.168/16 prefix\n\t\tIPv4AddressSegment seg0 = getSegment(0);\n\t\tIPv4AddressSegment seg1 = getSegment(1);\n\t\treturn seg0.matches(10)\n\t\t\t|| seg0.matches(172) && seg1.matchesWithPrefixMask(16, 4)\n\t\t\t|| seg0.matches(192) && seg1.matches(168);\n\t}", "private void addContentInfo() {\n\n if (!m_cms.getRequestContext().getCurrentProject().isOnlineProject()\n && (null == m_searchController.getCommon().getConfig().getSolrIndex())\n && (null != m_addContentInfoForEntries)) {\n CmsSolrQuery query = new CmsSolrQuery();\n m_searchController.addQueryParts(query, m_cms);\n query.setStart(Integer.valueOf(0));\n query.setRows(m_addContentInfoForEntries);\n CmsContentLoadCollectorInfo info = new CmsContentLoadCollectorInfo();\n info.setCollectorClass(this.getClass().getName());\n info.setCollectorParams(query.getQuery());\n info.setId((new CmsUUID()).getStringValue());\n if (CmsJspTagEditable.getDirectEditProvider(pageContext) != null) {\n try {\n CmsJspTagEditable.getDirectEditProvider(pageContext).insertDirectEditListMetadata(\n pageContext,\n info);\n } catch (JspException e) {\n LOG.error(\"Could not write content info.\", e);\n }\n }\n }\n }" ]
Sets the node meta data but allows overwriting values. @param key - the meta data key @param value - the meta data value @return the old node meta data value for this key @throws GroovyBugError if key is null
[ "public Object putNodeMetaData(Object key, Object value) {\n if (key == null) throw new GroovyBugError(\"Tried to set meta data with null key on \" + this + \".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n return metaDataMap.put(key, value);\n }" ]
[ "private static void writeUtf16Bom(OutputStream stream, boolean bigEndian) throws IOException {\n if (bigEndian) {\n stream.write(-2);\n stream.write(-1);\n } else {\n stream.write(-1);\n stream.write(-2);\n }\n }", "public double[][] Kernel2D(int size) {\n if (((size % 2) == 0) || (size < 3) || (size > 101)) {\n try {\n throw new Exception(\"Wrong size\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n int r = size / 2;\n double[][] kernel = new double[size][size];\n\n // compute kernel\n double sum = 0;\n for (int y = -r, i = 0; i < size; y++, i++) {\n for (int x = -r, j = 0; j < size; x++, j++) {\n kernel[i][j] = Function2D(x, y);\n sum += kernel[i][j];\n }\n }\n\n for (int i = 0; i < kernel.length; i++) {\n for (int j = 0; j < kernel[0].length; j++) {\n kernel[i][j] /= sum;\n }\n }\n\n return kernel;\n }", "private OperationEntry getInheritableOperationEntryLocked(final String operationName) {\n final OperationEntry entry = operations == null ? null : operations.get(operationName);\n if (entry != null && entry.isInherited()) {\n return entry;\n }\n return null;\n }", "public void append(LogSegment segment) {\n while (true) {\n List<LogSegment> curr = contents.get();\n List<LogSegment> updated = new ArrayList<LogSegment>(curr);\n updated.add(segment);\n if (contents.compareAndSet(curr, updated)) {\n return;\n }\n }\n }", "public static void writeFlowId(Message message, String flowId) {\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n headers.put(FLOWID_HTTP_HEADER_NAME, Collections.singletonList(flowId));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' set to: \" + flowId);\n }\n }", "private Client getClient(){\n final ClientConfig cfg = new DefaultClientConfig();\n cfg.getClasses().add(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider.class);\n cfg.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, timeout);\n\n return Client.create(cfg);\n }", "private double goldenMean(double a, double b) {\r\n if (geometric) {\r\n return a * Math.pow(b / a, GOLDEN_SECTION);\r\n } else {\r\n return a + (b - a) * GOLDEN_SECTION;\r\n }\r\n }", "public static ManagerFunctions.InputN createMultTransA() {\n return (inputs, manager) -> {\n if( inputs.size() != 2 )\n throw new RuntimeException(\"Two inputs required\");\n\n final Variable varA = inputs.get(0);\n final Variable varB = inputs.get(1);\n\n Operation.Info ret = new Operation.Info();\n\n if( varA instanceof VariableMatrix && varB instanceof VariableMatrix ) {\n\n // The output matrix or scalar variable must be created with the provided manager\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n ret.op = new Operation(\"multTransA-mm\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)varA).matrix;\n DMatrixRMaj mB = ((VariableMatrix)varB).matrix;\n\n CommonOps_DDRM.multTransA(mA,mB,output.matrix);\n }\n };\n } else {\n throw new IllegalArgumentException(\"Expected both inputs to be a matrix\");\n }\n\n return ret;\n };\n }", "protected void doConfigure() {\n if (config != null) {\n for (UserBean user : config.getUsersToCreate()) {\n setUser(user.getEmail(), user.getLogin(), user.getPassword());\n }\n getManagers().getUserManager().setAuthRequired(!config.isAuthenticationDisabled());\n }\n }" ]
Here we start a intern odmg-Transaction to hide transaction demarcation This method could be invoked several times within a transaction, but only the first call begin a intern odmg transaction
[ "private void beginInternTransaction()\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"beginInternTransaction was called\");\r\n J2EETransactionImpl tx = (J2EETransactionImpl) super.currentTransaction();\r\n if (tx == null) tx = newInternTransaction();\r\n if (!tx.isOpen())\r\n {\r\n // start the transaction\r\n tx.begin();\r\n tx.setInExternTransaction(true);\r\n }\r\n }" ]
[ "public String calculateCacheKey(String sql, int autoGeneratedKeys) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\ttmp.append(autoGeneratedKeys);\r\n\t\treturn tmp.toString();\r\n\t}", "public synchronized void delete(String name) {\n if (isEmpty(name)) {\n indexedProps.remove(name);\n } else {\n synchronized (context) {\n int scope = context.getAttributesScope(name);\n if (scope != -1) {\n context.removeAttribute(name, scope);\n }\n }\n }\n }", "public Where<T, ID> exists(QueryBuilder<?, ?> subQueryBuilder) {\n\t\t// we do this to turn off the automatic addition of the ID column in the select column list\n\t\tsubQueryBuilder.enableInnerQuery();\n\t\taddClause(new Exists(new InternalQueryBuilderWrapper(subQueryBuilder)));\n\t\treturn this;\n\t}", "private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) {\n // acquire write lock\n writeLock.lock();\n try {\n VectorClock clock = new VectorClock();\n if(metadataCache.containsKey(ROUTING_STRATEGY_KEY))\n clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion();\n\n logger.info(\"Updating routing strategy for all stores\");\n HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs);\n HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster,\n storeDefMap);\n this.metadataCache.put(ROUTING_STRATEGY_KEY,\n new Versioned<Object>(routingStrategyMap,\n clock.incremented(getNodeId(),\n System.currentTimeMillis())));\n\n for(String storeName: storeNameTolisteners.keySet()) {\n RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName);\n if(updatedRoutingStrategy != null) {\n try {\n for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) {\n listener.updateRoutingStrategy(updatedRoutingStrategy);\n listener.updateStoreDefinition(storeDefMap.get(storeName));\n }\n } catch(Exception e) {\n if(logger.isEnabledFor(Level.WARN))\n logger.warn(e, e);\n }\n }\n\n }\n } finally {\n writeLock.unlock();\n }\n }", "public ItemRequest<CustomField> findById(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"GET\");\n }", "public static boolean isConstantVal(DMatrixRMaj mat , double val , double tol )\n {\n // see if the result is an identity matrix\n int index = 0;\n for( int i = 0; i < mat.numRows; i++ ) {\n for( int j = 0; j < mat.numCols; j++ ) {\n if( !(Math.abs(mat.get(index++)-val) <= tol) )\n return false;\n\n }\n }\n\n return true;\n }", "public Date getFinish()\n {\n Date result = (Date) getCachedValue(AssignmentField.FINISH);\n if (result == null)\n {\n result = getTask().getFinish();\n }\n return result;\n }", "public static final void decodeBuffer(byte[] data, byte encryptionCode)\n {\n for (int i = 0; i < data.length; i++)\n {\n data[i] = (byte) (data[i] ^ encryptionCode);\n }\n }", "static void logConnectionException(URI uri, DiscoveryOption discoveryOption, boolean moreOptions, Exception e) {\n if (uri == null) {\n HostControllerLogger.ROOT_LOGGER.failedDiscoveringMaster(discoveryOption, e);\n } else {\n HostControllerLogger.ROOT_LOGGER.cannotConnect(uri, e);\n }\n if (!moreOptions) {\n // All discovery options have been exhausted\n HostControllerLogger.ROOT_LOGGER.noDiscoveryOptionsLeft();\n }\n }" ]
Converts a date series configuration to a date series bean. @return the date series bean.
[ "public CmsJspDateSeriesBean getToDateSeries() {\n\n if (m_dateSeries == null) {\n m_dateSeries = new CmsJspDateSeriesBean(this, m_cms.getRequestContext().getLocale());\n }\n return m_dateSeries;\n }" ]
[ "private static Point getScreenSize(Context context, Point p) {\n if (p == null) {\n p = new Point();\n }\n WindowManager windowManager = (WindowManager) context\n .getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n display.getSize(p);\n return p;\n }", "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 }", "public void removeOverride(int overrideId, int pathId, Integer ordinal, String clientUUID) {\n // TODO: reorder priorities after removal\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n int enabledId = getEnabledEndpoint(pathId, overrideId, ordinal, clientUUID).getId();\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, enabledId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public final static String process(final File file, final boolean safeMode) throws IOException\n {\n return process(file, Configuration.builder().setSafeMode(safeMode).build());\n }", "public Swagger read(Class<?> cls) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n\n return read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }", "protected void beginDragging(MouseDownEvent event) {\n\n m_dragging = true;\n m_windowWidth = Window.getClientWidth();\n m_clientLeft = Document.get().getBodyOffsetLeft();\n m_clientTop = Document.get().getBodyOffsetTop();\n DOM.setCapture(getElement());\n m_dragStartX = event.getX();\n m_dragStartY = event.getY();\n addStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().dragging());\n }", "public static RebalanceTaskInfoMap encodeRebalanceTaskInfoMap(RebalanceTaskInfo stealInfo) {\n return RebalanceTaskInfoMap.newBuilder()\n .setStealerId(stealInfo.getStealerId())\n .setDonorId(stealInfo.getDonorId())\n .addAllPerStorePartitionIds(ProtoUtils.encodeStoreToPartitionsTuple(stealInfo.getStoreToPartitionIds()))\n .setInitialCluster(new ClusterMapper().writeCluster(stealInfo.getInitialCluster()))\n .build();\n }", "public static tunneltrafficpolicy get(nitro_service service, String name) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\tobj.set_name(name);\n\t\ttunneltrafficpolicy response = (tunneltrafficpolicy) obj.get_resource(service);\n\t\treturn response;\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 }" ]
Create a JavadocComment, by formatting the text of the Javadoc using the given indentation.
[ "public JavadocComment toComment(String indentation) {\n for (char c : indentation.toCharArray()) {\n if (!Character.isWhitespace(c)) {\n throw new IllegalArgumentException(\"The indentation string should be composed only by whitespace characters\");\n }\n }\n StringBuilder sb = new StringBuilder();\n sb.append(EOL);\n final String text = toText();\n if (!text.isEmpty()) {\n for (String line : text.split(EOL)) {\n sb.append(indentation);\n sb.append(\" * \");\n sb.append(line);\n sb.append(EOL);\n }\n }\n sb.append(indentation);\n sb.append(\" \");\n return new JavadocComment(sb.toString());\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n\tpublic <T extends Annotation> T getAnnotation(Class<T> annotationType) {\n\t\tfor (Annotation annotation : this.annotations) {\n\t\t\tif (annotation.annotationType().equals(annotationType)) {\n\t\t\t\treturn (T) annotation;\n\t\t\t}\n\t\t}\n\t\tfor (Annotation metaAnn : this.annotations) {\n\t\t\tT ann = metaAnn.annotationType().getAnnotation(annotationType);\n\t\t\tif (ann != null) {\n\t\t\t\treturn ann;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public static String getPropertyName(String name) {\n if(name != null && (name.startsWith(\"get\") || name.startsWith(\"set\"))) {\n StringBuilder b = new StringBuilder(name);\n b.delete(0, 3);\n b.setCharAt(0, Character.toLowerCase(b.charAt(0)));\n return b.toString();\n } else {\n return name;\n }\n }", "private static boolean isAssignableFrom(WildcardType type1, Type type2) {\n if (!isAssignableFrom(type1.getUpperBounds()[0], type2)) {\n return false;\n }\n if (type1.getLowerBounds().length > 0 && !isAssignableFrom(type2, type1.getLowerBounds()[0])) {\n return false;\n }\n return true;\n }", "public static Date setTime(Date date, Date canonicalTime)\n {\n Date result;\n if (canonicalTime == null)\n {\n result = date;\n }\n else\n {\n //\n // The original naive implementation of this method generated\n // the \"start of day\" date (midnight) for the required day\n // then added the milliseconds from the canonical time\n // to move the time forward to the required point. Unfortunately\n // if the date we'e trying to do this for is the entry or\n // exit from DST, the result is wrong, hence I've switched to\n // the approach below.\n //\n Calendar cal = popCalendar(canonicalTime);\n int dayOffset = cal.get(Calendar.DAY_OF_YEAR) - 1;\n int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);\n int minute = cal.get(Calendar.MINUTE);\n int second = cal.get(Calendar.SECOND);\n int millisecond = cal.get(Calendar.MILLISECOND);\n\n cal.setTime(date);\n\n if (dayOffset != 0)\n {\n // The canonical time can be +1 day.\n // It's to do with the way we've historically\n // managed time ranges and midnight.\n cal.add(Calendar.DAY_OF_YEAR, dayOffset);\n }\n\n cal.set(Calendar.MILLISECOND, millisecond);\n cal.set(Calendar.SECOND, second);\n cal.set(Calendar.MINUTE, minute);\n cal.set(Calendar.HOUR_OF_DAY, hourOfDay);\n\n result = cal.getTime();\n pushCalendar(cal);\n }\n return result;\n }", "public void merge(GVRSkeleton newSkel)\n {\n int numBones = getNumBones();\n List<Integer> parentBoneIds = new ArrayList<Integer>(numBones + newSkel.getNumBones());\n List<String> newBoneNames = new ArrayList<String>(newSkel.getNumBones());\n List<Matrix4f> newMatrices = new ArrayList<Matrix4f>(newSkel.getNumBones());\n GVRPose oldBindPose = getBindPose();\n GVRPose curPose = getPose();\n\n for (int i = 0; i < numBones; ++i)\n {\n parentBoneIds.add(mParentBones[i]);\n }\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n String boneName = newSkel.getBoneName(j);\n int boneId = getBoneIndex(boneName);\n if (boneId < 0)\n {\n int parentId = newSkel.getParentBoneIndex(j);\n Matrix4f m = new Matrix4f();\n\n newSkel.getBindPose().getLocalMatrix(j, m);\n newMatrices.add(m);\n newBoneNames.add(boneName);\n if (parentId >= 0)\n {\n boneName = newSkel.getBoneName(parentId);\n parentId = getBoneIndex(boneName);\n }\n parentBoneIds.add(parentId);\n }\n }\n if (parentBoneIds.size() == numBones)\n {\n return;\n }\n int n = numBones + parentBoneIds.size();\n int[] parentIds = Arrays.copyOf(mParentBones, n);\n int[] boneOptions = Arrays.copyOf(mBoneOptions, n);\n String[] boneNames = Arrays.copyOf(mBoneNames, n);\n\n mBones = Arrays.copyOf(mBones, n);\n mPoseMatrices = new float[n * 16];\n for (int i = 0; i < parentBoneIds.size(); ++i)\n {\n n = numBones + i;\n parentIds[n] = parentBoneIds.get(i);\n boneNames[n] = newBoneNames.get(i);\n boneOptions[n] = BONE_ANIMATE;\n }\n mBoneOptions = boneOptions;\n mBoneNames = boneNames;\n mParentBones = parentIds;\n mPose = new GVRPose(this);\n mBindPose = new GVRPose(this);\n mBindPose.copy(oldBindPose);\n mPose.copy(curPose);\n mBindPose.sync();\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n mBindPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n mPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n }\n setBindPose(mBindPose);\n mPose.sync();\n updateBonePose();\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 }", "public static int[] binaryToRgb(boolean[] binaryArray) {\n int[] rgbArray = new int[binaryArray.length];\n\n for (int i = 0; i < binaryArray.length; i++) {\n if (binaryArray[i]) {\n rgbArray[i] = 0x00000000;\n } else {\n rgbArray[i] = 0x00FFFFFF;\n }\n }\n return rgbArray;\n }", "public void clearAnnotationData(Class<? extends Annotation> annotationClass) {\n stereotypes.invalidate(annotationClass);\n scopes.invalidate(annotationClass);\n qualifiers.invalidate(annotationClass);\n interceptorBindings.invalidate(annotationClass);\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<Symmetry454Date> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<Symmetry454Date>) super.zonedDateTime(temporal);\n }" ]
Returns all accessible projects of the given organizational unit. That is all projects which are owned by the current user or which are accessible for the group of the user.<p> @param cms the opencms context @param ouFqn the fully qualified name of the organizational unit to get projects for @param includeSubOus if all projects of sub-organizational units should be retrieved too @return all <code>{@link org.opencms.file.CmsProject}</code> objects in the organizational unit @throws CmsException if operation was not successful
[ "public List<CmsProject> getAllAccessibleProjects(CmsObject cms, String ouFqn, boolean includeSubOus)\n throws CmsException {\n\n CmsOrganizationalUnit orgUnit = readOrganizationalUnit(cms, ouFqn);\n return (m_securityManager.getAllAccessibleProjects(cms.getRequestContext(), orgUnit, includeSubOus));\n }" ]
[ "public static int rank(DMatrixRMaj A , double threshold ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,false,true);\n\n if( svd.inputModified() )\n A = A.copy();\n\n if( !svd.decompose(A) )\n throw new RuntimeException(\"Decomposition failed\");\n\n return SingularOps_DDRM.rank(svd, threshold);\n }", "public void setCastShadow(boolean enableFlag)\n {\n GVRSceneObject owner = getOwnerObject();\n\n if (owner != null)\n {\n GVRShadowMap shadowMap = (GVRShadowMap) getComponent(GVRRenderTarget.getComponentType());\n if (enableFlag)\n {\n if (shadowMap != null)\n {\n shadowMap.setEnable(true);\n }\n else\n {\n GVRCamera shadowCam = GVRShadowMap.makeOrthoShadowCamera(\n getGVRContext().getMainScene().getMainCameraRig().getCenterCamera());\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\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 static MediaType nonBinary( MediaType.Type type, String subType, Charset charSet ) {\n ApiUtil.notNull( charSet, \"charset must not be null\" );\n return new MediaType( type, subType, charSet );\n }", "public static double[][] toDouble(int[][] array) {\n double[][] n = new double[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (double) array[i][j];\n }\n }\n return n;\n }", "public static Searcher get(String variant) {\n final Searcher searcher = instances.get(variant);\n if (searcher == null) {\n throw new IllegalStateException(Errors.SEARCHER_GET_BEFORE_CREATE);\n }\n return searcher;\n }", "public Number getUnits(int field) throws MPXJException\n {\n Number result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n try\n {\n result = Double.valueOf(m_formats.getUnitsDecimalFormat().parse(m_fields[field]).doubleValue() * 100);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse units\", ex);\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public void adjustLinks(String sourceFolder, String targetFolder) throws CmsException {\n\n String rootSourceFolder = addSiteRoot(sourceFolder);\n String rootTargetFolder = addSiteRoot(targetFolder);\n String siteRoot = getRequestContext().getSiteRoot();\n getRequestContext().setSiteRoot(\"\");\n try {\n CmsLinkRewriter linkRewriter = new CmsLinkRewriter(this, rootSourceFolder, rootTargetFolder);\n linkRewriter.rewriteLinks();\n } finally {\n getRequestContext().setSiteRoot(siteRoot);\n }\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 }" ]
Parses the dictionary from an InputStream. @param client The SolrClient instance object. @param lang The language of the dictionary. @param is The InputStream object. @param documents List to put the assembled SolrInputObjects into. @param closeStream boolean flag that determines whether to close the inputstream or not.
[ "private static void readAndAddDocumentsFromStream(\n final SolrClient client,\n final String lang,\n final InputStream is,\n final List<SolrInputDocument> documents,\n final boolean closeStream) {\n\n final BufferedReader br = new BufferedReader(new InputStreamReader(is));\n\n try {\n String line = br.readLine();\n while (null != line) {\n\n final SolrInputDocument document = new SolrInputDocument();\n // Each field is named after the schema \"entry_xx\" where xx denotes\n // the two digit language code. See the file spellcheck/conf/schema.xml.\n document.addField(\"entry_\" + lang, line);\n documents.add(document);\n\n // Prevent OutOfMemoryExceptions ...\n if (documents.size() >= MAX_LIST_SIZE) {\n addDocuments(client, documents, false);\n documents.clear();\n }\n\n line = br.readLine();\n }\n } catch (IOException e) {\n LOG.error(\"Could not read spellcheck dictionary from input stream.\");\n } catch (SolrServerException e) {\n LOG.error(\"Error while adding documents to Solr server. \");\n } finally {\n try {\n if (closeStream) {\n br.close();\n }\n } catch (Exception e) {\n // Nothing to do here anymore ....\n }\n }\n }" ]
[ "public String expand(String macro) {\n if (!isMacro(macro)) {\n return macro;\n }\n String definition = macros.get(Config.canonical(macro));\n if (null == definition) {\n warn(\"possible missing definition of macro[%s]\", macro);\n }\n return null == definition ? macro : definition;\n }", "private boolean matchesFingerprint(byte[] buffer, Pattern fingerprint)\n {\n return fingerprint.matcher(m_charset == null ? new String(buffer) : new String(buffer, m_charset)).matches();\n }", "public static String renderJson(Object o) {\n\n Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()\n .create();\n return gson.toJson(o);\n }", "private void writeExceptions9(List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList, List<ProjectCalendarException> exceptions)\n {\n for (ProjectCalendarException exception : exceptions)\n {\n boolean working = exception.getWorking();\n\n Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay();\n dayList.add(day);\n day.setDayType(BIGINTEGER_ZERO);\n day.setDayWorking(Boolean.valueOf(working));\n\n Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod period = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayTimePeriod();\n day.setTimePeriod(period);\n period.setFromDate(exception.getFromDate());\n period.setToDate(exception.getToDate());\n\n if (working)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes();\n day.setWorkingTimes(times);\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n for (DateRange range : exception)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }", "private void setBelief(String bName, Object value) {\n introspector.setBeliefValue(this.getLocalName(), bName, value, null);\n }", "private void writeProjectExtendedAttributes(Project project)\n {\n Project.ExtendedAttributes attributes = m_factory.createProjectExtendedAttributes();\n project.setExtendedAttributes(attributes);\n List<Project.ExtendedAttributes.ExtendedAttribute> list = attributes.getExtendedAttribute();\n\n Set<FieldType> customFields = new HashSet<FieldType>();\n for (CustomField customField : m_projectFile.getCustomFields())\n {\n FieldType fieldType = customField.getFieldType();\n if (fieldType != null)\n {\n customFields.add(fieldType);\n }\n }\n\n customFields.addAll(m_extendedAttributesInUse);\n \n List<FieldType> customFieldsList = new ArrayList<FieldType>();\n customFieldsList.addAll(customFields);\n \n\n // Sort to ensure consistent order in file\n final CustomFieldContainer customFieldContainer = m_projectFile.getCustomFields();\n Collections.sort(customFieldsList, new Comparator<FieldType>()\n {\n @Override public int compare(FieldType o1, FieldType o2)\n {\n CustomField customField1 = customFieldContainer.getCustomField(o1);\n CustomField customField2 = customFieldContainer.getCustomField(o2);\n String name1 = o1.getClass().getSimpleName() + \".\" + o1.getName() + \" \" + customField1.getAlias();\n String name2 = o2.getClass().getSimpleName() + \".\" + o2.getName() + \" \" + customField2.getAlias();\n return name1.compareTo(name2);\n }\n });\n\n for (FieldType fieldType : customFieldsList)\n {\n Project.ExtendedAttributes.ExtendedAttribute attribute = m_factory.createProjectExtendedAttributesExtendedAttribute();\n list.add(attribute);\n attribute.setFieldID(String.valueOf(FieldTypeHelper.getFieldID(fieldType)));\n attribute.setFieldName(fieldType.getName());\n\n CustomField customField = customFieldContainer.getCustomField(fieldType);\n attribute.setAlias(customField.getAlias());\n }\n }", "public static TextEncryptor queryableText(CharSequence password, CharSequence salt) {\n\t\treturn new HexEncodingTextEncryptor(new AndroidAesBytesEncryptor(password.toString(), salt, AndroidKeyGenerators.shared(16)));\n\t}", "public BeanDefinitionInfo toDto(BeanDefinition beanDefinition) {\n\t\tif (beanDefinition instanceof GenericBeanDefinition) {\n\t\t\tGenericBeanDefinitionInfo info = new GenericBeanDefinitionInfo();\n\t\t\tinfo.setClassName(beanDefinition.getBeanClassName());\n\n\t\t\tif (beanDefinition.getPropertyValues() != null) {\n\t\t\t\tMap<String, BeanMetadataElementInfo> propertyValues = new HashMap<String, BeanMetadataElementInfo>();\n\t\t\t\tfor (PropertyValue value : beanDefinition.getPropertyValues().getPropertyValueList()) {\n\t\t\t\t\tObject obj = value.getValue();\n\t\t\t\t\tif (obj instanceof BeanMetadataElement) {\n\t\t\t\t\t\tpropertyValues.put(value.getName(), toDto((BeanMetadataElement) obj));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new IllegalArgumentException(\"Type \" + obj.getClass().getName()\n\t\t\t\t\t\t\t\t+ \" is not a BeanMetadataElement for property: \" + value.getName());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinfo.setPropertyValues(propertyValues);\n\t\t\t}\n\t\t\treturn info;\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Conversion to DTO of \" + beanDefinition.getClass().getName()\n\t\t\t\t\t+ \" not implemented\");\n\t\t}\n\t}", "@Deprecated\n public String get(String path) {\n final JsonValue value = this.values.get(this.pathToProperty(path));\n if (value == null) {\n return null;\n }\n if (!value.isString()) {\n return value.toString();\n }\n return value.asString();\n }" ]
Add an index on the given collection and field @param collection the collection to use for the index @param field the field to use for the index @param asc the sorting direction. <code>true</code> to sort ascending; <code>false</code> to sort descending @param background iff <code>true</code> the index is created in the background
[ "public static void addIndex(DBCollection collection, String field, boolean asc, boolean background) {\n int dir = (asc) ? 1 : -1;\n collection.createIndex(new BasicDBObject(field, dir), new BasicDBObject(\"background\", background));\n }" ]
[ "public static Date getTimestampFromLong(long timestamp)\n {\n TimeZone tz = TimeZone.getDefault();\n Date result = new Date(timestamp - tz.getRawOffset());\n\n if (tz.inDaylightTime(result) == true)\n {\n int savings;\n\n if (HAS_DST_SAVINGS == true)\n {\n savings = tz.getDSTSavings();\n }\n else\n {\n savings = DEFAULT_DST_SAVINGS;\n }\n\n result = new Date(result.getTime() - savings);\n }\n return (result);\n }", "protected boolean isFiltered(AbstractElement canddiate, Param param) {\n\t\tif (canddiate instanceof Group) {\n\t\t\tGroup group = (Group) canddiate;\n\t\t\tif (group.getGuardCondition() != null) {\n\t\t\t\tSet<Parameter> context = param.getAssignedParametes();\n\t\t\t\tConditionEvaluator evaluator = new ConditionEvaluator(context);\n\t\t\t\tif (!evaluator.evaluate(group.getGuardCondition())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "@Override public void close() throws IOException\n {\n long skippedLast = 0;\n if (m_remaining > 0)\n {\n skippedLast = skip(m_remaining);\n while (m_remaining > 0 && skippedLast > 0)\n {\n skippedLast = skip(m_remaining);\n }\n }\n }", "public static base_responses add(nitro_service client, cacheselector resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheselector addresources[] = new cacheselector[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cacheselector();\n\t\t\t\taddresources[i].selectorname = resources[i].selectorname;\n\t\t\t\taddresources[i].rule = resources[i].rule;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "@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 }", "@Override\r\n public boolean add(E o) {\r\n Integer index = indexes.get(o);\r\n if (index == null && ! locked) {\r\n index = objects.size();\r\n objects.add(o);\r\n indexes.put(o, index);\r\n return true;\r\n }\r\n return false;\r\n }", "private int getDaysInRange(Date startDate, Date endDate)\n {\n int result;\n Calendar cal = DateHelper.popCalendar(endDate);\n int endDateYear = cal.get(Calendar.YEAR);\n int endDateDayOfYear = cal.get(Calendar.DAY_OF_YEAR);\n\n cal.setTime(startDate);\n\n if (endDateYear == cal.get(Calendar.YEAR))\n {\n result = (endDateDayOfYear - cal.get(Calendar.DAY_OF_YEAR)) + 1;\n }\n else\n {\n result = 0;\n do\n {\n result += (cal.getActualMaximum(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR)) + 1;\n cal.roll(Calendar.YEAR, 1);\n cal.set(Calendar.DAY_OF_YEAR, 1);\n }\n while (cal.get(Calendar.YEAR) < endDateYear);\n result += endDateDayOfYear;\n }\n DateHelper.pushCalendar(cal);\n \n return result;\n }", "@Override\n public void solve(DMatrixRMaj B, DMatrixRMaj X) {\n X.reshape(blockA.numCols,B.numCols);\n blockB.reshape(B.numRows,B.numCols,false);\n blockX.reshape(X.numRows,X.numCols,false);\n MatrixOps_DDRB.convert(B,blockB);\n\n alg.solve(blockB,blockX);\n\n MatrixOps_DDRB.convert(blockX,X);\n }", "public static double Taneja(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double pq = p[i] + q[i];\n r += (pq / 2) * Math.log(pq / (2 * Math.sqrt(p[i] * q[i])));\n }\n }\n return r;\n }" ]
Transforms a list of Integer objects to an array of primitive int values. @param integers @return
[ "static int[] toIntArray(List<Integer> integers) {\n\t\tint[] ints = new int[integers.size()];\n\t\tint i = 0;\n\t\tfor (Integer n : integers) {\n\t\t\tints[i++] = n;\n\t\t}\n\t\treturn ints;\n\t}" ]
[ "public boolean absolute(int row) throws PersistenceBrokerException\r\n {\r\n // 1. handle the special cases first.\r\n if (row == 0)\r\n {\r\n return true;\r\n }\r\n\r\n if (row == 1)\r\n {\r\n m_activeIteratorIndex = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n m_activeIterator.absolute(1);\r\n return true;\r\n }\r\n if (row == -1)\r\n {\r\n m_activeIteratorIndex = m_rsIterators.size();\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n m_activeIterator.absolute(-1);\r\n return true;\r\n }\r\n\r\n // now do the real work.\r\n boolean movedToAbsolute = false;\r\n boolean retval = false;\r\n setNextIterator();\r\n\r\n // row is positive, so index from beginning.\r\n if (row > 0)\r\n {\r\n int sizeCount = 0;\r\n Iterator it = m_rsIterators.iterator();\r\n OJBIterator temp = null;\r\n while (it.hasNext() && !movedToAbsolute)\r\n {\r\n temp = (OJBIterator) it.next();\r\n if (temp.size() < row)\r\n {\r\n sizeCount += temp.size();\r\n }\r\n else\r\n {\r\n // move to the offset - sizecount\r\n m_currentCursorPosition = row - sizeCount;\r\n retval = temp.absolute(m_currentCursorPosition);\r\n movedToAbsolute = true;\r\n }\r\n }\r\n\r\n }\r\n\r\n // row is negative, so index from end\r\n else if (row < 0)\r\n {\r\n int sizeCount = 0;\r\n OJBIterator temp = null;\r\n for (int i = m_rsIterators.size(); ((i >= 0) && !movedToAbsolute); i--)\r\n {\r\n temp = (OJBIterator) m_rsIterators.get(i);\r\n if (temp.size() < row)\r\n {\r\n sizeCount += temp.size();\r\n }\r\n else\r\n {\r\n // move to the offset - sizecount\r\n m_currentCursorPosition = row + sizeCount;\r\n retval = temp.absolute(m_currentCursorPosition);\r\n movedToAbsolute = true;\r\n }\r\n }\r\n }\r\n\r\n return retval;\r\n }", "private void removeMount(SlotReference slot) {\n mediaDetails.remove(slot);\n if (mediaMounts.remove(slot)) {\n deliverMountUpdate(slot, false);\n }\n }", "private void checkModifications(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap features = new HashMap();\r\n FeatureDescriptorDef def;\r\n\r\n for (Iterator it = classDef.getFields(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getReferences(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getCollections(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n\r\n // now checking the modifications\r\n Properties mods;\r\n String modName;\r\n String propName;\r\n\r\n for (Iterator it = classDef.getModificationNames(); it.hasNext();)\r\n {\r\n modName = (String)it.next();\r\n if (!features.containsKey(modName))\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for an unknown feature \"+modName);\r\n }\r\n def = (FeatureDescriptorDef)features.get(modName);\r\n if (def.getOriginal() == null)\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for a feature \"+modName+\" that is not inherited but defined in the same class\");\r\n }\r\n // checking modification\r\n mods = classDef.getModification(modName);\r\n for (Iterator propIt = mods.keySet().iterator(); propIt.hasNext();)\r\n {\r\n propName = (String)propIt.next();\r\n if (!PropertyHelper.isPropertyAllowed(def.getClass(), propName))\r\n {\r\n throw new ConstraintException(\"The modification of attribute \"+propName+\" in class \"+classDef.getName()+\" is not applicable to the feature \"+modName);\r\n }\r\n }\r\n }\r\n }", "private static void parseStencil(JSONObject modelJSON,\n Shape current) throws JSONException {\n // get stencil type\n if (modelJSON.has(\"stencil\")) {\n JSONObject stencil = modelJSON.getJSONObject(\"stencil\");\n // TODO other attributes of stencil\n String stencilString = \"\";\n if (stencil.has(\"id\")) {\n stencilString = stencil.getString(\"id\");\n }\n current.setStencil(new StencilType(stencilString));\n }\n }", "public static Class<?> loadClass(String className) {\n try {\n return Class.forName(className);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }", "static boolean killProcess(final String processName, int id) {\n int pid;\n try {\n pid = processUtils.resolveProcessId(processName, id);\n if(pid > 0) {\n try {\n Runtime.getRuntime().exec(processUtils.getKillCommand(pid));\n return true;\n } catch (Throwable t) {\n ProcessLogger.ROOT_LOGGER.debugf(t, \"failed to kill process '%s' with pid '%s'\", processName, pid);\n }\n }\n } catch (Throwable t) {\n ProcessLogger.ROOT_LOGGER.debugf(t, \"failed to resolve pid of process '%s'\", processName);\n }\n return false;\n }", "public static base_response delete(nitro_service client, lbroute resource) throws Exception {\n\t\tlbroute deleteresource = new lbroute();\n\t\tdeleteresource.network = resource.network;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "static <T> StitchEvent<T> fromEvent(final Event event,\n final Decoder<T> decoder) {\n return new StitchEvent<>(event.getEventName(), event.getData(), decoder);\n }", "public GridCoverage2D call() {\n try {\n BufferedImage coverageImage = this.tiledLayer.createBufferedImage(\n this.tilePreparationInfo.getImageWidth(),\n this.tilePreparationInfo.getImageHeight());\n Graphics2D graphics = coverageImage.createGraphics();\n try {\n for (SingleTilePreparationInfo tileInfo: this.tilePreparationInfo.getSingleTiles()) {\n final TileTask task;\n if (tileInfo.getTileRequest() != null) {\n task = new SingleTileLoaderTask(\n tileInfo.getTileRequest(), this.errorImage, tileInfo.getTileIndexX(),\n tileInfo.getTileIndexY(), this.failOnError, this.registry, this.context);\n } else {\n task = new PlaceHolderImageTask(this.tiledLayer.getMissingTileImage(),\n tileInfo.getTileIndexX(), tileInfo.getTileIndexY());\n }\n Tile tile = task.call();\n if (tile.getImage() != null) {\n graphics.drawImage(tile.getImage(),\n tile.getxIndex() * this.tiledLayer.getTileSize().width,\n tile.getyIndex() * this.tiledLayer.getTileSize().height, null);\n }\n }\n } finally {\n graphics.dispose();\n }\n\n GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);\n GeneralEnvelope gridEnvelope = new GeneralEnvelope(this.tilePreparationInfo.getMapProjection());\n gridEnvelope.setEnvelope(this.tilePreparationInfo.getGridCoverageOrigin().x,\n this.tilePreparationInfo.getGridCoverageOrigin().y,\n this.tilePreparationInfo.getGridCoverageMaxX(),\n this.tilePreparationInfo.getGridCoverageMaxY());\n return factory.create(this.tiledLayer.createCommonUrl(), coverageImage, gridEnvelope,\n null, null, null);\n } catch (Exception e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }" ]
Stops and clears all transitions
[ "public void removeAllAnimations() {\n for (int i = 0, size = mAnimationList.size(); i < size; i++) {\n mAnimationList.get(i).removeAnimationListener(mAnimationListener);\n }\n mAnimationList.clear();\n }" ]
[ "public static <T> T assertNotNull(T value, String message) {\n if (value == null)\n throw new IllegalStateException(message);\n return value;\n }", "private static Map<String, String> mapCustomInfo(CustomInfoType ciType){\n Map<String, String> customInfo = new HashMap<String, String>();\n if (ciType != null){\n for (CustomInfoType.Item item : ciType.getItem()) {\n customInfo.put(item.getKey(), item.getValue());\n }\n }\n return customInfo;\n }", "void countNonZeroInR( int[] parent ) {\n TriangularSolver_DSCC.postorder(parent,n,post,gwork);\n columnCounts.process(A,parent,post,countsR);\n nz_in_R = 0;\n for (int k = 0; k < n; k++) {\n nz_in_R += countsR[k];\n }\n if( nz_in_R < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in R counts\");\n }", "static void init() {// NOPMD\n\n\t\tdetermineIfNTEventLogIsSupported();\n\n\t\tURL resource = null;\n\n\t\tfinal String configurationOptionStr = OptionConverter.getSystemProperty(DEFAULT_CONFIGURATION_KEY, null);\n\n\t\tif (configurationOptionStr != null) {\n\t\t\ttry {\n\t\t\t\tresource = new URL(configurationOptionStr);\n\t\t\t} catch (MalformedURLException ex) {\n\t\t\t\t// so, resource is not a URL:\n\t\t\t\t// attempt to get the resource from the class path\n\t\t\t\tresource = Loader.getResource(configurationOptionStr);\n\t\t\t}\n\t\t}\n\t\tif (resource == null) {\n\t\t\tresource = Loader.getResource(DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t}\n\n\t\tif (resource == null) {\n\t\t\tSystem.err.println(\"[FoundationLogger] Can not find resource: \" + DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t\tthrow new FoundationIOException(\"Can not find resource: \" + DEFAULT_CONFIGURATION_FILE); // NOPMD\n\t\t}\n\n\t\t// update the log manager to use the Foundation repository.\n\t\tfinal RepositorySelector foundationRepositorySelector = new FoundationRepositorySelector(FoundationLogFactory.foundationLogHierarchy);\n\t\tLogManager.setRepositorySelector(foundationRepositorySelector, null);\n\n\t\t// set logger to info so we always want to see these logs even if root\n\t\t// is set to ERROR.\n\t\tfinal Logger logger = getLogger(FoundationLogger.class);\n\n\t\tfinal String logPropFile = resource.getPath();\n\t\tlog4jConfigProps = getLogProperties(resource);\n\t\t\n\t\t// select and configure again so the loggers are created with the right\n\t\t// level after the repository selector was updated.\n\t\tOptionConverter.selectAndConfigure(resource, null, FoundationLogFactory.foundationLogHierarchy);\n\n\t\t// start watching for property changes\n\t\tsetUpPropFileReloading(logger, logPropFile, log4jConfigProps);\n\n\t\t// add syslog appender or windows event viewer appender\n//\t\tsetupOSSystemLog(logger, log4jConfigProps);\n\n\t\t// parseMarkerPatterns(log4jConfigProps);\n\t\t// parseMarkerPurePattern(log4jConfigProps);\n//\t\tudpateMarkerStructuredLogOverrideMap(logger);\n\n AbstractFoundationLoggingMarker.init();\n\n\t\tupdateSniffingLoggersLevel(logger);\n\n setupJULSupport(resource);\n\n }", "public String getProperty(String key, String defaultValue) {\n return mProperties.getProperty(key, defaultValue);\n }", "public synchronized Object removeRoleMapping(final String roleName) {\n /*\n * Would not expect this to happen during boot so don't offer the 'immediate' optimisation.\n */\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n if (newRoles.containsKey(roleName)) {\n RoleMappingImpl removed = newRoles.remove(roleName);\n Object removalKey = new Object();\n removedRoles.put(removalKey, removed);\n roleMappings = Collections.unmodifiableMap(newRoles);\n\n return removalKey;\n }\n\n return null;\n }", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) {\n d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds());\n\n if (start == null || end == null) {\n return false;\n }\n\n if (start.before(end) && (!(d.after(start) && d.before(end)))) {\n return false;\n }\n\n if (end.before(start) && (!(d.after(end) || d.before(start)))) {\n return false;\n }\n return true;\n }", "public VideoCollection generate(final int videoCount) {\n List<Video> videos = new LinkedList<Video>();\n for (int i = 0; i < videoCount; i++) {\n Video video = generateRandomVideo();\n videos.add(video);\n }\n return new VideoCollection(videos);\n }", "public static int getJSONColor(final JSONObject json, String elementName) throws JSONException {\n Object raw = json.get(elementName);\n return convertJSONColor(raw);\n }" ]
add converter at given index. The index can be changed during conversion if canReorder is true @param index @param converter
[ "public void addConverter(int index, IConverter converter) {\r\n\t\tconverterList.add(index, converter);\r\n\t\tif (converter instanceof IContainerConverter) {\r\n\t\t\tIContainerConverter containerConverter = (IContainerConverter) converter;\r\n\t\t\tif (containerConverter.getElementConverter() == null) {\r\n\t\t\t\tcontainerConverter.setElementConverter(elementConverter);\r\n\t\t\t}\r\n\t\t}\r\n\t}" ]
[ "public static Object instantiate(Constructor constructor) throws InstantiationException\r\n {\r\n if(constructor == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided!\");\r\n }\r\n\r\n Object result = null;\r\n try\r\n {\r\n result = constructor.newInstance(NO_ARGS);\r\n }\r\n catch(InstantiationException e)\r\n {\r\n throw e;\r\n }\r\n catch(Exception e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (constructor != null ? constructor.getDeclaringClass().getName() : \"null\")\r\n + \"' with given constructor: \" + e.getMessage(), e);\r\n }\r\n return result;\r\n }", "public String getMessage(Locale locale) {\n\t\tif (getCause() != null) {\n\t\t\tString message = getShortMessage(locale) + \", \" + translate(\"ROOT_CAUSE\", locale) + \" \";\n\t\t\tif (getCause() instanceof GeomajasException) {\n\t\t\t\treturn message + ((GeomajasException) getCause()).getMessage(locale);\n\t\t\t}\n\t\t\treturn message + getCause().getMessage();\n\t\t} else {\n\t\t\treturn getShortMessage(locale);\n\t\t}\n\t}", "protected boolean intersect(GVRSceneObject.BoundingVolume bv1, GVRSceneObject.BoundingVolume bv2)\n {\n return (bv1.maxCorner.x >= bv2.minCorner.x) &&\n (bv1.maxCorner.y >= bv2.minCorner.y) &&\n (bv1.maxCorner.z >= bv2.minCorner.z) &&\n (bv1.minCorner.x <= bv2.maxCorner.x) &&\n (bv1.minCorner.y <= bv2.maxCorner.y) &&\n (bv1.minCorner.z <= bv2.maxCorner.z);\n }", "public static File createTempDirectory(String prefix) {\n\tFile temp = null;\n\t\n\ttry {\n\t temp = File.createTempFile(prefix != null ? prefix : \"temp\", Long.toString(System.nanoTime()));\n\t\n\t if (!(temp.delete())) {\n\t throw new IOException(\"Could not delete temp file: \"\n\t\t + temp.getAbsolutePath());\n\t }\n\t\n\t if (!(temp.mkdir())) {\n\t throw new IOException(\"Could not create temp directory: \"\n\t + temp.getAbsolutePath());\n\t }\n\t} catch (IOException e) {\n\t throw new DukeException(\"Unable to create temporary directory with prefix \" + prefix, e);\n\t}\n\t\n\treturn temp;\n }", "private AffineTransform getAlignmentTransform() {\n final int offsetX;\n switch (this.settings.getParams().getAlign()) {\n case LEFT:\n offsetX = 0;\n break;\n case RIGHT:\n offsetX = this.settings.getMaxSize().width - this.settings.getSize().width;\n break;\n case CENTER:\n default:\n offsetX = (int) Math\n .floor(this.settings.getMaxSize().width / 2.0 - this.settings.getSize().width / 2.0);\n break;\n }\n\n final int offsetY;\n switch (this.settings.getParams().getVerticalAlign()) {\n case TOP:\n offsetY = 0;\n break;\n case BOTTOM:\n offsetY = this.settings.getMaxSize().height - this.settings.getSize().height;\n break;\n case MIDDLE:\n default:\n offsetY = (int) Math.floor(this.settings.getMaxSize().height / 2.0 -\n this.settings.getSize().height / 2.0);\n break;\n }\n\n return AffineTransform.getTranslateInstance(Math.round(offsetX), Math.round(offsetY));\n }", "public int createLogs(String topic, final int partitions, final boolean forceEnlarge) {\n TopicNameValidator.validate(topic);\n synchronized (logCreationLock) {\n final int configPartitions = getPartition(topic);\n if (configPartitions >= partitions || !forceEnlarge) {\n return configPartitions;\n }\n topicPartitionsMap.put(topic, partitions);\n if (config.getEnableZookeeper()) {\n if (getLogPool(topic, 0) != null) {//created already\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.ENLARGE, topic));\n } else {\n topicRegisterTasks.add(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n }\n return partitions;\n }\n }", "public static auditsyslogpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_lbvserver_binding obj = new auditsyslogpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_lbvserver_binding response[] = (auditsyslogpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private List<Row> join(List<Row> leftRows, String leftColumn, String rightTable, List<Row> rightRows, String rightColumn)\n {\n List<Row> result = new LinkedList<Row>();\n\n RowComparator leftComparator = new RowComparator(new String[]\n {\n leftColumn\n });\n RowComparator rightComparator = new RowComparator(new String[]\n {\n rightColumn\n });\n Collections.sort(leftRows, leftComparator);\n Collections.sort(rightRows, rightComparator);\n\n ListIterator<Row> rightIterator = rightRows.listIterator();\n Row rightRow = rightIterator.hasNext() ? rightIterator.next() : null;\n\n for (Row leftRow : leftRows)\n {\n Integer leftValue = leftRow.getInteger(leftColumn);\n boolean match = false;\n\n while (rightRow != null)\n {\n Integer rightValue = rightRow.getInteger(rightColumn);\n int comparison = leftValue.compareTo(rightValue);\n if (comparison == 0)\n {\n match = true;\n break;\n }\n\n if (comparison < 0)\n {\n if (rightIterator.hasPrevious())\n {\n rightRow = rightIterator.previous();\n }\n break;\n }\n\n rightRow = rightIterator.next();\n }\n\n if (match && rightRow != null)\n {\n Map<String, Object> newMap = new HashMap<String, Object>(((MapRow) leftRow).getMap());\n\n for (Entry<String, Object> entry : ((MapRow) rightRow).getMap().entrySet())\n {\n String key = entry.getKey();\n if (newMap.containsKey(key))\n {\n key = rightTable + \".\" + key;\n }\n newMap.put(key, entry.getValue());\n }\n\n result.add(new MapRow(newMap));\n }\n }\n\n return result;\n }", "public void update(int width, int height, byte[] grayscaleData)\n {\n NativeBitmapImage.updateFromMemory(getNative(), width, height, grayscaleData);\n }" ]
Gets the automaton by id. @param id the id @return the automaton by id @throws IOException Signals that an I/O exception has occurred.
[ "public Automaton getAutomatonById(String id) throws IOException {\n if (idToVersion.containsKey(id)) {\n List<BytesRef> bytesArray = new ArrayList<>();\n Set<String> data = get(id);\n if (data != null) {\n Term term;\n for (String item : data) {\n term = new Term(\"dummy\", item);\n bytesArray.add(term.bytes());\n }\n Collections.sort(bytesArray);\n return Automata.makeStringUnion(bytesArray);\n }\n }\n return null;\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 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 }", "protected AbstractColumn buildSimpleColumn() {\n\t\tSimpleColumn column = new SimpleColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumnProperty.getFieldProperties().putAll(fieldProperties);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setFieldDescription(fieldDescription);\n\t\treturn column;\n\t}", "private void readProjectProperties(Document cdp)\n {\n WorkspaceProperties props = cdp.getWorkspaceProperties();\n ProjectProperties mpxjProps = m_projectFile.getProjectProperties();\n mpxjProps.setSymbolPosition(props.getCurrencyPosition());\n mpxjProps.setCurrencyDigits(props.getCurrencyDigits());\n mpxjProps.setCurrencySymbol(props.getCurrencySymbol());\n mpxjProps.setDaysPerMonth(props.getDaysPerMonth());\n mpxjProps.setMinutesPerDay(props.getHoursPerDay());\n mpxjProps.setMinutesPerWeek(props.getHoursPerWeek());\n\n m_workHoursPerDay = mpxjProps.getMinutesPerDay().doubleValue() / 60.0;\n }", "public void addAll(Vertex vtx) {\n if (head == null) {\n head = vtx;\n } else {\n tail.next = vtx;\n }\n vtx.prev = tail;\n while (vtx.next != null) {\n vtx = vtx.next;\n }\n tail = vtx;\n }", "public String getLinkColor(JSONObject jsonObject){\n if(jsonObject == null) return null;\n try {\n return jsonObject.has(\"color\") ? jsonObject.getString(\"color\") : \"\";\n } catch (JSONException e) {\n Logger.v(\"Unable to get Link Text Color with JSON - \"+e.getLocalizedMessage());\n return null;\n }\n }", "public Map<String, ImplT> convertToUnmodifiableMap(List<InnerT> innerList) {\n Map<String, ImplT> result = new HashMap<>();\n for (InnerT inner : innerList) {\n result.put(name(inner), impl(inner));\n }\n\n return Collections.unmodifiableMap(result);\n }", "private String getHostHeaderForHost(String hostName) {\n List<ServerRedirect> servers = serverRedirectService.tableServers(requestInformation.get().client.getId());\n for (ServerRedirect server : servers) {\n if (server.getSrcUrl().compareTo(hostName) == 0) {\n String hostHeader = server.getHostHeader();\n if (hostHeader == null || hostHeader.length() == 0) {\n return null;\n }\n return hostHeader;\n }\n }\n return null;\n }", "public static String stringMatcherByPattern(String input, String patternStr) {\n\n String output = PcConstants.SYSTEM_FAIL_MATCH_REGEX;\n\n // 20140105: fix the NPE issue\n if (patternStr == null) {\n logger.error(\"patternStr is NULL! (Expected when the aggregation rule is not defined at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n return output;\n }\n\n if (input == null) {\n logger.error(\"input (Expected when the response is null and now try to match on response) is NULL in stringMatcherByPattern() at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n return output;\n } else {\n input = input.replace(\"\\n\", \"\").replace(\"\\r\", \"\");\n }\n\n logger.debug(\"input: \" + input);\n logger.debug(\"patternStr: \" + patternStr);\n\n Pattern patternMetric = Pattern.compile(patternStr, Pattern.MULTILINE);\n\n final Matcher matcher = patternMetric.matcher(input);\n if (matcher.matches()) {\n output = matcher.group(1);\n }\n return output;\n }" ]
binds the Identities Primary key values to the statement
[ "public void bindDelete(PreparedStatement stmt, Identity oid, ClassDescriptor cld) throws SQLException\r\n {\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n int i = 0;\r\n try\r\n {\r\n for (; i < pkValues.length; i++)\r\n {\r\n setObjectForStatement(stmt, i + 1, pkValues[i], pkFields[i].getJdbcType().getType());\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n m_log.error(\"bindDelete failed for: \" + oid.toString() + \", while set value '\" +\r\n pkValues[i] + \"' for column \" + pkFields[i].getColumnName());\r\n throw e;\r\n }\r\n }" ]
[ "public static void writeCorrelationId(Message message, String correlationId) {\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n headers.put(CORRELATIONID_HTTP_HEADER_NAME, Collections.singletonList(correlationId));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + CORRELATIONID_HTTP_HEADER_NAME + \"' set to: \" + correlationId);\n }\n }", "public Task add()\n {\n Task task = new Task(m_projectFile, (Task) null);\n add(task);\n m_projectFile.getChildTasks().add(task);\n return task;\n }", "public void updateInfo(Info info) {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"PUT\");\n request.setBody(info.getPendingChanges());\n BoxAPIResponse boxAPIResponse = request.send();\n\n if (boxAPIResponse instanceof BoxJSONResponse) {\n BoxJSONResponse response = (BoxJSONResponse) boxAPIResponse;\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }\n }", "public static base_responses update(nitro_service client, nsacl6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsacl6 updateresources[] = new nsacl6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsacl6();\n\t\t\t\tupdateresources[i].acl6name = resources[i].acl6name;\n\t\t\t\tupdateresources[i].aclaction = resources[i].aclaction;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].icmptype = resources[i].icmptype;\n\t\t\t\tupdateresources[i].icmpcode = resources[i].icmpcode;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].established = resources[i].established;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public void doRun(Properties properties) {\n ServerSetup[] serverSetup = new PropertiesBasedServerSetupBuilder().build(properties);\n\n if (serverSetup.length == 0) {\n printUsage(System.out);\n\n } else {\n greenMail = new GreenMail(serverSetup);\n log.info(\"Starting GreenMail standalone v{} using {}\",\n BuildInfo.INSTANCE.getProjectVersion(), Arrays.toString(serverSetup));\n greenMail.withConfiguration(new PropertiesBasedGreenMailConfigurationBuilder().build(properties))\n .start();\n }\n }", "public void executeUpdate(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeUpdate: \" + obj);\r\n }\r\n\r\n // obj with nothing but key fields is not updated\r\n if (cld.getNonPkRwFields().length == 0)\r\n {\r\n return;\r\n }\r\n\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n // BRJ: preserve current locking values\r\n // locking values will be restored in case of exception\r\n ValueContainer[] oldLockingValues;\r\n oldLockingValues = cld.getCurrentLockingValues(obj);\r\n try\r\n {\r\n stmt = sm.getUpdateStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getUpdateStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getUpdateStatement returned a null statement\");\r\n }\r\n\r\n sm.bindUpdate(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeUpdate: \" + stmt);\r\n\r\n if ((stmt.executeUpdate() == 0) && cld.isLocking()) //BRJ\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tString objToString = \"\";\r\n \ttry {\r\n \t\tobjToString = obj.toString();\r\n \t} catch (Exception ex) {}\r\n throw new OptimisticLockException(\"Object has been modified by someone else: \" + objToString, obj);\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getUpdateProcedure(), obj, stmt);\r\n }\r\n catch (OptimisticLockException e)\r\n {\r\n // Don't log as error\r\n if (logger.isDebugEnabled())\r\n logger.debug(\r\n \"OptimisticLockException during the execution of update: \" + e.getMessage(),\r\n e);\r\n throw e;\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // BRJ: restore old locking values\r\n setLockingValues(cld, obj, oldLockingValues);\r\n\r\n logger.error(\r\n \"PersistenceBrokerException during the execution of the update: \" + e.getMessage(),\r\n e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedUpdateStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }", "public static base_response update(nitro_service client, nsrpcnode resource) throws Exception {\n\t\tnsrpcnode updateresource = new nsrpcnode();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.srcip = resource.srcip;\n\t\tupdateresource.secure = resource.secure;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static base_responses clear(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 clearresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new route6();\n\t\t\t\tclearresources[i].routetype = resources[i].routetype;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}", "protected void finishBox()\n {\n \tif (textLine.length() > 0)\n \t{\n String s;\n if (isReversed(Character.getDirectionality(textLine.charAt(0))))\n s = textLine.reverse().toString();\n else\n s = textLine.toString();\n\n curstyle.setLeft(textMetrics.getX());\n curstyle.setTop(textMetrics.getTop());\n curstyle.setLineHeight(textMetrics.getHeight());\n\n\t renderText(s, textMetrics);\n\t textLine = new StringBuilder();\n\t textMetrics = null;\n \t}\n }" ]
helper to calculate the actionBar height @param context @return
[ "public static int getActionBarHeight(Context context) {\n int actionBarHeight = UIUtils.getThemeAttributeDimensionSize(context, R.attr.actionBarSize);\n if (actionBarHeight == 0) {\n actionBarHeight = context.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);\n }\n return actionBarHeight;\n }" ]
[ "public void setIsSeries(Boolean isSeries) {\r\n\r\n if (null != isSeries) {\r\n final boolean series = isSeries.booleanValue();\r\n if ((null != m_model.getParentSeriesId()) && series) {\r\n m_removeSeriesBindingConfirmDialog.show(new Command() {\r\n\r\n public void execute() {\r\n\r\n m_model.setParentSeriesId(null);\r\n setPattern(PatternType.DAILY.toString());\r\n\r\n }\r\n });\r\n } else {\r\n setPattern(series ? PatternType.DAILY.toString() : PatternType.NONE.toString());\r\n }\r\n }\r\n }", "private static int findNext(boolean reverse, int pos) {\n boolean backwards = IS_BACKWARDS_CHECKBOX.isSelected();\n backwards = backwards ? !reverse : reverse;\n\n String pattern = (String) FIND_FIELD.getSelectedItem();\n if (pattern != null && pattern.length() > 0) {\n try {\n Document doc = textComponent.getDocument();\n doc.getText(0, doc.getLength(), SEGMENT);\n }\n catch (Exception e) {\n // should NEVER reach here\n e.printStackTrace();\n }\n\n pos += textComponent.getSelectedText() == null ?\n (backwards ? -1 : 1) : 0;\n\n char first = backwards ?\n pattern.charAt(pattern.length() - 1) : pattern.charAt(0);\n char oppFirst = Character.isUpperCase(first) ?\n Character.toLowerCase(first) : Character.toUpperCase(first);\n int start = pos;\n boolean wrapped = WRAP_SEARCH_CHECKBOX.isSelected();\n int end = backwards ? 0 : SEGMENT.getEndIndex();\n pos += backwards ? -1 : 1;\n\n int length = textComponent.getDocument().getLength();\n if (pos > length) {\n pos = wrapped ? 0 : length;\n }\n\n boolean found = false;\n while (!found && (backwards ? pos > end : pos < end)) {\n found = !MATCH_CASE_CHECKBOX.isSelected() && SEGMENT.array[pos] == oppFirst;\n found = found ? found : SEGMENT.array[pos] == first;\n\n if (found) {\n pos += backwards ? -(pattern.length() - 1) : 0;\n for (int i = 0; found && i < pattern.length(); i++) {\n char c = pattern.charAt(i);\n found = SEGMENT.array[pos + i] == c;\n if (!MATCH_CASE_CHECKBOX.isSelected() && !found) {\n c = Character.isUpperCase(c) ?\n Character.toLowerCase(c) :\n Character.toUpperCase(c);\n found = SEGMENT.array[pos + i] == c;\n }\n }\n }\n\n if (!found) {\n pos += backwards ? -1 : 1;\n\n if (pos == end && wrapped) {\n pos = backwards ? SEGMENT.getEndIndex() : 0;\n end = start;\n wrapped = false;\n }\n }\n }\n pos = found ? pos : -1;\n }\n\n return pos;\n }", "public static List<List<RTFEmbeddedObject>> getEmbeddedObjects(String text)\n {\n List<List<RTFEmbeddedObject>> objects = null;\n List<RTFEmbeddedObject> objectData;\n\n int offset = text.indexOf(OBJDATA);\n if (offset != -1)\n {\n objects = new LinkedList<List<RTFEmbeddedObject>>();\n\n while (offset != -1)\n {\n objectData = new LinkedList<RTFEmbeddedObject>();\n objects.add(objectData);\n offset = readObjectData(offset, text, objectData);\n offset = text.indexOf(OBJDATA, offset);\n }\n }\n\n return (objects);\n }", "public final List<MtasSolrStatus> checkForExceptions() {\n List<MtasSolrStatus> statusWithException = null;\n for (MtasSolrStatus item : data) {\n if (item.checkResponseForException()) {\n if (statusWithException == null) {\n statusWithException = new ArrayList<>();\n }\n statusWithException.add(item);\n }\n }\n return statusWithException;\n }", "public int compareTo(Rational other)\n {\n if (denominator == other.getDenominator())\n {\n return ((Long) numerator).compareTo(other.getNumerator());\n }\n else\n {\n Long adjustedNumerator = numerator * other.getDenominator();\n Long otherAdjustedNumerator = other.getNumerator() * denominator;\n return adjustedNumerator.compareTo(otherAdjustedNumerator);\n }\n }", "private void writeTasks(List<Task> tasks) throws IOException\n {\n for (Task task : tasks)\n {\n writeTask(task);\n writeTasks(task.getChildTasks());\n }\n }", "public Set<? extends AbstractBean<?, ?>> resolveSpecializedBeans(Bean<?> specializingBean) {\n if (specializingBean instanceof AbstractClassBean<?>) {\n AbstractClassBean<?> abstractClassBean = (AbstractClassBean<?>) specializingBean;\n if (abstractClassBean.isSpecializing()) {\n return specializedBeans.getValue(specializingBean);\n }\n }\n if (specializingBean instanceof ProducerMethod<?, ?>) {\n ProducerMethod<?, ?> producerMethod = (ProducerMethod<?, ?>) specializingBean;\n if (producerMethod.isSpecializing()) {\n return specializedBeans.getValue(specializingBean);\n }\n }\n return Collections.emptySet();\n }", "private void allRelation(Options opt, RelationType rt, ClassDoc from) {\n\tString tagname = rt.lower;\n\tfor (Tag tag : from.tags(tagname)) {\n\t String t[] = tokenize(tag.text()); // l-src label l-dst target\n\t t = t.length == 1 ? new String[] { \"-\", \"-\", \"-\", t[0] } : t; // Shorthand\n\t if (t.length != 4) {\n\t\tSystem.err.println(\"Error in \" + from + \"\\n\" + tagname + \" expects four fields (l-src label l-dst target): \" + tag.text());\n\t\treturn;\n\t }\n\t ClassDoc to = from.findClass(t[3]);\n\t if (to != null) {\n\t\tif(hidden(to))\n\t\t continue;\n\t\trelation(opt, rt, from, to, t[0], t[1], t[2]);\n\t } else {\n\t\tif(hidden(t[3]))\n\t\t continue;\n\t\trelation(opt, rt, from, from.toString(), to, t[3], t[0], t[1], t[2]);\n\t }\n\t}\n }", "public static base_response rename(nitro_service client, nsacl6 resource, String new_acl6name) throws Exception {\n\t\tnsacl6 renameresource = new nsacl6();\n\t\trenameresource.acl6name = resource.acl6name;\n\t\treturn renameresource.rename_resource(client,new_acl6name);\n\t}" ]
Get upload status for the currently authenticated user. Requires authentication with 'read' permission using the new authentication API. @return A User object with upload status data fields filled @throws FlickrException
[ "public User getUploadStatus() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_UPLOAD_STATUS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"id\"));\r\n user.setPro(\"1\".equals(userElement.getAttribute(\"ispro\")));\r\n user.setUsername(XMLUtilities.getChildValue(userElement, \"username\"));\r\n\r\n Element bandwidthElement = XMLUtilities.getChild(userElement, \"bandwidth\");\r\n user.setBandwidthMax(bandwidthElement.getAttribute(\"max\"));\r\n user.setBandwidthUsed(bandwidthElement.getAttribute(\"used\"));\r\n user.setIsBandwidthUnlimited(\"1\".equals(bandwidthElement.getAttribute(\"unlimited\")));\r\n\r\n Element filesizeElement = XMLUtilities.getChild(userElement, \"filesize\");\r\n user.setFilesizeMax(filesizeElement.getAttribute(\"max\"));\r\n\r\n Element setsElement = XMLUtilities.getChild(userElement, \"sets\");\r\n user.setSetsCreated(setsElement.getAttribute(\"created\"));\r\n user.setSetsRemaining(setsElement.getAttribute(\"remaining\"));\r\n\r\n Element videosElement = XMLUtilities.getChild(userElement, \"videos\");\r\n user.setVideosUploaded(videosElement.getAttribute(\"uploaded\"));\r\n user.setVideosRemaining(videosElement.getAttribute(\"remaining\"));\r\n\r\n Element videoSizeElement = XMLUtilities.getChild(userElement, \"videosize\");\r\n user.setVideoSizeMax(videoSizeElement.getAttribute(\"maxbytes\"));\r\n\r\n return user;\r\n }" ]
[ "public AccrueType getAccrueType(int field)\n {\n AccrueType result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = AccrueTypeUtility.getInstance(m_fields[field], m_locale);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) {\n if(!lhs.getNodeIds().equals(rhs.getNodeIds())) {\n throw new VoldemortException(\"Node ids are not the same [ lhs cluster node ids (\"\n + lhs.getNodeIds()\n + \") not equal to rhs cluster node ids (\"\n + rhs.getNodeIds() + \") ]\");\n }\n }", "public static <K, V> Map<K, V> immutableMapView(Map<K, V> map) {\n if (map instanceof ImmutableMap<?, ?>) {\n return map;\n }\n return Collections.unmodifiableMap(map);\n }", "public Character getCharacter(int field)\n {\n Character result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Character.valueOf(m_fields[field].charAt(0));\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "void insertOne(final MongoNamespace namespace, final BsonDocument document) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n // Remove forbidden fields from the document before inserting it into the local collection.\n final BsonDocument docForStorage = sanitizeDocument(document);\n\n final NamespaceSynchronizationConfig nsConfig =\n this.syncConfig.getNamespaceConfig(namespace);\n final Lock lock = nsConfig.getLock().writeLock();\n lock.lock();\n final ChangeEvent<BsonDocument> event;\n final BsonValue documentId;\n try {\n getLocalCollection(namespace).insertOne(docForStorage);\n documentId = BsonUtils.getDocumentId(docForStorage);\n event = ChangeEvents.changeEventForLocalInsert(namespace, docForStorage, true);\n final CoreDocumentSynchronizationConfig config = syncConfig.addAndGetSynchronizedDocument(\n namespace,\n documentId\n );\n config.setSomePendingWritesAndSave(logicalT, event);\n } finally {\n lock.unlock();\n }\n checkAndInsertNamespaceListener(namespace);\n eventDispatcher.emitEvent(nsConfig, event);\n } finally {\n ongoingOperationsGroup.exit();\n }\n }", "private static LogPriorType intToType(int intPrior) {\r\n LogPriorType[] values = LogPriorType.values();\r\n for (LogPriorType val : values) {\r\n if (val.ordinal() == intPrior) {\r\n return val;\r\n }\r\n }\r\n throw new IllegalArgumentException(intPrior + \" is not a legal LogPrior.\");\r\n }", "public static String getFileFormat(POIFSFileSystem fs) throws IOException\n {\n String fileFormat = \"\";\n DirectoryEntry root = fs.getRoot();\n if (root.getEntryNames().contains(\"\\1CompObj\"))\n {\n CompObj compObj = new CompObj(new DocumentInputStream((DocumentEntry) root.getEntry(\"\\1CompObj\")));\n fileFormat = compObj.getFileFormat();\n }\n return fileFormat;\n }", "public void forAllIndices(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false);\r\n\r\n // first the default index\r\n _curIndexDef = _curTableDef.getIndex(null);\r\n if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique()))\r\n {\r\n generate(template);\r\n }\r\n for (Iterator it = _curTableDef.getIndices(); it.hasNext(); )\r\n {\r\n _curIndexDef = (IndexDef)it.next();\r\n if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique()))\r\n { \r\n generate(template);\r\n }\r\n }\r\n _curIndexDef = null;\r\n }", "public static Command newQuery(String identifier,\n String name,\n Object[] arguments) {\n return getCommandFactoryProvider().newQuery( identifier,\n name,\n arguments );\n }" ]
Use this API to fetch responderpolicy resource of given name .
[ "public static responderpolicy get(nitro_service service, String name) throws Exception{\n\t\tresponderpolicy obj = new responderpolicy();\n\t\tobj.set_name(name);\n\t\tresponderpolicy response = (responderpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public static String urlEncode(String path) throws URISyntaxException {\n if (isNullOrEmpty(path)) return path;\n\n return UrlEscapers.urlFragmentEscaper().escape(path);\n }", "public void saveFavorites(List<CmsFavoriteEntry> favorites) throws CmsException {\n\n try {\n JSONObject json = new JSONObject();\n JSONArray array = new JSONArray();\n for (CmsFavoriteEntry entry : favorites) {\n array.put(entry.toJson());\n }\n json.put(BASE_KEY, array);\n String data = json.toString();\n CmsUser user = readUser();\n user.setAdditionalInfo(ADDINFO_KEY, data);\n m_cms.writeUser(user);\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n\n }", "public void each(int offset, int maxRows, Closure closure) throws SQLException {\n eachRow(getSql(), getParameters(), offset, maxRows, closure);\n }", "public static nspbr6_stats get(nitro_service service, String name) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tobj.set_name(name);\n\t\tnspbr6_stats response = (nspbr6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public static ComplexNumber Divide(ComplexNumber z1, ComplexNumber z2) {\r\n\r\n ComplexNumber conj = ComplexNumber.Conjugate(z2);\r\n\r\n double a = z1.real * conj.real + ((z1.imaginary * conj.imaginary) * -1);\r\n double b = z1.real * conj.imaginary + (z1.imaginary * conj.real);\r\n\r\n double c = z2.real * conj.real + ((z2.imaginary * conj.imaginary) * -1);\r\n\r\n return new ComplexNumber(a / c, b / c);\r\n }", "public void addForeignKeyField(int newId)\r\n {\r\n if (m_ForeignKeyFields == null)\r\n {\r\n m_ForeignKeyFields = new Vector();\r\n }\r\n m_ForeignKeyFields.add(new Integer(newId));\r\n }", "protected String extractHeaderComment( File xmlFile )\n throws MojoExecutionException\n {\n\n try\n {\n SAXParser parser = SAXParserFactory.newInstance().newSAXParser();\n SaxHeaderCommentHandler handler = new SaxHeaderCommentHandler();\n parser.setProperty( \"http://xml.org/sax/properties/lexical-handler\", handler );\n parser.parse( xmlFile, handler );\n return handler.getHeaderComment();\n }\n catch ( Exception e )\n {\n throw new MojoExecutionException( \"Failed to parse XML from \" + xmlFile, e );\n }\n }", "public static ModelNode createRemoveOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createRemoveOperation(address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }", "protected String generateCacheKey(\n CmsObject cms,\n String targetSiteRoot,\n String detailPagePart,\n String absoluteLink) {\n\n return cms.getRequestContext().getSiteRoot() + \":\" + targetSiteRoot + \":\" + detailPagePart + absoluteLink;\n }" ]
Returns the primary port of the server. @return the primary {@link ServerPort} if the server is started. {@link Optional#empty()} otherwise.
[ "public Optional<ServerPort> activePort() {\n final Server server = this.server;\n return server != null ? server.activePort() : Optional.empty();\n }" ]
[ "public CollectionRequest<Project> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/projects\", workspace);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }", "public static void addIndex(DBCollection collection, String field, boolean asc, boolean background) {\n int dir = (asc) ? 1 : -1;\n collection.createIndex(new BasicDBObject(field, dir), new BasicDBObject(\"background\", background));\n }", "private static Map<Integer, LinkedList<MetadataCache>> gatherCandidateAttachmentGroups() {\n Map<Integer,LinkedList<MetadataCache>> candidateGroups = new TreeMap<Integer, LinkedList<MetadataCache>>();\n final Iterator<File> iterator = MetadataFinder.getInstance().getAutoAttachCacheFiles().iterator();\n while (iterator.hasNext()) {\n final File file = iterator.next();\n try {\n final MetadataCache candidate = new MetadataCache(file);\n if (candidateGroups.get(candidate.sourcePlaylist) == null) {\n candidateGroups.put(candidate.sourcePlaylist, new LinkedList<MetadataCache>());\n }\n candidateGroups.get(candidate.sourcePlaylist).add(candidate);\n } catch (Exception e) {\n logger.error(\"Unable to open metadata cache file \" + file + \", discarding\", e);\n iterator.remove();\n }\n }\n return candidateGroups;\n }", "public int getVertices(double[] coords) {\n for (int i = 0; i < numVertices; i++) {\n Point3d pnt = pointBuffer[vertexPointIndices[i]].pnt;\n coords[i * 3 + 0] = pnt.x;\n coords[i * 3 + 1] = pnt.y;\n coords[i * 3 + 2] = pnt.z;\n }\n return numVertices;\n }", "public AddonChange addAddon(String appName, String addonName) {\n return connection.execute(new AddonInstall(appName, addonName), apiKey);\n }", "static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) {\n final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE);\n return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName));\n }", "private Resolvable createMetadataProvider(Class<?> rawType) {\n Set<Type> types = Collections.<Type>singleton(rawType);\n return new ResolvableImpl(rawType, types, declaringBean, qualifierInstances, delegate);\n }", "public Collection<BoxGroupMembership.Info> getMemberships() {\n final BoxAPIConnection api = this.getAPI();\n final String groupID = this.getID();\n\n Iterable<BoxGroupMembership.Info> iter = new Iterable<BoxGroupMembership.Info>() {\n public Iterator<BoxGroupMembership.Info> iterator() {\n URL url = MEMBERSHIPS_URL_TEMPLATE.build(api.getBaseURL(), groupID);\n return new BoxGroupMembershipIterator(api, url);\n }\n };\n\n // We need to iterate all results because this method must return a Collection. This logic should be removed in\n // the next major version, and instead return the Iterable directly.\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>();\n for (BoxGroupMembership.Info membership : iter) {\n memberships.add(membership);\n }\n return memberships;\n }", "public static gslbdomain_stats[] get(nitro_service service) throws Exception{\n\t\tgslbdomain_stats obj = new gslbdomain_stats();\n\t\tgslbdomain_stats[] response = (gslbdomain_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}" ]
Set the default size of the texture buffers. You can call this to reduce the buffer size of views with anti-aliasing issue. The max value to the buffer size should be the Math.max(width, height) of attached view. @param size buffer size. Value > 0 and <= Math.max(width, height).
[ "public void setTextureBufferSize(final int size) {\n mRootViewGroup.post(new Runnable() {\n @Override\n public void run() {\n mRootViewGroup.setTextureBufferSize(size);\n }\n });\n }" ]
[ "@JmxGetter(name = \"avgUpdateEntriesNetworkTimeMs\", description = \"average time spent on network, for streaming operations\")\n public double getAvgUpdateEntriesNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.UPDATE_ENTRIES).getAvgEventValue()\n / Time.NS_PER_MS;\n }", "private Calendar cleanHistCalendar(Calendar cal) {\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.HOUR, 0);\n return cal;\n }", "public void synchTransaction(SimpleFeatureStore featureStore) {\n\t\t// check if transaction is active, otherwise do nothing (auto-commit mode)\n\t\tif (TransactionSynchronizationManager.isActualTransactionActive()) {\n\t\t\tDataAccess<SimpleFeatureType, SimpleFeature> dataStore = featureStore.getDataStore();\n\t\t\tif (!transactions.containsKey(dataStore)) {\n\t\t\t\tTransaction transaction = null;\n\t\t\t\tif (dataStore instanceof JDBCDataStore) {\n\t\t\t\t\tJDBCDataStore jdbcDataStore = (JDBCDataStore) dataStore;\n\t\t\t\t\ttransaction = jdbcDataStore.buildTransaction(DataSourceUtils\n\t\t\t\t\t\t\t.getConnection(jdbcDataStore.getDataSource()));\n\t\t\t\t} else {\n\t\t\t\t\ttransaction = new DefaultTransaction();\n\t\t\t\t}\n\t\t\t\ttransactions.put(dataStore, transaction);\n\t\t\t}\n\t\t\tfeatureStore.setTransaction(transactions.get(dataStore));\n\t\t}\n\t}", "public <T> void cleanNullReferences(Class<T> clazz) {\n\t\tMap<Object, Reference<Object>> objectMap = getMapForClass(clazz);\n\t\tif (objectMap != null) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}", "public String getSQL92LikePattern() throws IllegalArgumentException {\n\t\tif (escape.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> escape char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardSingle.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardSingle char should be of length exactly 1\");\n\t\t}\n\t\tif (wildcardMulti.length() != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Like Pattern --> wildcardMulti char should be of length exactly 1\");\n\t\t}\n\t\treturn LikeFilterImpl.convertToSQL92(escape.charAt(0), wildcardMulti.charAt(0), wildcardSingle.charAt(0),\n\t\t\t\tisMatchingCase(), pattern);\n\t}", "public static nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_binding obj = new nstrafficdomain_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public ModelNode buildExecutableRequest(CommandContext ctx) throws Exception {\n try {\n for (FailureDescProvider h : providers) {\n effectiveProviders.add(h);\n }\n // In case some key-store needs to be persisted\n for (String ks : ksToStore) {\n composite.get(Util.STEPS).add(ElytronUtil.storeKeyStore(ctx, ks));\n effectiveProviders.add(new FailureDescProvider() {\n @Override\n public String stepFailedDescription() {\n return \"Storing the key-store \" + ksToStore;\n }\n });\n }\n // Final steps\n for (int i = 0; i < finalSteps.size(); i++) {\n composite.get(Util.STEPS).add(finalSteps.get(i));\n effectiveProviders.add(finalProviders.get(i));\n }\n return composite;\n } catch (Exception ex) {\n try {\n failureOccured(ctx, null);\n } catch (Exception ex2) {\n ex.addSuppressed(ex2);\n }\n throw ex;\n }\n }", "private Pair<Double, String>\n summarizeBalance(final Map<Integer, Integer> nodeIdToPartitionCount, String title) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\n\" + title + \"\\n\");\n\n Map<Integer, ZoneBalanceStats> zoneToBalanceStats = new HashMap<Integer, ZoneBalanceStats>();\n for(Integer zoneId: cluster.getZoneIds()) {\n zoneToBalanceStats.put(zoneId, new ZoneBalanceStats());\n }\n\n for(Node node: cluster.getNodes()) {\n int curCount = nodeIdToPartitionCount.get(node.getId());\n builder.append(\"\\tNode ID: \" + node.getId() + \" : \" + curCount + \" (\" + node.getHost()\n + \")\\n\");\n zoneToBalanceStats.get(node.getZoneId()).addPartitions(curCount);\n }\n\n // double utilityToBeMinimized = Double.MIN_VALUE;\n double utilityToBeMinimized = 0;\n for(Integer zoneId: cluster.getZoneIds()) {\n builder.append(\"Zone \" + zoneId + \"\\n\");\n builder.append(zoneToBalanceStats.get(zoneId).dumpStats());\n utilityToBeMinimized += zoneToBalanceStats.get(zoneId).getUtility();\n /*- \n * Another utility function to consider \n if(zoneToBalanceStats.get(zoneId).getMaxMinRatio() > utilityToBeMinimized) {\n utilityToBeMinimized = zoneToBalanceStats.get(zoneId).getUtility();\n }\n */\n }\n\n return Pair.create(utilityToBeMinimized, builder.toString());\n }", "public PortComponentMetaData getPortComponentByWsdlPort(String name)\n {\n ArrayList<String> pcNames = new ArrayList<String>();\n for (PortComponentMetaData pc : portComponents)\n {\n String wsdlPortName = pc.getWsdlPort().getLocalPart();\n if (wsdlPortName.equals(name))\n return pc;\n\n pcNames.add(wsdlPortName);\n }\n\n Loggers.METADATA_LOGGER.cannotGetPortComponentName(name, pcNames);\n return null;\n }" ]
Parse parameters from this request using HTTP. @param req The ServletRequest containing all request parameters. @param cms The OpenCms object. @return CmsSpellcheckingRequest object that contains parsed parameters.
[ "private CmsSpellcheckingRequest parseHttpRequest(final ServletRequest req, final CmsObject cms) {\n\n if ((null != cms) && OpenCms.getRoleManager().hasRole(cms, CmsRole.ROOT_ADMIN)) {\n try {\n if (null != req.getParameter(HTTP_PARAMETER_CHECKREBUILD)) {\n if (CmsSpellcheckDictionaryIndexer.updatingIndexNecessesary(cms)) {\n\n parseAndAddDictionaries(cms);\n\n }\n }\n\n if (null != req.getParameter(HTTP_PARAMTER_REBUILD)) {\n parseAndAddDictionaries(cms);\n }\n } catch (CmsRoleViolationException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n\n final String q = req.getParameter(HTTP_PARAMETER_WORDS);\n\n if (null == q) {\n LOG.debug(\"Invalid HTTP request: No parameter \\\"\" + HTTP_PARAMETER_WORDS + \"\\\" defined. \");\n return null;\n }\n\n final StringTokenizer st = new StringTokenizer(q);\n final List<String> wordsToCheck = new ArrayList<String>();\n while (st.hasMoreTokens()) {\n final String word = st.nextToken();\n wordsToCheck.add(word);\n\n if (Character.isUpperCase(word.codePointAt(0))) {\n wordsToCheck.add(word.toLowerCase());\n }\n }\n\n final String[] w = wordsToCheck.toArray(new String[wordsToCheck.size()]);\n final String dict = req.getParameter(HTTP_PARAMETER_LANG) == null\n ? LANG_DEFAULT\n : req.getParameter(HTTP_PARAMETER_LANG);\n\n return new CmsSpellcheckingRequest(w, dict);\n }" ]
[ "public static Operation createDeployOperation(final Set<DeploymentDescription> deployments) {\n Assertions.requiresNotNullOrNotEmptyParameter(\"deployments\", deployments);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n for (DeploymentDescription deployment : deployments) {\n addDeployOperationStep(builder, deployment);\n }\n return builder.build();\n }", "public static void registerDataPersisters(DataPersister... dataPersisters) {\n\t\t// we build the map and replace it to lower the chance of concurrency issues\n\t\tList<DataPersister> newList = new ArrayList<DataPersister>();\n\t\tif (registeredPersisters != null) {\n\t\t\tnewList.addAll(registeredPersisters);\n\t\t}\n\t\tfor (DataPersister persister : dataPersisters) {\n\t\t\tnewList.add(persister);\n\t\t}\n\t\tregisteredPersisters = newList;\n\t}", "public static base_response delete(nitro_service client, String domain) throws Exception {\n\t\tdnstxtrec deleteresource = new dnstxtrec();\n\t\tdeleteresource.domain = domain;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public 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 void sendEventsFromQueue() {\n if (null == queue || stopSending) {\n return;\n }\n LOG.fine(\"Scheduler called for sending events\");\n\n int packageSize = getEventsPerMessageCall();\n\n while (!queue.isEmpty()) {\n final List<Event> list = new ArrayList<Event>();\n int i = 0;\n while (i < packageSize && !queue.isEmpty()) {\n Event event = queue.remove();\n if (event != null && !filter(event)) {\n list.add(event);\n i++;\n }\n }\n if (list.size() > 0) {\n executor.execute(new Runnable() {\n public void run() {\n try {\n sendEvents(list);\n } catch (MonitoringException e) {\n e.logException(Level.SEVERE);\n }\n }\n });\n\n }\n }\n\n }", "void lockInterruptibly(final Integer permit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n sync.acquireInterruptibly(permit);\n }", "public static base_responses add(nitro_service client, cacheselector resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheselector addresources[] = new cacheselector[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cacheselector();\n\t\t\t\taddresources[i].selectorname = resources[i].selectorname;\n\t\t\t\taddresources[i].rule = resources[i].rule;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public void credentialsMigration(T overrider, Class overriderClass) {\n try {\n deployerMigration(overrider, overriderClass);\n resolverMigration(overrider, overriderClass);\n } catch (NoSuchFieldException | IllegalAccessException | IOException e) {\n converterErrors.add(getConversionErrorMessage(overrider, e));\n }\n }", "private Collection<Locale> initLocales() {\n\n Collection<Locale> locales = null;\n switch (m_bundleType) {\n case DESCRIPTOR:\n locales = new ArrayList<Locale>(1);\n locales.add(Descriptor.LOCALE);\n break;\n case XML:\n case PROPERTY:\n locales = OpenCms.getLocaleManager().getAvailableLocales(m_cms, m_resource);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return locales;\n\n }" ]
Generate a set of datetime patterns to accommodate variations in MPX files. @param datePattern date pattern element @param timePatterns time patterns @return datetime patterns
[ "private List<String> generateDateTimePatterns(String datePattern, String[] timePatterns)\n {\n List<String> patterns = new ArrayList<String>();\n for (String timePattern : timePatterns)\n {\n patterns.add(datePattern + \" \" + timePattern);\n }\n\n // Always fall back on the date-only pattern\n patterns.add(datePattern);\n\n return patterns;\n }" ]
[ "public static void addToMediaStore(Context context, File file) {\n String[] path = new String[]{file.getPath()};\n MediaScannerConnection.scanFile(context, path, null, null);\n }", "public EventBus emitSync(String event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }", "public RedwoodConfiguration captureStdout(){\r\n tasks.add(new Runnable() { public void run() { Redwood.captureSystemStreams(true, false); } });\r\n return this;\r\n }", "public Map<String, List<Locale>> getAvailableLocales() {\n\n if (m_availableLocales == null) {\n // create lazy map only on demand\n m_availableLocales = CmsCollectionsGenericWrapper.createLazyMap(new CmsAvailableLocaleLoaderTransformer());\n }\n return m_availableLocales;\n }", "@SuppressWarnings(\"unchecked\")\n protected Class<? extends Annotation> annotationTypeForName(String name) {\n try {\n return (Class<? extends Annotation>) resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_ANNOTATION;\n }\n }", "public static String takeWhile(GString self, @ClosureParams(value=SimpleType.class, options=\"char\") Closure condition) {\n return (String) takeWhile(self.toString(), condition);\n }", "public static <T> T withStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.InputStream\",\"java.io.OutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n try {\n T result = closure.call(new Object[]{input, output});\n\n InputStream temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(input);\n closeWithWarning(output);\n }\n }", "private void initializeSignProperties() {\n if (!signPackage && !signChanges) {\n return;\n }\n\n if (key != null && keyring != null && passphrase != null) {\n return;\n }\n\n Map<String, String> properties =\n readPropertiesFromActiveProfiles(signCfgPrefix, KEY, KEYRING, PASSPHRASE);\n\n key = lookupIfEmpty(key, properties, KEY);\n keyring = lookupIfEmpty(keyring, properties, KEYRING);\n passphrase = decrypt(lookupIfEmpty(passphrase, properties, PASSPHRASE));\n\n if (keyring == null) {\n try {\n keyring = Utils.guessKeyRingFile().getAbsolutePath();\n console.info(\"Located keyring at \" + keyring);\n } catch (FileNotFoundException e) {\n console.warn(e.getMessage());\n }\n }\n }", "public double loglikelihood(List<IN> lineInfos) {\r\n double cll = 0.0;\r\n\r\n for (int i = 0; i < lineInfos.size(); i++) {\r\n Datum<String, String> d = makeDatum(lineInfos, i, featureFactory);\r\n Counter<String> c = classifier.logProbabilityOf(d);\r\n\r\n double total = Double.NEGATIVE_INFINITY;\r\n for (String s : c.keySet()) {\r\n total = SloppyMath.logAdd(total, c.getCount(s));\r\n }\r\n cll -= c.getCount(d.label()) - total;\r\n }\r\n // quadratic prior\r\n // HN: TODO: add other priors\r\n\r\n if (classifier instanceof LinearClassifier) {\r\n double sigmaSq = flags.sigma * flags.sigma;\r\n LinearClassifier<String, String> lc = (LinearClassifier<String, String>)classifier;\r\n for (String feature: lc.features()) {\r\n for (String classLabel: classIndex) {\r\n double w = lc.weight(feature, classLabel);\r\n cll += w * w / 2.0 / sigmaSq;\r\n }\r\n }\r\n }\r\n return cll;\r\n }" ]
This method maps the currency symbol position from the representation used in the MPP file to the representation used by MPX. @param value MPP symbol position @return MPX symbol position
[ "public static CurrencySymbolPosition getSymbolPosition(int value)\n {\n CurrencySymbolPosition result;\n\n switch (value)\n {\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n\n case 0:\n default:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n }\n\n return (result);\n }" ]
[ "static String fromPackageName(String packageName) {\n List<String> tokens = tokenOf(packageName);\n return fromTokens(tokens);\n }", "static int[] toIntArray(List<Integer> integers) {\n\t\tint[] ints = new int[integers.size()];\n\t\tint i = 0;\n\t\tfor (Integer n : integers) {\n\t\t\tints[i++] = n;\n\t\t}\n\t\treturn ints;\n\t}", "public void start() {\n if (this.started) {\n throw new IllegalStateException(\"Cannot start the EventStream because it isn't stopped.\");\n }\n\n final long initialPosition;\n\n if (this.startingPosition == STREAM_POSITION_NOW) {\n BoxAPIRequest request = new BoxAPIRequest(this.api, EVENT_URL.build(this.api.getBaseURL(), \"now\"), \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n initialPosition = jsonObject.get(\"next_stream_position\").asLong();\n } else {\n assert this.startingPosition >= 0 : \"Starting position must be non-negative\";\n initialPosition = this.startingPosition;\n }\n\n this.poller = new Poller(initialPosition);\n\n this.pollerThread = new Thread(this.poller);\n this.pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {\n public void uncaughtException(Thread t, Throwable e) {\n EventStream.this.notifyException(e);\n }\n });\n this.pollerThread.start();\n\n this.started = true;\n }", "public static wisite_binding get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_binding obj = new wisite_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_binding response = (wisite_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher cancelPendingRequests() {\n if (pendingRequests.size() != 0) {\n for (int i = 0; i < pendingRequests.size(); i++) {\n int reqId = pendingRequests.keyAt(i);\n Request r = pendingRequests.valueAt(i);\n if (!r.isFinished() && !r.isCancelled()) {\n cancelRequest(r, reqId);\n }\n }\n }\n return this;\n }", "public V put(K key, V value) {\n final int hash;\n int index;\n if (key == null) {\n hash = 0;\n index = indexOfNull();\n } else {\n hash = key.hashCode();\n index = indexOf(key, hash);\n }\n if (index >= 0) {\n index = (index<<1) + 1;\n final V old = (V)mArray[index];\n mArray[index] = value;\n return old;\n }\n\n index = ~index;\n if (mSize >= mHashes.length) {\n final int n = mSize >= (BASE_SIZE*2) ? (mSize+(mSize>>1))\n : (mSize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE);\n\n final int[] ohashes = mHashes;\n final Object[] oarray = mArray;\n allocArrays(n);\n\n if (mHashes.length > 0) {\n System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);\n System.arraycopy(oarray, 0, mArray, 0, oarray.length);\n }\n\n freeArrays(ohashes, oarray, mSize);\n }\n\n if (index < mSize) {\n System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index);\n System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1);\n }\n\n mHashes[index] = hash;\n mArray[index<<1] = key;\n mArray[(index<<1)+1] = value;\n mSize++;\n return null;\n }", "private List<Row> getTable(String name)\n {\n List<Row> result = m_tables.get(name);\n if (result == null)\n {\n result = Collections.emptyList();\n }\n return result;\n }", "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}", "private static int resolveDomainTimeoutAdder() {\n String propValue = WildFlySecurityManager.getPropertyPrivileged(DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_STRING);\n if (sysPropDomainValue == null || !sysPropDomainValue.equals(propValue)) {\n // First call or the system property changed\n sysPropDomainValue = propValue;\n int number = -1;\n try {\n number = Integer.valueOf(sysPropDomainValue);\n } catch (NumberFormatException nfe) {\n // ignored\n }\n\n if (number > 0) {\n defaultDomainValue = number; // this one is in ms\n } else {\n ControllerLogger.MGMT_OP_LOGGER.invalidDefaultBlockingTimeout(sysPropDomainValue, DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_ADDER);\n defaultDomainValue = DEFAULT_DOMAIN_TIMEOUT_ADDER;\n }\n }\n return defaultDomainValue;\n }" ]
Straight conversion from an ObjectName to a PathAddress. There may not necessarily be a Resource at this path address (if that correspond to a pattern) but it must match a model in the registry. @param domain the name of the caller's JMX domain @param registry the root resource for the management model @param name the ObjectName to convert @return the PathAddress, or {@code null} if no address matches the object name
[ "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 }" ]
[ "private final void replyErrors(final String errorMessage,\n final String stackTrace, final String statusCode,\n final int statusCodeInt) {\n reply(true, errorMessage, stackTrace, statusCode, statusCodeInt,\n PcConstants.NA, null);\n\n }", "public static <T> T createObject(final Class<T> clazz, final Object[] args, final Map<String,Object> vars) \n throws NoSuchConstructorException, AmbiguousConstructorException, ReflectiveOperationException {\n return invokeSetters(findConstructor(clazz, args).newInstance(args), vars);\n }", "private static String getHostname() {\n if (Hostname == null) {\n try {\n Hostname = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n Hostname = \"default\";\n LOGGER.warn(\"Can not get current hostname\", e);\n }\n }\n return Hostname;\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}", "private double u_neg_inf(double x, double tau) {\n\t\treturn f(boundaryCondition.getValueAtLowerBoundary(model, f_t(tau), f_s(x)), x, tau);\n\t}", "public static<T> Vendor<T> vendor(Func0<T> f) {\n\treturn j.vendor(f);\n }", "public List<ProjectListType.Project> getProject()\n {\n if (project == null)\n {\n project = new ArrayList<ProjectListType.Project>();\n }\n return this.project;\n }", "public static appflowpolicylabel[] get(nitro_service service) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tappflowpolicylabel[] response = (appflowpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private Properties parseXML(Document doc, String sectionName) {\n\t\tint found = -1;\n\t\tProperties results = new Properties();\n\t\tNodeList config = null;\n\t\tif (sectionName == null){\n\t\t\tconfig = doc.getElementsByTagName(\"default-config\");\n\t\t\tfound = 0;\n\t\t} else {\n\t\t\tconfig = doc.getElementsByTagName(\"named-config\");\n\t\t\tif(config != null && config.getLength() > 0) {\n\t\t\t\tfor (int i = 0; i < config.getLength(); i++) {\n\t\t\t\t\tNode node = config.item(i);\n\t\t\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE ){\n\t\t\t\t\t\tNamedNodeMap attributes = node.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tNode name = attributes.getNamedItem(\"name\");\n\t\t\t\t\t\t\tif (name.getNodeValue().equalsIgnoreCase(sectionName)){\n\t\t\t\t\t\t\t\tfound = i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found == -1){\n\t\t\t\tconfig = null;\n\t\t\t\tlogger.warn(\"Did not find \"+sectionName+\" section in config file. Reverting to defaults.\");\n\t\t\t}\n\t\t}\n\n\t\tif(config != null && config.getLength() > 0) {\n\t\t\tNode node = config.item(found);\n\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE){\n\t\t\t\tElement elementEntry = (Element)node;\n\t\t\t\tNodeList childNodeList = elementEntry.getChildNodes();\n\t\t\t\tfor (int j = 0; j < childNodeList.getLength(); j++) {\n\t\t\t\t\tNode node_j = childNodeList.item(j);\n\t\t\t\t\tif (node_j.getNodeType() == Node.ELEMENT_NODE) {\n\t\t\t\t\t\tElement piece = (Element) node_j;\n\t\t\t\t\t\tNamedNodeMap attributes = piece.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tresults.put(attributes.item(0).getNodeValue(), piece.getTextContent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}" ]
Get the element at the index as a json array. @param i the index of the element to access
[ "public final PJsonArray getJSONArray(final int i) {\n JSONArray val = this.array.optJSONArray(i);\n final String context = \"[\" + i + \"]\";\n if (val == null) {\n throw new ObjectMissingException(this, context);\n }\n return new PJsonArray(this, val, context);\n }" ]
[ "public static final int getInt(byte[] data, int offset)\n {\n int result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "static void initSingleParam(String key, String initValue, DbConn cnx)\n {\n try\n {\n cnx.runSelectSingle(\"globalprm_select_by_key\", 2, String.class, key);\n return;\n }\n catch (NoResultException e)\n {\n GlobalParameter.create(cnx, key, initValue);\n }\n catch (NonUniqueResultException e)\n {\n // It exists! Nothing to do...\n }\n }", "public void executeInsert(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeInsert: \" + obj);\r\n }\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n try\r\n {\r\n stmt = sm.getInsertStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getInsertStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getInsertStatement returned a null statement\");\r\n }\r\n // before bind values perform autoincrement sequence columns\r\n assignAutoincrementSequences(cld, obj);\r\n sm.bindInsert(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeInsert: \" + stmt);\r\n stmt.executeUpdate();\r\n // after insert read and assign identity columns\r\n assignAutoincrementIdentityColumns(cld, obj);\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getInsertProcedure(), obj, stmt);\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of the insert: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch(SequenceManagerException e)\r\n {\r\n throw new PersistenceBrokerException(\"Error while try to assign identity value\", e);\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }", "public static <OutT, InT> PagedList<OutT> toPagedList(List<InT> list, final Func1<InT, OutT> mapper) {\n PageImpl<InT> page = new PageImpl<>();\n page.setItems(list);\n page.setNextPageLink(null);\n PagedList<InT> pagedList = new PagedList<InT>(page) {\n @Override\n public Page<InT> nextPage(String nextPageLink) {\n return null;\n }\n };\n PagedListConverter<InT, OutT> converter = new PagedListConverter<InT, OutT>() {\n @Override\n public Observable<OutT> typeConvertAsync(InT inner) {\n return Observable.just(mapper.call(inner));\n }\n };\n return converter.convert(pagedList);\n }", "public boolean hasNullPKField(ClassDescriptor cld, Object obj)\r\n {\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n boolean hasNull = false;\r\n // an unmaterialized proxy object can never have nullified PK's\r\n IndirectionHandler handler = ProxyHelper.getIndirectionHandler(obj);\r\n if(handler == null || handler.alreadyMaterialized())\r\n {\r\n if(handler != null) obj = handler.getRealSubject();\r\n FieldDescriptor fld;\r\n for(int i = 0; i < fields.length; i++)\r\n {\r\n fld = fields[i];\r\n hasNull = representsNull(fld, fld.getPersistentField().get(obj));\r\n if(hasNull) break;\r\n }\r\n }\r\n return hasNull;\r\n }", "public void sendMessageToAgentsWithExtraProperties(String[] agent_name,\n String msgtype, Object message_content,\n ArrayList<Object> properties, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n\n for (Object property : properties) {\n // Logger logger = Logger.getLogger(\"JadexMessenger\");\n // logger.info(\"Sending message with extra property: \"+property.get(0)+\", with value \"+property.get(1));\n hm.put((String) ((Tuple) property).get(0), ((Tuple) property).get(1));\n }\n\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 }", "protected void updateModel(final OperationContext context, final ModelNode operation) throws OperationFailedException {\n // verify that the resource exist before removing it\n context.readResource(PathAddress.EMPTY_ADDRESS, false);\n Resource resource = context.removeResource(PathAddress.EMPTY_ADDRESS);\n recordCapabilitiesAndRequirements(context, operation, resource);\n }", "public void notifySubscriberCallback(ContentNotification cn) {\n String content = fetchContentFromPublisher(cn);\n\n distributeContentToSubscribers(content, cn.getUrl());\n }", "public static int[] insertArray(int[] original, int index, int[] inserted) {\n int[] modified = new int[original.length + inserted.length];\n System.arraycopy(original, 0, modified, 0, index);\n System.arraycopy(inserted, 0, modified, index, inserted.length);\n System.arraycopy(original, index, modified, index + inserted.length, modified.length - index - inserted.length);\n return modified;\n }" ]
Helper. Current transaction is committed in some cases.
[ "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 }" ]
[ "public QueryBuilder<T, ID> join(QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException {\n\t\taddJoinInfo(JoinType.INNER, null, null, joinedQueryBuilder, JoinWhereOperation.AND);\n\t\treturn this;\n\t}", "public synchronized void bindShader(GVRScene scene, boolean isMultiview)\n {\n GVRRenderPass pass = mRenderPassList.get(0);\n GVRShaderId shader = pass.getMaterial().getShaderType();\n GVRShader template = shader.getTemplate(getGVRContext());\n if (template != null)\n {\n template.bindShader(getGVRContext(), this, scene, isMultiview);\n }\n for (int i = 1; i < mRenderPassList.size(); ++i)\n {\n pass = mRenderPassList.get(i);\n shader = pass.getMaterial().getShaderType();\n template = shader.getTemplate(getGVRContext());\n if (template != null)\n {\n template.bindShader(getGVRContext(), pass, scene, isMultiview);\n }\n }\n }", "private void readProjectHeader()\n {\n Table table = m_tables.get(\"DIR\");\n MapRow row = table.find(\"\");\n if (row != null)\n {\n setFields(PROJECT_FIELDS, row, m_projectFile.getProjectProperties());\n m_wbsFormat = new P3WbsFormat(row);\n }\n }", "public static int findVerticalOffset(JRDesignBand band) {\n\t\tint finalHeight = 0;\n\t\tif (band != null) {\n\t\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\t\tJRDesignElement element = (JRDesignElement) jrChild;\n\t\t\t\tint currentHeight = element.getY() + element.getHeight();\n\t\t\t\tif (currentHeight > finalHeight) finalHeight = currentHeight;\n\t\t\t}\n\t\t\treturn finalHeight;\n\t\t}\n\t\treturn finalHeight;\n\t}", "@Subscribe\n @SuppressForbidden(\"legitimate printStackTrace().\")\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n try {\n if (jsonWriter == null)\n return;\n\n slaves.put(e.getSlave().id, e.getSlave());\n e.serialize(jsonWriter, outputStreams);\n } catch (Exception ex) {\n ex.printStackTrace();\n junit4.log(\"Error serializing to JSON file: \"\n + Throwables.getStackTraceAsString(ex), Project.MSG_WARN);\n if (jsonWriter != null) {\n try {\n jsonWriter.close();\n } catch (Throwable ignored) {\n // Ignore.\n } finally {\n jsonWriter = null;\n }\n }\n }\n }", "public static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) {\r\n Expression leftExpression = declarationExpression.getLeftExpression();\r\n\r\n // !important: performance enhancement\r\n if (leftExpression instanceof ArrayExpression) {\r\n List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof TupleExpression) {\r\n List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof VariableExpression) {\r\n return Arrays.asList(leftExpression);\r\n }\r\n // todo: write warning\r\n return Collections.emptyList();\r\n }", "public static int getLineCount(String str) {\r\n if (null == str || str.isEmpty()) {\r\n return 0;\r\n }\r\n int count = 1;\r\n for (char c : str.toCharArray()) {\r\n if ('\\n' == c) {\r\n count++;\r\n }\r\n }\r\n return count;\r\n }", "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 add(Vector3d v1, Vector3d v2) {\n x = v1.x + v2.x;\n y = v1.y + v2.y;\n z = v1.z + v2.z;\n }" ]
This method displays the resource assignments for each resource. This time rather than just iterating through the list of all assignments in the file, we extract the assignments on a resource-by-resource basis. @param file MPX file
[ "private static void listAssignmentsByResource(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Assignments for resource \" + resource.getName() + \":\");\n\n for (ResourceAssignment assignment : resource.getTaskAssignments())\n {\n Task task = assignment.getTask();\n System.out.println(\" \" + task.getName());\n }\n }\n\n System.out.println();\n }" ]
[ "@Override\n public T getById(Object id)\n {\n return context.getFramed().getFramedVertex(this.type, id);\n }", "public static base_response unset(nitro_service client, sslcertkey resource, String[] args) throws Exception{\n\t\tsslcertkey unsetresource = new sslcertkey();\n\t\tunsetresource.certkey = resource.certkey;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private void initPatternButtonGroup() {\n\n m_groupPattern = new CmsRadioButtonGroup();\n m_patternButtons = new HashMap<>();\n\n createAndAddButton(PatternType.DAILY, Messages.GUI_SERIALDATE_TYPE_DAILY_0);\n m_patternButtons.put(PatternType.NONE, m_patternButtons.get(PatternType.DAILY));\n createAndAddButton(PatternType.WEEKLY, Messages.GUI_SERIALDATE_TYPE_WEEKLY_0);\n createAndAddButton(PatternType.MONTHLY, Messages.GUI_SERIALDATE_TYPE_MONTHLY_0);\n createAndAddButton(PatternType.YEARLY, Messages.GUI_SERIALDATE_TYPE_YEARLY_0);\n // createAndAddButton(PatternType.INDIVIDUAL, Messages.GUI_SERIALDATE_TYPE_INDIVIDUAL_0);\n\n m_groupPattern.addValueChangeHandler(new ValueChangeHandler<String>() {\n\n public void onValueChange(ValueChangeEvent<String> event) {\n\n if (handleChange()) {\n String value = event.getValue();\n if (value != null) {\n m_controller.setPattern(value);\n }\n }\n }\n });\n\n }", "public static cacheselector[] get(nitro_service service, String selectorname[]) throws Exception{\n\t\tif (selectorname !=null && selectorname.length>0) {\n\t\t\tcacheselector response[] = new cacheselector[selectorname.length];\n\t\t\tcacheselector obj[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++) {\n\t\t\t\tobj[i] = new cacheselector();\n\t\t\t\tobj[i].set_selectorname(selectorname[i]);\n\t\t\t\tresponse[i] = (cacheselector) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "private Class[] getInterfaces(Class clazz) {\r\n Class superClazz = clazz;\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n // clazz can be an interface itself and when getInterfaces()\r\n // is called on an interface it returns only the extending\r\n // interfaces, not the interface itself.\r\n if (clazz.isInterface()) {\r\n Class[] tempInterfaces = new Class[interfaces.length + 1];\r\n tempInterfaces[0] = clazz;\r\n\r\n System.arraycopy(interfaces, 0, tempInterfaces, 1, interfaces.length);\r\n interfaces = tempInterfaces;\r\n }\r\n\r\n // add all interfaces implemented by superclasses to the interfaces array\r\n while ((superClazz = superClazz.getSuperclass()) != null) {\r\n Class[] superInterfaces = superClazz.getInterfaces();\r\n Class[] combInterfaces = new Class[interfaces.length + superInterfaces.length];\r\n System.arraycopy(interfaces, 0, combInterfaces, 0, interfaces.length);\r\n System.arraycopy(superInterfaces, 0, combInterfaces, interfaces.length, superInterfaces.length);\r\n interfaces = combInterfaces;\r\n }\r\n\r\n /**\r\n * Must remove duplicate interfaces before calling Proxy.getProxyClass().\r\n * Duplicates can occur if a subclass re-declares that it implements\r\n * the same interface as one of its ancestor classes.\r\n **/\r\n HashMap unique = new HashMap();\r\n for (int i = 0; i < interfaces.length; i++) {\r\n unique.put(interfaces[i].getName(), interfaces[i]);\r\n }\r\n /* Add the OJBProxy interface as well */\r\n unique.put(OJBProxy.class.getName(), OJBProxy.class);\r\n\r\n interfaces = (Class[])unique.values().toArray(new Class[unique.size()]);\r\n\r\n return interfaces;\r\n }", "@Override\n public HandlerRegistration addSearchNoResultHandler(final SearchNoResultEvent.SearchNoResultHandler handler) {\n return addHandler(handler, SearchNoResultEvent.TYPE);\n }", "ResultAction executeOperation() {\n\n assert isControllingThread();\n try {\n /** Execution has begun */\n executing = true;\n\n processStages();\n\n if (resultAction == ResultAction.KEEP) {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationSucceeded());\n } else {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationRollingBack());\n }\n } catch (RuntimeException e) {\n handleUncaughtException(e);\n ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations);\n } finally {\n // On failure close any attached response streams\n if (resultAction != ResultAction.KEEP && !isBooting()) {\n synchronized (this) {\n if (responseStreams != null) {\n int i = 0;\n for (OperationResponse.StreamEntry is : responseStreams.values()) {\n try {\n is.getStream().close();\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.debugf(e, \"Failed closing stream at index %d\", i);\n }\n i++;\n }\n responseStreams.clear();\n }\n }\n }\n }\n\n\n return resultAction;\n }", "public void addNode(NodeT node) {\n node.setOwner(this);\n nodeTable.put(node.key(), node);\n }", "private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) {\n final ModelNode op = ServerOperations.createAddOperation(address);\n for (Map.Entry<String, String> prop : properties.entrySet()) {\n final String[] props = prop.getKey().split(\",\");\n if (props.length == 0) {\n throw new RuntimeException(\"Invalid property \" + prop);\n }\n ModelNode node = op;\n for (int i = 0; i < props.length - 1; ++i) {\n node = node.get(props[i]);\n }\n final String value = prop.getValue() == null ? \"\" : prop.getValue();\n if (value.startsWith(\"!!\")) {\n handleDmrString(node, props[props.length - 1], value);\n } else {\n node.get(props[props.length - 1]).set(value);\n }\n }\n return op;\n }" ]
The entity instance is already in the session cache Copied from Loader#instanceAlreadyLoaded
[ "private void instanceAlreadyLoaded(\n\t\tfinal Tuple resultset,\n\t\tfinal int i,\n\t\t\t//TODO create an interface for this usage\n\t\tfinal OgmEntityPersister persister,\n\t\tfinal org.hibernate.engine.spi.EntityKey key,\n\t\tfinal Object object,\n\t\tfinal LockMode lockMode,\n\t\tfinal SharedSessionContractImplementor session)\n\tthrows HibernateException {\n\t\tif ( !persister.isInstance( object ) ) {\n\t\t\tthrow new WrongClassException(\n\t\t\t\t\t\"loaded object was of wrong class \" + object.getClass(),\n\t\t\t\t\tkey.getIdentifier(),\n\t\t\t\t\tpersister.getEntityName()\n\t\t\t\t);\n\t\t}\n\n\t\tif ( LockMode.NONE != lockMode && upgradeLocks() ) { // no point doing this if NONE was requested\n\n\t\t\tfinal boolean isVersionCheckNeeded = persister.isVersioned() &&\n\t\t\t\t\tsession.getPersistenceContext().getEntry( object )\n\t\t\t\t\t\t\t.getLockMode().lessThan( lockMode );\n\t\t\t// we don't need to worry about existing version being uninitialized\n\t\t\t// because this block isn't called by a re-entrant load (re-entrant\n\t\t\t// loads _always_ have lock mode NONE)\n\t\t\tif ( isVersionCheckNeeded ) {\n\t\t\t\t//we only check the version when _upgrading_ lock modes\n\t\t\t\tObject oldVersion = session.getPersistenceContext().getEntry( object ).getVersion();\n\t\t\t\tpersister.checkVersionAndRaiseSOSE( key.getIdentifier(), oldVersion, session, resultset );\n\t\t\t\t//we need to upgrade the lock mode to the mode requested\n\t\t\t\tsession.getPersistenceContext().getEntry( object )\n\t\t\t\t\t\t.setLockMode( lockMode );\n\t\t\t}\n\t\t}\n\t}" ]
[ "public byte[] toByteArray() {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(this);\n return baos.toByteArray();\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }", "public static TransactionalProtocolClient.PreparedOperation<TransactionalProtocolClient.Operation> executeBlocking(final ModelNode operation, TransactionalProtocolClient client) throws IOException, InterruptedException {\n final BlockingQueueOperationListener<TransactionalProtocolClient.Operation> listener = new BlockingQueueOperationListener<>();\n client.execute(listener, operation, OperationMessageHandler.DISCARD, OperationAttachments.EMPTY);\n return listener.retrievePreparedOperation();\n }", "@Override\n public void sendResponse(StoreStats performanceStats,\n boolean isFromLocalZone,\n long startTimeInMs) throws Exception {\n\n /*\n * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.\n * However when writing to the outputStream we only send the multiPart object and not the entire\n * mimeMessage. This is intentional.\n *\n * In the earlier version of this code we used to create a multiPart object and just send that multiPart\n * across the wire.\n *\n * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates\n * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated\n * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the\n * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()\n * on the body part. It's this updateHeaders call that transfers the content type from the\n * DataHandler to the part's MIME Content-Type header.\n *\n * To make sure that the Content-Type headers are being updated (without changing too much code), we decided\n * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.\n * This is to make sure multiPart's headers are updated accurately.\n */\n\n MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));\n MimeMultipart multiPart = new MimeMultipart();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n String base64Key = RestUtils.encodeVoldemortKey(key.get());\n String contentLocationKey = \"/\" + this.storeName + \"/\" + base64Key;\n\n for(Versioned<byte[]> versionedValue: versionedValues) {\n\n byte[] responseValue = versionedValue.getValue();\n\n VectorClock vectorClock = (VectorClock) versionedValue.getVersion();\n String eTag = RestUtils.getSerializedVectorClock(vectorClock);\n numVectorClockEntries += vectorClock.getVersionMap().size();\n\n // Create the individual body part for each versioned value of the\n // requested key\n MimeBodyPart body = new MimeBodyPart();\n try {\n // Add the right headers\n body.addHeader(CONTENT_TYPE, \"application/octet-stream\");\n body.addHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);\n body.setContent(responseValue, \"application/octet-stream\");\n body.addHeader(RestMessageHeaders.CONTENT_LENGTH,\n Integer.toString(responseValue.length));\n\n multiPart.addBodyPart(body);\n } catch(MessagingException me) {\n logger.error(\"Exception while constructing body part\", me);\n outputStream.close();\n throw me;\n }\n\n }\n message.setContent(multiPart);\n message.saveChanges();\n try {\n multiPart.writeTo(outputStream);\n } catch(Exception e) {\n logger.error(\"Exception while writing multipart to output stream\", e);\n outputStream.close();\n throw e;\n }\n ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();\n responseContent.writeBytes(outputStream.toByteArray());\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\n\n // Set the right headers\n response.setHeader(CONTENT_TYPE, \"multipart/binary\");\n response.setHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n response.setHeader(CONTENT_LOCATION, contentLocationKey);\n\n // Copy the data into the payload\n response.setContent(responseContent);\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n if(logger.isDebugEnabled()) {\n String keyStr = RestUtils.getKeyHexString(this.key);\n debugLog(\"GET\",\n this.storeName,\n keyStr,\n startTimeInMs,\n System.currentTimeMillis(),\n numVectorClockEntries);\n }\n this.messageEvent.getChannel().write(response);\n\n if(performanceStats != null && isFromLocalZone) {\n recordStats(performanceStats, startTimeInMs, Tracked.GET);\n }\n\n outputStream.close();\n\n }", "static <T> boolean syncInstantiation(T objectType) {\n List<Template> templates = new ArrayList<>();\n Templates tr = TEMP_FINDER.findAnnotations(templates, objectType);\n if (tr == null) {\n /* Default to synchronous instantiation */\n return true;\n } else {\n return tr.syncInstantiation();\n }\n }", "private JsonObject getPendingJSONObject() {\n for (Map.Entry<String, BoxJSONObject> entry : this.children.entrySet()) {\n BoxJSONObject child = entry.getValue();\n JsonObject jsonObject = child.getPendingJSONObject();\n if (jsonObject != null) {\n if (this.pendingChanges == null) {\n this.pendingChanges = new JsonObject();\n }\n\n this.pendingChanges.set(entry.getKey(), jsonObject);\n }\n }\n return this.pendingChanges;\n }", "public static base_response unset(nitro_service client, bridgetable resource, String[] args) throws Exception{\n\t\tbridgetable unsetresource = new bridgetable();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static String nameFromOffset(long offset) {\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMinimumIntegerDigits(20);\n nf.setMaximumFractionDigits(0);\n nf.setGroupingUsed(false);\n return nf.format(offset) + Log.FileSuffix;\n }", "public void setSpecularIntensity(float r, float g, float b, float a) {\n setVec4(\"specular_intensity\", r, g, b, a);\n }", "protected synchronized StealerBasedRebalanceTask scheduleNextTask(boolean executeService) {\n // Make sure there is work left to do.\n if(doneSignal.getCount() == 0) {\n logger.info(\"All tasks completion signaled... returning\");\n\n return null;\n }\n // Limit number of tasks outstanding.\n if(this.numTasksExecuting >= maxParallelRebalancing) {\n logger.info(\"Executing more tasks than [\" + this.numTasksExecuting\n + \"] the parallel allowed \" + maxParallelRebalancing);\n return null;\n }\n // Shuffle list of stealer IDs each time a new task to schedule needs to\n // be found. Randomizing the order should avoid prioritizing one\n // specific stealer's work ahead of all others.\n List<Integer> stealerIds = new ArrayList<Integer>(tasksByStealer.keySet());\n Collections.shuffle(stealerIds);\n for(int stealerId: stealerIds) {\n if(nodeIdsWithWork.contains(stealerId)) {\n logger.info(\"Stealer \" + stealerId + \" is already working... continuing\");\n continue;\n }\n\n for(StealerBasedRebalanceTask sbTask: tasksByStealer.get(stealerId)) {\n int donorId = sbTask.getStealInfos().get(0).getDonorId();\n if(nodeIdsWithWork.contains(donorId)) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" is already working... continuing\");\n continue;\n }\n // Book keeping\n addNodesToWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting++;\n // Remove this task from list thus destroying list being\n // iterated over. This is safe because returning directly out of\n // this branch.\n tasksByStealer.get(stealerId).remove(sbTask);\n try {\n if(executeService) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" going to schedule work\");\n service.execute(sbTask);\n }\n } catch(RejectedExecutionException ree) {\n logger.error(\"Stealer \" + stealerId\n + \"Rebalancing task rejected by executor service.\", ree);\n throw new VoldemortRebalancingException(\"Stealer \"\n + stealerId\n + \"Rebalancing task rejected by executor service.\");\n }\n return sbTask;\n }\n }\n printRemainingTasks(stealerIds);\n return null;\n }" ]
Sets the target translator for all cells in the table. It will also remove any other translator set. Nothing will happen if the argument is null. @param targetTranslator translator @return this to allow chaining
[ "public AsciiTable setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "protected static void captureSystemStreams(boolean captureOut, boolean captureErr){\r\n if(captureOut){\r\n System.setOut(new RedwoodPrintStream(STDOUT, realSysOut));\r\n }\r\n if(captureErr){\r\n System.setErr(new RedwoodPrintStream(STDERR, realSysErr));\r\n }\r\n }", "protected <T> RequestBuilder doPrepareRequestBuilder(\n ResponseReader responseReader, String methodName, RpcStatsContext statsContext,\n String requestData, AsyncCallback<T> callback) {\n\n RequestBuilder rb = doPrepareRequestBuilderImpl(responseReader, methodName,\n statsContext, requestData, callback);\n\n return rb;\n }", "public void setValue(T value)\n {\n try\n {\n lock.writeLock().lock();\n this.value = value;\n }\n finally\n {\n lock.writeLock().unlock();\n }\n }", "protected static BigInteger getRadixPower(BigInteger radix, int power) {\n\t\tlong key = (((long) radix.intValue()) << 32) | power;\n\t\tBigInteger result = radixPowerMap.get(key);\n\t\tif(result == null) {\n\t\t\tif(power == 1) {\n\t\t\t\tresult = radix;\n\t\t\t} else if((power & 1) == 0) {\n\t\t\t\tBigInteger halfPower = getRadixPower(radix, power >> 1);\n\t\t\t\tresult = halfPower.multiply(halfPower);\n\t\t\t} else {\n\t\t\t\tBigInteger halfPower = getRadixPower(radix, (power - 1) >> 1);\n\t\t\t\tresult = halfPower.multiply(halfPower).multiply(radix);\n\t\t\t}\n\t\t\tradixPowerMap.put(key, result);\n\t\t}\n\t\treturn result;\n\t}", "@SuppressWarnings(\"SameParameterValue\")\n public static long bytesToNumberLittleEndian(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start + length - 1; index >= start; index--) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }", "public void postConstruct() throws URISyntaxException {\n WmsVersion.lookup(this.version);\n Assert.isTrue(validateBaseUrl(), \"invalid baseURL\");\n\n Assert.isTrue(this.layers.length > 0, \"There must be at least one layer defined for a WMS request\" +\n \" to make sense\");\n\n // OpenLayers 2 compatibility. It will post a single empty style no matter how many layers there are\n\n if (this.styles != null && this.styles.length != this.layers.length && this.styles.length == 1 &&\n this.styles[0].trim().isEmpty()) {\n this.styles = null;\n } else {\n Assert.isTrue(this.styles == null || this.layers.length == this.styles.length,\n String.format(\n \"If styles are defined then there must be one for each layer. Number of\" +\n \" layers: %s\\nStyles: %s\", this.layers.length,\n Arrays.toString(this.styles)));\n }\n\n if (this.imageFormat.indexOf('/') < 0) {\n LOGGER.warn(\"The format {} should be a mime type\", this.imageFormat);\n this.imageFormat = \"image/\" + this.imageFormat;\n }\n\n Assert.isTrue(this.method == HttpMethod.GET || this.method == HttpMethod.POST,\n String.format(\"Unsupported method %s for WMS layer\", this.method.toString()));\n }", "private JSONArray datesToJson(Collection<Date> individualDates) {\n\n if (null != individualDates) {\n JSONArray result = new JSONArray();\n for (Date d : individualDates) {\n result.put(dateToJson(d));\n }\n return result;\n }\n return null;\n }", "@Override\n public Optional<String> hash(final Optional<URL> url) throws IOException {\n if (!url.isPresent()) {\n return Optional.absent();\n }\n logger.debug(\"Calculating md5 hash, url:{}\", url);\n if (isHotReloadModeOff()) {\n final String md5 = cache.getIfPresent(url.get());\n\n logger.debug(\"md5 hash:{}\", md5);\n\n if (md5 != null) {\n return Optional.of(md5);\n }\n }\n\n final InputStream is = url.get().openStream();\n final String md5 = getMD5Checksum(is);\n\n if (isHotReloadModeOff()) {\n logger.debug(\"caching url:{} with hash:{}\", url, md5);\n\n cache.put(url.get(), md5);\n }\n\n return Optional.fromNullable(md5);\n }", "public void setSiteRoot(String siteRoot) {\n\n if (siteRoot != null) {\n siteRoot = siteRoot.replaceFirst(\"/$\", \"\");\n }\n m_siteRoot = siteRoot;\n }" ]
Adds a new Site matcher object to the map of server names. @param matcher the SiteMatcher of the server @param site the site to add
[ "private void addServer(CmsSiteMatcher matcher, CmsSite site) {\n\n Map<CmsSiteMatcher, CmsSite> siteMatcherSites = new HashMap<CmsSiteMatcher, CmsSite>(m_siteMatcherSites);\n siteMatcherSites.put(matcher, site);\n setSiteMatcherSites(siteMatcherSites);\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 }", "public void animate(float timeInSec)\n {\n GVRSkeleton skel = getSkeleton();\n GVRPose pose = skel.getPose();\n computePose(timeInSec,pose);\n skel.poseToBones();\n skel.updateBonePose();\n skel.updateSkinPose();\n }", "static JobContext copy() {\n JobContext current = current_.get();\n //JobContext ctxt = new JobContext(keepParent ? current : null);\n JobContext ctxt = new JobContext(null);\n if (null != current) {\n ctxt.bag_.putAll(current.bag_);\n }\n return ctxt;\n }", "public double[] getBasisVector( int which ) {\n if( which < 0 || which >= numComponents )\n throw new IllegalArgumentException(\"Invalid component\");\n\n DMatrixRMaj v = new DMatrixRMaj(1,A.numCols);\n CommonOps_DDRM.extract(V_t,which,which+1,0,A.numCols,v,0,0);\n\n return v.data;\n }", "public static Identifiers convertProfileAndPathIdentifier(String profileIdentifier, String pathIdentifier) throws Exception {\n Identifiers id = new Identifiers();\n\n Integer profileId = null;\n try {\n profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n } catch (Exception e) {\n // this is OK for this since it isn't always needed\n }\n Integer pathId = convertPathIdentifier(pathIdentifier, profileId);\n\n id.setProfileId(profileId);\n id.setPathId(pathId);\n\n return id;\n }", "public StochasticPathwiseLevenbergMarquardt getCloneWithModifiedTargetValues(List<RandomVariable> newTargetVaues, List<RandomVariable> newWeights, boolean isUseBestParametersAsInitialParameters) throws CloneNotSupportedException {\n\t\tStochasticPathwiseLevenbergMarquardt clonedOptimizer = clone();\n\t\tclonedOptimizer.targetValues = numberListToDoubleArray(newTargetVaues);\n\t\tclonedOptimizer.weights = numberListToDoubleArray(newWeights);\n\n\t\tif(isUseBestParametersAsInitialParameters && this.done()) {\n\t\t\tclonedOptimizer.initialParameters = this.getBestFitParameters();\n\t\t}\n\n\t\treturn clonedOptimizer;\n\t}", "public void setEveryWorkingDay(final boolean isEveryWorkingDay) {\n\n if (m_model.isEveryWorkingDay() != isEveryWorkingDay) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay));\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }", "public static boolean hasAnnotation(AnnotatedNode node, String name) {\r\n return AstUtil.getAnnotation(node, name) != null;\r\n }", "ArgumentsBuilder param(String param, Integer value) {\n if (value != null) {\n args.add(param);\n args.add(value.toString());\n }\n return this;\n }" ]
Copy the contents of the given InputStream into a String. Leaves the stream open when done. @param in the InputStream to copy from @return the String that has been copied to @throws IOException in case of I/O errors
[ "public static String copyToString(InputStream in, Charset charset) throws IOException {\n\t\tAssert.notNull(in, \"No InputStream specified\");\n\t\tStringBuilder out = new StringBuilder();\n\t\tInputStreamReader reader = new InputStreamReader(in, charset);\n\t\tchar[] buffer = new char[BUFFER_SIZE];\n\t\tint bytesRead = -1;\n\t\twhile ((bytesRead = reader.read(buffer)) != -1) {\n\t\t\tout.append(buffer, 0, bytesRead);\n\t\t}\n\t\treturn out.toString();\n\t}" ]
[ "@Override\n public Optional<SoyMapData> toSoyMap(@Nullable final Object model) throws Exception {\n if (model instanceof SoyMapData) {\n return Optional.of((SoyMapData) model);\n }\n if (model instanceof Map) {\n return Optional.of(new SoyMapData(model));\n }\n\n return Optional.of(new SoyMapData());\n }", "public double getDouble(Integer id, Integer type)\n {\n double result = Double.longBitsToDouble(getLong(id, type));\n if (Double.isNaN(result))\n {\n result = 0;\n }\n return result;\n }", "void update(JsonObject jsonObject) {\n for (JsonObject.Member member : jsonObject) {\n if (member.getValue().isNull()) {\n continue;\n }\n\n this.parseJSONMember(member);\n }\n\n this.clearPendingChanges();\n }", "public static gslbservice_stats[] get(nitro_service service) throws Exception{\n\t\tgslbservice_stats obj = new gslbservice_stats();\n\t\tgslbservice_stats[] response = (gslbservice_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public void removeChildTask(Task child)\n {\n if (m_children.remove(child))\n {\n child.m_parent = null;\n }\n setSummary(!m_children.isEmpty());\n }", "public void setTimeWarp(String l) {\n\n long warp = CmsContextInfo.CURRENT_TIME;\n try {\n warp = Long.parseLong(l);\n } catch (NumberFormatException e) {\n // if parsing the time warp fails, it will be set to -1 (i.e. disabled)\n }\n m_settings.setTimeWarp(warp);\n }", "private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException {\n\t\tif (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultSvgDocument document = new DefaultSvgDocument(writer, false);\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer()));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new SvgTileWriter());\n\t\t\treturn document;\n\t\t} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultVmlDocument document = new DefaultVmlDocument(writer);\n\t\t\tint coordWidth = tile.getScreenWidth();\n\t\t\tint coordHeight = tile.getScreenHeight();\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,\n\t\t\t\t\tcoordHeight));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight));\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\treturn document;\n\t\t} else {\n\t\t\tthrow new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);\n\t\t}\n\t}", "public static void writeShort(byte[] bytes, short value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 8));\n bytes[offset + 1] = (byte) (0xFF & value);\n }", "protected <T, A> ActiveOperation<T, A> getActiveOperation(final Integer id) {\n //noinspection unchecked\n return (ActiveOperation<T, A>) activeRequests.get(id);\n }" ]
Returns an array specifing the index of each hull vertex with respect to the original input points. @return vertex indices with respect to the original points
[ "public int[] getVertexPointIndices() {\n int[] indices = new int[numVertices];\n for (int i = 0; i < numVertices; i++) {\n indices[i] = vertexPointIndices[i];\n }\n return indices;\n }" ]
[ "public List<BoxAPIResponse> execute(List<BoxAPIRequest> requests) {\n this.prepareRequest(requests);\n BoxJSONResponse batchResponse = (BoxJSONResponse) send();\n return this.parseResponse(batchResponse);\n }", "private void sendEvents(final List<Event> events) {\n if (null != handlers) {\n for (EventHandler current : handlers) {\n for (Event event : events) {\n current.handleEvent(event);\n }\n }\n }\n\n LOG.info(\"Put events(\" + events.size() + \") to Monitoring Server.\");\n\n try {\n if (sendToEventadmin) {\n EventAdminPublisher.publish(events);\n } else {\n monitoringServiceClient.putEvents(events);\n }\n } catch (MonitoringException e) {\n throw e;\n } catch (Exception e) {\n throw new MonitoringException(\"002\",\n \"Unknown error while execute put events to Monitoring Server\", e);\n }\n\n }", "public static boolean equal(Vector3f v1, Vector3f v2) {\n return equal(v1.x, v2.x) && equal(v1.y, v2.y) && equal(v1.z, v2.z);\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 rsskeytype get(nitro_service service) throws Exception{\n\t\trsskeytype obj = new rsskeytype();\n\t\trsskeytype[] response = (rsskeytype[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) {\n if (!ignoreUnaffectedServerGroups) {\n return model;\n }\n model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups);\n addServerGroupsToModel(hostModel, model);\n return model;\n }", "private static String makeAsciiTableCell(Object obj, int padLeft, int padRight, boolean tsv) {\r\n String result = obj.toString();\r\n if (padLeft > 0) {\r\n result = padLeft(result, padLeft);\r\n }\r\n if (padRight > 0) {\r\n result = pad(result, padRight);\r\n }\r\n if (tsv) {\r\n result = result + '\\t';\r\n }\r\n return result;\r\n }", "private Path getPath(PropertyWriter writer, JsonStreamContext sc) {\n LinkedList<PathElement> elements = new LinkedList<>();\n\n if (sc != null) {\n elements.add(new PathElement(writer.getName(), sc.getCurrentValue()));\n sc = sc.getParent();\n }\n\n while (sc != null) {\n if (sc.getCurrentName() != null && sc.getCurrentValue() != null) {\n elements.addFirst(new PathElement(sc.getCurrentName(), sc.getCurrentValue()));\n }\n sc = sc.getParent();\n }\n\n return new Path(elements);\n }", "private static void listAssignments(ProjectFile file)\n {\n Task task;\n Resource resource;\n String taskName;\n String resourceName;\n\n for (ResourceAssignment assignment : file.getResourceAssignments())\n {\n task = assignment.getTask();\n if (task == null)\n {\n taskName = \"(null task)\";\n }\n else\n {\n taskName = task.getName();\n }\n\n resource = assignment.getResource();\n if (resource == null)\n {\n resourceName = \"(null resource)\";\n }\n else\n {\n resourceName = resource.getName();\n }\n\n System.out.println(\"Assignment: Task=\" + taskName + \" Resource=\" + resourceName);\n if (task != null)\n {\n listTimephasedWork(assignment);\n }\n }\n\n System.out.println();\n }" ]
Install the installation manager service. @param serviceTarget @return the service controller for the installed installation manager
[ "public static ServiceController<InstallationManager> installService(ServiceTarget serviceTarget) {\n final InstallationManagerService service = new InstallationManagerService();\n return serviceTarget.addService(InstallationManagerService.NAME, service)\n .addDependency(JBOSS_PRODUCT_CONFIG_SERVICE, ProductConfig.class, service.productConfig)\n .setInitialMode(ServiceController.Mode.ACTIVE)\n .install();\n }" ]
[ "private ModelNode resolveExpressionsRecursively(final ModelNode node) throws OperationFailedException {\n if (!node.isDefined()) {\n return node;\n }\n\n ModelType type = node.getType();\n ModelNode resolved;\n if (type == ModelType.EXPRESSION) {\n resolved = resolveExpressionStringRecursively(node.asExpression().getExpressionString(), lenient, true);\n } else if (type == ModelType.OBJECT) {\n resolved = node.clone();\n for (Property prop : resolved.asPropertyList()) {\n resolved.get(prop.getName()).set(resolveExpressionsRecursively(prop.getValue()));\n }\n } else if (type == ModelType.LIST) {\n resolved = node.clone();\n ModelNode list = new ModelNode();\n list.setEmptyList();\n for (ModelNode current : resolved.asList()) {\n list.add(resolveExpressionsRecursively(current));\n }\n resolved = list;\n } else if (type == ModelType.PROPERTY) {\n resolved = node.clone();\n resolved.set(resolved.asProperty().getName(), resolveExpressionsRecursively(resolved.asProperty().getValue()));\n } else {\n resolved = node;\n }\n\n return resolved;\n }", "public RelatedTagsList getRelated(String tag) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_RELATED);\n\n parameters.put(\"tag\", tag);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element tagsElement = response.getPayload();\n\n RelatedTagsList tags = new RelatedTagsList();\n tags.setSource(tagsElement.getAttribute(\"source\"));\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag t = new Tag();\n t.setValue(XMLUtilities.getValue(tagElement));\n tags.add(t);\n }\n return tags;\n }", "public static vrid_nsip6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvrid_nsip6_binding obj = new vrid_nsip6_binding();\n\t\tobj.set_id(id);\n\t\tvrid_nsip6_binding response[] = (vrid_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "final void roll(final long timeForSuffix) {\n\n final File backupFile = this.prepareBackupFile(timeForSuffix);\n\n // close filename\n this.getAppender().closeFile();\n\n // rename filename on disk to filename+suffix(+number)\n this.doFileRoll(this.getAppender().getIoFile(), backupFile);\n\n // setup new file 'filename'\n this.getAppender().openFile();\n\n this.fireFileRollEvent(new FileRollEvent(this, backupFile));\n }", "public Object getColumnValue(String columnName) {\n\t\tfor ( int j = 0; j < columnNames.length; j++ ) {\n\t\t\tif ( columnNames[j].equals( columnName ) ) {\n\t\t\t\treturn columnValues[j];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public String[][] getRequiredRuleNames(Param param) {\n\t\tif (isFiltered(param)) {\n\t\t\treturn EMPTY_ARRAY;\n\t\t}\n\t\tAbstractElement elementToParse = param.elementToParse;\n\t\tString ruleName = param.ruleName;\n\t\tif (ruleName == null) {\n\t\t\treturn getRequiredRuleNames(param, elementToParse);\n\t\t}\n\t\treturn getAdjustedRequiredRuleNames(param, elementToParse, ruleName);\n\t}", "public static double findMax( double[] u, int startU , int length ) {\n double max = -1;\n\n int index = startU*2;\n int stopIndex = (startU + length)*2;\n for( ; index < stopIndex;) {\n double real = u[index++];\n double img = u[index++];\n\n double val = real*real + img*img;\n\n if( val > max ) {\n max = val;\n }\n }\n\n return Math.sqrt(max);\n }", "public static List<String> splitAsList(String text, String delimiter) {\n List<String> answer = new ArrayList<String>();\n if (text != null && text.length() > 0) {\n answer.addAll(Arrays.asList(text.split(delimiter)));\n }\n return answer;\n }", "public static List<CmsJspResourceWrapper> convertResourceList(CmsObject cms, List<CmsResource> list) {\n\n List<CmsJspResourceWrapper> result = new ArrayList<CmsJspResourceWrapper>(list.size());\n for (CmsResource res : list) {\n result.add(CmsJspResourceWrapper.wrap(cms, res));\n }\n return result;\n }" ]
Calls the specified function with the specified arguments. This is used for v2 response overrides @param className name of class @param methodName name of method @param pluginArgs plugin arguments @param args arguments to supply to function @throws Exception exception
[ "public void callFunction(String className, String methodName, PluginArguments pluginArgs, Object... args) throws Exception {\n Class<?> cls = getClass(className);\n\n ArrayList<Object> newArgs = new ArrayList<>();\n newArgs.add(pluginArgs);\n com.groupon.odo.proxylib.models.Method m = preparePluginMethod(newArgs, className, methodName, args);\n\n m.getMethod().invoke(cls, newArgs.toArray(new Object[0]));\n }" ]
[ "protected void onNewParentObject(GVRSceneObject parent) {\n for (GVRComponent comp : mComponents.values()) {\n comp.onNewOwnersParent(parent);\n }\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 Capsule newCapsule(String mode, Path wrappedJar) {\n final String oldMode = properties.getProperty(PROP_MODE);\n final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();\n Thread.currentThread().setContextClassLoader(capsuleClass.getClassLoader());\n try {\n setProperty(PROP_MODE, mode);\n\n final Constructor<?> ctor = accessible(capsuleClass.getDeclaredConstructor(Path.class));\n final Object capsule = ctor.newInstance(jarFile);\n\n if (wrappedJar != null) {\n final Method setTarget = accessible(capsuleClass.getDeclaredMethod(\"setTarget\", Path.class));\n setTarget.invoke(capsule, wrappedJar);\n }\n\n return wrap(capsule);\n } catch (ReflectiveOperationException e) {\n throw new RuntimeException(\"Could not create capsule instance.\", e);\n } finally {\n setProperty(PROP_MODE, oldMode);\n Thread.currentThread().setContextClassLoader(oldCl);\n }\n }", "public byte[] getResource(String pluginName, String fileName) throws Exception {\n // TODO: This is going to be slow.. future improvement is to cache the data instead of searching all jars\n for (String jarFilename : jarInformation) {\n JarFile jarFile = new JarFile(new File(jarFilename));\n Enumeration<?> enumer = jarFile.entries();\n\n // Use the Plugin-Name manifest entry to match with the provided pluginName\n String jarPluginName = jarFile.getManifest().getMainAttributes().getValue(\"Plugin-Name\");\n\n if (!jarPluginName.equals(pluginName)) {\n continue;\n }\n\n while (enumer.hasMoreElements()) {\n Object element = enumer.nextElement();\n String elementName = element.toString();\n\n // Skip items in the jar that don't start with \"resources/\"\n if (!elementName.startsWith(\"resources/\")) {\n continue;\n }\n\n elementName = elementName.replace(\"resources/\", \"\");\n if (elementName.equals(fileName)) {\n // get the file from the jar\n ZipEntry ze = jarFile.getEntry(element.toString());\n\n InputStream fileStream = jarFile.getInputStream(ze);\n byte[] data = new byte[(int) ze.getSize()];\n DataInputStream dataIs = new DataInputStream(fileStream);\n dataIs.readFully(data);\n dataIs.close();\n return data;\n }\n }\n }\n throw new FileNotFoundException(\"Could not find resource\");\n }", "static File getTargetFile(final File root, final MiscContentItem item) {\n return PatchContentLoader.getMiscPath(root, item);\n }", "public boolean matches(Property property) {\n return property.getName().equals(key) && (value == WILDCARD_VALUE || property.getValue().asString().equals(value));\n }", "public static double[] singularValues( DMatrixRMaj A ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,true,true);\n\n if( svd.inputModified() ) {\n A = A.copy();\n }\n if( !svd.decompose(A)) {\n throw new RuntimeException(\"SVD Failed!\");\n }\n\n double sv[] = svd.getSingularValues();\n Arrays.sort(sv,0,svd.numberOfSingularValues());\n\n // change the ordering to ascending\n for (int i = 0; i < sv.length/2; i++) {\n double tmp = sv[i];\n sv[i] = sv[sv.length-i-1];\n sv[sv.length-i-1] = tmp;\n }\n\n return sv;\n }", "public static void setField(Object object, String field, Object value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {\n\t\tClass<?> clazz = object.getClass();\n\t\tMethod m = clazz.getMethod( PROPERTY_ACCESSOR_PREFIX_SET + capitalize( field ), value.getClass() );\n\t\tm.invoke( object, value );\n\t}", "public static String getChildValue(Element element, String name) {\r\n return getValue(getChild(element, name));\r\n }" ]
Retrieve a map of custom document properties. @return the Document Summary Information Map
[ "@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }" ]
[ "protected void setBeanStore(BoundBeanStore beanStore) {\n if (beanStore == null) {\n this.beanStore.remove();\n } else {\n this.beanStore.set(beanStore);\n }\n }", "void scan() {\n if (acquireScanLock()) {\n boolean scheduleRescan = false;\n try {\n scheduleRescan = scan(false, deploymentOperations);\n } finally {\n try {\n if (scheduleRescan) {\n synchronized (this) {\n if (scanEnabled) {\n rescanIncompleteTask = scheduledExecutor.schedule(scanRunnable, 200, TimeUnit.MILLISECONDS);\n }\n }\n }\n } finally {\n releaseScanLock();\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 }", "public static Optimizer<DifferentiableFunction> getRegularizedOptimizer(final Optimizer<DifferentiableFunction> opt,\n final double l1Lambda, final double l2Lambda) {\n if (l1Lambda == 0 && l2Lambda == 0) {\n return opt;\n }\n return new Optimizer<DifferentiableFunction>() {\n \n @Override\n public boolean minimize(DifferentiableFunction objective, IntDoubleVector point) {\n DifferentiableFunction fn = getRegularizedFn(objective, false, l1Lambda, l2Lambda);\n return opt.minimize(fn, point);\n }\n \n };\n }", "public void add(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n boolean matchFilter = declarationFilter.matches(declaration.getMetadata());\n declarations.put(declarationSRef, matchFilter);\n }", "public static base_responses add(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver addresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new ntpserver();\n\t\t\t\taddresources[i].serverip = resources[i].serverip;\n\t\t\t\taddresources[i].servername = resources[i].servername;\n\t\t\t\taddresources[i].minpoll = resources[i].minpoll;\n\t\t\t\taddresources[i].maxpoll = resources[i].maxpoll;\n\t\t\t\taddresources[i].autokey = resources[i].autokey;\n\t\t\t\taddresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static int scanright(Color color, int height, int width, int col, PixelsExtractor f, int tolerance) {\n if (col == width || !PixelTools.colorMatches(color, tolerance, f.apply(new Area(col, 0, 1, height))))\n return col;\n else\n return scanright(color, height, width, col + 1, f, tolerance);\n }", "private static String getBundle(String friendlyName, String className, int truncate)\r\n\t{\r\n\t\ttry {\r\n\t\t\tcl.loadClass(className);\r\n\t\t\tint start = className.length();\r\n\t\t\tfor (int i = 0; i < truncate; ++i)\r\n\t\t\t\tstart = className.lastIndexOf('.', start - 1);\r\n\t\t\tfinal String bundle = className.substring(0, start);\r\n\t\t\treturn \"+ \" + friendlyName + align(friendlyName) + \"- \" + bundle;\r\n\t\t}\r\n\t\tcatch (final ClassNotFoundException e) {}\r\n\t\tcatch (final NoClassDefFoundError e) {}\r\n\t\treturn \"- \" + friendlyName + align(friendlyName) + \"- not available\";\r\n\t}", "public final TagConfiguration.Builder configureTag( Class<? extends Annotation> tagAnnotation ) {\n TagConfiguration configuration = new TagConfiguration( tagAnnotation );\n tagConfigurations.put( tagAnnotation, configuration );\n return new TagConfiguration.Builder( configuration );\n }" ]
Convert a wavelength to an RGB value. @param wavelength wavelength in nanometres @return the RGB value
[ "public static int wavelengthToRGB(float wavelength) {\n\t\tfloat gamma = 0.80f;\n\t\tfloat r, g, b, factor;\n\n\t\tint w = (int)wavelength;\n\t\tif (w < 380) {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 440) {\n\t\t\tr = -(wavelength - 440) / (440 - 380);\n\t\t\tg = 0.0f;\n\t\t\tb = 1.0f;\n\t\t} else if (w < 490) {\n\t\t\tr = 0.0f;\n\t\t\tg = (wavelength - 440) / (490 - 440);\n\t\t\tb = 1.0f;\n\t\t} else if (w < 510) {\n\t\t\tr = 0.0f;\n\t\t\tg = 1.0f;\n\t\t\tb = -(wavelength - 510) / (510 - 490);\n\t\t} else if (w < 580) {\n\t\t\tr = (wavelength - 510) / (580 - 510);\n\t\t\tg = 1.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 645) {\n\t\t\tr = 1.0f;\n\t\t\tg = -(wavelength - 645) / (645 - 580);\n\t\t\tb = 0.0f;\n\t\t} else if (w <= 780) {\n\t\t\tr = 1.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t}\n\n\t\t// Let the intensity fall off near the vision limits\n\t\tif (380 <= w && w <= 419)\n\t\t\tfactor = 0.3f + 0.7f*(wavelength - 380) / (420 - 380);\n\t\telse if (420 <= w && w <= 700)\n\t\t\tfactor = 1.0f;\n\t\telse if (701 <= w && w <= 780)\n\t\t\tfactor = 0.3f + 0.7f*(780 - wavelength) / (780 - 700);\n\t\telse\n\t\t\tfactor = 0.0f;\n\n\t\tint ir = adjust(r, factor, gamma);\n\t\tint ig = adjust(g, factor, gamma);\n\t\tint ib = adjust(b, factor, gamma);\n\n\t\treturn 0xff000000 | (ir << 16) | (ig << 8) | ib;\n\t}" ]
[ "public void notifyHeaderItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= headerItemCount || toPosition >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \" + toPosition + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition, toPosition);\n }", "public synchronized int put(byte[] src, int off, int len) {\n if (available == capacity) {\n return 0;\n }\n\n // limit is last index to put + 1\n int limit = idxPut < idxGet ? idxGet : capacity;\n int count = Math.min(limit - idxPut, len);\n System.arraycopy(src, off, buffer, idxPut, count);\n idxPut += count;\n\n if (idxPut == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxGet);\n if (count2 > 0) {\n System.arraycopy(src, off + count, buffer, 0, count2);\n idxPut = count2;\n count += count2;\n } else {\n idxPut = 0;\n }\n }\n available += count;\n return count;\n }", "@Deprecated\n public String get(String path) {\n final JsonValue value = this.values.get(this.pathToProperty(path));\n if (value == null) {\n return null;\n }\n if (!value.isString()) {\n return value.toString();\n }\n return value.asString();\n }", "protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) {\r\n MethodNode setter = new MethodNode(\r\n setterName,\r\n propertyNode.getModifiers(),\r\n ClassHelper.VOID_TYPE,\r\n params(param(propertyNode.getType(), \"value\")),\r\n ClassNode.EMPTY_ARRAY,\r\n setterBlock);\r\n setter.setSynthetic(true);\r\n // add it to the class\r\n declaringClass.addMethod(setter);\r\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 void writeResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n Project.Resources.Resource.ExtendedAttribute attrib;\n List<Project.Resources.Resource.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (ResourceField mpxFieldID : getAllResourceExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPResourceField.getID(mpxFieldID) | MPPResourceField.RESOURCE_FIELD_BASE);\n\n attrib = m_factory.createProjectResourcesResourceExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }", "protected static boolean isOperatorLR( Symbol s ) {\n if( s == null )\n return false;\n\n switch( s ) {\n case ELEMENT_DIVIDE:\n case ELEMENT_TIMES:\n case ELEMENT_POWER:\n case RDIVIDE:\n case LDIVIDE:\n case TIMES:\n case POWER:\n case PLUS:\n case MINUS:\n case ASSIGN:\n return true;\n }\n return false;\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 AsciiTable setPaddingRight(int paddingRight) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingRight(paddingRight);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
Obtain parameters from query @param query query to scan @return Map of parameters
[ "public static HashMap<String, String> getParameters(String query) {\n HashMap<String, String> params = new HashMap<String, String>();\n if (query == null || query.length() == 0) {\n return params;\n }\n\n String[] splitQuery = query.split(\"&\");\n for (String splitItem : splitQuery) {\n String[] items = splitItem.split(\"=\");\n\n if (items.length == 1) {\n params.put(items[0], \"\");\n } else {\n params.put(items[0], items[1]);\n }\n }\n\n return params;\n }" ]
[ "private void logState(final FileRollEvent fileRollEvent) {\n\n//\t\tif (ApplicationState.isApplicationStateEnabled()) {\n\t\t\t\n\t\t\tsynchronized (this) {\n\t\t\t\t\n\t\t\t\tfinal Collection<ApplicationState.ApplicationStateMessage> entries = ApplicationState.getAppStateEntries();\n\t\t\t\tfor (ApplicationState.ApplicationStateMessage entry : entries) {\n Level level = ApplicationState.getLog4jLevel(entry.getLevel());\n\t\t\t\t if(level.isGreaterOrEqual(ApplicationState.LOGGER.getEffectiveLevel())) {\n\t\t\t\t\t\tfinal org.apache.log4j.spi.LoggingEvent loggingEvent = new org.apache.log4j.spi.LoggingEvent(ApplicationState.FQCN, ApplicationState.LOGGER, level, entry.getMessage(), null);\n\n\t\t\t\t\t\t//Save the current layout before changing it to the original (relevant for marker cases when the layout was changed)\n\t\t\t\t\t\tLayout current=fileRollEvent.getSource().getLayout();\n\t\t\t\t\t\t//fileRollEvent.getSource().activeOriginalLayout();\n\t\t\t\t\t\tString flowContext = (String) MDC.get(\"flowCtxt\");\n\t\t\t\t\t\tMDC.remove(\"flowCtxt\");\n\t\t\t\t\t\t//Write applicationState:\n\t\t\t\t\t\tif(fileRollEvent.getSource().isAddApplicationState() && fileRollEvent.getSource().getFile().endsWith(\"log\")){\n\t\t\t\t\t\t\tfileRollEvent.dispatchToAppender(loggingEvent);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Set current again.\n\t\t\t\t\t\tfileRollEvent.getSource().setLayout(current);\n\t\t\t\t\t\tif (flowContext != null) {\n\t\t\t\t\t\t\tMDC.put(\"flowCtxt\", flowContext);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n//\t\t}\n\t}", "public static void registerMbean(Object mbean, ObjectName name) {\n registerMbean(ManagementFactory.getPlatformMBeanServer(),\n JmxUtils.createModelMBean(mbean),\n name);\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 }", "public Where<T, ID> raw(String rawStatement, ArgumentHolder... args) {\n\t\tfor (ArgumentHolder arg : args) {\n\t\t\tString columnName = arg.getColumnName();\n\t\t\tif (columnName == null) {\n\t\t\t\tif (arg.getSqlType() == null) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Either the column name or SqlType must be set on each argument\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\targ.setMetaInfo(findColumnFieldType(columnName));\n\t\t\t}\n\t\t}\n\t\taddClause(new Raw(rawStatement, args));\n\t\treturn this;\n\t}", "private void sendOneAsyncHint(final ByteArray slopKey,\n final Versioned<byte[]> slopVersioned,\n final List<Node> nodesToTry) {\n Node nodeToHostHint = null;\n boolean foundNode = false;\n while(nodesToTry.size() > 0) {\n nodeToHostHint = nodesToTry.remove(0);\n if(!failedNodes.contains(nodeToHostHint) && failureDetector.isAvailable(nodeToHostHint)) {\n foundNode = true;\n break;\n }\n }\n if(!foundNode) {\n Slop slop = slopSerializer.toObject(slopVersioned.getValue());\n logger.error(\"Trying to send an async hint but used up all nodes. key: \"\n + slop.getKey() + \" version: \" + slopVersioned.getVersion().toString());\n return;\n }\n final Node node = nodeToHostHint;\n int nodeId = node.getId();\n\n NonblockingStore nonblockingStore = nonblockingSlopStores.get(nodeId);\n Utils.notNull(nonblockingStore);\n\n final Long startNs = System.nanoTime();\n NonblockingStoreCallback callback = new NonblockingStoreCallback() {\n\n @Override\n public void requestComplete(Object result, long requestTime) {\n Slop slop = null;\n boolean loggerDebugEnabled = logger.isDebugEnabled();\n if(loggerDebugEnabled) {\n slop = slopSerializer.toObject(slopVersioned.getValue());\n }\n Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,\n slopKey,\n result,\n requestTime);\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(!failedNodes.contains(node))\n failedNodes.add(node);\n if(response.getValue() instanceof UnreachableStoreException) {\n UnreachableStoreException use = (UnreachableStoreException) response.getValue();\n\n if(loggerDebugEnabled) {\n logger.debug(\"Write of key \" + slop.getKey() + \" for \"\n + slop.getNodeId() + \" to node \" + node\n + \" failed due to unreachable: \" + use.getMessage());\n }\n\n failureDetector.recordException(node, (System.nanoTime() - startNs)\n / Time.NS_PER_MS, use);\n }\n sendOneAsyncHint(slopKey, slopVersioned, nodesToTry);\n }\n\n if(loggerDebugEnabled)\n logger.debug(\"Slop write of key \" + slop.getKey() + \" for node \"\n + slop.getNodeId() + \" to node \" + node + \" succeeded in \"\n + (System.nanoTime() - startNs) + \" ns\");\n\n failureDetector.recordSuccess(node, (System.nanoTime() - startNs) / Time.NS_PER_MS);\n\n }\n };\n nonblockingStore.submitPutRequest(slopKey, slopVersioned, null, callback, timeoutMs);\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 }", "public void reportCompletion(NodeT completed) {\n completed.setPreparer(true);\n String dependency = completed.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onSuccessfulResolution(dependency);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }", "public static BufferedImage cloneImage( BufferedImage image ) {\n\t\tBufferedImage newImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB );\n\t\tGraphics2D g = newImage.createGraphics();\n\t\tg.drawRenderedImage( image, null );\n\t\tg.dispose();\n\t\treturn newImage;\n\t}", "private void pushRight( int row ) {\n if( isOffZero(row))\n return;\n\n// B = createB();\n// B.print();\n rotatorPushRight(row);\n int end = N-2-row;\n for( int i = 0; i < end && bulge != 0; i++ ) {\n rotatorPushRight2(row,i+2);\n }\n// }\n }" ]
Set the mbean server on the QueryExp and try and pass back any previously set one
[ "private static MBeanServer setQueryExpServer(QueryExp query, MBeanServer toSet) {\n // We assume the QueryExp is a QueryEval subclass or uses the QueryEval thread local\n // mechanism to store any existing MBeanServer. If that's not the case we have no\n // way to access the old mbeanserver to let us restore it\n MBeanServer result = QueryEval.getMBeanServer();\n query.setMBeanServer(toSet);\n return result;\n }" ]
[ "public static double StdDev( int[] values, double mean ){\n double stddev = 0;\n double diff;\n int hits;\n int total = 0;\n\n // for all values\n for ( int i = 0, n = values.length; i < n; i++ )\n {\n hits = values[i];\n diff = (double) i - mean;\n // accumulate std.dev.\n stddev += diff * diff * hits;\n // accumalate total\n total += hits;\n }\n\n return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) );\n }", "protected static String createDotStoryName(String scenarioName) {\n String[] words = scenarioName.trim().split(\" \");\n String result = \"\";\n for (int i = 0; i < words.length; i++) {\n String word1 = words[i];\n String word2 = word1.toLowerCase();\n if (!word1.equals(word2)) {\n String finalWord = \"\";\n for (int j = 0; j < word1.length(); j++) {\n if (i != 0) {\n char c = word1.charAt(j);\n if (Character.isUpperCase(c)) {\n if (j==0) {\n finalWord += Character.toLowerCase(c);\n } else {\n finalWord += \"_\" + Character.toLowerCase(c); \n }\n } else {\n finalWord += c;\n }\n } else {\n finalWord = word2;\n break;\n }\n }\n\n result += finalWord;\n } else {\n result += word2;\n }\n // I don't add the '_' to the last word.\n if (!(i == words.length - 1))\n result += \"_\";\n }\n return result;\n }", "private void writeCalendar(ProjectCalendar mpxjCalendar, net.sf.mpxj.planner.schema.Calendar plannerCalendar) throws JAXBException\n {\n //\n // Populate basic details\n //\n plannerCalendar.setId(getIntegerString(mpxjCalendar.getUniqueID()));\n plannerCalendar.setName(getString(mpxjCalendar.getName()));\n\n //\n // Set working and non working days\n //\n DefaultWeek dw = m_factory.createDefaultWeek();\n plannerCalendar.setDefaultWeek(dw);\n dw.setMon(getWorkingDayString(mpxjCalendar, Day.MONDAY));\n dw.setTue(getWorkingDayString(mpxjCalendar, Day.TUESDAY));\n dw.setWed(getWorkingDayString(mpxjCalendar, Day.WEDNESDAY));\n dw.setThu(getWorkingDayString(mpxjCalendar, Day.THURSDAY));\n dw.setFri(getWorkingDayString(mpxjCalendar, Day.FRIDAY));\n dw.setSat(getWorkingDayString(mpxjCalendar, Day.SATURDAY));\n dw.setSun(getWorkingDayString(mpxjCalendar, Day.SUNDAY));\n\n //\n // Set working hours\n //\n OverriddenDayTypes odt = m_factory.createOverriddenDayTypes();\n plannerCalendar.setOverriddenDayTypes(odt);\n List<OverriddenDayType> typeList = odt.getOverriddenDayType();\n Sequence uniqueID = new Sequence(0);\n\n //\n // This is a bit arbitrary, so not ideal, however...\n // The idea here is that MS Project allows us to specify working hours\n // for each day of the week individually. Planner doesn't do this,\n // but instead allows us to specify working hours for each day type.\n // What we are doing here is stepping through the days of the week to\n // find the first working day, then using the hours for that day\n // as the hours for the working day type in Planner.\n //\n for (int dayLoop = 1; dayLoop < 8; dayLoop++)\n {\n Day day = Day.getInstance(dayLoop);\n if (mpxjCalendar.isWorkingDay(day))\n {\n processWorkingHours(mpxjCalendar, uniqueID, day, typeList);\n break;\n }\n }\n\n //\n // Process exception days\n //\n Days plannerDays = m_factory.createDays();\n plannerCalendar.setDays(plannerDays);\n List<net.sf.mpxj.planner.schema.Day> dayList = plannerDays.getDay();\n processExceptionDays(mpxjCalendar, dayList);\n\n m_eventManager.fireCalendarWrittenEvent(mpxjCalendar);\n\n //\n // Process any derived calendars\n //\n List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();\n\n for (ProjectCalendar mpxjDerivedCalendar : mpxjCalendar.getDerivedCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerDerivedCalendar = m_factory.createCalendar();\n calendarList.add(plannerDerivedCalendar);\n writeCalendar(mpxjDerivedCalendar, plannerDerivedCalendar);\n }\n }", "public static void columnMaxAbs( DMatrixSparseCSC A , double []values ) {\n if( values.length < A.numCols )\n throw new IllegalArgumentException(\"Array is too small. \"+values.length+\" < \"+A.numCols);\n\n for (int i = 0; i < A.numCols; i++) {\n int idx0 = A.col_idx[i];\n int idx1 = A.col_idx[i+1];\n\n double maxabs = 0;\n for (int j = idx0; j < idx1; j++) {\n double v = Math.abs(A.nz_values[j]);\n if( v > maxabs )\n maxabs = v;\n }\n values[i] = maxabs;\n }\n }", "private void processUDF(UDFTypeType udf)\n {\n FieldTypeClass fieldType = FIELD_TYPE_MAP.get(udf.getSubjectArea());\n if (fieldType != null)\n {\n UserFieldDataType dataType = UserFieldDataType.getInstanceFromXmlName(udf.getDataType());\n String name = udf.getTitle();\n FieldType field = addUserDefinedField(fieldType, dataType, name);\n if (field != null)\n {\n m_fieldTypeMap.put(udf.getObjectId(), field);\n }\n }\n }", "protected void putResponse(JSONObject json,\n String param,\n Object value) {\n try {\n json.put(param,\n value);\n } catch (JSONException e) {\n logger.error(\"json write error\",\n e);\n }\n }", "public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }", "private void getYearlyRelativeDates(Calendar calendar, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.set(Calendar.MONTH, NumberHelper.getInt(m_monthNumber) - 1);\n\n int dayNumber = NumberHelper.getInt(m_dayNumber);\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.YEAR, 1);\n }\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 }" ]