query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Pool configuration.
@param props
@throws HibernateException | [
"public void configure(Properties props) throws HibernateException {\r\n\t\ttry{\r\n\t\t\tthis.config = new BoneCPConfig(props);\r\n\r\n\t\t\t// old hibernate config\r\n\t\t\tString url = props.getProperty(CONFIG_CONNECTION_URL);\r\n\t\t\tString username = props.getProperty(CONFIG_CONNECTION_USERNAME);\r\n\t\t\tString password = props.getProperty(CONFIG_CONNECTION_PASSWORD);\r\n\t\t\tString driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS);\r\n\t\t\tif (url == null){\r\n\t\t\t\turl = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (username == null){\r\n\t\t\t\tusername = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (password == null){\r\n\t\t\t\tpassword = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (driver == null){\r\n\t\t\t\tdriver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE);\r\n\t\t\t}\r\n\r\n\t\t\tif (url != null){\r\n\t\t\t\tthis.config.setJdbcUrl(url);\r\n\t\t\t}\r\n\t\t\tif (username != null){\r\n\t\t\t\tthis.config.setUsername(username);\r\n\t\t\t}\r\n\t\t\tif (password != null){\r\n\t\t\t\tthis.config.setPassword(password);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t// Remember Isolation level\r\n\t\t\tthis.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props);\r\n\t\t\tthis.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props);\r\n\r\n\t\t\tlogger.debug(this.config.toString());\r\n\r\n\t\t\tif (driver != null && !driver.trim().equals(\"\")){\r\n\t\t\t\tloadClass(driver);\r\n\t\t\t}\r\n\t\t\tif (this.config.getConnectionHookClassName() != null){\r\n\t\t\t\tObject hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance();\r\n\t\t\t\tthis.config.setConnectionHook((ConnectionHook) hookClass);\r\n\t\t\t}\r\n\t\t\t// create the connection pool\r\n\t\t\tthis.pool = createPool(this.config);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new HibernateException(e);\r\n\t\t}\r\n\t}"
] | [
"public boolean isMaskCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\tif(!isMultiple()) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn super.isMaskCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}",
"private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n if (join.right.hasJoins())\r\n {\r\n buf.append(\"(\");\r\n appendTableWithJoins(join.right, where, buf);\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n appendTableWithJoins(join.right, where, buf);\r\n }\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n }",
"public static base_response Force(nitro_service client, clustersync resource) throws Exception {\n\t\tclustersync Forceresource = new clustersync();\n\t\treturn Forceresource.perform_operation(client,\"Force\");\n\t}",
"private String getResourceField(int key)\n {\n String result = null;\n\n if (key > 0 && key < m_resourceNames.length)\n {\n result = m_resourceNames[key];\n }\n\n return (result);\n }",
"@Override\n protected void runUnsafe() throws Exception {\n Path reportDirectory = getReportDirectoryPath();\n Files.walkFileTree(reportDirectory, new DeleteVisitor());\n LOGGER.info(\"Report directory <{}> was successfully cleaned.\", reportDirectory);\n }",
"public static base_responses add(nitro_service client, vpath resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tvpath addresources[] = new vpath[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new vpath();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].destip = resources[i].destip;\n\t\t\t\taddresources[i].encapmode = resources[i].encapmode;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"GVRSceneObject makeParticleMesh(float[] vertices, float[] velocities,\n float[] particleTimeStamps )\n {\n mParticleMesh = new GVRMesh(mGVRContext);\n\n //pass the particle positions as vertices, velocities as normals, and\n //spawning times as texture coordinates.\n mParticleMesh.setVertices(vertices);\n mParticleMesh.setNormals(velocities);\n mParticleMesh.setTexCoords(particleTimeStamps);\n\n particleID = new GVRShaderId(ParticleShader.class);\n material = new GVRMaterial(mGVRContext, particleID);\n\n material.setVec4(\"u_color\", mColorMultiplier.x, mColorMultiplier.y,\n mColorMultiplier.z, mColorMultiplier.w);\n material.setFloat(\"u_particle_age\", mAge);\n material.setVec3(\"u_acceleration\", mAcceleration.x, mAcceleration.y, mAcceleration.z);\n material.setFloat(\"u_particle_size\", mSize);\n material.setFloat(\"u_size_change_rate\", mParticleSizeRate);\n material.setFloat(\"u_fade\", mFadeWithAge);\n material.setFloat(\"u_noise_factor\", mNoiseFactor);\n\n GVRRenderData renderData = new GVRRenderData(mGVRContext);\n renderData.setMaterial(material);\n renderData.setMesh(mParticleMesh);\n material.setMainTexture(mTexture);\n\n GVRSceneObject meshObject = new GVRSceneObject(mGVRContext);\n meshObject.attachRenderData(renderData);\n meshObject.getRenderData().setMaterial(material);\n\n // Set the draw mode to GL_POINTS, disable writing to depth buffer, enable depth testing\n // and set the rendering order to transparent.\n // Disabling writing to depth buffer ensure that the particles blend correctly\n // and keeping the depth test on along with rendering them\n // after the geometry queue makes sure they occlude, and are occluded, correctly.\n\n meshObject.getRenderData().setDrawMode(GL_POINTS);\n meshObject.getRenderData().setDepthTest(true);\n meshObject.getRenderData().setDepthMask(false);\n meshObject.getRenderData().setRenderingOrder(GVRRenderData.GVRRenderingOrder.TRANSPARENT);\n\n return meshObject;\n }",
"public static String getShortClassName(Object o) {\r\n String name = o.getClass().getName();\r\n int index = name.lastIndexOf('.');\r\n if (index >= 0) {\r\n name = name.substring(index + 1);\r\n }\r\n return name;\r\n }",
"public synchronized X509Certificate getCertificateByHostname(final String hostname) throws KeyStoreException, CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException{\n\n\t\tString alias = _subjectMap.get(getSubjectForHostname(hostname));\n\n\t\tif(alias != null) {\n\t\t\treturn (X509Certificate)_ks.getCertificate(alias);\n\t\t}\n return getMappedCertificateForHostname(hostname);\n\t}"
] |
Inserts the specified objects at the specified index in the array.
@param items The objects to insert into the array.
@param index The index at which the object must be inserted. | [
"public void addAll(int index, T... items) {\n List<T> collection = Arrays.asList(items);\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.addAll(index, collection);\n } else {\n mObjects.addAll(index, collection);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }"
] | [
"public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}",
"protected void checkForPrimaryKeys(final Object realObject) throws ClassNotPersistenceCapableException\r\n {\r\n // if no PKs are specified OJB can't handle this class !\r\n if (m_pkValues == null || m_pkValues.length == 0)\r\n {\r\n throw createException(\"OJB needs at least one primary key attribute for class: \", realObject, null);\r\n }\r\n// arminw: should never happen\r\n// if(m_pkValues[0] instanceof ValueContainer)\r\n// throw new OJBRuntimeException(\"Can't handle pk values of type \"+ValueContainer.class.getName());\r\n }",
"public base_response enable_modes(String[] modes) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsmode resource = new nsmode();\n\t\tresource.set_mode(modes);\n\t\toptions option = new options();\n\t\toption.set_action(\"enable\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}",
"public static clusterinstance_binding get(nitro_service service, Long clid) throws Exception{\n\t\tclusterinstance_binding obj = new clusterinstance_binding();\n\t\tobj.set_clid(clid);\n\t\tclusterinstance_binding response = (clusterinstance_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void createAndLockDescriptorFile() throws CmsException {\n\n String sitePath = m_sitepath + m_basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX;\n m_desc = m_cms.createResource(\n sitePath,\n OpenCms.getResourceManager().getResourceType(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString()));\n m_descFile = LockedFile.lockResource(m_cms, m_desc);\n m_descFile.setCreated(true);\n }",
"private List<ModelNode> describeAsNodeList(PathAddress rootAddress, final Resource resource, boolean isRuntimeChange) {\n final List<ModelNode> list = new ArrayList<ModelNode>();\n\n describe(rootAddress, resource, list, isRuntimeChange);\n return list;\n }",
"protected NodeData createBodyStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"background-color\", tf.createColor(255, 255, 255)));\n return ret;\n }",
"protected boolean showMoreEntries(Calendar nextDate, int previousOccurrences) {\n\n switch (getSerialEndType()) {\n case DATE:\n boolean moreByDate = nextDate.getTimeInMillis() < m_endMillis;\n boolean moreByOccurrences = previousOccurrences < CmsSerialDateUtil.getMaxEvents();\n if (moreByDate && !moreByOccurrences) {\n m_hasTooManyOccurrences = Boolean.TRUE;\n }\n return moreByDate && moreByOccurrences;\n case TIMES:\n case SINGLE:\n return previousOccurrences < getOccurrences();\n default:\n throw new IllegalArgumentException();\n }\n }",
"public void setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tif(targetTranslator!=null){\r\n\t\t\tthis.targetTranslator = targetTranslator;\r\n\t\t\tthis.charTranslator = null;\r\n\t\t\tthis.htmlElementTranslator = null;\r\n\t\t}\r\n\t}"
] |
Returns any events for the given resource ID since the last sync token
@param resource Globally unique identifier for the resource.
@param sync Sync token provided by a previous call to the events API
@return Request object | [
"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 }"
] | [
"@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 boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {\n if (!t1.getJavaClass().equals(t2.getJavaClass())) {\n return false;\n }\n if (!compareAnnotated(t1, t2)) {\n return false;\n }\n\n if (t1.getFields().size() != t2.getFields().size()) {\n return false;\n }\n Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();\n for (AnnotatedField<?> f : t2.getFields()) {\n fields.put(f.getJavaMember(), f);\n }\n for (AnnotatedField<?> f : t1.getFields()) {\n if (fields.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n if (t1.getMethods().size() != t2.getMethods().size()) {\n return false;\n }\n Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();\n for (AnnotatedMethod<?> f : t2.getMethods()) {\n methods.put(f.getJavaMember(), f);\n }\n for (AnnotatedMethod<?> f : t1.getMethods()) {\n if (methods.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n if (t1.getConstructors().size() != t2.getConstructors().size()) {\n return false;\n }\n Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>();\n for (AnnotatedConstructor<?> f : t2.getConstructors()) {\n constructors.put(f.getJavaMember(), f);\n }\n for (AnnotatedConstructor<?> f : t1.getConstructors()) {\n if (constructors.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n\n }",
"public static void append(File file, Writer writer, String charset) throws IOException {\n appendBuffered(file, writer, charset);\n }",
"private static boolean scanForEndSig(File file, FileChannel channel) throws IOException, NonScannableZipException {\n\n // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long start = channel.size();\n long end = Math.max(0, start - MAX_REVERSE_SCAN);\n long channelPos = Math.max(0, start - CHUNK_SIZE);\n long lastChannelPos = channelPos;\n boolean firstRead = true;\n while (lastChannelPos >= end) {\n\n read(bb, channel, channelPos);\n\n int actualRead = bb.limit();\n if (firstRead) {\n long expectedRead = Math.min(CHUNK_SIZE, start);\n if (actualRead > expectedRead) {\n // File is still growing\n return false;\n }\n firstRead = false;\n }\n\n int bufferPos = actualRead -1;\n while (bufferPos >= SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the pattern is static\n // b) the pattern has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && ENDSIG_PATTERN[patternPos] == bb.get(bufferPos - patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid end of central dir record\n long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1;\n if (validateEndRecord(file, channel, startEndRecord)) {\n return true;\n }\n // wasn't a valid end record; continue scan\n bufferPos -= 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE;\n bufferPos -= END_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos -= 4;\n }\n }\n\n // Move back a full chunk. If we didn't read a full chunk, that's ok,\n // it means we read all data and the outer while loop will terminate\n if (channelPos <= bufferPos) {\n break;\n }\n lastChannelPos = channelPos;\n channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos);\n }\n\n return false;\n }",
"public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\n }",
"private void init(boolean upgrade)\n {\n initAdapter();\n initQueries();\n if (upgrade)\n {\n dbUpgrade();\n }\n\n // First contact with the DB is version checking (if no connection opened by pool).\n // If DB is in wrong version or not available, just wait for it to be ready.\n boolean versionValid = false;\n while (!versionValid)\n {\n try\n {\n checkSchemaVersion();\n versionValid = true;\n }\n catch (Exception e)\n {\n String msg = e.getLocalizedMessage();\n if (e.getCause() != null)\n {\n msg += \" - \" + e.getCause().getLocalizedMessage();\n }\n jqmlogger.error(\"Database not ready: \" + msg + \". Waiting for database...\");\n try\n {\n Thread.sleep(10000);\n }\n catch (Exception e2)\n {\n }\n }\n }\n }",
"public int execute(DatabaseConnection databaseConnection, T data, ID newId, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\ttry {\n\t\t\t// the arguments are the new-id and old-id\n\t\t\tObject[] args = new Object[] { convertIdToFieldObject(newId), extractIdToFieldObject(data) };\n\t\t\tint rowC = databaseConnection.update(statement, args, argFieldTypes);\n\t\t\tif (rowC > 0) {\n\t\t\t\tif (objectCache != null) {\n\t\t\t\t\tObject oldId = idField.extractJavaFieldValue(data);\n\t\t\t\t\tT obj = objectCache.updateId(clazz, oldId, newId);\n\t\t\t\t\tif (obj != null && obj != data) {\n\t\t\t\t\t\t// if our cached value is not the data that will be updated then we need to update it specially\n\t\t\t\t\t\tidField.assignField(connectionSource, obj, newId, false, objectCache);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// adjust the object to assign the new id\n\t\t\t\tidField.assignField(connectionSource, data, newId, false, objectCache);\n\t\t\t}\n\t\t\tlogger.debug(\"updating-id with statement '{}' and {} args, changed {} rows\", statement, args.length, rowC);\n\t\t\tif (args.length > 0) {\n\t\t\t\t// need to do the cast otherwise we only print the first object in args\n\t\t\t\tlogger.trace(\"updating-id arguments: {}\", (Object) args);\n\t\t\t}\n\t\t\treturn rowC;\n\t\t} catch (SQLException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Unable to run update-id stmt on object \" + data + \": \" + statement, e);\n\t\t}\n\t}",
"public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // check constraints now after all classes have been processed\r\n for (Iterator it = getClasses(); it.hasNext();)\r\n {\r\n ((ClassDescriptorDef)it.next()).checkConstraints(checkLevel);\r\n }\r\n // additional model constraints that either deal with bigger parts of the model or\r\n // can only be checked after the individual classes have been checked (e.g. specific\r\n // attributes have been ensured)\r\n new ModelConstraints().check(this, checkLevel);\r\n }",
"public Value get(Object key) {\n /* If the length is under and we are asking for the key, then just look for the key. Don't build the map. */\n if (map == null && items.length < 20) {\n for (Object item : items) {\n MapItemValue miv = (MapItemValue) item;\n if (key.equals(miv.name.toValue())) {\n return miv.value;\n }\n }\n return null;\n } else {\n if (map == null) buildIfNeededMap();\n return map.get(key);\n }\n }"
] |
Lookup the Gallery for the specified ID.
@param galleryId
The user profile URL
@return The Gallery
@throws FlickrException | [
"public Gallery lookupGallery(String galleryId) throws FlickrException {\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GALLERY);\r\n parameters.put(\"url\", galleryId);\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 galleryElement = response.getPayload();\r\n Gallery gallery = new Gallery();\r\n gallery.setId(galleryElement.getAttribute(\"id\"));\r\n gallery.setUrl(galleryElement.getAttribute(\"url\"));\r\n\r\n User owner = new User();\r\n owner.setId(galleryElement.getAttribute(\"owner\"));\r\n gallery.setOwner(owner);\r\n gallery.setCreateDate(galleryElement.getAttribute(\"date_create\"));\r\n gallery.setUpdateDate(galleryElement.getAttribute(\"date_update\"));\r\n gallery.setPrimaryPhotoId(galleryElement.getAttribute(\"primary_photo_id\"));\r\n gallery.setPrimaryPhotoServer(galleryElement.getAttribute(\"primary_photo_server\"));\r\n gallery.setVideoCount(galleryElement.getAttribute(\"count_videos\"));\r\n gallery.setPhotoCount(galleryElement.getAttribute(\"count_photos\"));\r\n gallery.setPrimaryPhotoFarm(galleryElement.getAttribute(\"farm\"));\r\n gallery.setPrimaryPhotoSecret(galleryElement.getAttribute(\"secret\"));\r\n\r\n gallery.setTitle(XMLUtilities.getChildValue(galleryElement, \"title\"));\r\n gallery.setDesc(XMLUtilities.getChildValue(galleryElement, \"description\"));\r\n return gallery;\r\n }"
] | [
"public void updateAnimation()\n {\n Date time = new Date();\n long currentTime = time.getTime() - this.beginAnimation;\n if (currentTime > animationTime)\n {\n this.currentQuaternion.set(endQuaternion);\n for (int i = 0; i < 3; i++)\n {\n\n this.currentPos[i] = this.endPos[i];\n }\n this.animate = false;\n }\n\n else\n {\n float t = (float) currentTime / animationTime;\n this.currentQuaternion = this.beginQuaternion.slerp(this.endQuaternion,\n t);\n for (int i = 0; i < 3; i++)\n {\n this.currentPos[i] = this.beginPos[i] + totalTranslation[i] * t;\n }\n\n }\n }",
"@Override\n public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {\n this.problemReporter.abortDueToInternalError(\n Messages.bind(Messages.abort_againstSourceModel, new String[] { String.valueOf(sourceTypes[0].getName()), String.valueOf(sourceTypes[0].getFileName()) }));\n }",
"private void logError(LifecycleListener listener, Exception e) {\n LOGGER.error(\"Error for listener \" + listener.getClass(), e);\n }",
"protected boolean check(String id, List<String> includes) {\n\t\tif (null != includes) {\n\t\t\tfor (String check : includes) {\n\t\t\t\tif (check(id, check)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public static CharSequence getAt(CharSequence text, IntRange range) {\n return getAt(text, (Range) range);\n }",
"public void setOutlineCode(int index, String value)\n {\n set(selectField(TaskFieldLists.CUSTOM_OUTLINE_CODE, index), value);\n }",
"public FileModel getChildFile(ArchiveModel archiveModel, String filePath)\n {\n filePath = FilenameUtils.separatorsToUnix(filePath);\n StringTokenizer stk = new StringTokenizer(filePath, \"/\");\n\n FileModel currentFileModel = archiveModel;\n while (stk.hasMoreTokens() && currentFileModel != null)\n {\n String pathElement = stk.nextToken();\n\n currentFileModel = findFileModel(currentFileModel, pathElement);\n }\n return currentFileModel;\n }",
"public String[] parseMFString(String mfString) {\n Vector<String> strings = new Vector<String>();\n\n StringReader sr = new StringReader(mfString);\n StreamTokenizer st = new StreamTokenizer(sr);\n st.quoteChar('\"');\n st.quoteChar('\\'');\n String[] mfStrings = null;\n\n int tokenType;\n try {\n while ((tokenType = st.nextToken()) != StreamTokenizer.TT_EOF) {\n\n strings.add(st.sval);\n\n }\n } catch (IOException e) {\n\n Log.d(TAG, \"String parsing Error: \" + e);\n\n e.printStackTrace();\n }\n mfStrings = new String[strings.size()];\n for (int i = 0; i < strings.size(); i++) {\n mfStrings[i] = strings.get(i);\n }\n return mfStrings;\n }",
"OTMConnection getConnection()\r\n {\r\n if (m_connection == null)\r\n {\r\n OTMConnectionRuntimeException ex = new OTMConnectionRuntimeException(\"Connection is null.\");\r\n sendEvents(ConnectionEvent.CONNECTION_ERROR_OCCURRED, ex, null);\r\n }\r\n return m_connection;\r\n }"
] |
Create and serialize a WorkerStatus.
@param queue the queue the Job came from
@param job the Job currently being processed
@return the JSON representation of a new WorkerStatus
@throws IOException if there was an error serializing the WorkerStatus | [
"protected String statusMsg(final String queue, final Job job) throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setQueue(queue);\n status.setPayload(job);\n return ObjectMapperFactory.get().writeValueAsString(status);\n }"
] | [
"public static base_responses unset(nitro_service client, Long clid[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance unsetresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tunsetresources[i] = new clusterinstance();\n\t\t\t\tunsetresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public static Span prefix(Bytes rowPrefix) {\n Objects.requireNonNull(rowPrefix);\n Bytes fp = followingPrefix(rowPrefix);\n return new Span(rowPrefix, true, fp == null ? Bytes.EMPTY : fp, false);\n }",
"@Deprecated\r\n public Location resolvePlaceId(String placeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_RESOLVE_PLACE_ID);\r\n\r\n parameters.put(\"place_id\", placeId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }",
"public PeriodicEvent runEvery(Runnable task, float delay, float period,\n KeepRunning callback) {\n validateDelay(delay);\n validatePeriod(period);\n return new Event(task, delay, period, callback);\n }",
"private static Predicate join(final String joinWord, final List<Predicate> preds) {\n return new Predicate() {\n public void init(AbstractSqlCreator creator) {\n for (Predicate p : preds) {\n p.init(creator);\n }\n }\n public String toSql() {\n StringBuilder sb = new StringBuilder()\n .append(\"(\");\n boolean first = true;\n for (Predicate p : preds) {\n if (!first) {\n sb.append(\" \").append(joinWord).append(\" \");\n }\n sb.append(p.toSql());\n first = false;\n }\n return sb.append(\")\").toString();\n }\n };\n }",
"public static CmsSolrSpellchecker getInstance(CoreContainer container) {\n\n if (null == instance) {\n synchronized (CmsSolrSpellchecker.class) {\n if (null == instance) {\n @SuppressWarnings(\"resource\")\n SolrCore spellcheckCore = container.getCore(CmsSolrSpellchecker.SPELLCHECKER_INDEX_CORE);\n if (spellcheckCore == null) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_SPELLCHECK_CORE_NOT_AVAILABLE_1,\n CmsSolrSpellchecker.SPELLCHECKER_INDEX_CORE));\n return null;\n }\n instance = new CmsSolrSpellchecker(container, spellcheckCore);\n }\n }\n }\n\n return instance;\n }",
"public static filterhtmlinjectionparameter get(nitro_service service, options option) throws Exception{\n\t\tfilterhtmlinjectionparameter obj = new filterhtmlinjectionparameter();\n\t\tfilterhtmlinjectionparameter[] response = (filterhtmlinjectionparameter[])obj.get_resources(service,option);\n\t\treturn response[0];\n\t}",
"public static void checkDelegateType(Decorator<?> decorator) {\n\n Set<Type> types = new HierarchyDiscovery(decorator.getDelegateType()).getTypeClosure();\n\n for (Type decoratedType : decorator.getDecoratedTypes()) {\n if(!types.contains(decoratedType)) {\n throw BeanLogger.LOG.delegateMustSupportEveryDecoratedType(decoratedType, decorator);\n }\n }\n }",
"private void readResource(Document.Resources.Resource resource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setName(resource.getName());\n mpxjResource.setResourceCalendar(m_calendarMap.get(resource.getCalendarID()));\n mpxjResource.setStandardRate(new Rate(resource.getCost(), resource.getCostTimeUnit()));\n mpxjResource.setEmailAddress(resource.getEMail());\n mpxjResource.setGroup(resource.getGroup());\n //resource.getHyperlinks()\n mpxjResource.setUniqueID(resource.getID());\n //resource.getMarkerID()\n mpxjResource.setNotes(resource.getNote());\n mpxjResource.setID(Integer.valueOf(resource.getOutlineNumber()));\n //resource.getStyleProject()\n mpxjResource.setType(resource.getSubType() == null ? resource.getType() : resource.getSubType());\n }"
] |
Stop offering shared dbserver sessions. | [
"public synchronized void stop() {\n if (isRunning()) {\n running.set(false);\n DeviceFinder.getInstance().removeDeviceAnnouncementListener(announcementListener);\n dbServerPorts.clear();\n for (Client client : openClients.values()) {\n try {\n client.close();\n } catch (Exception e) {\n logger.warn(\"Problem closing \" + client + \" when stopping\", e);\n }\n }\n openClients.clear();\n useCounts.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }"
] | [
"public void checkpoint(ObjectEnvelope mod)\r\n throws org.apache.ojb.broker.PersistenceBrokerException\r\n {\r\n mod.doUpdate();\r\n }",
"public static RgbaColor fromHex(String hex) {\n if (hex.length() == 0 || hex.charAt(0) != '#') return getDefaultColor();\n\n // #rgb\n if (hex.length() == 4) {\n\n return new RgbaColor(parseHex(hex, 1, 2),\n parseHex(hex, 2, 3),\n parseHex(hex, 3, 4));\n\n }\n // #rrggbb\n else if (hex.length() == 7) {\n\n return new RgbaColor(parseHex(hex, 1, 3),\n parseHex(hex, 3, 5),\n parseHex(hex, 5, 7));\n\n }\n else {\n return getDefaultColor();\n }\n }",
"public static List<DbModule> getAllSubmodules(final DbModule module) {\n final List<DbModule> submodules = new ArrayList<DbModule>();\n submodules.addAll(module.getSubmodules());\n\n for(final DbModule submodule: module.getSubmodules()){\n submodules.addAll(getAllSubmodules(submodule));\n }\n\n return submodules;\n }",
"public Where<T, ID> in(String columnName, Object... objects) throws SQLException {\n\t\treturn in(true, columnName, objects);\n\t}",
"@Override\n\tpublic synchronized boolean fireEventAndWait(Eventable eventable)\n\t\t\tthrows ElementNotVisibleException, NoSuchElementException, InterruptedException {\n\t\ttry {\n\n\t\t\tboolean handleChanged = false;\n\t\t\tboolean result = false;\n\n\t\t\tif (eventable.getRelatedFrame() != null && !eventable.getRelatedFrame().equals(\"\")) {\n\t\t\t\tLOGGER.debug(\"switching to frame: \" + eventable.getRelatedFrame());\n\t\t\t\ttry {\n\n\t\t\t\t\tswitchToFrame(eventable.getRelatedFrame());\n\t\t\t\t} catch (NoSuchFrameException e) {\n\t\t\t\t\tLOGGER.debug(\"Frame not found, possibly while back-tracking..\", e);\n\t\t\t\t\t// TODO Stefan, This exception is caught to prevent stopping\n\t\t\t\t\t// from working\n\t\t\t\t\t// This was the case on the Gmail case; find out if not switching\n\t\t\t\t\t// (catching)\n\t\t\t\t\t// Results in good performance...\n\t\t\t\t}\n\t\t\t\thandleChanged = true;\n\t\t\t}\n\n\t\t\tWebElement webElement =\n\t\t\t\t\tbrowser.findElement(eventable.getIdentification().getWebDriverBy());\n\n\t\t\tif (webElement != null) {\n\t\t\t\tresult = fireEventWait(webElement, eventable);\n\t\t\t}\n\n\t\t\tif (handleChanged) {\n\t\t\t\tbrowser.switchTo().defaultContent();\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tthrow e;\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\treturn false;\n\t\t}\n\t}",
"public static void removeZeros( DMatrixSparseCSC input , DMatrixSparseCSC output , double tol ) {\n ImplCommonOps_DSCC.removeZeros(input,output,tol);\n }",
"public static boolean blockAligned( int blockLength , DSubmatrixD1 A ) {\n if( A.col0 % blockLength != 0 )\n return false;\n if( A.row0 % blockLength != 0 )\n return false;\n\n if( A.col1 % blockLength != 0 && A.col1 != A.original.numCols ) {\n return false;\n }\n\n if( A.row1 % blockLength != 0 && A.row1 != A.original.numRows) {\n return false;\n }\n\n return true;\n }",
"public static HttpConnection connect(String requestMethod,\n URL url,\n String contentType) {\n return new HttpConnection(requestMethod, url, contentType);\n }",
"public synchronized boolean isComplete(int requestId, boolean remove) {\n if (!operations.containsKey(requestId))\n throw new VoldemortException(\"No operation with id \" + requestId + \" found\");\n\n if (operations.get(requestId).getStatus().isComplete()) {\n if (logger.isDebugEnabled())\n logger.debug(\"Operation complete \" + requestId);\n\n if (remove)\n operations.remove(requestId);\n\n return true;\n }\n\n return false;\n }"
] |
Transfer the data from the inputStream to the outputStream. Then close both streams. | [
"private void copy(InputStream input, OutputStream output) throws IOException {\n try {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = input.read(buffer);\n while (bytesRead != -1) {\n output.write(buffer, 0, bytesRead);\n bytesRead = input.read(buffer);\n }\n } finally {\n input.close();\n output.close();\n }\n }"
] | [
"public static byte[] addContentToExplodedAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {\n final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);\n ModelNode contentItem = getContentItem(deploymentResource);\n byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItem).asBytes();\n List<ModelNode> contents = CONTENT_PARAM_ALL_EXPLODED.resolveModelAttribute(context, operation).asList();\n final List<ExplodedContent> addedFiles = new ArrayList<>(contents.size());\n\n final ModelNode slave = operation.clone();\n ModelNode slaveAddedfiles = slave.get(UPDATED_PATHS.getName()).setEmptyList();\n for(ModelNode content : contents) {\n InputStream in;\n if(hasValidContentAdditionParameterDefined(content)) {\n in = getInputStream(context, content);\n } else {\n in = null;\n }\n String path = TARGET_PATH.resolveModelAttribute(context, content).asString();\n addedFiles.add(new ExplodedContent(path, in));\n slaveAddedfiles.add(path);\n }\n final boolean overwrite = OVERWRITE.resolveModelAttribute(context, operation).asBoolean(true);\n final byte[] hash = contentRepository.addContentToExploded(oldHash, addedFiles, overwrite);\n\n // Clear the contents and update with the hash\n ModelNode addedContent = new ModelNode().setEmptyObject();\n addedContent.get(HASH).set(hash);\n addedContent.get(TARGET_PATH.getName()).set(\".\");\n slave.get(CONTENT).setEmptyList().add(addedContent);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }",
"public Object getRealKey()\r\n {\r\n if(keyRealSubject != null)\r\n {\r\n return keyRealSubject;\r\n }\r\n else\r\n {\r\n TransactionExt tx = getTransaction();\r\n\r\n if((tx != null) && tx.isOpen())\r\n {\r\n prepareKeyRealSubject(tx.getBroker());\r\n }\r\n else\r\n {\r\n if(getPBKey() != null)\r\n {\r\n PBCapsule capsule = new PBCapsule(getPBKey(), null);\r\n\r\n try\r\n {\r\n prepareKeyRealSubject(capsule.getBroker());\r\n }\r\n finally\r\n {\r\n capsule.destroy();\r\n }\r\n }\r\n else\r\n {\r\n getLog().warn(\"No tx, no PBKey - can't materialise key with Identity \" + getKeyOid());\r\n }\r\n }\r\n }\r\n return keyRealSubject;\r\n }",
"protected TokenList.Token parseBlockNoParentheses(TokenList tokens, Sequence sequence, boolean insideMatrixConstructor) {\n\n // search for matrix bracket operations\n if( !insideMatrixConstructor ) {\n parseBracketCreateMatrix(tokens, sequence);\n }\n\n // First create sequences from anything involving a colon\n parseSequencesWithColons(tokens, sequence );\n\n // process operators depending on their priority\n parseNegOp(tokens, sequence);\n parseOperationsL(tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.POWER, Symbol.ELEMENT_POWER}, tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.TIMES, Symbol.RDIVIDE, Symbol.LDIVIDE, Symbol.ELEMENT_TIMES, Symbol.ELEMENT_DIVIDE}, tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.PLUS, Symbol.MINUS}, tokens, sequence);\n\n // Commas are used in integer sequences. Can be used to force to compiler to treat - as negative not\n // minus. They can now be removed since they have served their purpose\n stripCommas(tokens);\n\n // now construct rest of the lists and combine them together\n parseIntegerLists(tokens);\n parseCombineIntegerLists(tokens);\n\n if( !insideMatrixConstructor ) {\n if (tokens.size() > 1) {\n System.err.println(\"Remaining tokens: \"+tokens.size);\n TokenList.Token t = tokens.first;\n while( t != null ) {\n System.err.println(\" \"+t);\n t = t.next;\n }\n throw new RuntimeException(\"BUG in parser. There should only be a single token left\");\n }\n return tokens.first;\n } else {\n return null;\n }\n }",
"public PathElement getLastElement() {\n final List<PathElement> list = pathAddressList;\n return list.size() == 0 ? null : list.get(list.size() - 1);\n }",
"public double distance(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n }",
"public static URL codeLocationFromClass(Class<?> codeLocationClass) {\n String pathOfClass = codeLocationClass.getName().replace(\".\", \"/\") + \".class\";\n URL classResource = codeLocationClass.getClassLoader().getResource(pathOfClass);\n String codeLocationPath = removeEnd(getPathFromURL(classResource), pathOfClass);\n if(codeLocationPath.endsWith(\".jar!/\")) {\n codeLocationPath=removeEnd(codeLocationPath,\"!/\");\n }\n return codeLocationFromPath(codeLocationPath);\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getCount(String event) {\n EventDetail eventDetail = getLocalDataStore().getEventDetail(event);\n if (eventDetail != null) return eventDetail.getCount();\n\n return -1;\n }",
"public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }",
"private void processClientId(HttpServletRequest httpServletRequest, History history) {\n // get the client id from the request header if applicable.. otherwise set to default\n // also set the client uuid in the history object\n if (httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME) != null &&\n !httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME).equals(\"\")) {\n history.setClientUUID(httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME));\n } else {\n history.setClientUUID(Constants.PROFILE_CLIENT_DEFAULT_ID);\n }\n logger.info(\"Client UUID is: {}\", history.getClientUUID());\n }"
] |
Use this API to add inat. | [
"public static base_response add(nitro_service client, inat resource) throws Exception {\n\t\tinat addresource = new inat();\n\t\taddresource.name = resource.name;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.privateip = resource.privateip;\n\t\taddresource.tcpproxy = resource.tcpproxy;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.tftp = resource.tftp;\n\t\taddresource.usip = resource.usip;\n\t\taddresource.usnip = resource.usnip;\n\t\taddresource.proxyip = resource.proxyip;\n\t\taddresource.mode = resource.mode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"@SafeVarargs\n\tpublic static <T> Set<T> asSet(T... ts) {\n\t\tif ( ts == null ) {\n\t\t\treturn null;\n\t\t}\n\t\telse if ( ts.length == 0 ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\tSet<T> set = new HashSet<T>( getInitialCapacityFromExpectedSize( ts.length ) );\n\t\t\tCollections.addAll( set, ts );\n\t\t\treturn Collections.unmodifiableSet( set );\n\t\t}\n\t}",
"public static GVRSceneObject loadModel(final GVRContext gvrContext,\n final String modelFile) throws IOException {\n return loadModel(gvrContext, modelFile, new HashMap<String, Integer>());\n }",
"void insertMacros(TokenList tokens ) {\n TokenList.Token t = tokens.getFirst();\n while( t != null ) {\n if( t.getType() == Type.WORD ) {\n Macro v = lookupMacro(t.word);\n if (v != null) {\n TokenList.Token before = t.previous;\n List<TokenList.Token> inputs = new ArrayList<TokenList.Token>();\n t = parseMacroInput(inputs,t.next);\n\n TokenList sniplet = v.execute(inputs);\n tokens.extractSubList(before.next,t);\n tokens.insertAfter(before,sniplet);\n t = sniplet.last;\n }\n }\n t = t.next;\n }\n }",
"private static ModelNode createOperation(ServerIdentity identity) {\n // The server address\n final ModelNode address = new ModelNode();\n address.add(ModelDescriptionConstants.HOST, identity.getHostName());\n address.add(ModelDescriptionConstants.RUNNING_SERVER, identity.getServerName());\n //\n final ModelNode operation = OPERATION.clone();\n operation.get(ModelDescriptionConstants.OP_ADDR).set(address);\n return operation;\n }",
"public ItemRequest<Project> update(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"PUT\");\n }",
"protected void postConnection(ConnectionHandle handle, long statsObtainTime){\r\n\r\n\t\thandle.renewConnection(); // mark it as being logically \"open\"\r\n\r\n\t\t// Give an application a chance to do something with it.\r\n\t\tif (handle.getConnectionHook() != null){\r\n\t\t\thandle.getConnectionHook().onCheckOut(handle);\r\n\t\t}\r\n\r\n\t\tif (this.pool.closeConnectionWatch){ // a debugging tool\r\n\t\t\tthis.pool.watchConnection(handle);\r\n\t\t}\r\n\r\n\t\tif (this.pool.statisticsEnabled){\r\n\t\t\tthis.pool.statistics.addCumulativeConnectionWaitTime(System.nanoTime()-statsObtainTime);\r\n\t\t}\r\n\t}",
"private float getQuaternionW(float x, float y, float z) {\n return (float) Math.cos(Math.asin(Math.sqrt(x * x + y * y + z * z)));\n }",
"public void processCalendar(Row calendarRow, Map<Integer, Row> workPatternMap, Map<Integer, List<Row>> workPatternAssignmentMap, Map<Integer, List<Row>> exceptionAssignmentMap, Map<Integer, List<Row>> timeEntryMap, Map<Integer, DayType> exceptionTypeMap)\n {\n //\n // Create the calendar and add the default working hours\n //\n ProjectCalendar calendar = m_project.addCalendar();\n Integer dominantWorkPatternID = calendarRow.getInteger(\"DOMINANT_WORK_PATTERN\");\n calendar.setUniqueID(calendarRow.getInteger(\"CALENDARID\"));\n processWorkPattern(calendar, dominantWorkPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n calendar.setName(calendarRow.getString(\"NAMK\"));\n\n //\n // Add any additional working weeks\n //\n List<Row> rows = workPatternAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"WORK_PATTERN\");\n if (!workPatternID.equals(dominantWorkPatternID))\n {\n ProjectCalendarWeek week = calendar.addWorkWeek();\n week.setDateRange(new DateRange(row.getDate(\"START_DATE\"), row.getDate(\"END_DATE\")));\n processWorkPattern(week, workPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n }\n }\n }\n\n //\n // Add exceptions - not sure how exceptions which turn non-working days into working days are handled by Asta - if at all?\n //\n rows = exceptionAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Date startDate = row.getDate(\"STARU_DATE\");\n Date endDate = row.getDate(\"ENE_DATE\");\n calendar.addCalendarException(startDate, endDate);\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }",
"public static base_responses add(nitro_service client, dnspolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnspolicylabel addresources[] = new dnspolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnspolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].transform = resources[i].transform;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Return the raw source line corresponding to the specified AST node
@param node - the Groovy AST node | [
"protected String sourceLine(ASTNode node) {\r\n return sourceCode.getLines().get(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }"
] | [
"public boolean checkPrefixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.startsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"protected void addFreeConnection(ConnectionHandle connectionHandle) throws SQLException{\r\n\t\tconnectionHandle.setOriginatingPartition(this);\r\n\t\t// assume success to avoid racing where we insert an item in a queue and having that item immediately\r\n\t\t// taken and closed off thus decrementing the created connection count.\r\n\t\tupdateCreatedConnections(1);\r\n\t\tif (!this.disableTracking){\r\n\t\t\ttrackConnectionFinalizer(connectionHandle); \r\n\t\t}\r\n\t\t\r\n\t\t// the instant the following line is executed, consumers can start making use of this \r\n\t\t// connection.\r\n\t\tif (!this.freeConnections.offer(connectionHandle)){\r\n\t\t\t// we failed. rollback.\r\n\t\t\tupdateCreatedConnections(-1); // compensate our createdConnection count.\r\n\t\t\t\r\n\t\t\tif (!this.disableTracking){\r\n\t\t\t\tthis.pool.getFinalizableRefs().remove(connectionHandle.getInternalConnection());\r\n\t\t\t}\r\n\t\t\t// terminate the internal handle.\r\n\t\t\tconnectionHandle.internalClose();\r\n\t\t}\r\n\t}",
"protected static void sendInitSQL(Connection connection, String initSQL) throws SQLException{\r\n\t\t// fetch any configured setup sql.\r\n\t\tif (initSQL != null){\r\n\t\t\tStatement stmt = null;\r\n\t\t\ttry{\r\n\t\t\t\tstmt = connection.createStatement();\r\n\t\t\t\tstmt.execute(initSQL);\r\n\t\t\t\tif (testSupport){ // only to aid code coverage, normally set to false\r\n\t\t\t\t\tstmt = null;\r\n\t\t\t\t}\r\n\t\t\t} finally{\r\n\t\t\t\tif (stmt != null){\r\n\t\t\t\t\tstmt.close();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"private List<Variable> parseAssignRange(Sequence sequence, TokenList tokens, TokenList.Token t0) {\n // find assignment symbol\n TokenList.Token tokenAssign = t0.next;\n while( tokenAssign != null && tokenAssign.symbol != Symbol.ASSIGN ) {\n tokenAssign = tokenAssign.next;\n }\n\n if( tokenAssign == null )\n throw new ParseError(\"Can't find assignment operator\");\n\n // see if it is a sub matrix before\n if( tokenAssign.previous.symbol == Symbol.PAREN_RIGHT ) {\n TokenList.Token start = t0.next;\n if( start.symbol != Symbol.PAREN_LEFT )\n throw new ParseError((\"Expected left param for assignment\"));\n TokenList.Token end = tokenAssign.previous;\n TokenList subTokens = tokens.extractSubList(start,end);\n subTokens.remove(subTokens.getFirst());\n subTokens.remove(subTokens.getLast());\n\n handleParentheses(subTokens,sequence);\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(subTokens, sequence);\n\n if (inputs.isEmpty())\n throw new ParseError(\"Empty function input parameters\");\n\n List<Variable> range = new ArrayList<>();\n addSubMatrixVariables(inputs, range);\n if( range.size() != 1 && range.size() != 2 ) {\n throw new ParseError(\"Unexpected number of range variables. 1 or 2 expected\");\n }\n return range;\n }\n\n return null;\n }",
"private void generateCopyingPart(WrappingHint.Builder builder) {\n ImmutableCollection<CopyMethod> copyMethods = ImmutableMultimap.<String, CopyMethod>builder()\n .putAll(configuration.FIELD_TYPE_TO_COPY_METHODS)\n .putAll(userDefinedCopyMethods)\n .build()\n .get(typeAssignedToField);\n \n if (copyMethods.isEmpty()) {\n throw new WrappingHintGenerationException();\n }\n \n CopyMethod firstSuitable = copyMethods.iterator().next();\n builder.setCopyMethodOwnerName(firstSuitable.owner.toString())\n .setCopyMethodName(firstSuitable.name);\n \n if (firstSuitable.isGeneric && typeSignature != null) {\n CollectionField withRemovedWildcards = CollectionField.from(typeAssignedToField, typeSignature)\n .transformGenericTree(GenericType::withoutWildcard);\n builder.setCopyTypeParameterName(formatTypeParameter(withRemovedWildcards.asSimpleString()));\n }\n }",
"public 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(\"&\");\n break;\n case '<':\n out.append(\"<\");\n break;\n case '>':\n out.append(\">\");\n break;\n default:\n out.append(c);\n }\n }\n }",
"private void addProperties(final PropertyDescriptor[] _properties) throws ColumnBuilderException, ClassNotFoundException {\n for (final PropertyDescriptor property : _properties) {\n if (isValidProperty(property)) {\n addColumn(getColumnTitle(property), property.getName(), property.getPropertyType().getName(), getColumnWidth(property));\n }\n }\n setUseFullPageWidth(true);\n }",
"public ItemRequest<Project> addCustomFieldSetting(String project) {\n \n String path = String.format(\"/projects/%s/addCustomFieldSetting\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\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 }"
] |
Sets the target hosts from json path.
@param jsonPath
the json path
@param sourcePath
the source path
@param sourceType
the source type
@return the parallel task builder
@throws TargetHostsLoadException
the target hosts load exception | [
"public ParallelTaskBuilder setTargetHostsFromJsonPath(String jsonPath,\n String sourcePath, HostsSourceType sourceType)\n throws TargetHostsLoadException {\n\n this.targetHosts = targetHostBuilder.setTargetHostsFromJsonPath(jsonPath, sourcePath,\n sourceType);\n return this;\n\n }"
] | [
"public Integer getVarDataKey(FieldType type)\n {\n Integer result = null;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getVarDataKey();\n }\n return result;\n }",
"public List<Method> getMethodsFromGroupId(int groupId, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.OVERRIDE_GROUP_ID + \" = ?\"\n );\n statement.setInt(1, groupId);\n results = statement.executeQuery();\n while (results.next()) {\n Method method = PathOverrideService.getInstance().getMethodForOverrideId(results.getInt(\"id\"));\n if (method == null) {\n continue;\n }\n\n // decide whether or not to add this method based on the filters\n boolean add = true;\n if (filters != null) {\n add = false;\n for (String filter : filters) {\n if (method.getMethodType().endsWith(filter)) {\n add = true;\n break;\n }\n }\n }\n\n if (add && !methods.contains(method)) {\n methods.add(method);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return methods;\n }",
"public Collection<EmailAlias> getEmailAliases() {\n URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n Collection<EmailAlias> emailAliases = new ArrayList<EmailAlias>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject emailAliasJSON = value.asObject();\n emailAliases.add(new EmailAlias(emailAliasJSON));\n }\n\n return emailAliases;\n }",
"public Profile[] getProfilesForServerName(String serverName) throws Exception {\n int profileId = -1;\n ArrayList<Profile> returnProfiles = new ArrayList<Profile>();\n\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_PROFILE_ID + \" FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ? GROUP BY \" +\n Constants.GENERIC_PROFILE_ID\n );\n queryStatement.setString(1, serverName);\n results = queryStatement.executeQuery();\n\n while (results.next()) {\n profileId = results.getInt(Constants.GENERIC_PROFILE_ID);\n\n Profile profile = ProfileService.getInstance().findProfile(profileId);\n\n returnProfiles.add(profile);\n }\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\n if (returnProfiles.size() == 0) {\n return null;\n }\n return returnProfiles.toArray(new Profile[0]);\n }",
"private void doSend(byte[] msg, boolean wait, KNXAddress dst)\r\n\t\tthrows KNXAckTimeoutException, KNXLinkClosedException\r\n\t{\r\n\t\tif (closed)\r\n\t\t\tthrow new KNXLinkClosedException(\"link closed\");\r\n\t\ttry {\r\n\t\t\tlogger.info(\"send message to \" + dst + (wait ? \", wait for ack\" : \"\"));\r\n\t\t\tlogger.trace(\"EMI \" + DataUnitBuilder.toHex(msg, \" \"));\r\n\t\t\tconn.send(msg, wait);\r\n\t\t\tlogger.trace(\"send to \" + dst + \" succeeded\");\r\n\t\t}\r\n\t\tcatch (final KNXPortClosedException e) {\r\n\t\t\tlogger.error(\"send error, closing link\", e);\r\n\t\t\tclose();\r\n\t\t\tthrow new KNXLinkClosedException(\"link closed, \" + e.getMessage());\r\n\t\t}\r\n\t}",
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static byte checkByte(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInByteRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), BYTE_MIN, BYTE_MAX);\n\t\t}\n\n\t\treturn number.byteValue();\n\t}",
"public static lbvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_cachepolicy_binding obj = new lbvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_cachepolicy_binding response[] = (lbvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static base_response unset(nitro_service client, Interface resource, String[] args) throws Exception{\n\t\tInterface unsetresource = new Interface();\n\t\tunsetresource.id = resource.id;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public void printProbs(String filename,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n ObjectBank<List<IN>> docs =\r\n makeObjectBankFromFile(filename, readerAndWriter);\r\n printProbsDocuments(docs);\r\n }"
] |
Add a creatable "post-run" dependent for this task item.
@param creatable the creatable "post-run" dependent.
@return the key to be used as parameter to taskResult(string) method to retrieve created "post-run" dependent | [
"@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Creatable<? extends Indexable> creatable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatable;\n return this.addPostRunDependent(dependency);\n }"
] | [
"public static InterceptorFactory getInstance()\r\n\t{\r\n\t\tif (instance == null)\r\n\t\t{\r\n\t\t\tinstance = new InterceptorFactory();\r\n\t\t\tOjbConfigurator.getInstance().configure(instance);\r\n\t\t}\r\n\t\treturn instance;\r\n\t}",
"@Deprecated\n public ApnsServiceBuilder withProxySocket(Socket proxySocket) {\n return this.withProxy(new Proxy(Proxy.Type.SOCKS,\n proxySocket.getRemoteSocketAddress()));\n }",
"private void addProgressInterceptor() {\n httpClient.networkInterceptors().add(new Interceptor() {\n @Override\n public Response intercept(Interceptor.Chain chain) throws IOException {\n final Request request = chain.request();\n final Response originalResponse = chain.proceed(request);\n if (request.tag() instanceof ApiCallback) {\n final ApiCallback callback = (ApiCallback) request.tag();\n return originalResponse.newBuilder()\n .body(new ProgressResponseBody(originalResponse.body(), callback)).build();\n }\n return originalResponse;\n }\n });\n }",
"private ColumnDef addColumnFor(FieldDescriptorDef fieldDef, TableDef tableDef)\r\n {\r\n String name = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);\r\n ColumnDef columnDef = tableDef.getColumn(name);\r\n\r\n if (columnDef == null)\r\n {\r\n columnDef = new ColumnDef(name);\r\n tableDef.addColumn(columnDef);\r\n }\r\n if (!fieldDef.isNested())\r\n { \r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_JAVANAME, fieldDef.getName());\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_ID, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID));\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_PRIMARYKEY, \"true\");\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n else if (!fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_NULLABLE, true))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n if (\"database\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT)))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_AUTOINCREMENT, \"true\");\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_SIZE, fieldDef.getSizeConstraint());\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION));\r\n }\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION));\r\n }\r\n return columnDef;\r\n }",
"private static BsonDocument withNewVersion(\n final BsonDocument document,\n final BsonDocument newVersion\n ) {\n final BsonDocument newDocument = BsonUtils.copyOfDocument(document);\n newDocument.put(DOCUMENT_VERSION_FIELD, newVersion);\n return newDocument;\n }",
"public static base_response update(nitro_service client, ntpserver resource) throws Exception {\n\t\tntpserver updateresource = new ntpserver();\n\t\tupdateresource.serverip = resource.serverip;\n\t\tupdateresource.servername = resource.servername;\n\t\tupdateresource.minpoll = resource.minpoll;\n\t\tupdateresource.maxpoll = resource.maxpoll;\n\t\tupdateresource.preferredntpserver = resource.preferredntpserver;\n\t\tupdateresource.autokey = resource.autokey;\n\t\tupdateresource.key = resource.key;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private <T> InternalProviderImpl installInternalProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> internalProvider,\n boolean isBound, boolean isTestProvider) {\n if (bindingName == null) {\n if (isBound) {\n return installUnNamedProvider(mapClassesToUnNamedBoundProviders, clazz, internalProvider, isTestProvider);\n } else {\n return installUnNamedProvider(mapClassesToUnNamedUnBoundProviders, clazz, internalProvider, isTestProvider);\n }\n } else {\n return installNamedProvider(mapClassesToNamedBoundProviders, clazz, bindingName, internalProvider, isTestProvider);\n }\n }",
"public void add(final String source, final T destination) {\n\n // replace multiple slashes with a single slash.\n String path = source.replaceAll(\"/+\", \"/\");\n\n path = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n\n String[] parts = path.split(\"/\", maxPathParts + 2);\n if (parts.length - 1 > maxPathParts) {\n throw new IllegalArgumentException(String.format(\"Number of parts of path %s exceeds allowed limit %s\",\n source, maxPathParts));\n }\n StringBuilder sb = new StringBuilder();\n List<String> groupNames = new ArrayList<>();\n\n for (String part : parts) {\n Matcher groupMatcher = GROUP_PATTERN.matcher(part);\n if (groupMatcher.matches()) {\n groupNames.add(groupMatcher.group(1));\n sb.append(\"([^/]+?)\");\n } else if (WILD_CARD_PATTERN.matcher(part).matches()) {\n sb.append(\".*?\");\n } else {\n sb.append(part);\n }\n sb.append(\"/\");\n }\n\n //Ignore the last \"/\"\n sb.setLength(sb.length() - 1);\n\n Pattern pattern = Pattern.compile(sb.toString());\n patternRouteList.add(ImmutablePair.of(pattern, new RouteDestinationWithGroups(destination, groupNames)));\n }",
"public static boolean toBoolean(String value, boolean defaultValue)\r\n {\r\n return \"true\".equals(value) ? true : (\"false\".equals(value) ? false : defaultValue);\r\n }"
] |
Return the numeraire at a given time.
The numeraire is provided for interpolated points. If requested on points which are not
part of the tenor discretization, the numeraire uses a linear interpolation of the reciprocal
value. See ISBN 0470047224 for details.
@param time Time time <i>t</i> for which the numeraire should be returned <i>N(t)</i>.
@return The numeraire at the specified time as <code>RandomVariableFromDoubleArray</code>
@throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. | [
"@Override\n\tpublic RandomVariable getNumeraire(double time) throws CalculationException {\n\t\tint timeIndex = getLiborPeriodIndex(time);\n\n\t\tif(timeIndex < 0) {\n\t\t\t// Interpolation of Numeraire: linear interpolation of the reciprocal.\n\t\t\tint lowerIndex = -timeIndex -1;\n\t\t\tint upperIndex = -timeIndex;\n\t\t\tdouble alpha = (time-getLiborPeriod(lowerIndex)) / (getLiborPeriod(upperIndex) - getLiborPeriod(lowerIndex));\n\t\t\treturn getNumeraire(getLiborPeriod(upperIndex)).invert().mult(alpha).add(getNumeraire(getLiborPeriod(lowerIndex)).invert().mult(1.0-alpha)).invert();\n\t\t}\n\n\t\t// Calculate the numeraire, when time is part of liborPeriodDiscretization\n\n\t\t// Get the start of the product\n\t\tint firstLiborIndex\t\t= getLiborPeriodIndex(time);\n\t\tif(firstLiborIndex < 0) {\n\t\t\tthrow new CalculationException(\"Simulation time discretization not part of forward rate tenor discretization.\");\n\t\t}\n\n\t\t// Get the end of the product\n\t\tint lastLiborIndex \t= liborPeriodDiscretization.getNumberOfTimeSteps()-1;\n\n\t\tif(measure == Measure.SPOT) {\n\t\t\t// Spot measure\n\t\t\tfirstLiborIndex\t= 0;\n\t\t\tlastLiborIndex\t= getLiborPeriodIndex(time)-1;\n\t\t}\n\n\t\t/*\n\t\t * Calculation of the numeraire\n\t\t */\n\n\t\t// Initialize to 1.0\n\t\tRandomVariable numeraire = new RandomVariableFromDoubleArray(time, 1.0);\n\n\t\t// The product\n\t\tfor(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) {\n\t\t\tRandomVariable libor = getLIBOR(getTimeIndex(Math.min(time,liborPeriodDiscretization.getTime(liborIndex))), liborIndex);\n\n\t\t\tdouble periodLength = liborPeriodDiscretization.getTimeStep(liborIndex);\n\n\t\t\tif(measure == Measure.SPOT) {\n\t\t\t\tnumeraire = numeraire.accrue(libor, periodLength);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnumeraire = numeraire.discount(libor, periodLength);\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Adjust for discounting\n\t\t */\n\t\tif(discountCurve != null) {\n\t\t\tDiscountCurve discountcountCurveFromForwardPerformance = new DiscountCurveFromForwardCurve(forwardRateCurve);\n\t\t\tdouble deterministicNumeraireAdjustment = discountcountCurveFromForwardPerformance.getDiscountFactor(time) / discountCurve.getDiscountFactor(time);\n\t\t\tnumeraire = numeraire.mult(deterministicNumeraireAdjustment);\n\t\t}\n\t\treturn numeraire;\n\t}"
] | [
"private void writeTermStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\n\t\t// Make sure all keys are present in label count map:\n\t\tfor (String key : usageStatistics.aliasCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\t\tfor (String key : usageStatistics.descriptionCounts.keySet()) {\n\t\t\tcountKey(usageStatistics.labelCounts, key, 0);\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Language,Labels,Descriptions,Aliases\");\n\t\t\tfor (Entry<String, Integer> entry : usageStatistics.labelCounts\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tcountKey(usageStatistics.aliasCounts, entry.getKey(), 0);\n\t\t\t\tint aCount = usageStatistics.aliasCounts.get(entry.getKey());\n\t\t\t\tcountKey(usageStatistics.descriptionCounts, entry.getKey(), 0);\n\t\t\t\tint dCount = usageStatistics.descriptionCounts.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue() + \",\"\n\t\t\t\t\t\t+ dCount + \",\" + aCount);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"private Date getDateTime(String value) throws MPXJException\n {\n try\n {\n Number year = m_fourDigitFormat.parse(value.substring(0, 4));\n Number month = m_twoDigitFormat.parse(value.substring(4, 6));\n Number day = m_twoDigitFormat.parse(value.substring(6, 8));\n\n Number hours = m_twoDigitFormat.parse(value.substring(9, 11));\n Number minutes = m_twoDigitFormat.parse(value.substring(11, 13));\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.YEAR, year.intValue());\n cal.set(Calendar.MONTH, month.intValue() - 1);\n cal.set(Calendar.DAY_OF_MONTH, day.intValue());\n\n cal.set(Calendar.HOUR_OF_DAY, hours.intValue());\n cal.set(Calendar.MINUTE, minutes.intValue());\n\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n Date result = cal.getTime();\n DateHelper.pushCalendar(cal);\n \n return result;\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse date-time \" + value, ex);\n }\n }",
"private boolean markAsObsolete(ContentReference ref) {\n if (obsoleteContents.containsKey(ref.getHexHash())) { //This content is already marked as obsolete\n if (obsoleteContents.get(ref.getHexHash()) + obsolescenceTimeout < System.currentTimeMillis()) {\n DeploymentRepositoryLogger.ROOT_LOGGER.obsoleteContentCleaned(ref.getContentIdentifier());\n removeContent(ref);\n return true;\n }\n } else {\n obsoleteContents.put(ref.getHexHash(), System.currentTimeMillis()); //Mark content as obsolete\n }\n return false;\n }",
"public static synchronized ExecutionStatistics get()\n {\n Thread currentThread = Thread.currentThread();\n if (stats.get(currentThread) == null)\n {\n stats.put(currentThread, new ExecutionStatistics());\n }\n return stats.get(currentThread);\n }",
"public static base_response unset(nitro_service client, lbsipparameters resource, String[] args) throws Exception{\n\t\tlbsipparameters unsetresource = new lbsipparameters();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"CueList getCueList(int rekordboxId, CdjStatus.TrackSourceSlot slot, Client client)\n throws IOException {\n Message response = client.simpleRequest(Message.KnownType.CUE_LIST_REQ, null,\n client.buildRMST(Message.MenuIdentifier.DATA, slot), new NumberField(rekordboxId));\n if (response.knownType == Message.KnownType.CUE_LIST) {\n return new CueList(response);\n }\n logger.error(\"Unexpected response type when requesting cue list: {}\", response);\n return null;\n }",
"private boolean interpolationsDisagree(TrackPositionUpdate lastUpdate, TrackPositionUpdate currentUpdate) {\n long now = System.nanoTime();\n return Math.abs(interpolateTimeSinceUpdate(lastUpdate, now) - interpolateTimeSinceUpdate(currentUpdate, now)) >\n slack.get();\n }",
"public static boolean organizeAssociationMapByRowKey(\n\t\t\torg.hibernate.ogm.model.spi.Association association,\n\t\t\tAssociationKey key,\n\t\t\tAssociationContext associationContext) {\n\n\t\tif ( association.isEmpty() ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( key.getMetadata().getRowKeyIndexColumnNames().length != 1 ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tObject valueOfFirstRow = association.get( association.getKeys().iterator().next() )\n\t\t\t\t.get( key.getMetadata().getRowKeyIndexColumnNames()[0] );\n\n\t\tif ( !( valueOfFirstRow instanceof String ) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// The list style may be explicitly enforced for compatibility reasons\n\t\treturn getMapStorage( associationContext ) == MapStorageType.BY_KEY;\n\t}",
"public T copy() {\n T ret = createLike();\n ret.getMatrix().set(this.getMatrix());\n return ret;\n }"
] |
Get the last date to keep logs from, by a given current date.
@param currentDate the date of today
@return the last date to keep log files from. | [
"private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}"
] | [
"public static boolean isTrue(Expression expression) {\r\n if (expression == null) {\r\n return false;\r\n }\r\n if (expression instanceof PropertyExpression\r\n && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) {\r\n if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression\r\n && \"TRUE\".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) {\r\n return true;\r\n }\r\n }\r\n return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isTrueExpression()) ||\r\n \"Boolean.TRUE\".equals(expression.getText());\r\n }",
"private void verifyApplicationName(String name) {\n if (name == null) {\n throw new IllegalArgumentException(\"Application name cannot be null\");\n }\n if (name.isEmpty()) {\n throw new IllegalArgumentException(\"Application name length must be > 0\");\n }\n String reason = null;\n char[] chars = name.toCharArray();\n char c;\n for (int i = 0; i < chars.length; i++) {\n c = chars[i];\n if (c == 0) {\n reason = \"null character not allowed @\" + i;\n break;\n } else if (c == '/' || c == '.' || c == ':') {\n reason = \"invalid character '\" + c + \"'\";\n break;\n } else if (c > '\\u0000' && c <= '\\u001f' || c >= '\\u007f' && c <= '\\u009F'\n || c >= '\\ud800' && c <= '\\uf8ff' || c >= '\\ufff0' && c <= '\\uffff') {\n reason = \"invalid character @\" + i;\n break;\n }\n }\n if (reason != null) {\n throw new IllegalArgumentException(\n \"Invalid application name \\\"\" + name + \"\\\" caused by \" + reason);\n }\n }",
"@UiHandler(\"m_everyDay\")\r\n void onEveryDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setInterval(m_everyDay.getFormValueAsString());\r\n }\r\n\r\n }",
"public BoneCP getPool() {\r\n\t\tFinalWrapper<BoneCP> wrapper = this.pool;\r\n\t\treturn wrapper == null ? null : wrapper.value;\r\n\t}",
"private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception {\n if (tries >= 5) {\n throw new BindException(\"Unable to bind to several ports, most recently \" + relay.getPort() + \". Giving up\");\n }\n try {\n if (server.isStarted()) {\n relay.start();\n } else {\n throw new RuntimeException(\"Can't start SslRelay: server is not started (perhaps it was just shut down?)\");\n }\n } catch (BindException e) {\n // doh - the port is being used up, let's pick a new port\n LOG.info(\"Unable to bind to port %d, going to try port %d now\", relay.getPort(), relay.getPort() + 1);\n relay.setPort(relay.getPort() + 1);\n startRelayWithPortTollerance(server, relay, tries + 1);\n }\n }",
"public void stopListenting() {\n if (channel != null) {\n log.info(\"closing server channel\");\n channel.close().syncUninterruptibly();\n channel = null;\n }\n }",
"public static base_responses update(nitro_service client, nd6ravariables resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnd6ravariables updateresources[] = new nd6ravariables[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nd6ravariables();\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].ceaserouteradv = resources[i].ceaserouteradv;\n\t\t\t\tupdateresources[i].sendrouteradv = resources[i].sendrouteradv;\n\t\t\t\tupdateresources[i].srclinklayeraddroption = resources[i].srclinklayeraddroption;\n\t\t\t\tupdateresources[i].onlyunicastrtadvresponse = resources[i].onlyunicastrtadvresponse;\n\t\t\t\tupdateresources[i].managedaddrconfig = resources[i].managedaddrconfig;\n\t\t\t\tupdateresources[i].otheraddrconfig = resources[i].otheraddrconfig;\n\t\t\t\tupdateresources[i].currhoplimit = resources[i].currhoplimit;\n\t\t\t\tupdateresources[i].maxrtadvinterval = resources[i].maxrtadvinterval;\n\t\t\t\tupdateresources[i].minrtadvinterval = resources[i].minrtadvinterval;\n\t\t\t\tupdateresources[i].linkmtu = resources[i].linkmtu;\n\t\t\t\tupdateresources[i].reachabletime = resources[i].reachabletime;\n\t\t\t\tupdateresources[i].retranstime = resources[i].retranstime;\n\t\t\t\tupdateresources[i].defaultlifetime = resources[i].defaultlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {\n Map<String, Object> dataClone = new HashMap<String, Object>(data);\n dataClone.put(\"auth\", getAuthData());\n\n Map<String, String> payload = new HashMap<String, String>();\n payload.put(\"params\", jsonifyData(dataClone));\n\n if (transloadit.shouldSignRequest) {\n payload.put(\"signature\", getSignature(jsonifyData(dataClone)));\n }\n return payload;\n }",
"private boolean hidden(String className) {\n\tclassName = removeTemplate(className);\n\tClassInfo ci = classnames.get(className);\n\treturn ci != null ? ci.hidden : optionProvider.getOptionsFor(className).matchesHideExpression(className);\n }"
] |
The range of velocities that a particle generated from this emitter can have.
@param minV Minimum velocity that a particle can have
@param maxV Maximum velocity that a particle can have | [
"public void setVelocityRange( final Vector3f minV, final Vector3f maxV )\n {\n if (null != mGVRContext) {\n mGVRContext.runOnGlThread(new Runnable() {\n\n @Override\n public void run() {\n minVelocity = minV;\n maxVelocity = maxV;\n }\n });\n }\n }"
] | [
"public synchronized int cancelByTag(String tagToCancel) {\n int i = 0;\n if (taskList.containsKey(tagToCancel)) {\n removeDoneTasks();\n\n for (Future<BlurWorker.Result> future : taskList.get(tagToCancel)) {\n BuilderUtil.logVerbose(Dali.getConfig().logTag, \"Canceling task with tag \" + tagToCancel, Dali.getConfig().debugMode);\n future.cancel(true);\n i++;\n }\n\n //remove all canceled tasks\n Iterator<Future<BlurWorker.Result>> iter = taskList.get(tagToCancel).iterator();\n while (iter.hasNext()) {\n if (iter.next().isCancelled()) {\n iter.remove();\n }\n }\n }\n return i;\n }",
"protected boolean isSlopDead(Cluster cluster, Set<String> storeNames, Slop slop) {\n // destination node , no longer exists\n if(!cluster.getNodeIds().contains(slop.getNodeId())) {\n return true;\n }\n\n // destination store, no longer exists\n if(!storeNames.contains(slop.getStoreName())) {\n return true;\n }\n\n // else. slop is alive\n return false;\n }",
"public Map<Integer, TableDefinition> tableDefinitions()\n {\n Map<Integer, TableDefinition> result = new HashMap<Integer, TableDefinition>();\n\n result.put(Integer.valueOf(2), new TableDefinition(\"PROJECT_SUMMARY\", columnDefinitions(PROJECT_SUMMARY_COLUMNS, projectSummaryColumnsOrder())));\n result.put(Integer.valueOf(7), new TableDefinition(\"BAR\", columnDefinitions(BAR_COLUMNS, barColumnsOrder())));\n result.put(Integer.valueOf(11), new TableDefinition(\"CALENDAR\", columnDefinitions(CALENDAR_COLUMNS, calendarColumnsOrder())));\n result.put(Integer.valueOf(12), new TableDefinition(\"EXCEPTIONN\", columnDefinitions(EXCEPTIONN_COLUMNS, exceptionColumnsOrder())));\n result.put(Integer.valueOf(14), new TableDefinition(\"EXCEPTION_ASSIGNMENT\", columnDefinitions(EXCEPTION_ASSIGNMENT_COLUMNS, exceptionAssignmentColumnsOrder())));\n result.put(Integer.valueOf(15), new TableDefinition(\"TIME_ENTRY\", columnDefinitions(TIME_ENTRY_COLUMNS, timeEntryColumnsOrder())));\n result.put(Integer.valueOf(17), new TableDefinition(\"WORK_PATTERN\", columnDefinitions(WORK_PATTERN_COLUMNS, workPatternColumnsOrder()))); \n result.put(Integer.valueOf(18), new TableDefinition(\"TASK_COMPLETED_SECTION\", columnDefinitions(TASK_COMPLETED_SECTION_COLUMNS, taskCompletedSectionColumnsOrder()))); \n result.put(Integer.valueOf(21), new TableDefinition(\"TASK\", columnDefinitions(TASK_COLUMNS, taskColumnsOrder())));\n result.put(Integer.valueOf(22), new TableDefinition(\"MILESTONE\", columnDefinitions(MILESTONE_COLUMNS, milestoneColumnsOrder())));\n result.put(Integer.valueOf(23), new TableDefinition(\"EXPANDED_TASK\", columnDefinitions(EXPANDED_TASK_COLUMNS, expandedTaskColumnsOrder())));\n result.put(Integer.valueOf(25), new TableDefinition(\"LINK\", columnDefinitions(LINK_COLUMNS, linkColumnsOrder())));\n result.put(Integer.valueOf(61), new TableDefinition(\"CONSUMABLE_RESOURCE\", columnDefinitions(CONSUMABLE_RESOURCE_COLUMNS, consumableResourceColumnsOrder())));\n result.put(Integer.valueOf(62), new TableDefinition(\"PERMANENT_RESOURCE\", columnDefinitions(PERMANENT_RESOURCE_COLUMNS, permanentResourceColumnsOrder())));\n result.put(Integer.valueOf(63), new TableDefinition(\"PERM_RESOURCE_SKILL\", columnDefinitions(PERMANENT_RESOURCE_SKILL_COLUMNS, permanentResourceSkillColumnsOrder())));\n result.put(Integer.valueOf(67), new TableDefinition(\"PERMANENT_SCHEDUL_ALLOCATION\", columnDefinitions(PERMANENT_SCHEDULE_ALLOCATION_COLUMNS, permanentScheduleAllocationColumnsOrder())));\n result.put(Integer.valueOf(190), new TableDefinition(\"WBS_ENTRY\", columnDefinitions(WBS_ENTRY_COLUMNS, wbsEntryColumnsOrder())));\n\n return result;\n }",
"public static boolean setCustomRequestForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, false, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public void readFrom(IIMReader reader, int recover) throws IOException, InvalidDataSetException {\r\n\t\tfinal boolean doLog = log != null;\r\n\t\tfor (;;) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSet ds = reader.read();\r\n\t\t\t\tif (ds == null) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (doLog) {\r\n\t\t\t\t\tlog.debug(\"Read data set \" + ds);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\t\tSerializer s = info.getSerializer();\r\n\t\t\t\tif (s != null) {\r\n\t\t\t\t\tif (info.getDataSetNumber() == IIM.DS(1, 90)) {\r\n\t\t\t\t\t\tsetCharacterSet((String) s.deserialize(ds.getData(), activeSerializationContext));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tdataSets.add(ds);\r\n\r\n\t\t\t\tif (stopAfter9_10 && info.getDataSetNumber() == IIM.DS(9, 10))\r\n\t\t\t\t\tbreak;\r\n\t\t\t} catch (IIMFormatException e) {\r\n\t\t\t\tif (recoverFromIIMFormat && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (UnsupportedDataSetException e) {\r\n\t\t\t\tif (recoverFromUnsupportedDataSet && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (InvalidDataSetException e) {\r\n\t\t\t\tif (recoverFromInvalidDataSet && recover-- > 0) {\r\n\t\t\t\t\tboolean r = reader.recover();\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.debug(r ? \"Recoved from \" + e : \"Failed to recover from \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!r)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\tif (recover-- > 0 && !dataSets.isEmpty()) {\r\n\t\t\t\t\tif (doLog) {\r\n\t\t\t\t\t\tlog.error(\"IOException while reading, however some data sets where recovered, \" + e);\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public EventBus emitAsync(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }",
"private static Document objectForInsert(Tuple tuple, Document dbObject) {\n\t\tMongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();\n\t\tfor ( TupleOperation operation : tuple.getOperations() ) {\n\t\t\tString column = operation.getColumn();\n\t\t\tif ( notInIdField( snapshot, column ) ) {\n\t\t\t\tswitch ( operation.getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tMongoHelpers.setValue( dbObject, column, operation.getValue() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PUT_NULL:\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tMongoHelpers.resetValue( dbObject, column );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dbObject;\n\t}",
"public static nsrpcnode[] get(nitro_service service) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tnsrpcnode[] response = (nsrpcnode[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public PhotoList<Photo> search(SearchParameters params, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SEARCH);\r\n\r\n parameters.putAll(params.getAsParameters());\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }"
] |
Retrieve the default aliases to be applied to MPXJ task and resource fields.
@return map of aliases | [
"public static Map<FieldType, String> getDefaultAliases()\n {\n Map<FieldType, String> map = new HashMap<FieldType, String>();\n\n map.put(TaskField.DATE1, \"Suspend Date\");\n map.put(TaskField.DATE2, \"Resume Date\");\n map.put(TaskField.TEXT1, \"Code\");\n map.put(TaskField.TEXT2, \"Activity Type\");\n map.put(TaskField.TEXT3, \"Status\");\n map.put(TaskField.NUMBER1, \"Primary Resource Unique ID\");\n\n return map;\n }"
] | [
"public double getYield(double bondPrice, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenYield(0.0,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\n\t}",
"public static int serialize(final File directory, String name, Object obj) {\n try (FileOutputStream stream = new FileOutputStream(new File(directory, name))) {\n return serialize(stream, obj);\n } catch (IOException e) {\n throw new ReportGenerationException(e);\n }\n }",
"public Where<T, ID> ne(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.NOT_EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}",
"private void logColumn(FastTrackColumn column)\n {\n if (m_log != null)\n {\n m_log.println(\"TABLE: \" + m_currentTable.getType());\n m_log.println(column.toString());\n m_log.flush();\n }\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 nssimpleacl[] get(nitro_service service, String aclname[]) throws Exception{\n\t\tif (aclname !=null && aclname.length>0) {\n\t\t\tnssimpleacl response[] = new nssimpleacl[aclname.length];\n\t\t\tnssimpleacl obj[] = new nssimpleacl[aclname.length];\n\t\t\tfor (int i=0;i<aclname.length;i++) {\n\t\t\t\tobj[i] = new nssimpleacl();\n\t\t\t\tobj[i].set_aclname(aclname[i]);\n\t\t\t\tresponse[i] = (nssimpleacl) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public int millisecondsToX(long milliseconds) {\n if (autoScroll.get()) {\n int playHead = (getWidth() / 2) + 2;\n long offset = milliseconds - getFurthestPlaybackPosition();\n return playHead + (Util.timeToHalfFrame(offset) / scale.get());\n }\n return Util.timeToHalfFrame(milliseconds) / scale.get();\n }",
"private boolean replaceValues(Locale locale) {\n\n try {\n SortedProperties localization = getLocalization(locale);\n if (hasDescriptor()) {\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n } else {\n m_container.removeAllItems();\n Set<Object> keyset = m_keyset.getKeySet();\n for (Object key : keyset) {\n Object itemId = m_container.addItem();\n Item item = m_container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n if (m_container.getItemIds().isEmpty()) {\n m_container.addItem();\n }\n }\n return true;\n } catch (IOException | CmsException e) {\n // The problem should typically be a problem with locking or reading the file containing the translation.\n // This should be reported in the editor, if false is returned here.\n return false;\n }\n }",
"public static <GROUP extends Serializable> ExecutorConfig<GROUP> basicGroupable() {\n return new ExecutorConfig<GROUP>()\n .withTaskIdAdapter((TaskIdAdapter<Groupable<GROUP>, GROUP, ?>) new DefaultGroupableTaskIdAdapter<GROUP>());\n }"
] |
Helper method to split a string by a given character, with empty parts omitted. | [
"private static Iterable<String> splitAndOmitEmpty(final String str, final char splitChar) {\n return new Iterable<String>() {\n @Override\n public Iterator<String> iterator() {\n return new Iterator<String>() {\n\n int startIdx = 0;\n String next = null;\n\n @Override\n public boolean hasNext() {\n while (next == null && startIdx < str.length()) {\n int idx = str.indexOf(splitChar, startIdx);\n if (idx == startIdx) {\n // Omit empty string\n startIdx++;\n continue;\n }\n if (idx >= 0) {\n // Found the next part\n next = str.substring(startIdx, idx);\n startIdx = idx;\n } else {\n // The last part\n if (startIdx < str.length()) {\n next = str.substring(startIdx);\n startIdx = str.length();\n }\n break;\n }\n }\n return next != null;\n }\n\n @Override\n public String next() {\n if (hasNext()) {\n String next = this.next;\n this.next = null;\n return next;\n }\n throw new NoSuchElementException(\"No more element\");\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"Remove not supported\");\n }\n };\n }\n };\n }"
] | [
"private void setFittingWeekDay(Calendar date) {\n\n date.set(Calendar.DAY_OF_MONTH, 1);\n int weekDayFirst = date.get(Calendar.DAY_OF_WEEK);\n int firstFittingWeekDay = (((m_weekDay.toInt() + I_CmsSerialDateValue.NUM_OF_WEEKDAYS) - weekDayFirst)\n % I_CmsSerialDateValue.NUM_OF_WEEKDAYS) + 1;\n int fittingWeekDay = firstFittingWeekDay + (I_CmsSerialDateValue.NUM_OF_WEEKDAYS * m_weekOfMonth.ordinal());\n if (fittingWeekDay > date.getActualMaximum(Calendar.DAY_OF_MONTH)) {\n fittingWeekDay -= I_CmsSerialDateValue.NUM_OF_WEEKDAYS;\n }\n date.set(Calendar.DAY_OF_MONTH, fittingWeekDay);\n }",
"public UniqueEntityLoader buildLoader(\n\t\t\tOuterJoinLoadable persister,\n\t\t\tint batchSize,\n\t\t\tLockOptions lockOptions,\n\t\t\tSessionFactoryImplementor factory,\n\t\t\tLoadQueryInfluencers influencers,\n\t\t\tBatchableEntityLoaderBuilder innerEntityLoaderBuilder) {\n\t\tif ( batchSize <= 1 ) {\n\t\t\t// no batching\n\t\t\treturn buildNonBatchingLoader( persister, lockOptions, factory, influencers, innerEntityLoaderBuilder );\n\t\t}\n\t\treturn buildBatchingLoader( persister, batchSize, lockOptions, factory, influencers, innerEntityLoaderBuilder );\n\t}",
"public static Trajectory resample(Trajectory t, int n){\n\t\tTrajectory t1 = new Trajectory(2);\n\t\t\n\t\tfor(int i = 0; i < t.size(); i=i+n){\n\t\t\tt1.add(t.get(i));\n\t\t}\n\t\t\n\t\treturn t1;\n\t}",
"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 }",
"public Node insertEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEntityQuery(), params );\n\t\treturn singleResult( result );\n\t}",
"private void processWorkWeeks(byte[] data, int offset, ProjectCalendar cal)\n {\n // System.out.println(\"Calendar=\" + cal.getName());\n // System.out.println(\"Work week block start offset=\" + offset);\n // System.out.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n\n // skip 4 byte header\n offset += 4;\n\n while (data.length >= offset + ((7 * 60) + 2 + 2 + 8 + 4))\n {\n //System.out.println(\"Week start offset=\" + offset);\n ProjectCalendarWeek week = cal.addWorkWeek();\n for (Day day : Day.values())\n {\n // 60 byte block per day\n processWorkWeekDay(data, offset, week, day);\n offset += 60;\n }\n\n Date startDate = DateHelper.getDayStartDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n Date finishDate = DateHelper.getDayEndDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n // skip unknown 8 bytes\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 8, false));\n offset += 8;\n\n //\n // Extract the name length - ensure that it is aligned to a 4 byte boundary\n //\n int nameLength = MPPUtility.getInt(data, offset);\n if (nameLength % 4 != 0)\n {\n nameLength = ((nameLength / 4) + 1) * 4;\n }\n offset += 4;\n\n if (nameLength != 0)\n {\n String name = MPPUtility.getUnicodeString(data, offset, nameLength);\n offset += nameLength;\n week.setName(name);\n }\n\n week.setDateRange(new DateRange(startDate, finishDate));\n // System.out.println(week);\n }\n }",
"protected int parseZoneId() {\n int result = -1;\n String zoneIdStr = this.request.getHeader(RestMessageHeaders.X_VOLD_ZONE_ID);\n if(zoneIdStr != null) {\n try {\n int zoneId = Integer.parseInt(zoneIdStr);\n if(zoneId < 0) {\n logger.error(\"ZoneId cannot be negative. Assuming the default zone id.\");\n } else {\n result = zoneId;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect zone id parameter. Cannot parse this to int: \"\n + zoneIdStr,\n nfe);\n }\n }\n return result;\n }",
"@Override\n\tpublic Integer getPrefixLengthForSingleBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = 0;\n\t\tfor(int i = 0; i < count; i++) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tInteger divPrefix = div.getPrefixLengthForSingleBlock();\n\t\t\tif(divPrefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\ttotalPrefix += divPrefix;\n\t\t\tif(divPrefix < div.getBitCount()) {\n\t\t\t\t//remaining segments must be full range or we return null\n\t\t\t\tfor(i++; i < count; i++) {\n\t\t\t\t\tAddressDivisionBase laterDiv = getDivision(i);\n\t\t\t\t\tif(!laterDiv.isFullRange()) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cacheBits(totalPrefix);\n\t}",
"void resetCurrentRevisionData() {\n\t\tthis.revisionId = NO_REVISION_ID; // impossible as an id in MediaWiki\n\t\tthis.parentRevisionId = NO_REVISION_ID;\n\t\tthis.text = null;\n\t\tthis.comment = null;\n\t\tthis.format = null;\n\t\tthis.timeStamp = null;\n\t\tthis.model = null;\n\t}"
] |
Returns the default shared instance of the CleverTap SDK.
@param context The Android context
@return The {@link CleverTapAPI} object | [
"@SuppressWarnings(\"WeakerAccess\")\n public static @Nullable CleverTapAPI getDefaultInstance(Context context) {\n // For Google Play Store/Android Studio tracking\n sdkVersion = BuildConfig.SDK_VERSION_STRING;\n if (defaultConfig == null) {\n ManifestInfo manifest = ManifestInfo.getInstance(context);\n String accountId = manifest.getAccountId();\n String accountToken = manifest.getAcountToken();\n String accountRegion = manifest.getAccountRegion();\n if(accountId == null || accountToken == null) {\n Logger.i(\"Account ID or Account token is missing from AndroidManifest.xml, unable to create default instance\");\n return null;\n }\n if (accountRegion == null) {\n Logger.i(\"Account Region not specified in the AndroidManifest - using default region\");\n }\n defaultConfig = CleverTapInstanceConfig.createDefaultInstance(context, accountId, accountToken, accountRegion);\n defaultConfig.setDebugLevel(getDebugLevel());\n }\n return instanceWithConfig(context, defaultConfig);\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 CmsScheduledJobInfo getJob(String id) {\n\n Iterator<CmsScheduledJobInfo> it = m_jobs.iterator();\n while (it.hasNext()) {\n CmsScheduledJobInfo job = it.next();\n if (job.getId().equals(id)) {\n return job;\n }\n }\n // not found\n return null;\n }",
"public Swagger read(Set<Class<?>> classes) {\n Set<Class<?>> sortedClasses = new TreeSet<>((class1, class2) -> {\n if (class1.equals(class2)) {\n return 0;\n } else if (class1.isAssignableFrom(class2)) {\n return -1;\n } else if (class2.isAssignableFrom(class1)) {\n return 1;\n }\n return class1.getName().compareTo(class2.getName());\n });\n sortedClasses.addAll(classes);\n\n Map<Class<?>, ReaderListener> listeners = new HashMap<Class<?>, ReaderListener>();\n\n for (Class<?> cls : sortedClasses) {\n if (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)) {\n try {\n listeners.put(cls, (ReaderListener) cls.newInstance());\n } catch (Exception e) {\n LOGGER.error(\"Failed to create ReaderListener\", e);\n }\n }\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.beforeScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking beforeScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n // process SwaggerDefinitions first - so we get tags in desired order\n for (Class<?> cls : sortedClasses) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n }\n\n for (Class<?> cls : sortedClasses) {\n read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.afterScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking afterScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n return swagger;\n }",
"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 }",
"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}",
"private Video generateRandomVideo() {\n Video video = new Video();\n configureFavoriteStatus(video);\n configureLikeStatus(video);\n configureLiveStatus(video);\n configureTitleAndThumbnail(video);\n return video;\n }",
"public boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }",
"public final static int readUntil(final StringBuilder out, final String in, final int start, final char end)\n {\n int pos = start;\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 if (ch == end)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }",
"private void removeObsoleteElements(List<String> names,\n Map<String, View> sharedElements,\n List<String> elementsToRemove) {\n if (elementsToRemove.size() > 0) {\n names.removeAll(elementsToRemove);\n for (String elementToRemove : elementsToRemove) {\n sharedElements.remove(elementToRemove);\n }\n }\n }"
] |
Returns the first number available, starting at portNumberStartingPoint that's not already in the reservedPorts
list.
@param portNumberStartingPoint first port number to start from.
@param reservedPorts the ports already reserved.
@return first number available not in the given list, starting at the given parameter. | [
"private int findAvailablePortNumber( Integer portNumberStartingPoint, List<Integer> reservedPorts )\n {\n assert portNumberStartingPoint != null;\n int candidate = portNumberStartingPoint;\n while ( reservedPorts.contains( candidate ) )\n {\n candidate++;\n }\n return candidate;\n }"
] | [
"public static boolean containsOnlyNull(Object... values){\t\n\t\tfor(Object o : values){\n\t\t\tif(o!= null){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"private void writeResources()\n {\n for (Resource resource : m_projectFile.getResources())\n {\n if (resource.getUniqueID().intValue() != 0)\n {\n writeResource(resource);\n }\n }\n }",
"public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure);\n }",
"public void setOutlineCode(int index, String value)\n {\n set(selectField(TaskFieldLists.CUSTOM_OUTLINE_CODE, index), value);\n }",
"public static responderpolicylabel_responderpolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tresponderpolicylabel_responderpolicy_binding obj = new responderpolicylabel_responderpolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tresponderpolicylabel_responderpolicy_binding response[] = (responderpolicylabel_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public boolean removeHandlerFor(final GVRSceneObject sceneObject) {\n sceneObject.detachComponent(GVRCollider.getComponentType());\n return null != touchHandlers.remove(sceneObject);\n }",
"public static snmpalarm[] get(nitro_service service, String trapname[]) throws Exception{\n\t\tif (trapname !=null && trapname.length>0) {\n\t\t\tsnmpalarm response[] = new snmpalarm[trapname.length];\n\t\t\tsnmpalarm obj[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++) {\n\t\t\t\tobj[i] = new snmpalarm();\n\t\t\t\tobj[i].set_trapname(trapname[i]);\n\t\t\t\tresponse[i] = (snmpalarm) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"protected List splitInCriteria(Object attribute, Collection values, boolean negative, int inLimit)\r\n {\r\n List result = new ArrayList();\r\n Collection inCollection = new ArrayList();\r\n\r\n if (values == null || values.isEmpty())\r\n {\r\n // OQL creates empty Criteria for late binding\r\n result.add(buildInCriteria(attribute, negative, values));\r\n }\r\n else\r\n {\r\n Iterator iter = values.iterator();\r\n\r\n while (iter.hasNext())\r\n {\r\n inCollection.add(iter.next());\r\n if (inCollection.size() == inLimit || !iter.hasNext())\r\n {\r\n result.add(buildInCriteria(attribute, negative, inCollection));\r\n inCollection = new ArrayList();\r\n }\r\n }\r\n }\r\n return result;\r\n }",
"public Where<T, ID> in(String columnName, Object... objects) throws SQLException {\n\t\treturn in(true, columnName, objects);\n\t}"
] |
Starting with the given column index, will return the first column index
which contains a colour that does not match the given color. | [
"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 }"
] | [
"public String[] getUrl() {\n String[] valueDestination = new String[ url.size() ];\n this.url.getValue(valueDestination);\n return valueDestination;\n }",
"public static final Duration parseDuration(String value)\n {\n Duration result = null;\n if (value != null)\n {\n int split = value.indexOf(' ');\n if (split != -1)\n {\n double durationValue = Double.parseDouble(value.substring(0, split));\n TimeUnit durationUnits = parseTimeUnits(value.substring(split + 1));\n\n result = Duration.getInstance(durationValue, durationUnits);\n\n }\n }\n return result;\n }",
"public void normalize() {\n double lenSqr = x * x + y * y + z * z;\n double err = lenSqr - 1;\n if (err > (2 * DOUBLE_PREC) || err < -(2 * DOUBLE_PREC)) {\n double len = Math.sqrt(lenSqr);\n x /= len;\n y /= len;\n z /= len;\n }\n }",
"public synchronized void submitOperation(int requestId, AsyncOperation operation) {\n if(this.operations.containsKey(requestId))\n throw new VoldemortException(\"Request \" + requestId\n + \" already submitted to the system\");\n\n this.operations.put(requestId, operation);\n scheduler.scheduleNow(operation);\n logger.debug(\"Handling async operation \" + requestId);\n }",
"private String getQueryParam() {\n\n final String param = parseOptionalStringValue(XML_ELEMENT_QUERYPARAM);\n if (param == null) {\n return DEFAULT_QUERY_PARAM;\n } else {\n return param;\n }\n }",
"private List<Group> getGroups() throws Exception {\n List<Group> groups = new ArrayList<Group>();\n List<Group> sourceGroups = PathOverrideService.getInstance().findAllGroups();\n\n // loop through the groups\n for (Group sourceGroup : sourceGroups) {\n Group group = new Group();\n\n // add all methods\n ArrayList<Method> methods = new ArrayList<Method>();\n for (Method sourceMethod : EditService.getInstance().getMethodsFromGroupId(sourceGroup.getId(), null)) {\n Method method = new Method();\n method.setClassName(sourceMethod.getClassName());\n method.setMethodName(sourceMethod.getMethodName());\n methods.add(method);\n }\n\n group.setMethods(methods);\n group.setName(sourceGroup.getName());\n groups.add(group);\n }\n\n return groups;\n }",
"private DBHandling createDBHandling() throws BuildException\r\n {\r\n if ((_handling == null) || (_handling.length() == 0))\r\n {\r\n throw new BuildException(\"No handling specified\");\r\n }\r\n try\r\n {\r\n String className = \"org.apache.ojb.broker.platforms.\"+\r\n \t\t\t\t\t Character.toTitleCase(_handling.charAt(0))+_handling.substring(1)+\r\n \t\t\t\t\t \"DBHandling\";\r\n Class handlingClass = ClassHelper.getClass(className);\r\n\r\n return (DBHandling)handlingClass.newInstance();\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new BuildException(\"Invalid handling '\"+_handling+\"' specified\");\r\n }\r\n }",
"public static base_responses delete(nitro_service client, String Dnssuffix[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (Dnssuffix != null && Dnssuffix.length > 0) {\n\t\t\tdnssuffix deleteresources[] = new dnssuffix[Dnssuffix.length];\n\t\t\tfor (int i=0;i<Dnssuffix.length;i++){\n\t\t\t\tdeleteresources[i] = new dnssuffix();\n\t\t\t\tdeleteresources[i].Dnssuffix = Dnssuffix[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public float getTangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_tangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }"
] |
The indices space is ignored for reduce ops other than min or max. | [
"public static int cudnnReduceTensor(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n Pointer indices, \n long indicesSizeInBytes, \n Pointer workspace, \n long workspaceSizeInBytes, \n Pointer alpha, \n cudnnTensorDescriptor aDesc, \n Pointer A, \n Pointer beta, \n cudnnTensorDescriptor cDesc, \n Pointer C)\n {\n return checkResult(cudnnReduceTensorNative(handle, reduceTensorDesc, indices, indicesSizeInBytes, workspace, workspaceSizeInBytes, alpha, aDesc, A, beta, cDesc, C));\n }"
] | [
"private void ensureReferencedPKs(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException\r\n {\r\n String targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);\r\n ClassDescriptorDef targetClassDef = modelDef.getClass(targetClassName);\r\n\r\n ensurePKsFromHierarchy(targetClassDef);\r\n }",
"private void readWeekDay(ProjectCalendar mpxjCalendar, WeekDay day)\n {\n if (day.isIsDayWorking())\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day.getDay());\n for (Document.Calendars.Calendar.WeekDays.WeekDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod())\n {\n hours.addRange(new DateRange(period.getFrom(), period.getTo()));\n }\n }\n }",
"private void readExceptionDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay day)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod timePeriod = day.getTimePeriod();\n Date fromDate = timePeriod.getFromDate();\n Date toDate = timePeriod.getToDate();\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = day.getWorkingTimes();\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n\n if (times != null)\n {\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> time = times.getWorkingTime();\n for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : time)\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n exception.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }",
"public static void registerMbean(Object mbean, ObjectName name) {\n registerMbean(ManagementFactory.getPlatformMBeanServer(),\n JmxUtils.createModelMBean(mbean),\n name);\n }",
"public static dnspolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tdnspolicylabel obj = new dnspolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tdnspolicylabel response = (dnspolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"@Override\n public boolean visit(VariableDeclarationStatement node)\n {\n for (int i = 0; i < node.fragments().size(); ++i)\n {\n String nodeType = node.getType().toString();\n VariableDeclarationFragment frag = (VariableDeclarationFragment) node.fragments().get(i);\n state.getNames().add(frag.getName().getIdentifier());\n state.getNameInstance().put(frag.getName().toString(), nodeType.toString());\n }\n\n processType(node.getType(), TypeReferenceLocation.VARIABLE_DECLARATION,\n compilationUnit.getLineNumber(node.getStartPosition()),\n compilationUnit.getColumnNumber(node.getStartPosition()), node.getLength(), node.toString());\n return super.visit(node);\n }",
"private int getBeliefCount() {\n Integer count = (Integer)introspector.getBeliefBase(ListenerMockAgent.this).get(Definitions.RECEIVED_MESSAGE_COUNT);\n if (count == null) count = 0; // Just in case, not really sure if this is necessary.\n return count;\n }",
"public static double computeRowMax( ZMatrixRMaj A ,\n int row , int col0 , int col1 ) {\n double max = 0;\n\n int indexA = A.getIndex(row,col0);\n double h[] = A.data;\n\n for (int i = col0; i < col1; i++) {\n double realVal = h[indexA++];\n double imagVal = h[indexA++];\n\n double magVal = realVal*realVal + imagVal*imagVal;\n if( max < magVal ) {\n max = magVal;\n }\n }\n return Math.sqrt(max);\n }",
"@Override\n public ImageSource apply(ImageSource input) {\n int w = input.getWidth();\n int h = input.getHeight();\n\n MatrixSource output = new MatrixSource(input);\n\n Vector3 n = new Vector3(0, 0, 1);\n\n for (int y = 0; y < h; y++) {\n for (int x = 0; x < w; x++) {\n\n if (x < border || x == w - border || y < border || y == h - border) {\n output.setRGB(x, y, VectorHelper.Z_NORMAL);\n continue;\n }\n\n float s0 = input.getR(x - 1, y + 1);\n float s1 = input.getR(x, y + 1);\n float s2 = input.getR(x + 1, y + 1);\n float s3 = input.getR(x - 1, y);\n float s5 = input.getR(x + 1, y);\n float s6 = input.getR(x - 1, y - 1);\n float s7 = input.getR(x, y - 1);\n float s8 = input.getR(x + 1, y - 1);\n\n float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6);\n float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2);\n\n n.set(nx, ny, scale);\n n.nor();\n\n int rgb = VectorHelper.vectorToColor(n);\n output.setRGB(x, y, rgb);\n }\n }\n\n return new MatrixSource(output);\n }"
] |
Execute the operation.
@param listener the transactional operation listener
@param client the transactional protocol client
@param identity the server identity
@param operation the operation
@param transformer the operation result transformer
@return whether the operation was executed | [
"protected boolean executeOperation(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, TransactionalProtocolClient client, final ServerIdentity identity, final ModelNode operation, final OperationResultTransformer transformer) {\n if(client == null) {\n return false;\n }\n final OperationMessageHandler messageHandler = new DelegatingMessageHandler(context);\n final OperationAttachments operationAttachments = new DelegatingOperationAttachments(context);\n final ServerOperation serverOperation = new ServerOperation(identity, operation, messageHandler, operationAttachments, transformer);\n try {\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Sending %s to %s\", operation, identity);\n final Future<OperationResponse> result = client.execute(listener, serverOperation);\n recordExecutedRequest(new ExecutedServerRequest(identity, result, transformer));\n } catch (IOException e) {\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), transformer));\n }\n return true;\n }"
] | [
"private ApplicationReportIndexModel createApplicationReportIndex(GraphContext context,\n ProjectModel applicationProjectModel)\n {\n ApplicationReportIndexService applicationReportIndexService = new ApplicationReportIndexService(context);\n ApplicationReportIndexModel index = applicationReportIndexService.create();\n\n addAllProjectModels(index, applicationProjectModel);\n\n return index;\n }",
"private static void listResources(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Resource: \" + resource.getName() + \" (Unique ID=\" + resource.getUniqueID() + \") Start=\" + resource.getStart() + \" Finish=\" + resource.getFinish());\n }\n System.out.println();\n }",
"protected <T1> void dispatchCommand(final BiConsumer<P, T1> action, final T1 routable1) {\n routingFor(routable1)\n .routees()\n .forEach(routee -> routee.receiveCommand(action, routable1));\n }",
"public void set(int index, T object) {\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.set(index, object);\n } else {\n mObjects.set(index, object);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }",
"public static ComplexNumber Add(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real + z2.real, z1.imaginary + z2.imaginary);\r\n }",
"public static final Priority parsePriority(BigInteger priority)\n {\n return (priority == null ? null : Priority.getInstance(priority.intValue()));\n }",
"private void updateWorkTimeUnit(FastTrackColumn column)\n {\n if (m_workTimeUnit == null && isWorkColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_workTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }",
"private void precheckStateAllNull() throws IllegalStateException {\n if ((doubleValue != null) || (doubleArray != null)\n || (longValue != null) || (longArray != null)\n || (stringValue != null) || (stringArray != null)\n || (map != null)) {\n throw new IllegalStateException(\"Expected all properties to be empty: \" + this);\n }\n }",
"public void calculateSize(PdfContext context) {\n\t\tfloat width = 0;\n\t\tfloat height = 0;\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.calculateSize(context);\n\t\t\tfloat cw = child.getBounds().getWidth() + 2 * child.getConstraint().getMarginX();\n\t\t\tfloat ch = child.getBounds().getHeight() + 2 * child.getConstraint().getMarginY();\n\t\t\tswitch (getConstraint().getFlowDirection()) {\n\t\t\t\tcase LayoutConstraint.FLOW_NONE:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_X:\n\t\t\t\t\twidth += cw;\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_Y:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight += ch;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unknown flow direction \" + getConstraint().getFlowDirection());\n\t\t\t}\n\t\t}\n\t\tif (getConstraint().getWidth() != 0) {\n\t\t\twidth = getConstraint().getWidth();\n\t\t}\n\t\tif (getConstraint().getHeight() != 0) {\n\t\t\theight = getConstraint().getHeight();\n\t\t}\n\t\tsetBounds(new Rectangle(0, 0, width, height));\n\t}"
] |
Sets the name of the optional two tabs.
The contents of the tabs are filtered based on the name of the tab.
@param tabs ArrayList of Strings | [
"public void setTabs(ArrayList<String>tabs) {\n if (tabs == null || tabs.size() <= 0) return;\n\n if (platformSupportsTabs) {\n ArrayList<String> toAdd;\n if (tabs.size() > MAX_TABS) {\n toAdd = new ArrayList<>(tabs.subList(0, MAX_TABS));\n } else {\n toAdd = tabs;\n }\n this.tabs = toAdd.toArray(new String[0]);\n } else {\n Logger.d(\"Please upgrade com.android.support:design library to v28.0.0 to enable Tabs for App Inbox, dropping Tabs\");\n }\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 final String decodePassword(byte[] data, byte encryptionCode)\n {\n String result;\n\n if (data.length < MINIMUM_PASSWORD_DATA_LENGTH)\n {\n result = null;\n }\n else\n {\n MPPUtility.decodeBuffer(data, encryptionCode);\n\n StringBuilder buffer = new StringBuilder();\n char c;\n\n for (int i = 0; i < PASSWORD_MASK.length; i++)\n {\n int index = PASSWORD_MASK[i];\n c = (char) data[index];\n\n if (c == 0)\n {\n break;\n }\n buffer.append(c);\n }\n\n result = buffer.toString();\n }\n\n return (result);\n }",
"public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, null);\n }",
"public boolean hasInstance(Scriptable instance) {\n // Default for JS objects (other than Function) is to do prototype\n // chasing.\n Scriptable proto = instance.getPrototype();\n while (proto != null) {\n if (proto.equals(this)) return true;\n proto = proto.getPrototype();\n }\n return false;\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 void remove(String directoryName) {\n if ((directoryName == null) || (conn == null))\n return;\n\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n try {\n Map headers = new TreeMap();\n headers.put(\"Content-Type\", Arrays.asList(\"text/plain\"));\n if (usingPreSignedUrls()) {\n conn.delete(pre_signed_delete_url).connection.getResponseMessage();\n } else {\n conn.delete(location, key, headers).connection.getResponseMessage();\n }\n }\n catch(Exception e) {\n ROOT_LOGGER.cannotRemoveS3File(e);\n }\n }",
"@JsonAnySetter\n public void setUnknownField(final String name, final Object value) {\n this.unknownFields.put(name, value);\n }",
"public Widget addControl(String name, int resId, String label, Widget.OnTouchListener listener) {\n return addControl(name, resId, label, listener, -1);\n }",
"private void configureCustomFields()\n {\n CustomFieldContainer customFields = m_projectFile.getCustomFields();\n\n // If the caller hasn't already supplied a value for this field\n if (m_activityIDField == null)\n {\n m_activityIDField = (TaskField) customFields.getFieldByAlias(FieldTypeClass.TASK, \"Code\");\n if (m_activityIDField == null)\n {\n m_activityIDField = TaskField.WBS;\n }\n }\n\n // If the caller hasn't already supplied a value for this field\n if (m_activityTypeField == null)\n {\n m_activityTypeField = (TaskField) customFields.getFieldByAlias(FieldTypeClass.TASK, \"Activity Type\");\n }\n }"
] |
Prepare the document before rendering.
@param outputStream output stream to render to, null if only for layout
@param format format
@throws DocumentException oops
@throws IOException oops
@throws PrintingException oops | [
"private void prepare() throws IOException, DocumentException, PrintingException {\n\t\tif (baos == null) {\n\t\t\tbaos = new ByteArrayOutputStream(); // let it grow as much as needed\n\t\t}\n\t\tbaos.reset();\n\t\tboolean resize = false;\n\t\tif (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {\n\t\t\tresize = true;\n\t\t}\n\t\t// Create a document in the requested ISO scale.\n\t\tDocument document = new Document(page.getBounds(), 0, 0, 0, 0);\n\t\tPdfWriter writer;\n\t\twriter = PdfWriter.getInstance(document, baos);\n\n\t\t// Render in correct colors for transparent rasters\n\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t// The mapView is not scaled to the document, we assume the mapView\n\t\t// has the right ratio.\n\n\t\t// Write document title and metadata\n\t\tdocument.open();\n\t\tPdfContext context = new PdfContext(writer);\n\t\tcontext.initSize(page.getBounds());\n\t\t// first pass of all children to calculate size\n\t\tpage.calculateSize(context);\n\t\tif (resize) {\n\t\t\t// we now know the bounds of the document\n\t\t\t// round 'm up and restart with a new document\n\t\t\tint width = (int) Math.ceil(page.getBounds().getWidth());\n\t\t\tint height = (int) Math.ceil(page.getBounds().getHeight());\n\t\t\tpage.getConstraint().setWidth(width);\n\t\t\tpage.getConstraint().setHeight(height);\n\n\t\t\tdocument = new Document(new Rectangle(width, height), 0, 0, 0, 0);\n\t\t\twriter = PdfWriter.getInstance(document, baos);\n\t\t\t// Render in correct colors for transparent rasters\n\t\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t\tdocument.open();\n\t\t\tbaos.reset();\n\t\t\tcontext = new PdfContext(writer);\n\t\t\tcontext.initSize(page.getBounds());\n\t\t}\n\t\t// int compressionLevel = writer.getCompressionLevel(); // For testing\n\t\t// writer.setCompressionLevel(0);\n\n\t\t// Actual drawing\n\t\tdocument.addTitle(\"Geomajas\");\n\t\t// second pass to layout\n\t\tpage.layout(context);\n\t\t// finally render (uses baos)\n\t\tpage.render(context);\n\n\t\tdocument.add(context.getImage());\n\t\t// Now close the document\n\t\tdocument.close();\n\t}"
] | [
"@Override\n public JulianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"private void checkLocking(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 jdbcType = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);\r\n\r\n if (!\"TIMESTAMP\".equals(jdbcType) && !\"INTEGER\".equals(jdbcType))\r\n {\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_LOCKING, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has locking set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UPDATE_LOCK, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has update-lock set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n }\r\n }",
"private void writeAssignmentBaselines(Project.Assignments.Assignment xml, ResourceAssignment mpxj)\n {\n Project.Assignments.Assignment.Baseline baseline = m_factory.createProjectAssignmentsAssignmentBaseline();\n boolean populated = false;\n\n Number cost = mpxj.getBaselineCost();\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printExtendedAttributeCurrency(cost));\n }\n\n Date date = mpxj.getBaselineFinish();\n if (date != null)\n {\n populated = true;\n baseline.setFinish(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n date = mpxj.getBaselineStart();\n if (date != null)\n {\n populated = true;\n baseline.setStart(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n Duration duration = mpxj.getBaselineWork();\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, duration));\n }\n\n if (populated)\n {\n baseline.setNumber(\"0\");\n xml.getBaseline().add(baseline);\n }\n\n for (int loop = 1; loop <= 10; loop++)\n {\n baseline = m_factory.createProjectAssignmentsAssignmentBaseline();\n populated = false;\n\n cost = mpxj.getBaselineCost(loop);\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printExtendedAttributeCurrency(cost));\n }\n\n date = mpxj.getBaselineFinish(loop);\n if (date != null)\n {\n populated = true;\n baseline.setFinish(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n date = mpxj.getBaselineStart(loop);\n if (date != null)\n {\n populated = true;\n baseline.setStart(DatatypeConverter.printExtendedAttributeDate(date));\n }\n\n duration = mpxj.getBaselineWork(loop);\n if (duration != null && duration.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, duration));\n }\n\n if (populated)\n {\n baseline.setNumber(Integer.toString(loop));\n xml.getBaseline().add(baseline);\n }\n }\n }",
"private void initHasMasterMode() throws CmsException {\n\n if (hasDescriptor()\n && m_cms.hasPermissions(m_desc, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) {\n m_hasMasterMode = true;\n } else {\n m_hasMasterMode = false;\n }\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushNotificationViewedEvent(Bundle extras){\n\n if (extras == null || extras.isEmpty() || extras.get(Constants.NOTIFICATION_TAG) == null) {\n getConfigLogger().debug(getAccountId(), \"Push notification: \" + (extras == null ? \"NULL\" : extras.toString()) + \" not from CleverTap - will not process Notification Viewed event.\");\n return;\n }\n\n if (!extras.containsKey(Constants.NOTIFICATION_ID_TAG) || (extras.getString(Constants.NOTIFICATION_ID_TAG) == null)) {\n getConfigLogger().debug(getAccountId(), \"Push notification ID Tag is null, not processing Notification Viewed event for: \" + extras.toString());\n return;\n }\n\n // Check for dupe notification views; if same notficationdId within specified time interval (2 secs) don't process\n boolean isDuplicate = checkDuplicateNotificationIds(extras, notificationViewedIdTagMap, Constants.NOTIFICATION_VIEWED_ID_TAG_INTERVAL);\n if (isDuplicate) {\n getConfigLogger().debug(getAccountId(), \"Already processed Notification Viewed event for \" + extras.toString() + \", dropping duplicate.\");\n return;\n }\n\n JSONObject event = new JSONObject();\n try {\n JSONObject notif = getWzrkFields(extras);\n event.put(\"evtName\", Constants.NOTIFICATION_VIEWED_EVENT_NAME);\n event.put(\"evtData\", notif);\n } catch (Throwable ignored) {\n //no-op\n }\n queueEvent(context, event, Constants.RAISED_EVENT);\n }",
"public void setColorRange(int firstIndex, int lastIndex, int color1, int color2) {\n\t\tfor (int i = firstIndex; i <= lastIndex; i++)\n\t\t\tmap[i] = ImageMath.mixColors((float)(i-firstIndex)/(lastIndex-firstIndex), color1, color2);\n\t}",
"public void removeMapping(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n Collection<V> newC = cf.newCollection();\r\n newC.addAll(c);\r\n newC.remove(value);\r\n map.put(key, newC);\r\n }\r\n\r\n } else {\r\n Collection<V> c = get(key);\r\n c.remove(value);\r\n }\r\n }",
"public int compareTo(WordTag wordTag) { \r\n int first = (word != null ? word().compareTo(wordTag.word()) : 0);\r\n if(first != 0)\r\n return first;\r\n else {\r\n if (tag() == null) {\r\n if (wordTag.tag() == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return tag().compareTo(wordTag.tag());\r\n }\r\n }",
"public ApnsServiceBuilder withSocksProxy(String host, int port) {\n Proxy proxy = new Proxy(Proxy.Type.SOCKS,\n new InetSocketAddress(host, port));\n return withProxy(proxy);\n }"
] |
Simply appends the given parameters and returns it to obtain a cache key
@param sql
@param resultSetConcurrency
@param resultSetHoldability
@param resultSetType
@return cache key to use | [
"public String calculateCacheKey(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability){\r\n\t\tStringBuilder tmp = calculateCacheKeyInternal(sql, resultSetType,\r\n\t\t\t\tresultSetConcurrency);\r\n\r\n\t\ttmp.append(\", H:\");\r\n\t\ttmp.append(resultSetHoldability);\r\n\r\n\t\treturn tmp.toString();\r\n\t}"
] | [
"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 void validateInjectionPoint(InjectionPoint ij, BeanManagerImpl beanManager) {\n validateInjectionPointForDefinitionErrors(ij, ij.getBean(), beanManager);\n validateMetadataInjectionPoint(ij, ij.getBean(), ValidatorLogger.INJECTION_INTO_NON_BEAN);\n validateEventMetadataInjectionPoint(ij);\n validateInjectionPointForDeploymentProblems(ij, ij.getBean(), beanManager);\n }",
"private void onClickAdd() {\n\n if (m_currentLocation.isPresent()) {\n CmsFavoriteEntry entry = m_currentLocation.get();\n List<CmsFavoriteEntry> entries = getEntries();\n entries.add(entry);\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n m_context.close();\n }\n }",
"public static String getXPathExpression(Node node) {\n\t\tObject xpathCache = node.getUserData(FULL_XPATH_CACHE);\n\t\tif (xpathCache != null) {\n\t\t\treturn xpathCache.toString();\n\t\t}\n\t\tNode parent = node.getParentNode();\n\n\t\tif ((parent == null) || parent.getNodeName().contains(\"#document\")) {\n\t\t\tString xPath = \"/\" + node.getNodeName() + \"[1]\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tif (node.hasAttributes() && node.getAttributes().getNamedItem(\"id\") != null) {\n\t\t\tString xPath = \"//\" + node.getNodeName() + \"[@id = '\"\n\t\t\t\t\t+ node.getAttributes().getNamedItem(\"id\").getNodeValue() + \"']\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tStringBuffer buffer = new StringBuffer();\n\n\t\tif (parent != node) {\n\t\t\tbuffer.append(getXPathExpression(parent));\n\t\t\tbuffer.append(\"/\");\n\t\t}\n\n\t\tbuffer.append(node.getNodeName());\n\n\t\tList<Node> mySiblings = getSiblings(parent, node);\n\n\t\tfor (int i = 0; i < mySiblings.size(); i++) {\n\t\t\tNode el = mySiblings.get(i);\n\n\t\t\tif (el.equals(node)) {\n\t\t\t\tbuffer.append('[').append(Integer.toString(i + 1)).append(']');\n\t\t\t\t// Found so break;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tString xPath = buffer.toString();\n\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\treturn xPath;\n\t}",
"public Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\n }",
"private void writePredecessors(Task task)\n {\n List<Relation> relations = task.getPredecessors();\n for (Relation mpxj : relations)\n {\n RelationshipType xml = m_factory.createRelationshipType();\n m_project.getRelationship().add(xml);\n\n xml.setLag(getDuration(mpxj.getLag()));\n xml.setObjectId(Integer.valueOf(++m_relationshipObjectID));\n xml.setPredecessorActivityObjectId(mpxj.getTargetTask().getUniqueID());\n xml.setSuccessorActivityObjectId(mpxj.getSourceTask().getUniqueID());\n xml.setPredecessorProjectObjectId(PROJECT_OBJECT_ID);\n xml.setSuccessorProjectObjectId(PROJECT_OBJECT_ID);\n xml.setType(RELATION_TYPE_MAP.get(mpxj.getType()));\n }\n }",
"public static void executorShutDown(ExecutorService executorService, long timeOutSec) {\n try {\n executorService.shutdown();\n executorService.awaitTermination(timeOutSec, TimeUnit.SECONDS);\n } catch(Exception e) {\n logger.warn(\"Error while stoping executor service.\", e);\n }\n }",
"private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\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 }"
] |
Transform a TMS layer description object into a raster layer info object.
@param tileMap
The TMS layer description object.
@return The raster layer info object as used by Geomajas. | [
"public RasterLayerInfo asLayerInfo(TileMap tileMap) {\n\t\tRasterLayerInfo layerInfo = new RasterLayerInfo();\n\n\t\tlayerInfo.setCrs(tileMap.getSrs());\n\t\tlayerInfo.setDataSourceName(tileMap.getTitle());\n\t\tlayerInfo.setLayerType(LayerType.RASTER);\n\t\tlayerInfo.setMaxExtent(asBbox(tileMap.getBoundingBox()));\n\t\tlayerInfo.setTileHeight(tileMap.getTileFormat().getHeight());\n\t\tlayerInfo.setTileWidth(tileMap.getTileFormat().getWidth());\n\n\t\tList<ScaleInfo> zoomLevels = new ArrayList<ScaleInfo>(tileMap.getTileSets().getTileSets().size());\n\t\tfor (TileSet tileSet : tileMap.getTileSets().getTileSets()) {\n\t\t\tzoomLevels.add(asScaleInfo(tileSet));\n\t\t}\n\t\tlayerInfo.setZoomLevels(zoomLevels);\n\n\t\treturn layerInfo;\n\t}"
] | [
"void reportError(Throwable throwable) {\n if (logger != null)\n logger.error(\"Timer reported error\", throwable);\n status = \"Thread blocked on error: \" + throwable;\n error_skips = error_factor;\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 static nd6ravariables[] get(nitro_service service, options option) throws Exception{\n\t\tnd6ravariables obj = new nd6ravariables();\n\t\tnd6ravariables[] response = (nd6ravariables[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"public static base_responses delete(nitro_service client, String ciphergroupname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ciphergroupname != null && ciphergroupname.length > 0) {\n\t\t\tsslcipher deleteresources[] = new sslcipher[ciphergroupname.length];\n\t\t\tfor (int i=0;i<ciphergroupname.length;i++){\n\t\t\t\tdeleteresources[i] = new sslcipher();\n\t\t\t\tdeleteresources[i].ciphergroupname = ciphergroupname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void check(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureElementClassRef(collDef, checkLevel);\r\n checkInheritedForeignkey(collDef, checkLevel);\r\n ensureCollectionClass(collDef, checkLevel);\r\n checkProxyPrefetchingLimit(collDef, checkLevel);\r\n checkOrderby(collDef, checkLevel);\r\n checkQueryCustomizer(collDef, checkLevel);\r\n }",
"public Reply getReplyInfo(String topicId, String replyId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REPLIES_GET_INFO);\r\n parameters.put(\"topic_id\", topicId);\r\n parameters.put(\"reply_id\", replyId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element replyElement = response.getPayload();\r\n\r\n return parseReply(replyElement);\r\n }",
"public synchronized Object[] getIds() {\n String[] keys = getAllKeys();\n int size = keys.length + indexedProps.size();\n Object[] res = new Object[size];\n System.arraycopy(keys, 0, res, 0, keys.length);\n int i = keys.length;\n // now add all indexed properties\n for (Object index : indexedProps.keySet()) {\n res[i++] = index;\n }\n return res;\n }",
"@SuppressWarnings({ \"unchecked\" })\n public static <T> T[] readArrayAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n final List<T> list = readListAttributeElement(reader, attributeName, type);\n return list.toArray((T[]) Array.newInstance(type, list.size()));\n }",
"public void prepareStatus() {\n globalLineCounter = new AtomicLong(0);\n time = new AtomicLong(System.currentTimeMillis());\n startTime = System.currentTimeMillis();\n lastCount = 0;\n\n // Status thread regularly reports on what is happening\n Thread statusThread = new Thread() {\n public void run() {\n while (true) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n System.out.println(\"Status thread interrupted\");\n }\n\n long thisTime = System.currentTimeMillis();\n long currentCount = globalLineCounter.get();\n\n if (thisTime - time.get() > 1000) {\n long oldTime = time.get();\n time.set(thisTime);\n double avgRate = 1000.0 * currentCount / (thisTime - startTime);\n double instRate = 1000.0 * (currentCount - lastCount) / (thisTime - oldTime);\n lastCount = currentCount;\n System.out.println(currentCount + \" AvgRage:\" + ((int) avgRate) + \" lines/sec instRate:\"\n + ((int) instRate) + \" lines/sec Unassigned Work: \"\n + remainingBlocks.get() + \" blocks\");\n }\n }\n }\n };\n statusThread.start();\n }"
] |
Sets the resource to which this calendar is linked. Note that this
method updates the calendar's name to be the same as the resource name.
If the resource does not yet have a name, then the calendar is given
a default name.
@param resource resource instance | [
"public void setResource(Resource resource)\n {\n m_resource = resource;\n String name = m_resource.getName();\n if (name == null || name.length() == 0)\n {\n name = \"Unnamed Resource\";\n }\n setName(name);\n }"
] | [
"@Override\n public List<JobInstance> getJobs(Query query)\n {\n return JqmClientFactory.getClient().getJobs(query);\n }",
"@Override protected View inflate(LayoutInflater inflater, ViewGroup parent) {\n View inflatedView = inflater.inflate(R.layout.video_renderer, parent, false);\n /*\n * You don't have to use ButterKnife library to implement the mapping between your layout\n * and your widgets you can implement setUpView and hookListener methods declared in\n * Renderer<T> class.\n */\n ButterKnife.bind(this, inflatedView);\n return inflatedView;\n }",
"public static base_response unset(nitro_service client, nstimeout resource, String[] args) throws Exception{\n\t\tnstimeout unsetresource = new nstimeout();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public ItemRequest<ProjectMembership> findById(String projectMembership) {\n \n String path = String.format(\"/project_memberships/%s\", projectMembership);\n return new ItemRequest<ProjectMembership>(this, ProjectMembership.class, path, \"GET\");\n }",
"public void print() {\n Iterator<String> iter = getKeys();\n while (iter.hasNext()) {\n String key = iter.next();\n log.info(key + \" = \" + getRawString(key));\n }\n }",
"protected void processLabels(List<MonolingualTextValue> labels) {\n for(MonolingualTextValue label : labels) {\n \tString lang = label.getLanguageCode();\n \tNameWithUpdate currentValue = newLabels.get(lang);\n \tif (currentValue == null || !currentValue.value.equals(label)) {\n\t newLabels.put(lang,\n\t new NameWithUpdate(label, true));\n\t \n\t // Delete any alias that matches the new label\n\t AliasesWithUpdate currentAliases = newAliases.get(lang);\n\t if (currentAliases != null && currentAliases.aliases.contains(label)) {\n\t \tdeleteAlias(label);\n\t }\n \t}\n }\n \n }",
"@JsonProperty(\"aliases\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, List<TermImpl>> getAliasUpdates() {\n \t\n \tMap<String, List<TermImpl>> updatedValues = new HashMap<>();\n \tfor(Map.Entry<String,AliasesWithUpdate> entry : newAliases.entrySet()) {\n \t\tAliasesWithUpdate update = entry.getValue();\n \t\tif (!update.write) {\n \t\t\tcontinue;\n \t\t}\n \t\tList<TermImpl> convertedAliases = new ArrayList<>();\n \t\tfor(MonolingualTextValue alias : update.aliases) {\n \t\t\tconvertedAliases.add(monolingualToJackson(alias));\n \t\t}\n \t\tupdatedValues.put(entry.getKey(), convertedAliases);\n \t}\n \treturn updatedValues;\n }",
"public Date getTime(Integer type)\n {\n Date result = null;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getTime(item, 0);\n }\n\n return (result);\n }",
"public void close() throws IOException {\n for (CloseableHttpClient c : cachedClients.values()) {\n c.close();\n }\n cachedClients.clear();\n }"
] |
Reset a timer of the given string name for the given thread. If no such
timer exists yet, then it will be newly created.
@param timerName
the name of the timer
@param todoFlags
@param threadId
of the thread to track, or 0 if only system clock should be
tracked | [
"public static void resetNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).reset();\n\t}"
] | [
"public void seekToHolidayYear(String holidayString, String yearString) {\n Holiday holiday = Holiday.valueOf(holidayString);\n assert(holiday != null);\n \n seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary());\n }",
"static void setSingleParam(String key, String value, DbConn cnx)\n {\n QueryResult r = cnx.runUpdate(\"globalprm_update_value_by_key\", value, key);\n if (r.nbUpdated == 0)\n {\n cnx.runUpdate(\"globalprm_insert\", key, value);\n }\n cnx.commit();\n }",
"private void allocateConnection() throws SQLException\n {\n if (m_connection == null)\n {\n m_connection = m_dataSource.getConnection();\n m_allocatedConnection = true;\n queryDatabaseMetaData();\n }\n }",
"public void setLargePayloadSupportEnabled(AmazonS3 s3, String s3BucketName) {\n\t\tif (s3 == null || s3BucketName == null) {\n\t\t\tString errorMessage = \"S3 client and/or S3 bucket name cannot be null.\";\n\t\t\tLOG.error(errorMessage);\n\t\t\tthrow new AmazonClientException(errorMessage);\n\t\t}\n\t\tif (isLargePayloadSupportEnabled()) {\n\t\t\tLOG.warn(\"Large-payload support is already enabled. Overwriting AmazonS3Client and S3BucketName.\");\n\t\t}\n\t\tthis.s3 = s3;\n\t\tthis.s3BucketName = s3BucketName;\n\t\tlargePayloadSupport = true;\n\t\tLOG.info(\"Large-payload support enabled.\");\n\t}",
"private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n\n m_project.getProjectProperties().setFileApplication(\"Merlin\");\n m_project.getProjectProperties().setFileType(\"SQLITE\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n populateEntityMap();\n processProject();\n processCalendars();\n processResources();\n processTasks();\n processAssignments();\n processDependencies();\n\n return m_project;\n }",
"public void updateActive(int profileId, String clientUUID, Boolean active) throws Exception {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_CLIENT +\n \" SET \" + Constants.CLIENT_IS_ACTIVE + \"= ?\" +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n statement.setBoolean(1, active);\n statement.setString(2, clientUUID);\n statement.setInt(3, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n // ok to swallow this.. just means there wasn't any\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"private static int abs(int a) {\n if(a >= 0)\n return a;\n else if(a != Integer.MIN_VALUE)\n return -a;\n return Integer.MAX_VALUE;\n }",
"public static String confSetName() {\n String profile = SysProps.get(AppConfigKey.PROFILE.key());\n if (S.blank(profile)) {\n profile = Act.mode().name().toLowerCase();\n }\n return profile;\n }",
"private Options getOptions() {\n\t\tOptions options = new Options();\n\t\toptions.addOption(\"h\", HELP, false, \"print this message\");\n\t\toptions.addOption(VERSION, false, \"print the version information and exit\");\n\n\t\toptions.addOption(\"b\", BROWSER, true,\n\t\t \"browser type: \" + availableBrowsers() + \". Default is Firefox\");\n\n\t\toptions.addOption(BROWSER_REMOTE_URL, true,\n\t\t \"The remote url if you have configured a remote browser\");\n\n\t\toptions.addOption(\"d\", DEPTH, true, \"crawl depth level. Default is 2\");\n\n\t\toptions.addOption(\"s\", MAXSTATES, true,\n\t\t \"max number of states to crawl. Default is 0 (unlimited)\");\n\n\t\toptions.addOption(\"p\", PARALLEL, true,\n\t\t \"Number of browsers to use for crawling. Default is 1\");\n\t\toptions.addOption(\"o\", OVERRIDE, false, \"Override the output directory if non-empty\");\n\n\t\toptions.addOption(\"a\", CRAWL_HIDDEN_ANCHORS, false,\n\t\t \"Crawl anchors even if they are not visible in the browser.\");\n\n\t\toptions.addOption(\"t\", TIME_OUT, true,\n\t\t \"Specify the maximum crawl time in minutes\");\n\n\t\toptions.addOption(CLICK, true,\n\t\t \"a comma separated list of HTML tags that should be clicked. Default is A and BUTTON\");\n\n\t\toptions.addOption(WAIT_AFTER_EVENT, true,\n\t\t \"the time to wait after an event has been fired in milliseconds. Default is \"\n\t\t + CrawlRules.DEFAULT_WAIT_AFTER_EVENT);\n\n\t\toptions.addOption(WAIT_AFTER_RELOAD, true,\n\t\t \"the time to wait after an URL has been loaded in milliseconds. Default is \"\n\t\t + CrawlRules.DEFAULT_WAIT_AFTER_RELOAD);\n\n\t\toptions.addOption(\"v\", VERBOSE, false, \"Be extra verbose\");\n\t\toptions.addOption(LOG_FILE, true, \"Log to this file instead of the console\");\n\n\t\treturn options;\n\t}"
] |
Creates a ServiceCall from an observable object.
@param observable the observable to create from
@param <T> the type of the response
@return the created ServiceCall | [
"public static <T> ServiceFuture<T> fromResponse(final Observable<ServiceResponse<T>> observable) {\n final ServiceFuture<T> serviceFuture = new ServiceFuture<>();\n serviceFuture.subscription = observable\n .last()\n .subscribe(new Action1<ServiceResponse<T>>() {\n @Override\n public void call(ServiceResponse<T> t) {\n serviceFuture.set(t.body());\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\n }"
] | [
"public long getStartTime(List<IInvokedMethod> methods)\n {\n long startTime = System.currentTimeMillis();\n for (IInvokedMethod method : methods)\n {\n startTime = Math.min(startTime, method.getDate());\n }\n return startTime;\n }",
"public static SPIProviderResolver getInstance(ClassLoader cl)\n {\n SPIProviderResolver resolver = (SPIProviderResolver)ServiceLoader.loadService(SPIProviderResolver.class.getName(), DEFAULT_SPI_PROVIDER_RESOLVER, cl);\n return resolver;\n }",
"public void applyToBackground(View view) {\n if (mColorInt != 0) {\n view.setBackgroundColor(mColorInt);\n } else if (mColorRes != -1) {\n view.setBackgroundResource(mColorRes);\n }\n }",
"public static ObjectName registerMbean(String typeName, Object obj) {\n MBeanServer server = ManagementFactory.getPlatformMBeanServer();\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()),\n typeName);\n registerMbean(server, JmxUtils.createModelMBean(obj), name);\n return name;\n }",
"public void addPieSlice(PieModel _Slice) {\n highlightSlice(_Slice);\n mPieData.add(_Slice);\n mTotalValue += _Slice.getValue();\n onDataChanged();\n }",
"public int getBoneIndex(GVRSceneObject bone)\n {\n for (int i = 0; i < getNumBones(); ++i)\n if (mBones[i] == bone)\n return i;\n return -1;\n }",
"private float max(float x, float y, float z) {\n if (x > y) {\n // not y\n if (x > z) {\n return x;\n }\n else {\n return z;\n }\n }\n else {\n // not x\n if (y > z) {\n return y;\n }\n else {\n return z;\n }\n }\n }",
"public static ObjectModelResolver get(String resolverId) {\n List<ObjectModelResolver> resolvers = getResolvers();\n\n for (ObjectModelResolver resolver : resolvers) {\n if (resolver.accept(resolverId)) {\n return resolver;\n }\n }\n\n return null;\n }",
"public static base_responses link(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey linkresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tlinkresources[i] = new sslcertkey();\n\t\t\t\tlinkresources[i].certkey = resources[i].certkey;\n\t\t\t\tlinkresources[i].linkcertkeyname = resources[i].linkcertkeyname;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, linkresources,\"link\");\n\t\t}\n\t\treturn result;\n\t}"
] |
Attach the given link to the classification, while checking for duplicates. | [
"public ClassificationModel attachLink(ClassificationModel classificationModel, LinkModel linkModel)\n {\n for (LinkModel existing : classificationModel.getLinks())\n {\n if (StringUtils.equals(existing.getLink(), linkModel.getLink()))\n {\n return classificationModel;\n }\n }\n classificationModel.addLink(linkModel);\n return classificationModel;\n }"
] | [
"public void updateSchema(String migrationPath) {\n try {\n logger.info(\"Updating schema... \");\n int current_version = 0;\n\n // first check the current schema version\n HashMap<String, Object> configuration = getFirstResult(\"SELECT * FROM \" + Constants.DB_TABLE_CONFIGURATION +\n \" WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \" = \\'\" + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + \"\\'\");\n\n if (configuration == null) {\n logger.info(\"Creating configuration table..\");\n // create configuration table\n executeUpdate(\"CREATE TABLE \"\n + Constants.DB_TABLE_CONFIGURATION\n + \" (\" + Constants.GENERIC_ID + \" INTEGER IDENTITY,\"\n + Constants.DB_TABLE_CONFIGURATION_NAME + \" VARCHAR(256),\"\n + Constants.DB_TABLE_CONFIGURATION_VALUE + \" VARCHAR(1024));\");\n\n executeUpdate(\"INSERT INTO \" + Constants.DB_TABLE_CONFIGURATION\n + \"(\" + Constants.DB_TABLE_CONFIGURATION_NAME + \",\" + Constants.DB_TABLE_CONFIGURATION_VALUE + \")\"\n + \" VALUES (\\'\"\n + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION\n + \"\\', '0');\");\n } else {\n logger.info(\"Getting current schema version..\");\n // get current version\n current_version = new Integer(configuration.get(\"VALUE\").toString());\n logger.info(\"Current schema version is {}\", current_version);\n }\n\n // loop through until we get up to the right schema version\n while (current_version < Constants.DB_CURRENT_SCHEMA_VERSION) {\n current_version++;\n\n // look for a schema file for this version\n logger.info(\"Updating to schema version {}\", current_version);\n String currentFile = migrationPath + \"/schema.\"\n + current_version;\n Resource migFile = new ClassPathResource(currentFile);\n BufferedReader in = new BufferedReader(new InputStreamReader(\n migFile.getInputStream()));\n\n String str;\n while ((str = in.readLine()) != null) {\n // execute each line\n if (str.length() > 0) {\n executeUpdate(str);\n }\n }\n in.close();\n }\n\n // update the configuration table with the correct version\n executeUpdate(\"UPDATE \" + Constants.DB_TABLE_CONFIGURATION\n + \" SET \" + Constants.DB_TABLE_CONFIGURATION_VALUE + \"='\" + current_version\n + \"' WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \"='\"\n + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + \"';\");\n } catch (Exception e) {\n logger.info(\"Error in executeUpdate\");\n e.printStackTrace();\n }\n }",
"public char pollChar() {\n if(hasNextChar()) {\n if(hasNextWord() &&\n character+1 >= parsedLine.words().get(word).lineIndex()+\n parsedLine.words().get(word).word().length())\n word++;\n return parsedLine.line().charAt(character++);\n }\n return '\\u0000';\n }",
"private void appendJoinSQL92NoParen(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n\r\n buf.append(join.right.getTableAndAlias());\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n\r\n appendTableWithJoins(join.right, where, buf);\r\n }",
"public static Double checkLatitude(String name, Double latitude) {\n if (latitude == null) {\n throw new IndexException(\"{} required\", name);\n } else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {\n throw new IndexException(\"{} must be in range [{}, {}], but found {}\",\n name,\n MIN_LATITUDE,\n MAX_LATITUDE,\n latitude);\n }\n return latitude;\n }",
"public void deleteComment(String commentId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_DELETE_COMMENT);\r\n\r\n parameters.put(\"comment_id\", commentId);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }",
"public List<BoxTaskAssignment.Info> getAssignments() {\n URL url = GET_ASSIGNMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTaskAssignment.Info> assignments = new ArrayList<BoxTaskAssignment.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject assignmentJSON = value.asObject();\n BoxTaskAssignment assignment = new BoxTaskAssignment(this.getAPI(), assignmentJSON.get(\"id\").asString());\n BoxTaskAssignment.Info info = assignment.new Info(assignmentJSON);\n assignments.add(info);\n }\n\n return assignments;\n }",
"static PathAddress toPathAddress(String domain, ImmutableManagementResourceRegistration registry, ObjectName name) {\n if (!name.getDomain().equals(domain)) {\n return PathAddress.EMPTY_ADDRESS;\n }\n if (name.equals(ModelControllerMBeanHelper.createRootObjectName(domain))) {\n return PathAddress.EMPTY_ADDRESS;\n }\n final Hashtable<String, String> properties = name.getKeyPropertyList();\n return searchPathAddress(PathAddress.EMPTY_ADDRESS, registry, properties);\n }",
"private static Class<?> getRawClass(Type type) {\n if (type instanceof Class) {\n return (Class<?>) type;\n }\n if (type instanceof ParameterizedType) {\n return getRawClass(((ParameterizedType) type).getRawType());\n }\n // For TypeVariable and WildcardType, returns the first upper bound.\n if (type instanceof TypeVariable) {\n return getRawClass(((TypeVariable) type).getBounds()[0]);\n }\n if (type instanceof WildcardType) {\n return getRawClass(((WildcardType) type).getUpperBounds()[0]);\n }\n if (type instanceof GenericArrayType) {\n Class<?> componentClass = getRawClass(((GenericArrayType) type).getGenericComponentType());\n return Array.newInstance(componentClass, 0).getClass();\n }\n // This shouldn't happen as we captured all implementations of Type above (as or Java 8)\n throw new IllegalArgumentException(\"Unsupported type \" + type + \" of type class \" + type.getClass());\n }",
"@Override\n public void destroy(SocketDestination dest, ClientRequestExecutor clientRequestExecutor)\n throws Exception {\n clientRequestExecutor.close();\n int numDestroyed = destroyed.incrementAndGet();\n if(stats != null) {\n stats.incrementCount(dest, ClientSocketStats.Tracked.CONNECTION_DESTROYED_EVENT);\n }\n\n if(logger.isDebugEnabled())\n logger.debug(\"Destroyed socket \" + numDestroyed + \" connection to \" + dest.getHost()\n + \":\" + dest.getPort());\n }"
] |
Convert an object to a list.
@param mapper the object mapper
@param source the source object
@param targetElementType the target list element type
@return list | [
"public static <E> List<E> listify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (List<E>) collectify(mapper, source, List.class, targetElementType);\n }"
] | [
"@Pure\n\tpublic static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure,\n\t\t\tfinal P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure4<P2, P3, P4, P5>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p2, P3 p3, P4 p4, P5 p5) {\n\t\t\t\tprocedure.apply(argument, p2, p3, p4, p5);\n\t\t\t}\n\t\t};\n\t}",
"private List<Variable> parseAssignRange(Sequence sequence, TokenList tokens, TokenList.Token t0) {\n // find assignment symbol\n TokenList.Token tokenAssign = t0.next;\n while( tokenAssign != null && tokenAssign.symbol != Symbol.ASSIGN ) {\n tokenAssign = tokenAssign.next;\n }\n\n if( tokenAssign == null )\n throw new ParseError(\"Can't find assignment operator\");\n\n // see if it is a sub matrix before\n if( tokenAssign.previous.symbol == Symbol.PAREN_RIGHT ) {\n TokenList.Token start = t0.next;\n if( start.symbol != Symbol.PAREN_LEFT )\n throw new ParseError((\"Expected left param for assignment\"));\n TokenList.Token end = tokenAssign.previous;\n TokenList subTokens = tokens.extractSubList(start,end);\n subTokens.remove(subTokens.getFirst());\n subTokens.remove(subTokens.getLast());\n\n handleParentheses(subTokens,sequence);\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(subTokens, sequence);\n\n if (inputs.isEmpty())\n throw new ParseError(\"Empty function input parameters\");\n\n List<Variable> range = new ArrayList<>();\n addSubMatrixVariables(inputs, range);\n if( range.size() != 1 && range.size() != 2 ) {\n throw new ParseError(\"Unexpected number of range variables. 1 or 2 expected\");\n }\n return range;\n }\n\n return null;\n }",
"public void localRollback()\r\n {\r\n log.info(\"Rollback was called, do rollback on current connection \" + con);\r\n if (!this.isInLocalTransaction)\r\n {\r\n throw new PersistenceBrokerException(\"Not in transaction, cannot abort\");\r\n }\r\n try\r\n {\r\n //truncate the local transaction\r\n this.isInLocalTransaction = false;\r\n if(!broker.isManaged())\r\n {\r\n if (batchCon != null)\r\n {\r\n batchCon.rollback();\r\n }\r\n else if (con != null && !con.isClosed())\r\n {\r\n con.rollback();\r\n }\r\n }\r\n else\r\n {\r\n if(log.isEnabledFor(Logger.INFO)) log.info(\r\n \"Found managed environment setting in PB, will ignore rollback call on connection, this should be done by JTA\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"Rollback on the underlying connection failed\", e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n \trestoreAutoCommitState();\r\n\t\t }\r\n catch(OJBRuntimeException ignore)\r\n {\r\n\t\t\t // Ignore or log exception\r\n\t\t }\r\n releaseConnection();\r\n }\r\n }",
"public void addHandlerFactory(ManagementRequestHandlerFactory factory) {\n for (;;) {\n final ManagementRequestHandlerFactory[] snapshot = updater.get(this);\n final int length = snapshot.length;\n final ManagementRequestHandlerFactory[] newVal = new ManagementRequestHandlerFactory[length + 1];\n System.arraycopy(snapshot, 0, newVal, 0, length);\n newVal[length] = factory;\n if (updater.compareAndSet(this, snapshot, newVal)) {\n return;\n }\n }\n }",
"public void setShadow(float radius, float dx, float dy, int color) {\n\t\tshadowRadius = radius;\n\t\tshadowDx = dx;\n\t\tshadowDy = dy;\n\t\tshadowColor = color;\n\t\tupdateShadow();\n\t}",
"private static String wordShapeDan1(String s) {\r\n boolean digit = true;\r\n boolean upper = true;\r\n boolean lower = true;\r\n boolean mixed = true;\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (!Character.isDigit(c)) {\r\n digit = false;\r\n }\r\n if (!Character.isLowerCase(c)) {\r\n lower = false;\r\n }\r\n if (!Character.isUpperCase(c)) {\r\n upper = false;\r\n }\r\n if ((i == 0 && !Character.isUpperCase(c)) || (i >= 1 && !Character.isLowerCase(c))) {\r\n mixed = false;\r\n }\r\n }\r\n if (digit) {\r\n return \"ALL-DIGITS\";\r\n }\r\n if (upper) {\r\n return \"ALL-UPPER\";\r\n }\r\n if (lower) {\r\n return \"ALL-LOWER\";\r\n }\r\n if (mixed) {\r\n return \"MIXED-CASE\";\r\n }\r\n return \"OTHER\";\r\n }",
"public static List<Sentence> splitSentences(CharSequence text) {\n return JavaConversions.seqAsJavaList(\n TwitterKoreanProcessor.splitSentences(text)\n );\n }",
"public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalStateException(message);\n return value;\n }"
] |
Create a new path
@param pathName friendly name of path
@param pathValue path value or regex
@param requestType path request type. "GET", "POST", etc | [
"public void createPath(String pathName, String pathValue, String requestType) {\n try {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"pathName\", pathName),\n new BasicNameValuePair(\"path\", pathValue),\n new BasicNameValuePair(\"requestType\", String.valueOf(type)),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH, params));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }"
] | [
"void setParent(ProjectCalendarWeek parent)\n {\n m_parent = parent;\n\n for (int loop = 0; loop < m_days.length; loop++)\n {\n if (m_days[loop] == null)\n {\n m_days[loop] = DayType.DEFAULT;\n }\n }\n }",
"public ApiResponse<TagsEnvelope> getTagCategoriesWithHttpInfo() throws ApiException {\n com.squareup.okhttp.Call call = getTagCategoriesValidateBeforeCall(null, null);\n Type localVarReturnType = new TypeToken<TagsEnvelope>(){}.getType();\n return apiClient.execute(call, localVarReturnType);\n }",
"private String getDestinationHostName(String hostName) {\n List<ServerRedirect> servers = serverRedirectService\n .tableServers(requestInformation.get().client.getId());\n for (ServerRedirect server : servers) {\n if (server.getSrcUrl().compareTo(hostName) == 0) {\n if (server.getDestUrl() != null && server.getDestUrl().compareTo(\"\") != 0) {\n return server.getDestUrl();\n } else {\n logger.warn(\"Using source URL as destination URL since no destination was specified for: {}\",\n server.getSrcUrl());\n }\n\n // only want to apply the first host name change found\n break;\n }\n }\n\n return hostName;\n }",
"private <T> RequestBuilder doPrepareRequestBuilderImpl(\n ResponseReader responseReader, String methodName, RpcStatsContext statsContext,\n String requestData, AsyncCallback<T> callback) {\n\n if (getServiceEntryPoint() == null) {\n throw new NoServiceEntryPointSpecifiedException();\n }\n\n RequestCallback responseHandler = doCreateRequestCallback(responseReader,\n methodName, statsContext, callback);\n\n ensureRpcRequestBuilder();\n\n rpcRequestBuilder.create(getServiceEntryPoint());\n rpcRequestBuilder.setCallback(responseHandler);\n \n // changed code\n rpcRequestBuilder.setSync(isSync(methodName));\n // changed code\n \n rpcRequestBuilder.setContentType(RPC_CONTENT_TYPE);\n rpcRequestBuilder.setRequestData(requestData);\n rpcRequestBuilder.setRequestId(statsContext.getRequestId());\n return rpcRequestBuilder.finish();\n }",
"public double distanceSquared(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return dx * dx + dy * dy + dz * dz;\n }",
"private static List< Block > createBlocks(int[] data, boolean debug) {\r\n\r\n List< Block > blocks = new ArrayList<>();\r\n Block current = null;\r\n\r\n for (int i = 0; i < data.length; i++) {\r\n EncodingMode mode = chooseMode(data[i]);\r\n if ((current != null && current.mode == mode) &&\r\n (mode != EncodingMode.NUM || current.length < MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n current.length++;\r\n } else {\r\n current = new Block(mode);\r\n blocks.add(current);\r\n }\r\n }\r\n\r\n if (debug) {\r\n System.out.println(\"Initial block pattern: \" + blocks);\r\n }\r\n\r\n smoothBlocks(blocks);\r\n\r\n if (debug) {\r\n System.out.println(\"Final block pattern: \" + blocks);\r\n }\r\n\r\n return blocks;\r\n }",
"public static base_responses delete(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 deleteresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new route6();\n\t\t\t\tdeleteresources[i].network = resources[i].network;\n\t\t\t\tdeleteresources[i].gateway = resources[i].gateway;\n\t\t\t\tdeleteresources[i].vlan = resources[i].vlan;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static servicegroup_lbmonitor_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroup_lbmonitor_binding obj = new servicegroup_lbmonitor_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroup_lbmonitor_binding response[] = (servicegroup_lbmonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void onThrowable(Throwable cause) {\n this.cause = cause;\n getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION, getSelf());\n\n }"
] |
perform the actual matching | [
"private boolean pathMatches(Path path, SquigglyContext context) {\n List<SquigglyNode> nodes = context.getNodes();\n Set<String> viewStack = null;\n SquigglyNode viewNode = null;\n\n int pathSize = path.getElements().size();\n int lastIdx = pathSize - 1;\n\n for (int i = 0; i < pathSize; i++) {\n PathElement element = path.getElements().get(i);\n\n if (viewNode != null && !viewNode.isSquiggly()) {\n Class beanClass = element.getBeanClass();\n\n if (beanClass != null && !Map.class.isAssignableFrom(beanClass)) {\n Set<String> propertyNames = getPropertyNamesFromViewStack(element, viewStack);\n\n if (!propertyNames.contains(element.getName())) {\n return false;\n }\n }\n\n } else if (nodes.isEmpty()) {\n return false;\n } else {\n\n SquigglyNode match = findBestSimpleNode(element, nodes);\n\n if (match == null) {\n match = findBestViewNode(element, nodes);\n\n if (match != null) {\n viewNode = match;\n viewStack = addToViewStack(viewStack, viewNode);\n }\n } else if (match.isAnyShallow()) {\n viewNode = match;\n } else if (match.isAnyDeep()) {\n return true;\n }\n\n if (match == null) {\n if (isJsonUnwrapped(element)) {\n continue;\n }\n\n return false;\n }\n\n if (match.isNegated()) {\n return false;\n }\n\n nodes = match.getChildren();\n\n if (i < lastIdx && nodes.isEmpty() && !match.isEmptyNested() && SquigglyConfig.isFilterImplicitlyIncludeBaseFields()) {\n nodes = BASE_VIEW_NODES;\n }\n }\n }\n\n return true;\n }"
] | [
"private Component createConvertToPropertyBundleButton() {\n\n Button addDescriptorButton = CmsToolBar.createButton(\n FontOpenCms.SETTINGS,\n m_messages.key(Messages.GUI_CONVERT_TO_PROPERTY_BUNDLE_0));\n\n addDescriptorButton.setDisableOnClick(true);\n\n addDescriptorButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n try {\n m_model.saveAsPropertyBundle();\n Notification.show(\"Conversion successful.\");\n } catch (CmsException | IOException e) {\n CmsVaadinUtils.showAlert(\"Conversion failed\", e.getLocalizedMessage(), null);\n }\n }\n });\n addDescriptorButton.setDisableOnClick(true);\n return addDescriptorButton;\n }",
"@Override\r\n public boolean containsKey(Object key) {\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n Object value = deltaMap.get(key);\r\n if (value == null) {\r\n return originalMap.containsKey(key);\r\n }\r\n if (value == removedValue) {\r\n return false;\r\n }\r\n return true;\r\n }",
"public static <K,V> MultiValueMap<K,V> unmodifiableMultiValueMap(MultiValueMap<? extends K, ? extends V> map) {\n\t\tAssert.notNull(map, \"'map' must not be null\");\n\t\tMap<K, List<V>> result = new LinkedHashMap<K, List<V>>(map.size());\n\t\tfor (Map.Entry<? extends K, ? extends List<? extends V>> entry : map.entrySet()) {\n\t\t\tList<V> values = Collections.unmodifiableList(entry.getValue());\n\t\t\tresult.put(entry.getKey(), values);\n\t\t}\n\t\tMap<K, List<V>> unmodifiableMap = Collections.unmodifiableMap(result);\n\t\treturn toMultiValueMap(unmodifiableMap);\n\t}",
"public static final String getSelectedValue(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getValue(index) : null;\n }",
"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 }",
"public static Map<String, Object> with(Object... params) {\n Map<String, Object> map = new HashMap<>();\n for (int i = 0; i < params.length; i++) {\n map.put(String.valueOf(i), params[i]);\n }\n return map;\n }",
"public static Deployment of(final URL url) {\n final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam(\"url\", url));\n return new Deployment(deploymentContent, null);\n }",
"@UiThread\n protected void collapseView() {\n setExpanded(false);\n onExpansionToggled(true);\n\n if (mParentViewHolderExpandCollapseListener != null) {\n mParentViewHolderExpandCollapseListener.onParentCollapsed(getAdapterPosition());\n }\n }",
"public void writeTo(WritableByteChannel channel) throws IOException {\n for (ByteBuffer buffer : toDirectByteBuffers()) {\n channel.write(buffer);\n }\n }"
] |
Gets the Chi Square distance between two normalized histograms.
@param histogram1 Histogram.
@param histogram2 Histogram.
@return The Chi Square distance between x and y. | [
"public static double ChiSquare(double[] histogram1, double[] histogram2) {\n double r = 0;\n for (int i = 0; i < histogram1.length; i++) {\n double t = histogram1[i] + histogram2[i];\n if (t != 0)\n r += Math.pow(histogram1[i] - histogram2[i], 2) / t;\n }\n\n return 0.5 * r;\n }"
] | [
"public static void directoryCheck(String dir) throws IOException {\n\t\tfinal File file = new File(dir);\n\n\t\tif (!file.exists()) {\n\t\t\tFileUtils.forceMkdir(file);\n\t\t}\n\t}",
"private void processFields(Map<FieldType, String> map, Row row, FieldContainer container)\n {\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n FieldType field = entry.getKey();\n String name = entry.getValue();\n\n Object value;\n switch (field.getDataType())\n {\n case INTEGER:\n {\n value = row.getInteger(name);\n break;\n }\n\n case BOOLEAN:\n {\n value = Boolean.valueOf(row.getBoolean(name));\n break;\n }\n\n case DATE:\n {\n value = row.getDate(name);\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n case PERCENTAGE:\n {\n value = row.getDouble(name);\n break;\n }\n\n case DELAY:\n case WORK:\n case DURATION:\n {\n value = row.getDuration(name);\n break;\n }\n\n case RESOURCE_TYPE:\n {\n value = RESOURCE_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case TASK_TYPE:\n {\n value = TASK_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case CONSTRAINT:\n {\n value = CONSTRAINT_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case PRIORITY:\n {\n value = PRIORITY_MAP.get(row.getString(name));\n break;\n }\n\n case GUID:\n {\n value = row.getUUID(name);\n break;\n }\n\n default:\n {\n value = row.getString(name);\n break;\n }\n }\n\n container.set(field, value);\n }\n }",
"public CustomHeadersInterceptor addHeaderMap(Map<String, String> headers) {\n for (Map.Entry<String, String> header : headers.entrySet()) {\n this.headers.put(header.getKey(), Collections.singletonList(header.getValue()));\n }\n return this;\n }",
"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 }",
"@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 final BigInteger printDurationInIntegerTenthsOfMinutes(Duration duration)\n {\n BigInteger result = null;\n\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigInteger.valueOf((long) printDurationFractionsOfMinutes(duration, 10));\n }\n\n return result;\n }",
"public String convertToPrefixLength() throws AddressStringException {\n\t\tIPAddress address = toAddress();\n\t\tInteger prefix;\n\t\tif(address == null) {\n\t\t\tif(isPrefixOnly()) {\n\t\t\t\tprefix = getNetworkPrefixLength();\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} else {\n\t\t\tprefix = address.getBlockMaskPrefixLength(true);\n\t\t\tif(prefix == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn IPAddressSegment.toUnsignedString(prefix, 10, \n\t\t\t\tnew StringBuilder(IPAddressSegment.toUnsignedStringLength(prefix, 10) + 1).append(IPAddress.PREFIX_LEN_SEPARATOR)).toString();\n\t}",
"public static String strMapToStr(Map<String, String> map) {\n\n StringBuilder sb = new StringBuilder();\n\n if (map == null || map.isEmpty())\n return sb.toString();\n\n for (Entry<String, String> entry : map.entrySet()) {\n\n sb.append(\"< \" + entry.getKey() + \", \" + entry.getValue() + \"> \");\n }\n return sb.toString();\n\n }",
"private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }"
] |
Sets a default style for every element that doesn't have one
@throws JRException | [
"protected void ensureDJStyles() {\n //first of all, register all parent styles if any\n for (Style style : getReport().getStyles().values()) {\n addStyleToDesign(style);\n }\n\n Style defaultDetailStyle = getReport().getOptions().getDefaultDetailStyle();\n\n Style defaultHeaderStyle = getReport().getOptions().getDefaultHeaderStyle();\n for (AbstractColumn column : report.getColumns()) {\n if (column.getStyle() == null)\n column.setStyle(defaultDetailStyle);\n if (column.getHeaderStyle() == null)\n column.setHeaderStyle(defaultHeaderStyle);\n }\n }"
] | [
"protected void setColumnsFinalWidth() {\n log.debug(\"Setting columns final width.\");\n float factor;\n int printableArea = report.getOptions().getColumnWidth();\n\n //Create a list with only the visible columns.\n List visibleColums = getVisibleColumns();\n\n\n if (report.getOptions().isUseFullPageWidth()) {\n int columnsWidth = 0;\n int notRezisableWidth = 0;\n\n //Store in a variable the total with of all visible columns\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n columnsWidth += col.getWidth();\n if (col.isFixedWidth())\n notRezisableWidth += col.getWidth();\n }\n\n\n factor = (float) (printableArea - notRezisableWidth) / (float) (columnsWidth - notRezisableWidth);\n\n log.debug(\"printableArea = \" + printableArea\n + \", columnsWidth = \" + columnsWidth\n + \", columnsWidth = \" + columnsWidth\n + \", notRezisableWidth = \" + notRezisableWidth\n + \", factor = \" + factor);\n\n int acumulated = 0;\n int colFinalWidth;\n\n //Select the non-resizable columns\n Collection resizableColumns = CollectionUtils.select(visibleColums, new Predicate() {\n public boolean evaluate(Object arg0) {\n return !((AbstractColumn) arg0).isFixedWidth();\n }\n\n });\n\n //Finally, set the new width to the resizable columns\n for (Iterator iter = resizableColumns.iterator(); iter.hasNext(); ) {\n AbstractColumn col = (AbstractColumn) iter.next();\n\n if (!iter.hasNext()) {\n col.setWidth(printableArea - notRezisableWidth - acumulated);\n } else {\n colFinalWidth = (new Float(col.getWidth() * factor)).intValue();\n acumulated += colFinalWidth;\n col.setWidth(colFinalWidth);\n }\n }\n }\n\n // If the columns width changed, the X position must be setted again.\n int posx = 0;\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n col.setPosX(posx);\n posx += col.getWidth();\n }\n }",
"protected static boolean numericEquals(Field vector1, Field vector2) {\n\t\tif (vector1.size() != vector2.size())\n\t\t\treturn false;\n\t\tif (vector1.isEmpty())\n\t\t\treturn true;\n\n\t\tIterator<Object> it1 = vector1.iterator();\n\t\tIterator<Object> it2 = vector2.iterator();\n\n\t\twhile (it1.hasNext()) {\n\t\t\tObject obj1 = it1.next();\n\t\t\tObject obj2 = it2.next();\n\n\t\t\tif (!(obj1 instanceof Number && obj2 instanceof Number))\n\t\t\t\treturn false;\n\n\t\t\tif (((Number) obj1).doubleValue() != ((Number) obj2).doubleValue())\n\t\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}",
"public static final Number parseExtendedAttributeCurrency(String value)\n {\n Number result;\n\n if (value == null)\n {\n result = null;\n }\n else\n {\n result = NumberHelper.getDouble(Double.parseDouble(correctNumberFormat(value)) / 100);\n }\n return result;\n }",
"private void checkProcedures(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ProcedureDef procDef;\r\n String type;\r\n String name;\r\n String fieldName;\r\n String argName;\r\n \r\n for (Iterator it = classDef.getProcedures(); it.hasNext();)\r\n {\r\n procDef = (ProcedureDef)it.next();\r\n type = procDef.getName();\r\n name = procDef.getProperty(PropertyHelper.OJB_PROPERTY_NAME);\r\n if ((name == null) || (name.length() == 0))\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure in class \"+classDef.getName()+\" doesn't have a name\");\r\n }\r\n fieldName = procDef.getProperty(PropertyHelper.OJB_PROPERTY_RETURN_FIELD_REF);\r\n if ((fieldName != null) && (fieldName.length() > 0))\r\n {\r\n if (classDef.getField(fieldName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure \"+name+\" in class \"+classDef.getName()+\" references an unknown or non-persistent return field \"+fieldName);\r\n }\r\n }\r\n for (CommaListIterator argIt = new CommaListIterator(procDef.getProperty(PropertyHelper.OJB_PROPERTY_ARGUMENTS)); argIt.hasNext();)\r\n {\r\n argName = argIt.getNext();\r\n if (classDef.getProcedureArgument(argName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure \"+name+\" in class \"+classDef.getName()+\" references an unknown argument \"+argName);\r\n }\r\n }\r\n }\r\n\r\n ProcedureArgumentDef argDef;\r\n\r\n for (Iterator it = classDef.getProcedureArguments(); it.hasNext();)\r\n {\r\n argDef = (ProcedureArgumentDef)it.next();\r\n type = argDef.getProperty(PropertyHelper.OJB_PROPERTY_TYPE);\r\n if (\"runtime\".equals(type))\r\n {\r\n fieldName = argDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELD_REF);\r\n if ((fieldName != null) && (fieldName.length() > 0))\r\n {\r\n if (classDef.getField(fieldName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-argument \"+argDef.getName()+\" in class \"+classDef.getName()+\" references an unknown or non-persistent return field \"+fieldName);\r\n }\r\n }\r\n }\r\n }\r\n }",
"public ItemRequest<CustomField> delete(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"DELETE\");\n }",
"public static CmsJspResourceWrapper convertResource(CmsObject cms, Object input) throws CmsException {\n\n CmsJspResourceWrapper result;\n if (input instanceof CmsResource) {\n result = CmsJspResourceWrapper.wrap(cms, (CmsResource)input);\n } else {\n result = CmsJspResourceWrapper.wrap(cms, convertRawResource(cms, input));\n }\n return result;\n }",
"private void createTimephasedData(ProjectFile file, ResourceAssignment assignment, List<TimephasedWork> timephasedPlanned, List<TimephasedWork> timephasedComplete)\n {\n if (timephasedPlanned.isEmpty() && timephasedComplete.isEmpty())\n {\n Duration totalMinutes = assignment.getWork().convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n\n Duration workPerDay;\n\n if (assignment.getResource() == null || assignment.getResource().getType() == ResourceType.WORK)\n {\n workPerDay = totalMinutes.getDuration() == 0 ? totalMinutes : ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n int units = NumberHelper.getInt(assignment.getUnits());\n if (units != 100)\n {\n workPerDay = Duration.getInstance((workPerDay.getDuration() * units) / 100.0, workPerDay.getUnits());\n }\n }\n else\n {\n if (assignment.getVariableRateUnits() == null)\n {\n Duration workingDays = assignment.getCalendar().getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.DAYS);\n double units = NumberHelper.getDouble(assignment.getUnits());\n double unitsPerDayAsMinutes = (units * 60) / (workingDays.getDuration() * 100);\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n else\n {\n double unitsPerHour = NumberHelper.getDouble(assignment.getUnits());\n workPerDay = ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n Duration hoursPerDay = workPerDay.convertUnits(TimeUnit.HOURS, file.getProjectProperties());\n double unitsPerDayAsHours = (unitsPerHour * hoursPerDay.getDuration()) / 100;\n double unitsPerDayAsMinutes = unitsPerDayAsHours * 60;\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n }\n\n Duration overtimeWork = assignment.getOvertimeWork();\n if (overtimeWork != null && overtimeWork.getDuration() != 0)\n {\n Duration totalOvertimeMinutes = overtimeWork.convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n totalMinutes = Duration.getInstance(totalMinutes.getDuration() - totalOvertimeMinutes.getDuration(), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(assignment.getStart());\n tra.setAmountPerDay(workPerDay);\n tra.setModified(false);\n tra.setFinish(assignment.getFinish());\n tra.setTotalAmount(totalMinutes);\n timephasedPlanned.add(tra);\n }\n }",
"@SuppressWarnings(\"resource\")\n public static FileChannel openChannel(File file, boolean mutable) throws IOException {\n if (mutable) {\n return new RandomAccessFile(file, \"rw\").getChannel();\n }\n return new FileInputStream(file).getChannel();\n }",
"public static void startTrack(final Object... args){\r\n if(isClosed){ return; }\r\n //--Create Record\r\n final int len = args.length == 0 ? 0 : args.length-1;\r\n final Object content = args.length == 0 ? \"\" : args[len];\r\n final Object[] tags = new Object[len];\r\n final StackTraceElement ste = getStackTrace();\r\n final long timestamp = System.currentTimeMillis();\r\n System.arraycopy(args,0,tags,0,len);\r\n //--Create Task\r\n final long threadID = Thread.currentThread().getId();\r\n final Runnable startTrack = new Runnable(){\r\n public void run(){\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n Record toPass = new Record(content,tags,depth,ste,timestamp);\r\n depth += 1;\r\n titleStack.push(args.length == 0 ? \"\" : args[len].toString());\r\n handlers.process(toPass, MessageType.START_TRACK, depth, toPass.timesstamp);\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n long threadId = Thread.currentThread().getId();\r\n attemptThreadControl( threadId, startTrack );\r\n } else {\r\n //(case: no threading)\r\n startTrack.run();\r\n }\r\n }"
] |
Use this API to update snmpalarm. | [
"public static base_response update(nitro_service client, snmpalarm resource) throws Exception {\n\t\tsnmpalarm updateresource = new snmpalarm();\n\t\tupdateresource.trapname = resource.trapname;\n\t\tupdateresource.thresholdvalue = resource.thresholdvalue;\n\t\tupdateresource.normalvalue = resource.normalvalue;\n\t\tupdateresource.time = resource.time;\n\t\tupdateresource.state = resource.state;\n\t\tupdateresource.severity = resource.severity;\n\t\tupdateresource.logging = resource.logging;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"private void checkInitializationMethod(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String initMethodName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_INITIALIZATION_METHOD);\r\n\r\n if (initMethodName == null)\r\n {\r\n return;\r\n }\r\n\r\n Class initClass;\r\n Method initMethod;\r\n\r\n try\r\n {\r\n initClass = InheritanceHelper.getClass(classDef.getName());\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" was not found on the classpath\");\r\n }\r\n try\r\n {\r\n initMethod = initClass.getDeclaredMethod(initMethodName, new Class[0]);\r\n }\r\n catch (NoSuchMethodException ex)\r\n {\r\n initMethod = null;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new ConstraintException(\"Exception while checking the class \"+classDef.getName()+\": \"+ex.getMessage());\r\n }\r\n if (initMethod == null)\r\n { \r\n try\r\n {\r\n initMethod = initClass.getMethod(initMethodName, new Class[0]);\r\n }\r\n catch (NoSuchMethodException ex)\r\n {\r\n throw new ConstraintException(\"No suitable initialization-method \"+initMethodName+\" found in class \"+classDef.getName());\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new ConstraintException(\"Exception while checking the class \"+classDef.getName()+\": \"+ex.getMessage());\r\n }\r\n }\r\n\r\n // checking modifiers\r\n int mods = initMethod.getModifiers();\r\n\r\n if (Modifier.isStatic(mods) || Modifier.isAbstract(mods))\r\n {\r\n throw new ConstraintException(\"The initialization-method \"+initMethodName+\" in class \"+classDef.getName()+\" must be a concrete instance method\");\r\n }\r\n }",
"public static boolean setCustomResponseForDefaultClient(String profileName, String pathName, String customData) {\n try {\n return setCustomForDefaultClient(profileName, pathName, true, customData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public static Date parseEpochTimestamp(String value)\n {\n Date result = null;\n\n if (value.length() > 0)\n {\n if (!value.equals(\"-1 -1\"))\n {\n Calendar cal = DateHelper.popCalendar(JAVA_EPOCH);\n\n int index = value.indexOf(' ');\n if (index == -1)\n {\n if (value.length() < 6)\n {\n value = \"000000\" + value;\n value = value.substring(value.length() - 6);\n }\n\n int hours = Integer.parseInt(value.substring(0, 2));\n int minutes = Integer.parseInt(value.substring(2, 4));\n int seconds = Integer.parseInt(value.substring(4));\n\n cal.set(Calendar.HOUR, hours);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, seconds);\n }\n else\n {\n long astaDays = Long.parseLong(value.substring(0, index));\n int astaSeconds = Integer.parseInt(value.substring(index + 1));\n\n cal.add(Calendar.DAY_OF_YEAR, (int) (astaDays - ASTA_EPOCH));\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.HOUR, 0);\n cal.add(Calendar.SECOND, astaSeconds);\n }\n\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n }\n\n return result;\n }",
"public void refreshConnection() throws SQLException{\r\n\t\tthis.connection.close(); // if it's still in use, close it.\r\n\t\ttry{\r\n\t\t\tthis.connection = this.pool.obtainRawInternalConnection();\r\n\t\t} catch(SQLException e){\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}",
"public static String keyVersionToString(ByteArray key,\n Map<Value, Set<ClusterNode>> versionMap,\n String storeName,\n Integer partitionId) {\n StringBuilder record = new StringBuilder();\n for (Map.Entry<Value, Set<ClusterNode>> versionSet : versionMap.entrySet()) {\n Value value = versionSet.getKey();\n Set<ClusterNode> nodeSet = versionSet.getValue();\n\n record.append(\"BAD_KEY,\");\n record.append(storeName + \",\");\n record.append(partitionId + \",\");\n record.append(ByteUtils.toHexString(key.get()) + \",\");\n record.append(nodeSet.toString().replace(\", \", \";\") + \",\");\n record.append(value.toString());\n }\n return record.toString();\n }",
"public ItemRequest<Workspace> addUser(String workspace) {\n \n String path = String.format(\"/workspaces/%s/addUser\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"POST\");\n }",
"public String getString(Integer id, Integer type)\n {\n return (getString(m_meta.getOffset(id, type)));\n }",
"private void writeTaskExtendedAttributes(Project.Tasks.Task xml, Task mpx)\n {\n Project.Tasks.Task.ExtendedAttribute attrib;\n List<Project.Tasks.Task.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (TaskField mpxFieldID : getAllTaskExtendedAttributes())\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(MPPTaskField.getID(mpxFieldID) | MPPTaskField.TASK_FIELD_BASE);\n\n attrib = m_factory.createProjectTasksTaskExtendedAttribute();\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 }",
"public Session startSshSessionAndObtainSession() {\n\n Session session = null;\n try {\n\n JSch jsch = new JSch();\n if (sshMeta.getSshLoginType() == SshLoginType.KEY) {\n\n String workingDir = System.getProperty(\"user.dir\");\n String privKeyAbsPath = workingDir + \"/\"\n + sshMeta.getPrivKeyRelativePath();\n logger.debug(\"use privkey: path: \" + privKeyAbsPath);\n\n if (!PcFileNetworkIoUtils.isFileExist(privKeyAbsPath)) {\n throw new RuntimeException(\"file not found at \"\n + privKeyAbsPath);\n }\n\n if (sshMeta.isPrivKeyUsePassphrase()\n && sshMeta.getPassphrase() != null) {\n jsch.addIdentity(privKeyAbsPath, sshMeta.getPassphrase());\n } else {\n jsch.addIdentity(privKeyAbsPath);\n }\n }\n\n session = jsch.getSession(sshMeta.getUserName(), targetHost,\n sshMeta.getSshPort());\n if (sshMeta.getSshLoginType() == SshLoginType.PASSWORD) {\n session.setPassword(sshMeta.getPassword());\n }\n\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n } catch (Exception t) {\n throw new RuntimeException(t);\n }\n return session;\n }"
] |
Filter on a search term. Can be course name, code or full ID. Must be at least 3 characters
@param searchTerm Search term to filter by
@return This object to allow adding more options | [
"public ListActiveCoursesInAccountOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }"
] | [
"@CheckReturnValue\n private LocalSyncWriteModelContainer resolveConflict(\n final NamespaceSynchronizationConfig nsConfig,\n final CoreDocumentSynchronizationConfig docConfig,\n final ChangeEvent<BsonDocument> remoteEvent\n ) {\n return resolveConflict(nsConfig, docConfig, docConfig.getLastUncommittedChangeEvent(),\n remoteEvent);\n }",
"public void generateOutlineNumber(Task parent)\n {\n String outline;\n\n if (parent == null)\n {\n if (NumberHelper.getInt(getUniqueID()) == 0)\n {\n outline = \"0\";\n }\n else\n {\n outline = Integer.toString(getParentFile().getChildTasks().size() + 1);\n }\n }\n else\n {\n outline = parent.getOutlineNumber();\n\n int index = outline.lastIndexOf(\".0\");\n\n if (index != -1)\n {\n outline = outline.substring(0, index);\n }\n\n int childTaskCount = parent.getChildTasks().size() + 1;\n if (outline.equals(\"0\"))\n {\n outline = Integer.toString(childTaskCount);\n }\n else\n {\n outline += (\".\" + childTaskCount);\n }\n }\n\n setOutlineNumber(outline);\n }",
"public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {\n\t\tDuration duration = Duration.between(referenceDate, date);\n\t\treturn ((double)duration.getSeconds()) / SECONDS_PER_DAY;\n\t}",
"private static Pod getRandomPod(KubernetesClient client, String name, String namespace) {\n Endpoints endpoints = client.endpoints().inNamespace(namespace).withName(name).get();\n List<String> pods = new ArrayList<>();\n if (endpoints != null) {\n for (EndpointSubset subset : endpoints.getSubsets()) {\n for (EndpointAddress address : subset.getAddresses()) {\n if (address.getTargetRef() != null && POD.equals(address.getTargetRef().getKind())) {\n String pod = address.getTargetRef().getName();\n if (pod != null && !pod.isEmpty()) {\n pods.add(pod);\n }\n }\n }\n }\n }\n if (pods.isEmpty()) {\n return null;\n } else {\n String chosen = pods.get(RANDOM.nextInt(pods.size()));\n return client.pods().inNamespace(namespace).withName(chosen).get();\n }\n }",
"public Optional<URL> getServiceUrl(String name) {\n Service service = client.services().inNamespace(namespace).withName(name).get();\n return service != null ? createUrlForService(service) : Optional.empty();\n }",
"public static CompressionType getDumpFileCompressionType(String fileName) {\n\t\tif (fileName.endsWith(\".gz\")) {\n\t\t\treturn CompressionType.GZIP;\n\t\t} else if (fileName.endsWith(\".bz2\")) {\n\t\t\treturn CompressionType.BZ2;\n\t\t} else {\n\t\t\treturn CompressionType.NONE;\n\t\t}\n\t}",
"public void delete(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_DELETE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }",
"public void handleEvent(Event event) {\n LOG.fine(\"ContentLengthHandler called\");\n\n //if maximum length is shorter then <cut><![CDATA[ ]]></cut> it's not possible to cut the content\n if(CUT_START_TAG.length() + CUT_END_TAG.length() > length) {\n LOG.warning(\"Trying to cut content. But length is shorter then needed for \"\n + CUT_START_TAG + CUT_END_TAG + \". So content is skipped.\");\n event.setContent(\"\");\n return;\n }\n\n int currentLength = length - CUT_START_TAG.length() - CUT_END_TAG.length();\n\n if (event.getContent() != null && event.getContent().length() > length) {\n LOG.fine(\"cutting content to \" + currentLength\n + \" characters. Original length was \"\n + event.getContent().length());\n LOG.fine(\"Content before cutting: \" + event.getContent());\n event.setContent(CUT_START_TAG\n + event.getContent().substring(0, currentLength) + CUT_END_TAG);\n LOG.fine(\"Content after cutting: \" + event.getContent());\n }\n }",
"protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }"
] |
Determine the length of a nul terminated UTF16LE string in bytes.
@param data string data
@param offset offset into string data
@return length in bytes | [
"private static final int getUnicodeStringLengthInBytes(byte[] data, int offset)\n {\n int result;\n if (data == null || offset >= data.length)\n {\n result = 0;\n }\n else\n {\n result = data.length - offset;\n\n for (int loop = offset; loop < (data.length - 1); loop += 2)\n {\n if (data[loop] == 0 && data[loop + 1] == 0)\n {\n result = loop - offset;\n break;\n }\n }\n }\n return result;\n }"
] | [
"public void initialize() {\n if (isClosed.get()) {\n logger.info(\"Initialing Parallel Client Resources: actor system, HttpClientStore, Task Manager ....\");\n ActorConfig.createAndGetActorSystem();\n httpClientStore.init();\n tcpSshPingResourceStore.init();\n isClosed.set(false);\n logger.info(\"Parallel Client Resources has been initialized.\");\n } else {\n logger.debug(\"NO OP. Parallel Client Resources has already been initialized.\");\n }\n }",
"public static AbstractBuild<?, ?> getRootBuild(AbstractBuild<?, ?> currentBuild) {\n AbstractBuild<?, ?> rootBuild = null;\n AbstractBuild<?, ?> parentBuild = getUpstreamBuild(currentBuild);\n while (parentBuild != null) {\n if (isPassIdentifiedDownstream(parentBuild)) {\n rootBuild = parentBuild;\n }\n parentBuild = getUpstreamBuild(parentBuild);\n }\n if (rootBuild == null && isPassIdentifiedDownstream(currentBuild)) {\n return currentBuild;\n }\n return rootBuild;\n }",
"protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }",
"protected boolean check(String id, List<String> includes) {\n\t\tif (null != includes) {\n\t\t\tfor (String check : includes) {\n\t\t\t\tif (check(id, check)) {\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\n protected StatisticsMatrix createMatrix(int numRows, int numCols, MatrixType type) {\n return new StatisticsMatrix(numRows,numCols);\n }",
"public void setPerms(String photoId, Permissions permissions) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", permissions.isPublicFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", permissions.isFriendFlag() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", permissions.isFamilyFlag() ? \"1\" : \"0\");\r\n parameters.put(\"perm_comment\", Integer.toString(permissions.getComment()));\r\n parameters.put(\"perm_addmeta\", Integer.toString(permissions.getAddmeta()));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public ItemRequest<Tag> findById(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"GET\");\n }",
"public void startTask(int id, String taskName) {\n if (isActivated) {\n durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));\n }\n }",
"public static cachepolicy_cacheglobal_binding[] get(nitro_service service, String policyname) throws Exception{\n\t\tcachepolicy_cacheglobal_binding obj = new cachepolicy_cacheglobal_binding();\n\t\tobj.set_policyname(policyname);\n\t\tcachepolicy_cacheglobal_binding response[] = (cachepolicy_cacheglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Return the containing group if it contains exactly one element.
@since 2.14 | [
"protected AbstractElement getEnclosingSingleElementGroup(AbstractElement elementToParse) {\n\t\tEObject container = elementToParse.eContainer();\n\t\tif (container instanceof Group) {\n\t\t\tif (((Group) container).getElements().size() == 1) {\n\t\t\t\treturn (AbstractElement) container;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}"
] | [
"public static base_responses update(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy updateresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new dospolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].qdepth = resources[i].qdepth;\n\t\t\t\tupdateresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\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 }",
"static void export(String path, String queueName, DbConn cnx) throws JqmXmlException\n {\n // Argument tests\n if (queueName == null)\n {\n throw new IllegalArgumentException(\"queue name cannot be null\");\n }\n if (cnx == null)\n {\n throw new IllegalArgumentException(\"database connection cannot be null\");\n }\n Queue q = CommonXml.findQueue(queueName, cnx);\n if (q == null)\n {\n throw new IllegalArgumentException(\"there is no queue named \" + queueName);\n }\n\n List<Queue> l = new ArrayList<>();\n l.add(q);\n export(path, l, cnx);\n }",
"public static final long getLong6(byte[] data, int offset)\n {\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 48; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }",
"public static DMatrixRMaj extractColumn(DMatrixRMaj a , int column , DMatrixRMaj out ) {\n if( out == null)\n out = new DMatrixRMaj(a.numRows,1);\n else if( !MatrixFeatures_DDRM.isVector(out) || out.getNumElements() != a.numRows )\n throw new MatrixDimensionException(\"Output must be a vector of length \"+a.numRows);\n\n int index = column;\n for (int i = 0; i < a.numRows; i++, index += a.numCols ) {\n out.data[i] = a.data[index];\n }\n return out;\n }",
"@SuppressWarnings(\"unchecked\")\r\n public static boolean addPropertyDefault(PropertiesImpl props, PropertyDefinition<?> propDef) {\r\n\r\n if ((props == null) || (props.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Props must not be null!\");\r\n }\r\n\r\n if (propDef == null) {\r\n return false;\r\n }\r\n\r\n List<?> defaultValue = propDef.getDefaultValue();\r\n if ((defaultValue != null) && (!defaultValue.isEmpty())) {\r\n switch (propDef.getPropertyType()) {\r\n case BOOLEAN:\r\n props.addProperty(new PropertyBooleanImpl(propDef.getId(), (List<Boolean>)defaultValue));\r\n break;\r\n case DATETIME:\r\n props.addProperty(new PropertyDateTimeImpl(propDef.getId(), (List<GregorianCalendar>)defaultValue));\r\n break;\r\n case DECIMAL:\r\n props.addProperty(new PropertyDecimalImpl(propDef.getId(), (List<BigDecimal>)defaultValue));\r\n break;\r\n case HTML:\r\n props.addProperty(new PropertyHtmlImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case ID:\r\n props.addProperty(new PropertyIdImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case INTEGER:\r\n props.addProperty(new PropertyIntegerImpl(propDef.getId(), (List<BigInteger>)defaultValue));\r\n break;\r\n case STRING:\r\n props.addProperty(new PropertyStringImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case URI:\r\n props.addProperty(new PropertyUriImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n default:\r\n throw new RuntimeException(\"Unknown datatype! Spec change?\");\r\n }\r\n\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"private void deliverTrackMetadataUpdate(int player, TrackMetadata metadata) {\n if (!getTrackMetadataListeners().isEmpty()) {\n final TrackMetadataUpdate update = new TrackMetadataUpdate(player, metadata);\n for (final TrackMetadataListener listener : getTrackMetadataListeners()) {\n try {\n listener.metadataChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering track metadata update to listener\", t);\n }\n }\n }\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 }",
"public Map<String, String> getMapAttribute(String name, String defaultValue) {\n return mapSplit(getAttribute(name), defaultValue);\n }"
] |
Deletes a path from the filesystem
If the path is a directory its contents
will be recursively deleted before it itself
is deleted.
Note that removal of a directory is not an atomic-operation
and so if an error occurs during removal, some of the directories
descendants may have already been removed
@throws IOException if an error occurs whilst removing a file or directory | [
"public static void forceDelete(final Path path) throws IOException {\n\t\tif (!java.nio.file.Files.isDirectory(path)) {\n\t\t\tjava.nio.file.Files.delete(path);\n\t\t} else {\n\t\t\tjava.nio.file.Files.walkFileTree(path, DeleteDirVisitor.getInstance());\n\t\t}\n\t}"
] | [
"private int readOptionalInt(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n try {\n return Integer.valueOf(str.stringValue()).intValue();\n } catch (@SuppressWarnings(\"unused\") NumberFormatException e) {\n // Do nothing, return default value\n }\n }\n return 0;\n }",
"public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }",
"static TarArchiveEntry defaultDirEntryWithName( final String dirName ) {\n TarArchiveEntry entry = new TarArchiveEntry(dirName, true);\n entry.setUserId(ROOT_UID);\n entry.setUserName(ROOT_NAME);\n entry.setGroupId(ROOT_UID);\n entry.setGroupName(ROOT_NAME);\n entry.setMode(TarArchiveEntry.DEFAULT_DIR_MODE);\n return entry;\n }",
"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 final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }",
"private void writeMap(String fieldName, Object value) throws IOException\n {\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> map = (Map<String, Object>) value;\n m_writer.writeStartObject(fieldName);\n for (Map.Entry<String, Object> entry : map.entrySet())\n {\n Object entryValue = entry.getValue();\n if (entryValue != null)\n {\n DataType type = TYPE_MAP.get(entryValue.getClass().getName());\n if (type == null)\n {\n type = DataType.STRING;\n entryValue = entryValue.toString();\n }\n writeField(entry.getKey(), type, entryValue);\n }\n }\n m_writer.writeEndObject();\n }",
"public static Artifact withVersion(Version v)\n {\n Artifact artifact = new Artifact();\n artifact.version = v;\n return artifact;\n }",
"private TableAlias getTableAliasForPath(String aPath, String aUserAlias, List hintClasses)\r\n {\r\n if (aUserAlias == null)\r\n {\r\n return getTableAliasForPath(aPath, hintClasses);\r\n }\r\n else\r\n {\r\n\t\t\treturn getTableAliasForPath(aUserAlias + ALIAS_SEPARATOR + aPath, hintClasses);\r\n }\r\n }",
"public static void resetNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).reset();\n\t}"
] |
private HttpServletResponse headers; | [
"@Override\n public Response toResponse(ErrorDto e)\n {\n // String type = headers.getContentType() == null ? MediaType.APPLICATION_JSON : headers.getContentType();\n return Response.status(e.httpStatus).entity(e).type(MediaType.APPLICATION_JSON).build();\n }"
] | [
"public static base_response update(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy updateresource = new spilloverpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.action = resource.action;\n\t\tupdateresource.comment = resource.comment;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void deselectChildren(CmsTreeItem item) {\r\n\r\n for (String childId : m_childrens.get(item.getId())) {\r\n CmsTreeItem child = m_categories.get(childId);\r\n deselectChildren(child);\r\n child.getCheckBox().setChecked(false);\r\n if (m_selectedCategories.contains(childId)) {\r\n m_selectedCategories.remove(childId);\r\n }\r\n }\r\n }",
"public static void acceptsFormat(OptionParser parser) {\n parser.accepts(OPT_FORMAT, \"format of key or entry, could be hex, json or binary\")\n .withRequiredArg()\n .describedAs(\"hex | json | binary\")\n .ofType(String.class);\n }",
"protected final void addPathTo(final StringBuilder result) {\n if (this.parent != null) {\n this.parent.addPathTo(result);\n if (!(this.parent instanceof PJsonArray)) {\n result.append(\".\");\n }\n }\n result.append(getPathElement(this.contextName));\n }",
"public static final Date parseFinishDateTime(String value)\n {\n Date result = parseDateTime(value);\n if (result != null)\n {\n result = DateHelper.addDays(result, -1);\n }\n return result;\n }",
"public void setHomeAsUpIndicator(Drawable indicator) {\n if(!deviceSupportMultiPane()) {\n pulsante.setHomeAsUpIndicator(indicator);\n }\n else {\n actionBar.setHomeAsUpIndicator(indicator);\n }\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 }",
"public void finished() throws Throwable {\n if( state == FINISHED ) {\n return;\n }\n\n State previousState = state;\n\n state = FINISHED;\n methodInterceptor.enableMethodInterception( false );\n\n try {\n if( previousState == STARTED ) {\n callFinishLifeCycleMethods();\n }\n } finally {\n listener.scenarioFinished();\n }\n }",
"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 }"
] |
Build call for postUiAutopilotWaypoint
@param addToBeginning
Whether this solar system should be added to the beginning of
all waypoints (required)
@param clearOtherWaypoints
Whether clean other waypoints beforing adding this one
(required)
@param destinationId
The destination to travel to, can be solar system, station or
structure's id (required)
@param datasource
The server name you would like data from (optional, default to
tranquility)
@param token
Access token to use if unable to set a header (optional)
@param callback
Callback for upload/download progress
@return Call to execute
@throws ApiException
If fail to serialize the request body object | [
"public com.squareup.okhttp.Call postUiAutopilotWaypointCall(Boolean addToBeginning, Boolean clearOtherWaypoints,\n Long destinationId, String datasource, String token, final ApiCallback callback) throws ApiException {\n Object localVarPostBody = new Object();\n\n // create path and map variables\n String localVarPath = \"/v2/ui/autopilot/waypoint/\";\n\n List<Pair> localVarQueryParams = new ArrayList<Pair>();\n List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();\n if (addToBeginning != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"add_to_beginning\", addToBeginning));\n }\n\n if (clearOtherWaypoints != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"clear_other_waypoints\", clearOtherWaypoints));\n }\n\n if (datasource != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"datasource\", datasource));\n }\n\n if (destinationId != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"destination_id\", destinationId));\n }\n\n if (token != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"token\", token));\n }\n\n Map<String, String> localVarHeaderParams = new HashMap<String, String>();\n Map<String, Object> localVarFormParams = new HashMap<String, Object>();\n final String[] localVarAccepts = {\n\n };\n final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);\n if (localVarAccept != null) {\n localVarHeaderParams.put(\"Accept\", localVarAccept);\n }\n\n final String[] localVarContentTypes = {\n\n };\n final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);\n localVarHeaderParams.put(\"Content-Type\", localVarContentType);\n\n String[] localVarAuthNames = new String[] { \"evesso\" };\n return apiClient.buildCall(localVarPath, \"POST\", localVarQueryParams, localVarCollectionQueryParams,\n localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);\n }"
] | [
"public ExecutionChain setErrorCallback(ErrorCallback callback) {\n if (state.get() == State.RUNNING) {\n throw new IllegalStateException(\n \"Invalid while ExecutionChain is running\");\n }\n errorCallback = callback;\n return this;\n }",
"private void readPattern(JSONObject patternJson) {\n\n setPatternType(readPatternType(patternJson));\n setInterval(readOptionalInt(patternJson, JsonKey.PATTERN_INTERVAL));\n setWeekDays(readWeekDays(patternJson));\n setDayOfMonth(readOptionalInt(patternJson, JsonKey.PATTERN_DAY_OF_MONTH));\n setEveryWorkingDay(readOptionalBoolean(patternJson, JsonKey.PATTERN_EVERYWORKINGDAY));\n setWeeksOfMonth(readWeeksOfMonth(patternJson));\n setIndividualDates(readDates(readOptionalArray(patternJson, JsonKey.PATTERN_DATES)));\n setMonth(readOptionalMonth(patternJson, JsonKey.PATTERN_MONTH));\n\n }",
"private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n for ( int i = 0; i < mEmitRate * 2; i +=2 )\n {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n return timeStamps;\n }",
"public Date getDate(String path) throws ParseException {\n return BoxDateFormat.parse(this.getValue(path).asString());\n }",
"public void setWorkDir(String dir) throws IOException\r\n {\r\n File workDir = new File(dir);\r\n\r\n if (!workDir.exists() || !workDir.canWrite() || !workDir.canRead())\r\n {\r\n throw new IOException(\"Cannot access directory \"+dir);\r\n }\r\n _workDir = workDir;\r\n }",
"public static void doBatchEnqueue(final Jedis jedis, final String namespace, final String queue, final List<String> jobJsons) {\n Pipeline pipelined = jedis.pipelined();\n pipelined.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n for (String jobJson : jobJsons) {\n pipelined.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }\n pipelined.sync();\n }",
"public List<TimephasedWork> getTimephasedBaselineWork(int index)\n {\n return m_timephasedBaselineWork[index] == null ? null : m_timephasedBaselineWork[index].getData();\n }",
"private static <D, T> D createDaoFromConfig(ConnectionSource connectionSource, Class<T> clazz) throws SQLException {\n\t\t// no loaded configs\n\t\tif (configMap == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDatabaseTableConfig<T> config = (DatabaseTableConfig<T>) configMap.get(clazz);\n\t\t// if we don't config information cached return null\n\t\tif (config == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// else create a DAO using configuration\n\t\tDao<T, ?> configedDao = doCreateDao(connectionSource, config);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) configedDao;\n\t\treturn castDao;\n\t}",
"private void writeProjectProperties()\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n\n m_plannerProject.setCompany(properties.getCompany());\n m_plannerProject.setManager(properties.getManager());\n m_plannerProject.setName(getString(properties.getName()));\n m_plannerProject.setProjectStart(getDateTime(properties.getStartDate()));\n m_plannerProject.setCalendar(getIntegerString(m_projectFile.getDefaultCalendar().getUniqueID()));\n m_plannerProject.setMrprojectVersion(\"2\");\n }"
] |
This method extracts data for a single predecessor from an MSPDI file.
@param currTask Current task object
@param link Predecessor data | [
"private void readPredecessor(Task currTask, Project.Tasks.Task.PredecessorLink link)\n {\n BigInteger uid = link.getPredecessorUID();\n if (uid != null)\n {\n Task prevTask = m_projectFile.getTaskByUniqueID(Integer.valueOf(uid.intValue()));\n if (prevTask != null)\n {\n RelationType type;\n if (link.getType() != null)\n {\n type = RelationType.getInstance(link.getType().intValue());\n }\n else\n {\n type = RelationType.FINISH_START;\n }\n\n TimeUnit lagUnits = DatatypeConverter.parseDurationTimeUnits(link.getLagFormat());\n\n Duration lagDuration;\n int lag = NumberHelper.getInt(link.getLinkLag());\n if (lag == 0)\n {\n lagDuration = Duration.getInstance(0, lagUnits);\n }\n else\n {\n if (lagUnits == TimeUnit.PERCENT || lagUnits == TimeUnit.ELAPSED_PERCENT)\n {\n lagDuration = Duration.getInstance(lag, lagUnits);\n }\n else\n {\n lagDuration = Duration.convertUnits(lag / 10.0, TimeUnit.MINUTES, lagUnits, m_projectFile.getProjectProperties());\n }\n }\n\n Relation relation = currTask.addPredecessor(prevTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }"
] | [
"public void close() throws IOException {\n for (CloseableHttpClient c : cachedClients.values()) {\n c.close();\n }\n cachedClients.clear();\n }",
"public static String get(String url, Map<String, String> customHeaders, Map<String, String> params) throws URISyntaxException, IOException, HTTPException {\n LOGGER.log(Level.INFO, \"Sending GET request to the url {0}\", url);\n\n URIBuilder uriBuilder = new URIBuilder(url);\n\n if (params != null && params.size() > 0) {\n for (Map.Entry<String, String> param : params.entrySet()) {\n uriBuilder.setParameter(param.getKey(), param.getValue());\n }\n }\n\n HttpGet httpGet = new HttpGet(uriBuilder.build());\n\n populateHeaders(httpGet, customHeaders);\n\n HttpClient httpClient = HttpClientBuilder.create().build();\n\n HttpResponse httpResponse = httpClient.execute(httpGet);\n\n int statusCode = httpResponse.getStatusLine().getStatusCode();\n if (isErrorStatus(statusCode)) {\n String jsonErrorResponse = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n throw new HTTPException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), jsonErrorResponse);\n }\n\n return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n }",
"public void forAllProcedureArguments(String template, Properties attributes) throws XDocletException\r\n {\r\n String argNameList = _curProcedureDef.getProperty(PropertyHelper.OJB_PROPERTY_ARGUMENTS);\r\n\r\n for (CommaListIterator it = new CommaListIterator(argNameList); it.hasNext();)\r\n {\r\n _curProcedureArgumentDef = _curClassDef.getProcedureArgument(it.getNext());\r\n generate(template);\r\n }\r\n _curProcedureArgumentDef = null;\r\n }",
"@Override\n public void setActive(boolean active) {\n this.active = active;\n\n if (parent != null) {\n fireCollapsibleHandler();\n removeStyleName(CssName.ACTIVE);\n if (header != null) {\n header.removeStyleName(CssName.ACTIVE);\n }\n if (active) {\n if (parent != null && parent.isAccordion()) {\n parent.clearActive();\n }\n addStyleName(CssName.ACTIVE);\n\n if (header != null) {\n header.addStyleName(CssName.ACTIVE);\n }\n }\n\n if (body != null) {\n body.setDisplay(active ? Display.BLOCK : Display.NONE);\n }\n } else {\n GWT.log(\"Please make sure that the Collapsible parent is attached or existed.\", new IllegalStateException());\n }\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n final Set<DeviceAnnouncement> lastDevices = getCurrentDevices();\n socket.get().close();\n socket.set(null);\n devices.clear();\n firstDeviceTime.set(0);\n // Report the loss of all our devices, on the proper thread, outside our lock\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeviceAnnouncement announcement : lastDevices) {\n deliverLostAnnouncement(announcement);\n }\n }\n });\n deliverLifecycleAnnouncement(logger, false);\n }\n }",
"private static String mapContent(DataHandler dh) {\n if (dh == null) {\n return \"\";\n }\n try {\n InputStream is = dh.getInputStream();\n String content = IOUtils.toString(is);\n is.close();\n return content;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }",
"public B set(String key, int value) {\n this.data.put(key, value);\n return (B) this;\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public String getProperty(Enum<?> key, boolean lowerCase) {\n final String keyName;\n if (lowerCase) {\n keyName = key.name().toLowerCase(Locale.ENGLISH);\n } else {\n keyName = key.name();\n }\n return getProperty(keyName);\n }",
"public void createPath(String pathName, String pathValue, String requestType) {\n try {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"pathName\", pathName),\n new BasicNameValuePair(\"path\", pathValue),\n new BasicNameValuePair(\"requestType\", String.valueOf(type)),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH, params));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }"
] |
Gets any assignments for this task.
@return a list of assignments for this task. | [
"public List<BoxTaskAssignment.Info> getAssignments() {\n URL url = GET_ASSIGNMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTaskAssignment.Info> assignments = new ArrayList<BoxTaskAssignment.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject assignmentJSON = value.asObject();\n BoxTaskAssignment assignment = new BoxTaskAssignment(this.getAPI(), assignmentJSON.get(\"id\").asString());\n BoxTaskAssignment.Info info = assignment.new Info(assignmentJSON);\n assignments.add(info);\n }\n\n return assignments;\n }"
] | [
"public static File createFolder(String path, String dest_dir)\n throws BeastException {\n File f = new File(dest_dir);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n logger.severe(\"Problem creating directory: \" + path\n + File.separator + dest_dir);\n }\n }\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n String message = \"Problem creating directory: \" + path\n + File.separator + dest_dir;\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n\n return f;\n }",
"private void handleSerialApiGetInitDataResponse(\n\t\t\tSerialMessage incomingMessage) {\n\t\tlogger.debug(String.format(\"Got MessageSerialApiGetInitData response.\"));\n\t\tthis.isConnected = true;\n\t\tint nodeBytes = incomingMessage.getMessagePayloadByte(2);\n\t\t\n\t\tif (nodeBytes != NODE_BYTES) {\n\t\t\tlogger.error(\"Invalid number of node bytes = {}\", nodeBytes);\n\t\t\treturn;\n\t\t}\n\n\t\tint nodeId = 1;\n\t\t\n\t\t// loop bytes\n\t\tfor (int i = 3;i < 3 + nodeBytes;i++) {\n\t\t\tint incomingByte = incomingMessage.getMessagePayloadByte(i);\n\t\t\t// loop bits in byte\n\t\t\tfor (int j=0;j<8;j++) {\n\t\t\t\tint b1 = incomingByte & (int)Math.pow(2.0D, j);\n\t\t\t\tint b2 = (int)Math.pow(2.0D, j);\n\t\t\t\tif (b1 == b2) {\n\t\t\t\t\tlogger.info(String.format(\"Found node id = %d\", nodeId));\n\t\t\t\t\t// Place nodes in the local ZWave Controller \n\t\t\t\t\tthis.zwaveNodes.put(nodeId, new ZWaveNode(this.homeId, nodeId, this));\n\t\t\t\t\tthis.getNode(nodeId).advanceNodeStage();\n\t\t\t\t}\n\t\t\t\tnodeId++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tlogger.info(\"------------Number of Nodes Found Registered to ZWave Controller------------\");\n\t\tlogger.info(String.format(\"# Nodes = %d\", this.zwaveNodes.size()));\n\t\tlogger.info(\"----------------------------------------------------------------------------\");\n\t\t\n\t\t// Advance node stage for the first node.\n\t}",
"public List<Class<?>> scanClasses(Predicate<String> filter)\n {\n List<Class<?>> discoveredClasses = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> discoveredFileNames = filterAddonResources(addon, filter);\n\n // Then try to load the classes.\n for (String discoveredFilename : discoveredFileNames)\n {\n String clsName = PathUtil.classFilePathToClassname(discoveredFilename);\n try\n {\n Class<?> clazz = addon.getClassLoader().loadClass(clsName);\n discoveredClasses.add(clazz);\n }\n catch (ClassNotFoundException ex)\n {\n LOG.log(Level.WARNING, \"Failed to load class for name '\" + clsName + \"':\\n\" + ex.getMessage(), ex);\n }\n }\n }\n return discoveredClasses;\n }",
"public static nd6ravariables[] get(nitro_service service, options option) throws Exception{\n\t\tnd6ravariables obj = new nd6ravariables();\n\t\tnd6ravariables[] response = (nd6ravariables[])obj.get_resources(service,option);\n\t\treturn response;\n\t}",
"public void setModel(Database databaseModel, DescriptorRepository objModel)\r\n {\r\n _dbModel = databaseModel;\r\n _preparedModel = new PreparedModel(objModel, databaseModel);\r\n }",
"protected void update(float scale) {\n // Updates only when the plane is in the scene\n GVRSceneObject owner = getOwnerObject();\n\n if ((owner != null) && isEnabled() && owner.isEnabled())\n {\n convertFromARtoVRSpace(scale);\n }\n }",
"public void addDependency(final ProcessorGraphNode node) {\n Assert.isTrue(node != this, \"A processor can't depends on himself\");\n\n this.dependencies.add(node);\n node.addRequirement(this);\n }",
"public void enable(ConduitSelectorHolder conduitSelectorHolder, SLPropertiesMatcher matcher,\n String selectionStrategy) {\n LocatorTargetSelector selector = new LocatorTargetSelector();\n selector.setEndpoint(conduitSelectorHolder.getConduitSelector().getEndpoint());\n\n String actualStrategy = selectionStrategy != null ? selectionStrategy : defaultLocatorSelectionStrategy;\n \n LocatorSelectionStrategy locatorSelectionStrategy = getLocatorSelectionStrategy(actualStrategy);\n locatorSelectionStrategy.setServiceLocator(locatorClient);\n if (matcher != null) {\n locatorSelectionStrategy.setMatcher(matcher);\n }\n selector.setLocatorSelectionStrategy(locatorSelectionStrategy);\n\n if (LOG.isLoggable(Level.INFO)) {\n LOG.log(Level.INFO, \"Client enabled with strategy \"\n + locatorSelectionStrategy.getClass().getName() + \".\");\n }\n conduitSelectorHolder.setConduitSelector(selector);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Successfully enabled client \" + conduitSelectorHolder\n + \" for the service locator\");\n }\n }",
"public final void save(final PrintJobStatusExtImpl entry) {\n getSession().merge(entry);\n getSession().flush();\n getSession().evict(entry);\n }"
] |
Adds to this set all of the elements in the specified map of members and their score.
@param scoredMember the members to add together with their scores
@return the number of members actually added | [
"public long addAll(final Map<String, Double> scoredMember) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zadd(getKey(), scoredMember);\n }\n });\n }"
] | [
"private static String getFileName(@Nullable final MapPrinter mapPrinter, final PJsonObject spec) {\n String fileName = spec.optString(Constants.OUTPUT_FILENAME_KEY);\n if (fileName != null) {\n return fileName;\n }\n\n if (mapPrinter != null) {\n final Configuration config = mapPrinter.getConfiguration();\n final String templateName = spec.getString(Constants.JSON_LAYOUT_KEY);\n\n final Template template = config.getTemplate(templateName);\n\n if (template.getOutputFilename() != null) {\n return template.getOutputFilename();\n }\n\n if (config.getOutputFilename() != null) {\n return config.getOutputFilename();\n }\n }\n return \"mapfish-print-report\";\n }",
"public static <T> PollingState<T> create(Response<ResponseBody> response, LongRunningOperationOptions lroOptions, int defaultRetryTimeout, Type resourceType, SerializerAdapter<?> serializerAdapter) throws IOException {\n PollingState<T> pollingState = new PollingState<>();\n pollingState.initialHttpMethod = response.raw().request().method();\n pollingState.defaultRetryTimeout = defaultRetryTimeout;\n pollingState.withResponse(response);\n pollingState.resourceType = resourceType;\n pollingState.serializerAdapter = serializerAdapter;\n pollingState.loggingContext = response.raw().request().header(LOGGING_HEADER);\n pollingState.finalStateVia = lroOptions.finalStateVia();\n\n String responseContent = null;\n PollingResource resource = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n if (responseContent != null && !responseContent.isEmpty()) {\n pollingState.resource = serializerAdapter.deserialize(responseContent, resourceType);\n resource = serializerAdapter.deserialize(responseContent, PollingResource.class);\n }\n final int statusCode = pollingState.response.code();\n if (resource != null && resource.properties != null\n && resource.properties.provisioningState != null) {\n pollingState.withStatus(resource.properties.provisioningState, statusCode);\n } else {\n switch (statusCode) {\n case 202:\n pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode);\n break;\n case 204:\n case 201:\n case 200:\n pollingState.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode);\n break;\n default:\n pollingState.withStatus(AzureAsyncOperation.FAILED_STATUS, statusCode);\n }\n }\n return pollingState;\n }",
"private void deliverFaderStartCommand(Set<Integer> playersToStart, Set<Integer> playersToStop) {\n for (final FaderStartListener listener : getFaderStartListeners()) {\n try {\n listener.fadersChanged(playersToStart, playersToStop);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering fader start command to listener\", t);\n }\n }\n }",
"public static String getVariablesMapExpression(Collection variables) {\n StringBuilder variablesMap = new StringBuilder(\"new \" + PropertiesMap.class.getName() + \"()\");\n for (Object variable : variables) {\n JRVariable jrvar = (JRVariable) variable;\n String varname = jrvar.getName();\n variablesMap.append(\".with(\\\"\").append(varname).append(\"\\\",$V{\").append(varname).append(\"})\");\n }\n return variablesMap.toString();\n }",
"@Override\n\tpublic EmbeddedBrowser get() {\n\t\tLOGGER.debug(\"Setting up a Browser\");\n\t\t// Retrieve the config values used\n\t\tImmutableSortedSet<String> filterAttributes =\n\t\t\t\tconfiguration.getCrawlRules().getPreCrawlConfig().getFilterAttributeNames();\n\t\tlong crawlWaitReload = configuration.getCrawlRules().getWaitAfterReloadUrl();\n\t\tlong crawlWaitEvent = configuration.getCrawlRules().getWaitAfterEvent();\n\n\t\t// Determine the requested browser type\n\t\tEmbeddedBrowser browser = null;\n\t\tEmbeddedBrowser.BrowserType browserType =\n\t\t\t\tconfiguration.getBrowserConfig().getBrowserType();\n\t\ttry {\n\t\t\tswitch (browserType) {\n\t\t\t\tcase CHROME:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHROME_HEADLESS:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload,\n\t\t\t\t\t\t\tcrawlWaitEvent, true);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX_HEADLESS:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\ttrue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOTE:\n\t\t\t\t\tbrowser = WebDriverBackedEmbeddedBrowser.withRemoteDriver(\n\t\t\t\t\t\t\tconfiguration.getBrowserConfig().getRemoteHubUrl(), filterAttributes,\n\t\t\t\t\t\t\tcrawlWaitEvent, crawlWaitReload);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHANTOMJS:\n\t\t\t\t\tbrowser =\n\t\t\t\t\t\t\tnewPhantomJSDriver(filterAttributes, crawlWaitReload, crawlWaitEvent);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unrecognized browser type \"\n\t\t\t\t\t\t\t+ configuration.getBrowserConfig().getBrowserType());\n\t\t\t}\n\t\t} catch (IllegalStateException e) {\n\t\t\tLOGGER.error(\"Crawling with {} failed: \" + e.getMessage(), browserType.toString());\n\t\t\tthrow e;\n\t\t}\n\n\t\t/* for Retina display. */\n\t\tif (browser instanceof WebDriverBackedEmbeddedBrowser) {\n\t\t\tint pixelDensity =\n\t\t\t\t\tthis.configuration.getBrowserConfig().getBrowserOptions().getPixelDensity();\n\t\t\tif (pixelDensity != -1)\n\t\t\t\t((WebDriverBackedEmbeddedBrowser) browser).setPixelDensity(pixelDensity);\n\t\t}\n\n\t\tplugins.runOnBrowserCreatedPlugins(browser);\n\t\treturn browser;\n\t}",
"private long doMemoryManagementAndPerFrameCallbacks() {\n long currentTime = GVRTime.getCurrentTime();\n mFrameTime = (currentTime - mPreviousTimeNanos) / 1e9f;\n mPreviousTimeNanos = currentTime;\n\n /*\n * Without the sensor data, can't draw a scene properly.\n */\n if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) {\n Runnable runnable;\n while ((runnable = mRunnables.poll()) != null) {\n try {\n runnable.run();\n } catch (final Exception exc) {\n Log.e(TAG, \"Runnable-on-GL %s threw %s\", runnable, exc.toString());\n exc.printStackTrace();\n }\n }\n\n final List<GVRDrawFrameListener> frameListeners = mFrameListeners;\n for (GVRDrawFrameListener listener : frameListeners) {\n try {\n listener.onDrawFrame(mFrameTime);\n } catch (final Exception exc) {\n Log.e(TAG, \"DrawFrameListener %s threw %s\", listener, exc.toString());\n exc.printStackTrace();\n }\n }\n }\n\n return currentTime;\n }",
"public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) {\n return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf);\n }",
"private IndexedContainer createContainerForBundleWithoutDescriptor() throws IOException, CmsException {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n Set<Object> keySet = m_keyset.getKeySet();\n for (Object key : keySet) {\n\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object translation = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n }\n\n return container;\n }",
"public void remove(Identity oid)\r\n {\r\n if (oid == null) return;\r\n\r\n ObjectCache cache = getCache(oid, null, METHOD_REMOVE);\r\n if (cache != null)\r\n {\r\n cache.remove(oid);\r\n }\r\n }"
] |
Display mode for output streams. | [
"public void setShowOutput(String mode) {\n try {\n this.outputMode = OutputMode.valueOf(mode.toUpperCase(Locale.ROOT));\n } catch (IllegalArgumentException e) {\n throw new IllegalArgumentException(\"showOutput accepts any of: \"\n + Arrays.toString(OutputMode.values()) + \", value is not valid: \" + mode);\n }\n }"
] | [
"public void setDataOffsets(int[] offsets)\n {\n assert(mLevels == offsets.length);\n NativeBitmapImage.updateCompressed(getNative(), mWidth, mHeight, mImageSize, mData, mLevels, offsets);\n mData = null;\n }",
"public static <T> void injectEEFields(Iterable<Set<ResourceInjection<?>>> resourceInjectionsHierarchy,\n T beanInstance, CreationalContext<T> ctx) {\n for (Set<ResourceInjection<?>> resourceInjections : resourceInjectionsHierarchy) {\n for (ResourceInjection<?> resourceInjection : resourceInjections) {\n resourceInjection.injectResourceReference(beanInstance, ctx);\n }\n }\n }",
"public static TagModel getSingleParent(TagModel tag)\n {\n final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator();\n if (!parents.hasNext())\n throw new WindupException(\"Tag is not designated by any tags: \" + tag);\n\n final TagModel maybeOnlyParent = parents.next();\n\n if (parents.hasNext()) {\n StringBuilder sb = new StringBuilder();\n tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(\", \"));\n throw new WindupException(String.format(\"Tag %s is designated by multiple tags: %s\", tag, sb.toString()));\n }\n\n return maybeOnlyParent;\n }",
"public void updateLockingValues(Object obj) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n if (fmd.isUpdateLock())\r\n {\r\n PersistentField f = fmd.getPersistentField();\r\n Object cv = f.get(obj);\r\n // int\r\n if ((f.getType() == int.class) || (f.getType() == Integer.class))\r\n {\r\n int newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).intValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Integer(newCv));\r\n }\r\n // long\r\n else if ((f.getType() == long.class) || (f.getType() == Long.class))\r\n {\r\n long newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).longValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Long(newCv));\r\n }\r\n // Timestamp\r\n else if (f.getType() == Timestamp.class)\r\n {\r\n long newCv = System.currentTimeMillis();\r\n f.set(obj, new Timestamp(newCv));\r\n }\r\n }\r\n }\r\n }",
"public void addExportedPackages(Set<String> packages) {\n\t\tString s = (String) getMainAttributes().get(EXPORT_PACKAGE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, packages, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(EXPORT_PACKAGE, result);\n\t}",
"public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {\n DMatrixRMaj A = new DMatrixRMaj(length,length);\n\n symmetric(A,min,max,rand);\n\n return A;\n }",
"public void refreshConnection() throws SQLException{\r\n\t\tthis.connection.close(); // if it's still in use, close it.\r\n\t\ttry{\r\n\t\t\tthis.connection = this.pool.obtainRawInternalConnection();\r\n\t\t} catch(SQLException e){\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}",
"protected void internalClose() throws SQLException {\r\n\t\ttry {\r\n\t\t\tclearStatementCaches(true);\r\n\t\t\tif (this.connection != null){ // safety!\r\n\t\t\t\tthis.connection.close();\r\n\r\n\t\t\t\tif (!this.connectionTrackingDisabled && this.finalizableRefs != null){\r\n\t\t\t\t\tthis.finalizableRefs.remove(this.connection);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tthis.logicallyClosed.set(true);\r\n\t\t} catch (SQLException e) {\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}",
"public double getAccruedInterest(LocalDate date, AnalyticModel model) {\n\t\tint periodIndex=schedule.getPeriodIndex(date);\n\t\tPeriod period=schedule.getPeriod(periodIndex);\n\t\tDayCountConvention dcc= schedule.getDaycountconvention();\n\t\tdouble accruedInterest=getCouponPayment(periodIndex,model)*(dcc.getDaycountFraction(period.getPeriodStart(), date))/schedule.getPeriodLength(periodIndex);\n\t\treturn accruedInterest;\n\t}"
] |
Merges the item from the resultLocaleValues into the corresponding item of the localeValues.
@param item the item to merge
@param localeValues the values where the item gets merged into
@param resultLocaleValues the values where the item to merge is read from
@return the modified localeValues with the merged item | [
"private Map<String, String> mergeItem(\r\n String item,\r\n Map<String, String> localeValues,\r\n Map<String, String> resultLocaleValues) {\r\n\r\n if (resultLocaleValues.get(item) != null) {\r\n if (localeValues.get(item) != null) {\r\n localeValues.put(item, localeValues.get(item) + \" \" + resultLocaleValues.get(item));\r\n } else {\r\n localeValues.put(item, resultLocaleValues.get(item));\r\n }\r\n }\r\n\r\n return localeValues;\r\n }"
] | [
"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 String flatten(String left, String right) {\n\t\treturn left == null || left.isEmpty() ? right : left + \".\" + right;\n\t}",
"public boolean deleteExisting(final File file) {\n if (!file.exists()) {\n return true;\n }\n boolean deleted = false;\n if (file.canWrite()) {\n deleted = file.delete();\n } else {\n LogLog.debug(file + \" is not writeable for delete (retrying)\");\n }\n if (!deleted) {\n if (!file.exists()) {\n deleted = true;\n } else {\n file.delete();\n deleted = (!file.exists());\n }\n }\n return deleted;\n }",
"public void alias(DMatrixRMaj variable , String name ) {\n if( isReserved(name))\n throw new RuntimeException(\"Reserved word or contains a reserved character\");\n VariableMatrix old = (VariableMatrix)variables.get(name);\n if( old == null ) {\n variables.put(name, new VariableMatrix(variable));\n }else {\n old.matrix = variable;\n }\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}",
"private void handleGlobalArguments(CommandLine cmd) {\n\t\tif (cmd.hasOption(CMD_OPTION_DUMP_LOCATION)) {\n\t\t\tthis.dumpDirectoryLocation = cmd\n\t\t\t\t\t.getOptionValue(CMD_OPTION_DUMP_LOCATION);\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_OFFLINE_MODE)) {\n\t\t\tthis.offlineMode = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_QUIET)) {\n\t\t\tthis.quiet = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CREATE_REPORT)) {\n\t\t\tthis.reportFilename = cmd.getOptionValue(CMD_OPTION_CREATE_REPORT);\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_LANGUAGES)) {\n\t\t\tsetLanguageFilters(cmd.getOptionValue(OPTION_FILTER_LANGUAGES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_SITES)) {\n\t\t\tsetSiteFilters(cmd.getOptionValue(OPTION_FILTER_SITES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_PROPERTIES)) {\n\t\t\tsetPropertyFilters(cmd.getOptionValue(OPTION_FILTER_PROPERTIES));\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_LOCAL_DUMPFILE)) {\n\t\t\tthis.inputDumpLocation = cmd.getOptionValue(OPTION_LOCAL_DUMPFILE);\n\t\t}\n\t}",
"private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"classes.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\t// Add direct subclass information:\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Integer superClass : classEntry.getValue().directSuperClasses) {\n\t\t\t\t\tthis.classRecords.get(superClass).nonemptyDirectSubclasses\n\t\t\t\t\t\t\t.add(classEntry.getKey().toString());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint count = 0;\n\t\t\tint countNoLabel = 0;\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (classEntry.getValue().label == null) {\n\t\t\t\t\tcountNoLabel++;\n\t\t\t\t}\n\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + classEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, classEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" class items.\");\n\t\t\tSystem.out.println(\" -- class items with missing label: \"\n\t\t\t\t\t+ countNoLabel);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"private void writeExceptions(List<ProjectCalendar> records) throws IOException\n {\n for (ProjectCalendar record : records)\n {\n if (!record.getCalendarExceptions().isEmpty())\n {\n // Need to move HOLI up here and get 15 exceptions per line as per USACE spec.\n // for now, we'll write one line for each calendar exception, hope there aren't too many\n //\n // changing this would be a serious upgrade, too much coding to do today....\n for (ProjectCalendarException ex : record.getCalendarExceptions())\n {\n writeCalendarException(record, ex);\n }\n }\n m_eventManager.fireCalendarWrittenEvent(record); // left here from MPX template, maybe not needed???\n }\n }",
"protected String sendRequestToDF(String df_service, Object msgContent) {\n\n IDFComponentDescription[] receivers = getReceivers(df_service);\n if (receivers.length > 0) {\n IMessageEvent mevent = createMessageEvent(\"send_request\");\n mevent.getParameter(SFipa.CONTENT).setValue(msgContent);\n for (int i = 0; i < receivers.length; i++) {\n mevent.getParameterSet(SFipa.RECEIVERS).addValue(\n receivers[i].getName());\n logger.info(\"The receiver is \" + receivers[i].getName());\n }\n sendMessage(mevent);\n }\n logger.info(\"Message sended to \" + df_service + \" to \"\n + receivers.length + \" receivers\");\n return (\"Message sended to \" + df_service);\n }"
] |
Determine the raw type for the given generic parameter type.
@param genericType the generic type to resolve
@param typeVariableMap the TypeVariable Map to resolved against
@return the resolved raw type | [
"static Type getRawType(Type genericType, Map<TypeVariable, Type> typeVariableMap) {\n\t\tType resolvedType = genericType;\n\t\tif (genericType instanceof TypeVariable) {\n\t\t\tTypeVariable tv = (TypeVariable) genericType;\n\t\t\tresolvedType = typeVariableMap.get(tv);\n\t\t\tif (resolvedType == null) {\n\t\t\t\tresolvedType = extractBoundForTypeVariable(tv);\n\t\t\t}\n\t\t}\n\t\tif (resolvedType instanceof ParameterizedType) {\n\t\t\treturn ((ParameterizedType) resolvedType).getRawType();\n\t\t}\n\t\telse {\n\t\t\treturn resolvedType;\n\t\t}\n\t}"
] | [
"@UiHandler(\"m_atNumber\")\r\n void onWeekOfMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekOfMonth(event.getValue());\r\n }\r\n }",
"private StringBuilder calculateCacheKeyInternal(String sql,\r\n\t\t\tint resultSetType, int resultSetConcurrency) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+20);\r\n\t\ttmp.append(sql);\r\n\r\n\t\ttmp.append(\", T\");\r\n\t\ttmp.append(resultSetType);\r\n\t\ttmp.append(\", C\");\r\n\t\ttmp.append(resultSetConcurrency);\r\n\t\treturn tmp;\r\n\t}",
"public static boolean containsAllQualifiers(Set<QualifierInstance> requiredQualifiers, Set<QualifierInstance> qualifiers) {\n return qualifiers.containsAll(requiredQualifiers);\n }",
"public static double blackScholesOptionRho(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate rho\n\t\t\tdouble dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\n\t\t\tdouble rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn rho;\n\t\t}\n\t}",
"public void fireTaskWrittenEvent(Task task)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.taskWritten(task);\n }\n }\n }",
"protected static void main(String args[]) {\r\n\tint from = Integer.parseInt(args[0]);\t\r\n\tint to = Integer.parseInt(args[1]);\r\n\t\r\n\tstatistics(from,to);\r\n}",
"public Photo getListPhoto(String photoId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_PHOTO);\n\n parameters.put(\"photo_id\", photoId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element photoElement = response.getPayload();\n Photo photo = new Photo();\n photo.setId(photoElement.getAttribute(\"id\"));\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) photoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setId(tagElement.getAttribute(\"id\"));\n tag.setAuthor(tagElement.getAttribute(\"author\"));\n tag.setAuthorName(tagElement.getAttribute(\"authorname\"));\n tag.setRaw(tagElement.getAttribute(\"raw\"));\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n photo.setTags(tags);\n return photo;\n }",
"private void useSearchService() throws Exception {\n\n System.out.println(\"Searching...\");\n\n WebClient wc = WebClient.create(\"http://localhost:\" + port + \"/services/personservice/search\");\n WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000L);\n wc.accept(MediaType.APPLICATION_XML);\n \n // Moves to \"/services/personservice/search\"\n wc.path(\"person\");\n \n SearchConditionBuilder builder = SearchConditionBuilder.instance(); \n \n System.out.println(\"Find people with the name Fred or Lorraine:\");\n \n String query = builder.is(\"name\").equalTo(\"Fred\").or()\n .is(\"name\").equalTo(\"Lorraine\")\n .query();\n findPersons(wc, query);\n \n System.out.println(\"Find all people who are no more than 30 years old\");\n query = builder.is(\"age\").lessOrEqualTo(30)\n \t\t.query();\n \n findPersons(wc, query);\n \n System.out.println(\"Find all people who are older than 28 and whose father name is John\");\n query = builder.is(\"age\").greaterThan(28)\n \t\t.and(\"fatherName\").equalTo(\"John\")\n \t\t.query();\n \n findPersons(wc, query);\n\n System.out.println(\"Find all people who have children with name Fred\");\n query = builder.is(\"childName\").equalTo(\"Fred\")\n \t\t.query();\n \n findPersons(wc, query);\n \n //Moves to \"/services/personservice/personinfo\"\n wc.reset().accept(MediaType.APPLICATION_XML);\n wc.path(\"personinfo\");\n \n System.out.println(\"Find all people younger than 40 using JPA2 Tuples\");\n query = builder.is(\"age\").lessThan(40).query();\n \n // Use URI path component to capture the query expression\n wc.path(query);\n \n \n Collection<? extends PersonInfo> personInfos = wc.getCollection(PersonInfo.class);\n for (PersonInfo pi : personInfos) {\n \tSystem.out.println(\"ID : \" + pi.getId());\n }\n\n wc.close();\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 }"
] |
lookup current maximum value for a single field in
table the given class descriptor was associated. | [
"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 MessageSet read(long readOffset, long size) throws IOException {\n return new FileMessageSet(channel, this.offset + readOffset, //\n Math.min(this.offset + readOffset + size, highWaterMark()), false, new AtomicBoolean(false));\n }",
"public Integer getOverrideIdForMethod(String className, String methodName) {\n Integer overrideId = null;\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.OVERRIDE_CLASS_NAME + \" = ?\" +\n \" AND \" + Constants.OVERRIDE_METHOD_NAME + \" = ?\"\n );\n query.setString(1, className);\n query.setString(2, methodName);\n results = query.executeQuery();\n\n if (results.next()) {\n overrideId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n return overrideId;\n }",
"public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public final double getMedian()\n {\n assertNotEmpty();\n // Sort the data (take a copy to do this).\n double[] dataCopy = new double[getSize()];\n System.arraycopy(dataSet, 0, dataCopy, 0, dataCopy.length);\n Arrays.sort(dataCopy);\n int midPoint = dataCopy.length / 2;\n if (dataCopy.length % 2 != 0)\n {\n return dataCopy[midPoint];\n }\n else\n {\n return dataCopy[midPoint - 1] + (dataCopy[midPoint] - dataCopy[midPoint - 1]) / 2;\n }\n }",
"public boolean ifTaskCompletedSuccessOrFailureFromResponse(\n ResponseOnSingeRequest myResponse) {\n\n boolean isCompleted = false;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return isCompleted;\n }\n\n String responseBody = myResponse.getResponseBody();\n if (responseBody.matches(successRegex)\n || responseBody.matches(failureRegex)) {\n isCompleted = true;\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n return isCompleted;\n }",
"protected synchronized void registerOpenDatabase(DatabaseImpl newDB)\r\n {\r\n DatabaseImpl old_db = getCurrentDatabase();\r\n if (old_db != null)\r\n {\r\n try\r\n {\r\n if (old_db.isOpen())\r\n {\r\n log.warn(\"## There is still an opened database, close old one ##\");\r\n old_db.close();\r\n }\r\n }\r\n catch (Throwable t)\r\n {\r\n //ignore\r\n }\r\n }\r\n if (log.isDebugEnabled()) log.debug(\"Set current database \" + newDB + \" PBKey was \" + newDB.getPBKey());\r\n setCurrentDatabase(newDB);\r\n// usedDatabases.add(newDB.getPBKey());\r\n }",
"public static Filter.Builder makeAndFilter(Iterable<Filter> subfilters) {\n return Filter.newBuilder()\n .setCompositeFilter(CompositeFilter.newBuilder()\n .addAllFilters(subfilters)\n .setOp(CompositeFilter.Operator.AND));\n }",
"public String code(final String code) {\n if (this.theme == null) {\n throw new TemplateProcessingException(\"Theme cannot be resolved because RequestContext was not found. \"\n + \"Are you using a Context object without a RequestContext variable?\");\n }\n return this.theme.getMessageSource().getMessage(code, null, \"\", this.locale);\n }",
"public Duration getStartVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.START_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineStart(), getStart(), format);\n set(AssignmentField.START_VARIANCE, variance);\n }\n return (variance);\n }"
] |
If the workspace for your project _is_ an organization, you must also
supply a `team` to share the project with.
Returns the full record of the newly created project.
@param workspace The workspace or organization to create the project in.
@return Request object | [
"public ItemRequest<Project> createInWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/projects\", workspace);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }"
] | [
"public void enable(ConduitSelectorHolder conduitSelectorHolder, SLPropertiesMatcher matcher,\n String selectionStrategy) {\n LocatorTargetSelector selector = new LocatorTargetSelector();\n selector.setEndpoint(conduitSelectorHolder.getConduitSelector().getEndpoint());\n\n String actualStrategy = selectionStrategy != null ? selectionStrategy : defaultLocatorSelectionStrategy;\n \n LocatorSelectionStrategy locatorSelectionStrategy = getLocatorSelectionStrategy(actualStrategy);\n locatorSelectionStrategy.setServiceLocator(locatorClient);\n if (matcher != null) {\n locatorSelectionStrategy.setMatcher(matcher);\n }\n selector.setLocatorSelectionStrategy(locatorSelectionStrategy);\n\n if (LOG.isLoggable(Level.INFO)) {\n LOG.log(Level.INFO, \"Client enabled with strategy \"\n + locatorSelectionStrategy.getClass().getName() + \".\");\n }\n conduitSelectorHolder.setConduitSelector(selector);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Successfully enabled client \" + conduitSelectorHolder\n + \" for the service locator\");\n }\n }",
"public static HttpConnection createPost(URI uri, String body, String contentType) {\n HttpConnection connection = Http.POST(uri, \"application/json\");\n if(body != null) {\n setEntity(connection, body, contentType);\n }\n return connection;\n }",
"private static CharSequence convertReverseDNSIPv4(String str, int suffixStartIndex) throws AddressStringException {\n\t\tStringBuilder builder = new StringBuilder(suffixStartIndex);\n\t\tint segCount = 0;\n\t\tint j = suffixStartIndex;\n\t\tfor(int i = suffixStartIndex - 1; i > 0; i--) {\n\t\t\tchar c1 = str.charAt(i);\n\t\t\tif(c1 == IPv4Address.SEGMENT_SEPARATOR) {\n\t\t\t\tif(j - i <= 1) {\n\t\t\t\t\tthrow new AddressStringException(str, i);\n\t\t\t\t}\n\t\t\t\tfor(int k = i + 1; k < j; k++) {\n\t\t\t\t\tbuilder.append(str.charAt(k));\n\t\t\t\t}\n\t\t\t\tbuilder.append(c1);\n\t\t\t\tj = i;\n\t\t\t\tsegCount++;\n\t\t\t}\n\t\t}\n\t\tfor(int k = 0; k < j; k++) {\n\t\t\tbuilder.append(str.charAt(k));\n\t\t}\n\t\tif(segCount + 1 != IPv4Address.SEGMENT_COUNT) {\n\t\t\tthrow new AddressStringException(str, 0);\n\t\t}\n\t\treturn builder;\n\t}",
"@SuppressWarnings(\"resource\")\n public static FileChannel openChannel(File file, boolean mutable) throws IOException {\n if (mutable) {\n return new RandomAccessFile(file, \"rw\").getChannel();\n }\n return new FileInputStream(file).getChannel();\n }",
"public static TxInfo getTransactionInfo(Environment env, Bytes prow, Column pcol, long startTs) {\n // TODO ensure primary is visible\n\n IteratorSetting is = new IteratorSetting(10, RollbackCheckIterator.class);\n RollbackCheckIterator.setLocktime(is, startTs);\n\n Entry<Key, Value> entry = ColumnUtil.checkColumn(env, is, prow, pcol);\n\n TxInfo txInfo = new TxInfo();\n\n if (entry == null) {\n txInfo.status = TxStatus.UNKNOWN;\n return txInfo;\n }\n\n ColumnType colType = ColumnType.from(entry.getKey());\n long ts = entry.getKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK;\n\n switch (colType) {\n case LOCK: {\n if (ts == startTs) {\n txInfo.status = TxStatus.LOCKED;\n txInfo.lockValue = entry.getValue().get();\n } else {\n txInfo.status = TxStatus.UNKNOWN; // locked by another tx\n }\n break;\n }\n case DEL_LOCK: {\n DelLockValue dlv = new DelLockValue(entry.getValue().get());\n\n if (ts != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(prow + \" \" + pcol + \" (\" + ts + \" != \" + startTs + \") \");\n }\n\n if (dlv.isRollback()) {\n txInfo.status = TxStatus.ROLLED_BACK;\n } else {\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = dlv.getCommitTimestamp();\n }\n break;\n }\n case WRITE: {\n long timePtr = WriteValue.getTimestamp(entry.getValue().get());\n\n if (timePtr != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(\n prow + \" \" + pcol + \" (\" + timePtr + \" != \" + startTs + \") \");\n }\n\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = ts;\n break;\n }\n default:\n throw new IllegalStateException(\"unexpected col type returned \" + colType);\n }\n\n return txInfo;\n }",
"public static filterglobal_filterpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tfilterglobal_filterpolicy_binding obj = new filterglobal_filterpolicy_binding();\n\t\tfilterglobal_filterpolicy_binding response[] = (filterglobal_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private boolean moreDates(Calendar calendar, List<Date> dates)\n {\n boolean result;\n if (m_finishDate == null)\n {\n int occurrences = NumberHelper.getInt(m_occurrences);\n if (occurrences < 1)\n {\n occurrences = 1;\n }\n result = dates.size() < occurrences;\n }\n else\n {\n result = calendar.getTimeInMillis() <= m_finishDate.getTime();\n }\n return result;\n }",
"private I_CmsSearchResultWrapper getSearchResults() {\n\n // The second parameter is just ignored - so it does not matter\n m_searchController.updateFromRequestParameters(pageContext.getRequest().getParameterMap(), false);\n I_CmsSearchControllerCommon common = m_searchController.getCommon();\n // Do not search for empty query, if configured\n if (common.getState().getQuery().isEmpty()\n && (!common.getConfig().getIgnoreQueryParam() && !common.getConfig().getSearchForEmptyQueryParam())) {\n return new CmsSearchResultWrapper(m_searchController, null, null, m_cms, null);\n }\n Map<String, String[]> queryParams = null;\n boolean isEditMode = CmsJspTagEditable.isEditableRequest(pageContext.getRequest());\n if (isEditMode) {\n String params = \"\";\n if (common.getConfig().getIgnoreReleaseDate()) {\n params += \"&fq=released:[* TO *]\";\n }\n if (common.getConfig().getIgnoreExpirationDate()) {\n params += \"&fq=expired:[* TO *]\";\n }\n if (!params.isEmpty()) {\n queryParams = CmsRequestUtil.createParameterMap(params.substring(1));\n }\n }\n CmsSolrQuery query = new CmsSolrQuery(null, queryParams);\n m_searchController.addQueryParts(query, m_cms);\n try {\n // use \"complicated\" constructor to allow more than 50 results -> set ignoreMaxResults to true\n // also set resource filter to allow for returning unreleased/expired resources if necessary.\n CmsSolrResultList solrResultList = m_index.search(\n m_cms,\n query.clone(), // use a clone of the query, since the search function manipulates the query (removes highlighting parts), but we want to keep the original one.\n true,\n isEditMode ? CmsResourceFilter.IGNORE_EXPIRATION : null);\n return new CmsSearchResultWrapper(m_searchController, solrResultList, query, m_cms, null);\n } catch (CmsSearchException e) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_TAG_SEARCH_SEARCH_FAILED_0), e);\n return new CmsSearchResultWrapper(m_searchController, null, query, m_cms, e);\n }\n }",
"public static PluginManager getInstance() {\n if (_instance == null) {\n _instance = new PluginManager();\n _instance.classInformation = new HashMap<String, ClassInformation>();\n _instance.methodInformation = new HashMap<String, com.groupon.odo.proxylib.models.Method>();\n _instance.jarInformation = new ArrayList<String>();\n\n if (_instance.proxyLibPath == null) {\n //Get the System Classloader\n ClassLoader sysClassLoader = Thread.currentThread().getContextClassLoader();\n\n //Get the URLs\n URL[] urls = ((URLClassLoader) sysClassLoader).getURLs();\n\n for (int i = 0; i < urls.length; i++) {\n if (urls[i].getFile().contains(\"proxylib\")) {\n // store the path to the proxylib\n _instance.proxyLibPath = urls[i].getFile();\n break;\n }\n }\n }\n _instance.initializePlugins();\n }\n return _instance;\n }"
] |
Populates default settings.
@param record MPX record
@param properties project properties
@throws MPXJException | [
"private void populateDefaultSettings(Record record, ProjectProperties properties) throws MPXJException\n {\n properties.setDefaultDurationUnits(record.getTimeUnit(0));\n properties.setDefaultDurationIsFixed(record.getNumericBoolean(1));\n properties.setDefaultWorkUnits(record.getTimeUnit(2));\n properties.setMinutesPerDay(Double.valueOf(NumberHelper.getDouble(record.getFloat(3)) * 60));\n properties.setMinutesPerWeek(Double.valueOf(NumberHelper.getDouble(record.getFloat(4)) * 60));\n properties.setDefaultStandardRate(record.getRate(5));\n properties.setDefaultOvertimeRate(record.getRate(6));\n properties.setUpdatingTaskStatusUpdatesResourceStatus(record.getNumericBoolean(7));\n properties.setSplitInProgressTasks(record.getNumericBoolean(8));\n }"
] | [
"public void generateMapFile(File jarFile, String mapFileName, boolean mapClassMethods) throws XMLStreamException, IOException, ClassNotFoundException, IntrospectionException\n {\n m_responseList = new LinkedList<String>();\n writeMapFile(mapFileName, jarFile, mapClassMethods);\n }",
"private String getClassNameFromPath(String path) {\n String className = path.replace(\".class\", \"\");\n\n // for *nix\n if (className.startsWith(\"/\")) {\n className = className.substring(1, className.length());\n }\n className = className.replace(\"/\", \".\");\n\n // for windows\n if (className.startsWith(\"\\\\\")) {\n className = className.substring(1, className.length());\n }\n className = className.replace(\"\\\\\", \".\");\n\n return className;\n }",
"public IndexDef getIndex(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n IndexDef def = null;\r\n\r\n for (Iterator it = getIndices(); it.hasNext();)\r\n {\r\n def = (IndexDef)it.next();\r\n if (def.getName().equals(realName))\r\n {\r\n return def;\r\n }\r\n }\r\n return null;\r\n }",
"public Tuple get(RowKey key) {\n\t\tAssociationOperation result = currentState.get( key );\n\t\tif ( result == null ) {\n\t\t\treturn cleared ? null : snapshot.get( key );\n\t\t}\n\t\telse if ( result.getType() == REMOVE ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn result.getValue();\n\t}",
"public static void mainInternal(String[] args) throws Exception {\n\n Options options = new Options();\n CmdLineParser parser = new CmdLineParser(options);\n try {\n parser.parseArgument(args);\n } catch (CmdLineException e) {\n helpScreen(parser);\n return;\n }\n\n try {\n List<String> configs = new ArrayList<>();\n if (options.configs != null) {\n configs.addAll(Arrays.asList(options.configs.split(\",\")));\n }\n ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);\n } catch (ConfigException ex) {\n ConfigLogger.error(ex);\n throw ex;\n } catch (Throwable th) {\n ConfigLogger.error(th);\n throw th;\n }\n }",
"public void setMat4(String key, float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4)\n {\n checkKeyIsUniform(key);\n NativeLight.setMat4(getNative(), key, x1, y1, z1, w1, x2, y2,\n z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }",
"public void afterLoading(CollectionProxyDefaultImpl colProxy)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"loading a proxied collection a collection: \" + colProxy);\r\n Collection data = colProxy.getData();\r\n for (Iterator iterator = data.iterator(); iterator.hasNext();)\r\n {\r\n Object o = iterator.next();\r\n if(!isOpen())\r\n {\r\n log.error(\"Collection proxy materialization outside of a running tx, obj=\" + o);\r\n try{throw new Exception(\"Collection proxy materialization outside of a running tx, obj=\" + o);}\r\n catch(Exception e)\r\n {e.printStackTrace();}\r\n }\r\n else\r\n {\r\n Identity oid = getBroker().serviceIdentity().buildIdentity(o);\r\n ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));\r\n RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n }\r\n unregisterFromCollectionProxy(colProxy);\r\n }",
"protected synchronized PersistenceBroker getBroker() throws PBFactoryException\r\n {\r\n /*\r\n mkalen:\r\n NB! The loadProfileIfNeeded must be called _before_ acquiring a broker below,\r\n since some methods in PersistenceBrokerImpl will keep a local reference to\r\n the descriptor repository that was active during broker construction/refresh\r\n (not checking the repository beeing used on method invocation).\r\n\r\n PersistenceBrokerImpl#getClassDescriptor(Class clazz) is such a method,\r\n that will throw ClassNotPersistenceCapableException on the following scenario:\r\n\r\n (All happens in one thread only):\r\n t0: activate per-thread metadata changes\r\n t1: load, register and activate profile A\r\n t2: load object O1 witch collection proxy C to objects {O2} (C stores profile key K(A))\r\n t3: close broker from t2\r\n t4: load, register and activate profile B\r\n t5: reference O1.getO2Collection, causing C loadData() to be invoked\r\n t6: C calls getBroker\r\n broker B is created and descriptorRepository is set to descriptors from profile B\r\n t7: C calls loadProfileIfNeeded, re-activating profile A\r\n t8: C calls B.getCollectionByQuery\r\n t9: B gets callback (via QueryReferenceBroker) to getClassDescriptor\r\n the local descriptorRepository from t6 is used!\r\n => We will now try to query for {O2} with profile B\r\n (even though we re-activated profile A in t7)\r\n => ClassNotPersistenceCapableException\r\n\r\n Keeping loadProfileIfNeeded() at the start of this method changes everything from t6:\r\n t6: C calls loadProfileIfNeeded, re-activating profile A\r\n t7: C calls getBroker,\r\n broker B is created and descriptorRepository is set to descriptors from profile A\r\n t8: C calls B.getCollectionByQuery\r\n t9: B gets callback to getClassDescriptor,\r\n the local descriptorRepository from t6 is used\r\n => We query for {O2} with profile A\r\n => All good :-)\r\n */\r\n if (_perThreadDescriptorsEnabled)\r\n {\r\n loadProfileIfNeeded();\r\n }\r\n\r\n PersistenceBroker broker;\r\n if (getBrokerKey() == null)\r\n {\r\n /*\r\n arminw:\r\n if no PBKey is set we throw an exception, because we don't\r\n know which PB (connection) should be used.\r\n */\r\n throw new OJBRuntimeException(\"Can't find associated PBKey. Need PBKey to obtain a valid\" +\r\n \"PersistenceBroker instance from intern resources.\");\r\n }\r\n // first try to use the current threaded broker to avoid blocking\r\n broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey());\r\n // current broker not found or was closed, create a intern new one\r\n if (broker == null || broker.isClosed())\r\n {\r\n broker = PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey());\r\n // signal that we use a new internal obtained PB instance to read the\r\n // data and that this instance have to be closed after use\r\n _needsClose = true;\r\n }\r\n return broker;\r\n }",
"public static Integer getDays(String days)\n {\n Integer result = null;\n if (days != null)\n {\n result = Integer.valueOf(Integer.parseInt(days, 2));\n }\n return (result);\n }"
] |
Print a date time value.
@param value date time value
@return string representation | [
"public static final String printDateTime(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }"
] | [
"public static Date getYearlyAbsoluteAsDate(RecurringData data)\n {\n Date result;\n Integer yearlyAbsoluteDay = data.getDayNumber();\n Integer yearlyAbsoluteMonth = data.getMonthNumber();\n Date startDate = data.getStartDate();\n\n if (yearlyAbsoluteDay == null || yearlyAbsoluteMonth == null || startDate == null)\n {\n result = null;\n }\n else\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n cal.set(Calendar.MONTH, yearlyAbsoluteMonth.intValue() - 1);\n cal.set(Calendar.DAY_OF_MONTH, yearlyAbsoluteDay.intValue());\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n return result;\n }",
"public ListActiveCoursesInAccountOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }",
"public File getTargetFile(final MiscContentItem item) {\n final State state = this.state;\n if (state == State.NEW || state == State.ROLLBACK_ONLY) {\n return getTargetFile(miscTargetRoot, item);\n } else {\n throw new IllegalStateException(); // internal wrong usage, no i18n\n }\n }",
"public static URL codeLocationFromClass(Class<?> codeLocationClass) {\n String pathOfClass = codeLocationClass.getName().replace(\".\", \"/\") + \".class\";\n URL classResource = codeLocationClass.getClassLoader().getResource(pathOfClass);\n String codeLocationPath = removeEnd(getPathFromURL(classResource), pathOfClass);\n if(codeLocationPath.endsWith(\".jar!/\")) {\n codeLocationPath=removeEnd(codeLocationPath,\"!/\");\n }\n return codeLocationFromPath(codeLocationPath);\n }",
"private void readRelationship(Link link)\n {\n Task sourceTask = m_taskIdMap.get(link.getSourceTaskID());\n Task destinationTask = m_taskIdMap.get(link.getDestinationTaskID());\n if (sourceTask != null && destinationTask != null)\n {\n Duration lag = getDuration(link.getLagUnit(), link.getLag());\n RelationType type = link.getType();\n Relation relation = destinationTask.addPredecessor(sourceTask, type, lag);\n relation.setUniqueID(link.getID());\n }\n }",
"public boolean detectMobileQuick() {\r\n\r\n //Let's exclude tablets\r\n if (isTierTablet) {\r\n return false;\r\n }\r\n //Most mobile browsing is done on smartphones\r\n if (detectSmartphone()) {\r\n return true;\r\n }\r\n\r\n //Catch-all for many mobile devices\r\n if (userAgent.indexOf(mobile) != -1) {\r\n return true;\r\n }\r\n\r\n if (detectOperaMobile()) {\r\n return true;\r\n }\r\n\r\n //We also look for Kindle devices\r\n if (detectKindle() || detectAmazonSilk()) {\r\n return true;\r\n }\r\n\r\n if (detectWapWml() || detectMidpCapable() || detectBrewDevice()) {\r\n return true;\r\n }\r\n\r\n if ((userAgent.indexOf(engineNetfront) != -1) || (userAgent.indexOf(engineUpBrowser) != -1)) {\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"public void configure(Properties props) throws HibernateException {\r\n\t\ttry{\r\n\t\t\tthis.config = new BoneCPConfig(props);\r\n\r\n\t\t\t// old hibernate config\r\n\t\t\tString url = props.getProperty(CONFIG_CONNECTION_URL);\r\n\t\t\tString username = props.getProperty(CONFIG_CONNECTION_USERNAME);\r\n\t\t\tString password = props.getProperty(CONFIG_CONNECTION_PASSWORD);\r\n\t\t\tString driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS);\r\n\t\t\tif (url == null){\r\n\t\t\t\turl = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (username == null){\r\n\t\t\t\tusername = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (password == null){\r\n\t\t\t\tpassword = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (driver == null){\r\n\t\t\t\tdriver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE);\r\n\t\t\t}\r\n\r\n\t\t\tif (url != null){\r\n\t\t\t\tthis.config.setJdbcUrl(url);\r\n\t\t\t}\r\n\t\t\tif (username != null){\r\n\t\t\t\tthis.config.setUsername(username);\r\n\t\t\t}\r\n\t\t\tif (password != null){\r\n\t\t\t\tthis.config.setPassword(password);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t// Remember Isolation level\r\n\t\t\tthis.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props);\r\n\t\t\tthis.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props);\r\n\r\n\t\t\tlogger.debug(this.config.toString());\r\n\r\n\t\t\tif (driver != null && !driver.trim().equals(\"\")){\r\n\t\t\t\tloadClass(driver);\r\n\t\t\t}\r\n\t\t\tif (this.config.getConnectionHookClassName() != null){\r\n\t\t\t\tObject hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance();\r\n\t\t\t\tthis.config.setConnectionHook((ConnectionHook) hookClass);\r\n\t\t\t}\r\n\t\t\t// create the connection pool\r\n\t\t\tthis.pool = createPool(this.config);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new HibernateException(e);\r\n\t\t}\r\n\t}",
"public static <T> T columnStringToObject(Class objClass, String str, String delimiterRegex, String[] fieldNames)\r\n throws InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException\r\n {\r\n Pattern delimiterPattern = Pattern.compile(delimiterRegex);\r\n return StringUtils.<T>columnStringToObject(objClass, str, delimiterPattern, fieldNames);\r\n }",
"public int getTotalLeased(){\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()-this.partitions[i].getAvailableConnections();\r\n\t\t}\r\n\t\treturn total;\r\n\t}"
] |
Sets the lower limits for the "moving" body rotation relative to joint point.
@param limitX the X axis lower rotation limit (in radians)
@param limitY the Y axis lower rotation limit (in radians)
@param limitZ the Z axis lower rotation limit (in radians) | [
"public void setAngularLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setAngularLowerLimits(getNative(), limitX, limitY, limitZ);\n }"
] | [
"public static <T extends CharSequence> T eachMatch(T self, CharSequence regex, @ClosureParams(value=FromString.class, options={\"List<String>\",\"String[]\"}) Closure closure) {\n eachMatch(self.toString(), regex.toString(), closure);\n return self;\n }",
"public void loadClassifier(File file, Properties props) throws ClassCastException, IOException,\r\n ClassNotFoundException {\r\n Timing.startDoing(\"Loading classifier from \" + file.getAbsolutePath());\r\n BufferedInputStream bis;\r\n if (file.getName().endsWith(\".gz\")) {\r\n bis = new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)));\r\n } else {\r\n bis = new BufferedInputStream(new FileInputStream(file));\r\n }\r\n loadClassifier(bis, props);\r\n bis.close();\r\n Timing.endDoing();\r\n }",
"public int getMinutesPerYear()\n {\n return m_minutesPerYear == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerYear()) : m_minutesPerYear.intValue();\n }",
"public static String getAt(String text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n String answer = text.substring(info.from, info.to);\n if (info.reverse) {\n answer = reverse(answer);\n }\n return answer;\n }",
"static BsonDocument getVersionedFilter(\n @Nonnull final BsonValue documentId,\n @Nullable final BsonValue version\n ) {\n final BsonDocument filter = new BsonDocument(\"_id\", documentId);\n if (version == null) {\n filter.put(DOCUMENT_VERSION_FIELD, new BsonDocument(\"$exists\", BsonBoolean.FALSE));\n } else {\n filter.put(DOCUMENT_VERSION_FIELD, version);\n }\n return filter;\n }",
"public List<Tag> getPrimeTags()\n {\n return this.definedTags.values().stream()\n .filter(Tag::isPrime)\n .collect(Collectors.toList());\n }",
"public int getVersion() {\n ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName()));\n Row result = resultSet.one();\n if (result == null) {\n return 0;\n }\n return result.getInt(0);\n }",
"private final void processMainRequest() {\n\n sender = getSender();\n startTimeMillis = System.currentTimeMillis();\n timeoutDuration = Duration.create(\n request.getActorMaxOperationTimeoutSec(), TimeUnit.SECONDS);\n\n actorMaxOperationTimeoutSec = request.getActorMaxOperationTimeoutSec();\n\n if (request.getProtocol() == RequestProtocol.HTTP \n || request.getProtocol() == RequestProtocol.HTTPS) {\n String urlComplete = String.format(\"%s://%s:%d%s\", request\n .getProtocol().toString(), trueTargetNode, request\n .getPort(), request.getResourcePath());\n\n // http://stackoverflow.com/questions/1600291/validating-url-in-java\n if (!PcHttpUtils.isUrlValid(urlComplete.trim())) {\n String errMsg = \"INVALID_URL\";\n logger.error(\"INVALID_URL: \" + urlComplete + \" return..\");\n replyErrors(errMsg, errMsg, PcConstants.NA, PcConstants.NA_INT);\n return;\n } else {\n logger.debug(\"url pass validation: \" + urlComplete);\n }\n\n asyncWorker = getContext().actorOf(\n Props.create(HttpWorker.class, actorMaxOperationTimeoutSec,\n client, urlComplete, request.getHttpMethod(),\n request.getPostData(), request.getHttpHeaderMap(), request.getResponseHeaderMeta()));\n\n } else if (request.getProtocol() == RequestProtocol.SSH ){\n asyncWorker = getContext().actorOf(\n Props.create(SshWorker.class, actorMaxOperationTimeoutSec,\n request.getSshMeta(), trueTargetNode));\n } else if (request.getProtocol() == RequestProtocol.TCP ){\n asyncWorker = getContext().actorOf(\n Props.create(TcpWorker.class, actorMaxOperationTimeoutSec,\n request.getTcpMeta(), trueTargetNode)); \n } else if (request.getProtocol() == RequestProtocol.UDP ){\n asyncWorker = getContext().actorOf(\n Props.create(UdpWorker.class, actorMaxOperationTimeoutSec,\n request.getUdpMeta(), trueTargetNode)); \n } else if (request.getProtocol() == RequestProtocol.PING ){\n asyncWorker = getContext().actorOf(\n Props.create(PingWorker.class, actorMaxOperationTimeoutSec, request.getPingMeta(),\n trueTargetNode));\n }\n\n asyncWorker.tell(RequestWorkerMsgType.PROCESS_REQUEST, getSelf());\n\n cancelExistingIfAnyAndScheduleTimeoutCall();\n\n }",
"protected void loadEntries(final StorageAwareResource resource, final ZipInputStream zipIn) throws IOException {\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream = new BufferedInputStream(zipIn);\n this.readContents(resource, _bufferedInputStream);\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream_1 = new BufferedInputStream(zipIn);\n this.readResourceDescription(resource, _bufferedInputStream_1);\n if (this.storeNodeModel) {\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream_2 = new BufferedInputStream(zipIn);\n this.readNodeModel(resource, _bufferedInputStream_2);\n }\n }"
] |
Token Info
Returns the Token Information
@return ApiResponse<TokenInfoSuccessResponse>
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"public ApiResponse<TokenInfoSuccessResponse> tokenInfoWithHttpInfo() throws ApiException {\n com.squareup.okhttp.Call call = tokenInfoValidateBeforeCall(null, null);\n Type localVarReturnType = new TypeToken<TokenInfoSuccessResponse>(){}.getType();\n return apiClient.execute(call, localVarReturnType);\n }"
] | [
"public void rename(String newName) {\n URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject updateInfo = new JsonObject();\n updateInfo.add(\"name\", newName);\n\n request.setBody(updateInfo.toString());\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"public RenderScript getRenderScript() {\n if (renderScript == null) {\n renderScript = RenderScript.create(context, renderScriptContextType);\n }\n return renderScript;\n }",
"private void populateConstraints(Row row, Task task)\n {\n Date endDateMax = row.getTimestamp(\"ZGIVENENDDATEMAX_\");\n Date endDateMin = row.getTimestamp(\"ZGIVENENDDATEMIN_\");\n Date startDateMax = row.getTimestamp(\"ZGIVENSTARTDATEMAX_\");\n Date startDateMin = row.getTimestamp(\"ZGIVENSTARTDATEMIN_\");\n\n ConstraintType constraintType = null;\n Date constraintDate = null;\n\n if (endDateMax != null)\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = endDateMax;\n }\n\n if (endDateMin != null)\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = endDateMin;\n }\n\n if (endDateMin != null && endDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = endDateMin;\n }\n\n if (startDateMax != null)\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = startDateMax;\n }\n\n if (startDateMin != null)\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = startDateMin;\n }\n\n if (startDateMin != null && startDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = endDateMin;\n }\n\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }",
"private ClassTypeSignature getClassTypeSignature(\r\n\t\t\tParameterizedType parameterizedType) {\r\n\t\tClass<?> rawType = (Class<?>) parameterizedType.getRawType();\r\n\t\tType[] typeArguments = parameterizedType.getActualTypeArguments();\r\n\t\tTypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArguments.length];\r\n\t\tfor (int i = 0; i < typeArguments.length; i++) {\r\n\t\t\ttypeArgSignatures[i] = getTypeArgSignature(typeArguments[i]);\r\n\t\t}\r\n\r\n\t\tString binaryName = rawType.isMemberClass() ? rawType.getSimpleName()\r\n\t\t\t\t: rawType.getName();\r\n\t\tClassTypeSignature ownerTypeSignature = parameterizedType\r\n\t\t\t\t.getOwnerType() == null ? null\r\n\t\t\t\t: (ClassTypeSignature) getFullTypeSignature(parameterizedType\r\n\t\t\t\t\t\t.getOwnerType());\r\n\t\tClassTypeSignature classTypeSignature = new ClassTypeSignature(\r\n\t\t\t\tbinaryName, typeArgSignatures, ownerTypeSignature);\r\n\t\treturn classTypeSignature;\r\n\t}",
"@SuppressWarnings(\"unchecked\")\n private static Object resolveConflictWithResolver(\n final ConflictHandler conflictResolver,\n final BsonValue documentId,\n final ChangeEvent localEvent,\n final ChangeEvent remoteEvent\n ) {\n return conflictResolver.resolveConflict(\n documentId,\n localEvent,\n remoteEvent);\n }",
"private static void validateAsMongoDBCollectionName(String collectionName) {\n\t\tContracts.assertStringParameterNotEmpty( collectionName, \"requestedName\" );\n\t\t//Yes it has some strange requirements.\n\t\tif ( collectionName.startsWith( \"system.\" ) ) {\n\t\t\tthrow log.collectionNameHasInvalidSystemPrefix( collectionName );\n\t\t}\n\t\telse if ( collectionName.contains( \"\\u0000\" ) ) {\n\t\t\tthrow log.collectionNameContainsNULCharacter( collectionName );\n\t\t}\n\t\telse if ( collectionName.contains( \"$\" ) ) {\n\t\t\tthrow log.collectionNameContainsDollarCharacter( collectionName );\n\t\t}\n\t}",
"public JsonNode wbRemoveClaims(List<String> statementIds,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(statementIds,\n\t\t\t\t\"statementIds parameter cannot be null when deleting statements\");\n\t\tValidate.notEmpty(statementIds,\n\t\t\t\t\"statement ids to delete must be non-empty when deleting statements\");\n\t\tValidate.isTrue(statementIds.size() <= 50,\n\t\t\t\t\"At most 50 statements can be deleted at once\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"claim\", String.join(\"|\", statementIds));\n\t\t\n\t\treturn performAPIAction(\"wbremoveclaims\", null, null, null, null, parameters, summary, baserevid, bot);\n\t}",
"public static String getDatatypeIriFromJsonDatatype(String jsonDatatype) {\n\t\tswitch (jsonDatatype) {\n\t\tcase JSON_DT_ITEM:\n\t\t\treturn DT_ITEM;\n\t\tcase JSON_DT_PROPERTY:\n\t\t\treturn DT_PROPERTY;\n\t\tcase JSON_DT_GLOBE_COORDINATES:\n\t\t\treturn DT_GLOBE_COORDINATES;\n\t\tcase JSON_DT_URL:\n\t\t\treturn DT_URL;\n\t\tcase JSON_DT_COMMONS_MEDIA:\n\t\t\treturn DT_COMMONS_MEDIA;\n\t\tcase JSON_DT_TIME:\n\t\t\treturn DT_TIME;\n\t\tcase JSON_DT_QUANTITY:\n\t\t\treturn DT_QUANTITY;\n\t\tcase JSON_DT_STRING:\n\t\t\treturn DT_STRING;\n\t\tcase JSON_DT_MONOLINGUAL_TEXT:\n\t\t\treturn DT_MONOLINGUAL_TEXT;\n\t\tdefault:\n\t\t\tif(!JSON_DATATYPE_PATTERN.matcher(jsonDatatype).matches()) {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid JSON datatype \\\"\" + jsonDatatype + \"\\\"\");\n\t\t\t}\n\n\t\t\tString[] parts = jsonDatatype.split(\"-\");\n\t\t\tfor(int i = 0; i < parts.length; i++) {\n\t\t\t\tparts[i] = StringUtils.capitalize(parts[i]);\n\t\t\t}\n\t\t\treturn \"http://wikiba.se/ontology#\" + StringUtils.join(parts);\n\t\t}\n\t}",
"public List<Shard> getShards() {\n InputStream response = null;\n try {\n response = client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path(\"_shards\")\n .build());\n return getResponseList(response, client.getGson(), DeserializationTypes.SHARDS);\n } finally {\n close(response);\n }\n }"
] |
Checks to see if the token is an integer scalar
@return true if integer or false if not | [
"private static boolean isVariableInteger(TokenList.Token t) {\n if( t == null )\n return false;\n\n return t.getScalarType() == VariableScalar.Type.INTEGER;\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 GVRAnimator findAnimation(String name)\n {\n for (GVRAnimator anim : mAnimations)\n {\n if (name.equals(anim.getName()))\n {\n return anim;\n }\n }\n return null;\n }",
"public static void validate(final Organization organization) {\n if(organization.getName() == null ||\n organization.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Organization name cannot be null or empty!\")\n .build());\n }\n }",
"public synchronized void unregisterJmxIfRequired() {\n referenceCount--;\n if (isRegistered == true && referenceCount <= 0) {\n JmxUtils.unregisterMbean(this.jmxObjectName);\n isRegistered = false;\n }\n }",
"public static float distance(final float ax, final float ay,\n final float bx, final float by) {\n return (float) Math.sqrt(\n (ax - bx) * (ax - bx) +\n (ay - by) * (ay - by)\n );\n }",
"public void setTimewarpInt(String timewarp) {\n\n try {\n m_userSettings.setTimeWarp(Long.valueOf(timewarp).longValue());\n } catch (Exception e) {\n m_userSettings.setTimeWarp(-1);\n }\n }",
"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 Entry<T>[] entries() {\n @SuppressWarnings(\"unchecked\")\n Entry<T>[] entries = new Entry[size];\n int idx = 0;\n for (Entry entry : table) {\n while (entry != null) {\n entries[idx++] = entry;\n entry = entry.next;\n }\n }\n return entries;\n }",
"private Properties parseXML(Document doc, String sectionName) {\n\t\tint found = -1;\n\t\tProperties results = new Properties();\n\t\tNodeList config = null;\n\t\tif (sectionName == null){\n\t\t\tconfig = doc.getElementsByTagName(\"default-config\");\n\t\t\tfound = 0;\n\t\t} else {\n\t\t\tconfig = doc.getElementsByTagName(\"named-config\");\n\t\t\tif(config != null && config.getLength() > 0) {\n\t\t\t\tfor (int i = 0; i < config.getLength(); i++) {\n\t\t\t\t\tNode node = config.item(i);\n\t\t\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE ){\n\t\t\t\t\t\tNamedNodeMap attributes = node.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tNode name = attributes.getNamedItem(\"name\");\n\t\t\t\t\t\t\tif (name.getNodeValue().equalsIgnoreCase(sectionName)){\n\t\t\t\t\t\t\t\tfound = i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found == -1){\n\t\t\t\tconfig = null;\n\t\t\t\tlogger.warn(\"Did not find \"+sectionName+\" section in config file. Reverting to defaults.\");\n\t\t\t}\n\t\t}\n\n\t\tif(config != null && config.getLength() > 0) {\n\t\t\tNode node = config.item(found);\n\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE){\n\t\t\t\tElement elementEntry = (Element)node;\n\t\t\t\tNodeList childNodeList = elementEntry.getChildNodes();\n\t\t\t\tfor (int j = 0; j < childNodeList.getLength(); j++) {\n\t\t\t\t\tNode node_j = childNodeList.item(j);\n\t\t\t\t\tif (node_j.getNodeType() == Node.ELEMENT_NODE) {\n\t\t\t\t\t\tElement piece = (Element) node_j;\n\t\t\t\t\t\tNamedNodeMap attributes = piece.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tresults.put(attributes.item(0).getNodeValue(), piece.getTextContent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}"
] |
Initial setup of the service worker registration. | [
"protected void setupRegistration() {\n if (isServiceWorkerSupported()) {\n Navigator.serviceWorker.register(getResource()).then(object -> {\n logger.info(\"Service worker has been successfully registered\");\n registration = (ServiceWorkerRegistration) object;\n\n onRegistered(new ServiceEvent(), registration);\n\n // Observe service worker lifecycle\n observeLifecycle(registration);\n\n // Setup Service Worker events events\n setupOnControllerChangeEvent();\n setupOnMessageEvent();\n setupOnErrorEvent();\n return null;\n }, error -> {\n logger.info(\"ServiceWorker registration failed: \" + error);\n return null;\n });\n } else {\n logger.info(\"Service worker is not supported by this browser.\");\n }\n }"
] | [
"public void setAssociation(String collectionRole, Association association) {\n\t\tif ( associations == null ) {\n\t\t\tassociations = new HashMap<>();\n\t\t}\n\t\tassociations.put( collectionRole, association );\n\t}",
"public static auditnslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_systemglobal_binding obj = new auditnslogpolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_systemglobal_binding response[] = (auditnslogpolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void writeNewLineIndent() throws IOException\n {\n if (m_pretty)\n {\n if (!m_indent.isEmpty())\n {\n m_writer.write('\\n');\n m_writer.write(m_indent);\n }\n }\n }",
"private void setCalendarToOrdinalRelativeDay(Calendar calendar, int dayNumber)\n {\n int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);\n int requiredDayOfWeek = getDayOfWeek().getValue();\n int dayOfWeekOffset = 0;\n if (requiredDayOfWeek > currentDayOfWeek)\n {\n dayOfWeekOffset = requiredDayOfWeek - currentDayOfWeek;\n }\n else\n {\n if (requiredDayOfWeek < currentDayOfWeek)\n {\n dayOfWeekOffset = 7 - (currentDayOfWeek - requiredDayOfWeek);\n }\n }\n\n if (dayOfWeekOffset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, dayOfWeekOffset);\n }\n\n if (dayNumber > 1)\n {\n calendar.add(Calendar.DAY_OF_YEAR, (7 * (dayNumber - 1)));\n }\n }",
"public int scrollToItem(int position) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToItem position = %d\", position);\n scrollToPosition(position);\n return mCurrentItemIndex;\n }",
"private void verityLicenseIsConflictFree(final DbLicense newComer) {\n if(newComer.getRegexp() == null || newComer.getRegexp().isEmpty()) {\n return;\n }\n\n final DbLicense existing = repoHandler.getLicense(newComer.getName());\n final List<DbLicense> licenses = repoHandler.getAllLicenses();\n\n if(null == existing) {\n licenses.add(newComer);\n } else {\n existing.setRegexp(newComer.getRegexp());\n }\n\n\n final Optional<Report> reportOp = ReportsRegistry.findById(MULTIPLE_LICENSE_MATCHING_STRINGS);\n if (reportOp.isPresent()) {\n final Report reportDef = reportOp.get();\n ReportRequest reportRequest = new ReportRequest();\n reportRequest.setReportId(reportDef.getId());\n\n Map<String, String> params = new HashMap<>();\n\n //\n // TODO: Make the organization come as an external parameter from the client side.\n // This may have impact on the UI, as when the user will update a license he will\n // have to specify which organization he's editing the license for (in case there\n // are more organizations defined in the collection).\n //\n params.put(\"organization\", \"Axway\");\n reportRequest.setParamValues(params);\n\n final RepositoryHandler wrapped = wrapperBuilder\n .start(repoHandler)\n .replaceGetMethod(\"getAllLicenses\", licenses)\n .build();\n\n final ReportExecution execution = reportDef.execute(wrapped, reportRequest);\n\n List<String[]> data = execution.getData();\n\n final Optional<String[]> first = data\n .stream()\n .filter(strings -> strings[2].contains(newComer.getName()))\n .findFirst();\n\n if(first.isPresent()) {\n final String[] strings = first.get();\n final String message = String.format(\n \"Pattern conflict for string entry %s matching multiple licenses: %s\",\n strings[1], strings[2]);\n LOG.info(message);\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(message)\n .build());\n } else {\n if(!data.isEmpty() && !data.get(0)[2].isEmpty()) {\n LOG.info(\"There are remote conflicts between existing licenses and artifact strings\");\n }\n }\n } else {\n if(LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"Cannot find report by id %s\", MULTIPLE_LICENSE_MATCHING_STRINGS));\n }\n }\n }",
"public static String getTemplateMapperConfig(ServletRequest request) {\n\n String result = null;\n CmsTemplateContext templateContext = (CmsTemplateContext)request.getAttribute(\n CmsTemplateContextManager.ATTR_TEMPLATE_CONTEXT);\n if (templateContext != null) {\n I_CmsTemplateContextProvider provider = templateContext.getProvider();\n if (provider instanceof I_CmsTemplateMappingContextProvider) {\n result = ((I_CmsTemplateMappingContextProvider)provider).getMappingConfigurationPath(\n templateContext.getKey());\n }\n }\n return result;\n }",
"public List<Set<String>> makeNWiseTuples(String[] variables, int nWise) {\r\n List<Set<String>> completeTuples = new ArrayList<>();\r\n makeNWiseTuplesHelper(completeTuples, variables, 0, new HashSet<String>(), nWise);\n\r\n return completeTuples;\r\n }",
"public static aaaglobal_binding get(nitro_service service) throws Exception{\n\t\taaaglobal_binding obj = new aaaglobal_binding();\n\t\taaaglobal_binding response = (aaaglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
This method performs a series of permissions checks given a directory and properties file path.
1 - Check whether the parent directory dirPath has proper execute and read permissions
2 - Check whether properties file path is readable and writable
If either of the permissions checks fail, update validFilePermissions and filePermissionsProblemPath
appropriately. | [
"private void validatePermissions(final File dirPath, final File file) {\n\n // Check execute and read permissions for parent dirPath\n if( !dirPath.canExecute() || !dirPath.canRead() ) {\n validFilePermissions = false;\n filePermissionsProblemPath = dirPath.getAbsolutePath();\n return;\n }\n\n // Check read and write permissions for properties file\n if( !file.canRead() || !file.canWrite() ) {\n validFilePermissions = false;\n filePermissionsProblemPath = dirPath.getAbsolutePath();\n }\n\n }"
] | [
"public PhotoList<Photo> getRecent(Set<String> extras, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_RECENT);\r\n\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }",
"public static ProjectReader getProjectReader(String name) throws MPXJException\n {\n int index = name.lastIndexOf('.');\n if (index == -1)\n {\n throw new IllegalArgumentException(\"Filename has no extension: \" + name);\n }\n\n String extension = name.substring(index + 1).toUpperCase();\n\n Class<? extends ProjectReader> fileClass = READER_MAP.get(extension);\n if (fileClass == null)\n {\n throw new IllegalArgumentException(\"Cannot read files of type: \" + extension);\n }\n\n try\n {\n ProjectReader file = fileClass.newInstance();\n return (file);\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to load project reader\", ex);\n }\n }",
"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}",
"private void deleteByQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled())\n {\n logger.debug(\"deleteByQuery \" + cld.getClassNameOfObject() + \", \" + query);\n }\n\n if (query instanceof QueryBySQL)\n {\n String sql = ((QueryBySQL) query).getSql();\n this.dbAccess.executeUpdateSQL(sql, cld);\n }\n else\n {\n // if query is Identity based transform it to a criteria based query first\n if (query instanceof QueryByIdentity)\n {\n QueryByIdentity qbi = (QueryByIdentity) query;\n Object oid = qbi.getExampleObject();\n // make sure it's an Identity\n if (!(oid instanceof Identity))\n {\n oid = serviceIdentity().buildIdentity(oid);\n }\n query = referencesBroker.getPKQuery((Identity) oid);\n }\n\n if (!cld.isInterface())\n {\n this.dbAccess.executeDelete(query, cld);\n }\n\n // if class is an extent, we have to delete all extent classes too\n String lastUsedTable = cld.getFullTableName();\n if (cld.isExtent())\n {\n Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();\n\n while (extents.hasNext())\n {\n ClassDescriptor extCld = (ClassDescriptor) extents.next();\n\n // read same table only once\n if (!extCld.getFullTableName().equals(lastUsedTable))\n {\n lastUsedTable = extCld.getFullTableName();\n this.dbAccess.executeDelete(query, extCld);\n }\n }\n }\n\n }\n }",
"public int[] getTenors(int moneynessBP, int maturityInMonths) {\r\n\r\n\t\ttry {\r\n\t\t\tList<Integer> ret = new ArrayList<>();\r\n\t\t\tfor(int tenor : getGridNodesPerMoneyness().get(moneynessBP)[1]) {\r\n\t\t\t\tif(containsEntryFor(maturityInMonths, tenor, moneynessBP)) {\r\n\t\t\t\t\tret.add(tenor);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn ret.stream().mapToInt(Integer::intValue).toArray();\r\n\t\t} catch (NullPointerException e) {\r\n\t\t\treturn new int[0];\r\n\t\t}\r\n\t}",
"public void createDB() throws PlatformException\r\n {\r\n if (_creationScript == null)\r\n {\r\n createCreationScript();\r\n }\r\n\r\n Project project = new Project();\r\n TorqueDataModelTask modelTask = new TorqueDataModelTask();\r\n File tmpDir = null;\r\n File scriptFile = null;\r\n \r\n try\r\n {\r\n tmpDir = new File(getWorkDir(), \"schemas\");\r\n tmpDir.mkdir();\r\n\r\n scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);\r\n\r\n writeCompressedText(scriptFile, _creationScript);\r\n\r\n project.setBasedir(tmpDir.getAbsolutePath());\r\n\r\n // we use the ant task 'sql' to perform the creation script\r\n\t SQLExec sqlTask = new SQLExec();\r\n\t SQLExec.OnError onError = new SQLExec.OnError();\r\n\t\r\n\t onError.setValue(\"continue\");\r\n\t sqlTask.setProject(project);\r\n\t sqlTask.setAutocommit(true);\r\n\t sqlTask.setDriver(_jcd.getDriver());\r\n\t sqlTask.setOnerror(onError);\r\n\t sqlTask.setUserid(_jcd.getUserName());\r\n\t sqlTask.setPassword(_jcd.getPassWord() == null ? \"\" : _jcd.getPassWord());\r\n\t sqlTask.setUrl(getDBCreationUrl());\r\n\t sqlTask.setSrc(scriptFile);\r\n\t sqlTask.execute();\r\n\r\n\t deleteDir(tmpDir);\r\n }\r\n catch (Exception ex)\r\n {\r\n // clean-up\r\n if ((tmpDir != null) && tmpDir.exists())\r\n {\r\n try\r\n {\r\n scriptFile.delete();\r\n }\r\n catch (NullPointerException e) \r\n {\r\n LoggerFactory.getLogger(this.getClass()).error(\"NPE While deleting scriptFile [\" + scriptFile.getName() + \"]\", e);\r\n }\r\n }\r\n throw new PlatformException(ex);\r\n }\r\n }",
"@Override public View getView(int position, View convertView, ViewGroup parent) {\n T content = getItem(position);\n rendererBuilder.withContent(content);\n rendererBuilder.withConvertView(convertView);\n rendererBuilder.withParent(parent);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext()));\n Renderer<T> renderer = rendererBuilder.build();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null Renderer\");\n }\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n return renderer.getRootView();\n }",
"protected void appendFacetOption(StringBuffer query, final String name, final String value) {\n\n query.append(\" facet.\").append(name).append(\"=\").append(value);\n }",
"protected List<Versioned<V>> resolveAndConstructVersionsToPersist(List<Versioned<V>> valuesInStorage,\n List<Versioned<V>> multiPutValues) {\n List<Versioned<V>> obsoleteVals = new ArrayList<Versioned<V>>(multiPutValues.size());\n // Go over all the values and determine whether the version is\n // acceptable\n for(Versioned<V> value: multiPutValues) {\n Iterator<Versioned<V>> iter = valuesInStorage.iterator();\n boolean obsolete = false;\n // Compare the current version with a set of accepted versions\n while(iter.hasNext()) {\n Versioned<V> curr = iter.next();\n Occurred occurred = value.getVersion().compare(curr.getVersion());\n if(occurred == Occurred.BEFORE) {\n obsolete = true;\n break;\n } else if(occurred == Occurred.AFTER) {\n iter.remove();\n }\n }\n if(obsolete) {\n // add to return value if obsolete\n obsoleteVals.add(value);\n } else {\n // else update the set of accepted versions\n valuesInStorage.add(value);\n }\n }\n\n return obsoleteVals;\n }"
] |
Returns a ReportWriter that which will use memory or a file depending on the parameter PAGES_THRESHOLD
@param _jasperPrint
@param _format
@param _parameters
@return | [
"public ReportWriter getReportWriter(final JasperPrint _jasperPrint, final String _format, final Map<JRExporterParameter,Object> _parameters) {\n final JRExporter exporter = FormatInfoRegistry.getInstance().getExporter(_format);\n exporter.setParameters(_parameters);\n\n if (_jasperPrint.getPages().size() > PAGES_THRESHHOLD) {\n return new FileReportWriter(_jasperPrint, exporter);\n } else {\n return new MemoryReportWriter(_jasperPrint, exporter);\n }\n }"
] | [
"public static int getScreenWidth(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.widthPixels;\n }",
"private void ensureIndexIsUnlocked(String dataDir) {\n\n Collection<File> lockFiles = new ArrayList<File>(2);\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"index\") + \"write.lock\"));\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"spellcheck\")\n + \"write.lock\"));\n for (File lockFile : lockFiles) {\n if (lockFile.exists()) {\n lockFile.delete();\n LOG.warn(\n \"Forcely unlocking index with data dir \\\"\"\n + dataDir\n + \"\\\" by removing file \\\"\"\n + lockFile.getAbsolutePath()\n + \"\\\".\");\n }\n }\n }",
"public static csvserver_copolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_copolicy_binding obj = new csvserver_copolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_copolicy_binding response[] = (csvserver_copolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private boolean isZonesSatisfied() {\n boolean zonesSatisfied = false;\n if(pipelineData.getZonesRequired() == null) {\n zonesSatisfied = true;\n } else {\n int numZonesSatisfied = pipelineData.getZoneResponses().size();\n if(numZonesSatisfied >= (pipelineData.getZonesRequired() + 1)) {\n zonesSatisfied = true;\n }\n }\n return zonesSatisfied;\n }",
"public Date getFinish()\n {\n Date result = (Date) getCachedValue(AssignmentField.FINISH);\n if (result == null)\n {\n result = getTask().getFinish();\n }\n return result;\n }",
"private float[] calculatePointerPosition(float angle) {\n\t\tfloat x = (float) (mColorWheelRadius * Math.cos(angle));\n\t\tfloat y = (float) (mColorWheelRadius * Math.sin(angle));\n\n\t\treturn new float[] { x, y };\n\t}",
"public void afterCompletion(int status)\r\n {\r\n if(afterCompletionCall) return;\r\n\r\n log.info(\"Method afterCompletion was called\");\r\n try\r\n {\r\n switch(status)\r\n {\r\n case Status.STATUS_COMMITTED:\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Method afterCompletion: Do commit internal odmg-tx, status of JTA-tx is \" + TxUtil.getStatusString(status));\r\n }\r\n commit();\r\n break;\r\n default:\r\n log.error(\"Method afterCompletion: Do abort call on internal odmg-tx, status of JTA-tx is \" + TxUtil.getStatusString(status));\r\n abort();\r\n }\r\n }\r\n finally\r\n {\r\n afterCompletionCall = true;\r\n log.info(\"Method afterCompletion finished\");\r\n }\r\n }",
"private Object getUdfValue(UDFAssignmentType udf)\n {\n if (udf.getCostValue() != null)\n {\n return udf.getCostValue();\n }\n \n if (udf.getDoubleValue() != null)\n {\n return udf.getDoubleValue();\n }\n \n if (udf.getFinishDateValue() != null)\n {\n return udf.getFinishDateValue();\n }\n \n if (udf.getIndicatorValue() != null)\n {\n return udf.getIndicatorValue();\n }\n \n if (udf.getIntegerValue() != null)\n {\n return udf.getIntegerValue();\n }\n \n if (udf.getStartDateValue() != null)\n {\n return udf.getStartDateValue();\n }\n \n if (udf.getTextValue() != null)\n {\n return udf.getTextValue();\n }\n \n return null;\n }",
"private void printClassRecord(PrintStream out, ClassRecord classRecord,\n\t\t\tEntityIdValue entityIdValue) {\n\t\tprintTerms(out, classRecord.itemDocument, entityIdValue, \"\\\"\"\n\t\t\t\t+ getClassLabel(entityIdValue) + \"\\\"\");\n\t\tprintImage(out, classRecord.itemDocument);\n\n\t\tout.print(\",\" + classRecord.itemCount + \",\" + classRecord.subclassCount);\n\n\t\tprintClassList(out, classRecord.superClasses);\n\n\t\tHashSet<EntityIdValue> superClasses = new HashSet<>();\n\t\tfor (EntityIdValue superClass : classRecord.superClasses) {\n\t\t\taddSuperClasses(superClass, superClasses);\n\t\t}\n\n\t\tprintClassList(out, superClasses);\n\n\t\tprintRelatedProperties(out, classRecord);\n\n\t\tout.println(\"\");\n\t}"
] |
Checks to see if the matrix is symmetric to within tolerance.
@param A Matrix being tested. Not modified.
@param tol Tolerance that defines how similar two values must be to be considered identical
@return true if symmetric or false if not | [
"public static boolean isSymmetric( DMatrixSparseCSC A , double tol ) {\n if( A.numRows != A.numCols )\n return false;\n\n int N = A.numCols;\n\n for (int i = 0; i < N; i++) {\n int idx0 = A.col_idx[i];\n int idx1 = A.col_idx[i+1];\n\n for (int index = idx0; index < idx1; index++) {\n int j = A.nz_rows[index];\n double value_ji = A.nz_values[index];\n double value_ij = A.get(i,j);\n\n if( Math.abs(value_ij-value_ji) > tol )\n return false;\n }\n }\n\n return true;\n }"
] | [
"public static void symmetric(DMatrixRMaj A, double min, double max, Random rand) {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be a square matrix\");\n\n double range = max-min;\n\n int length = A.numRows;\n\n for( int i = 0; i < length; i++ ) {\n for( int j = i; j < length; j++ ) {\n double val = rand.nextDouble()*range + min;\n A.set(i,j,val);\n A.set(j,i,val);\n }\n }\n }",
"public String getMessage(Locale locale) {\n\t\tif (getCause() != null) {\n\t\t\tString message = getShortMessage(locale) + \", \" + translate(\"ROOT_CAUSE\", locale) + \" \";\n\t\t\tif (getCause() instanceof GeomajasException) {\n\t\t\t\treturn message + ((GeomajasException) getCause()).getMessage(locale);\n\t\t\t}\n\t\t\treturn message + getCause().getMessage();\n\t\t} else {\n\t\t\treturn getShortMessage(locale);\n\t\t}\n\t}",
"public static void waitForDomain(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForDomain(null, client, startupTimeout);\n }",
"public static void addItemsHandled(String handledItemsType, int handledItemsNumber) {\n \tJobLogger jobLogger = (JobLogger) getInstance();\n if (jobLogger == null) {\n return;\n }\n\n jobLogger.addItemsHandledInstance(handledItemsType, handledItemsNumber);\n }",
"protected boolean hasVectorClock(boolean isVectorClockOptional) {\n boolean result = false;\n\n String vectorClockHeader = this.request.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK);\n if(vectorClockHeader != null) {\n ObjectMapper mapper = new ObjectMapper();\n try {\n VectorClockWrapper vcWrapper = mapper.readValue(vectorClockHeader,\n VectorClockWrapper.class);\n this.parsedVectorClock = new VectorClock(vcWrapper.getVersions(),\n vcWrapper.getTimestamp());\n result = true;\n } catch(Exception e) {\n logger.error(\"Exception while parsing and constructing vector clock\", e);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Invalid Vector Clock\");\n }\n } else if(!isVectorClockOptional) {\n logger.error(\"Error when validating request. Missing Vector Clock\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Vector Clock\");\n } else {\n result = true;\n }\n\n return result;\n }",
"public Where<T, ID> or(Where<T, ID> left, Where<T, ID> right, Where<T, ID>... others) {\n\t\tClause[] clauses = buildClauseArray(others, \"OR\");\n\t\tClause secondClause = pop(\"OR\");\n\t\tClause firstClause = pop(\"OR\");\n\t\taddClause(new ManyClause(firstClause, secondClause, clauses, ManyClause.OR_OPERATION));\n\t\treturn this;\n\t}",
"public static double distance(double lat1, double lon1,\n double lat2, double lon2) {\n double dLat = Math.toRadians(lat2-lat1);\n double dLon = Math.toRadians(lon2-lon1);\n lat1 = Math.toRadians(lat1);\n lat2 = Math.toRadians(lat2);\n\n double a = Math.sin(dLat/2) * Math.sin(dLat/2) +\n Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); \n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n return R * c;\n }",
"public void setAttribute(final String name, final Attribute attribute) {\n if (name.equals(MAP_KEY)) {\n this.mapAttribute = (MapAttribute) attribute;\n }\n }",
"private String getClassLabel(EntityIdValue entityIdValue) {\n\t\tClassRecord classRecord = this.classRecords.get(entityIdValue);\n\t\tString label;\n\t\tif (classRecord == null || classRecord.itemDocument == null) {\n\t\t\tlabel = entityIdValue.getId();\n\t\t} else {\n\t\t\tlabel = getLabel(entityIdValue, classRecord.itemDocument);\n\t\t}\n\n\t\tEntityIdValue labelOwner = this.labels.get(label);\n\t\tif (labelOwner == null) {\n\t\t\tthis.labels.put(label, entityIdValue);\n\t\t\treturn label;\n\t\t} else if (labelOwner.equals(entityIdValue)) {\n\t\t\treturn label;\n\t\t} else {\n\t\t\treturn label + \" (\" + entityIdValue.getId() + \")\";\n\t\t}\n\t}"
] |
Apply the necessary rotation to the transform so that it is in front of
the camera.
@param transform The transform to modify. | [
"public void rotateToFaceCamera(final GVRTransform transform) {\n //see http://stackoverflow.com/questions/5782658/extracting-yaw-from-a-quaternion\n final GVRTransform t = getMainCameraRig().getHeadTransform();\n final Quaternionf q = new Quaternionf(0, t.getRotationY(), 0, t.getRotationW()).normalize();\n\n transform.rotateWithPivot(q.w, q.x, q.y, q.z, 0, 0, 0);\n }"
] | [
"public static base_response Force(nitro_service client, clustersync resource) throws Exception {\n\t\tclustersync Forceresource = new clustersync();\n\t\treturn Forceresource.perform_operation(client,\"Force\");\n\t}",
"public <T> T handleResponse(Response response, Type returnType) throws ApiException {\n if (response.isSuccessful()) {\n if (returnType == null || response.code() == 204) {\n // returning null if the returnType is not defined,\n // or the status code is 204 (No Content)\n return null;\n } else {\n return deserialize(response, returnType);\n }\n } else {\n String respBody = null;\n if (response.body() != null) {\n try {\n respBody = response.body().string();\n } catch (IOException e) {\n throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());\n }\n }\n throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);\n }\n }",
"public GeoPermissions 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 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 // response:\r\n // <perms id=\"240935723\" ispublic=\"1\" iscontact=\"0\" isfriend=\"0\" isfamily=\"0\"/>\r\n GeoPermissions perms = new GeoPermissions();\r\n Element permsElement = response.getPayload();\r\n perms.setPublic(\"1\".equals(permsElement.getAttribute(\"ispublic\")));\r\n perms.setContact(\"1\".equals(permsElement.getAttribute(\"iscontact\")));\r\n perms.setFriend(\"1\".equals(permsElement.getAttribute(\"isfriend\")));\r\n perms.setFamily(\"1\".equals(permsElement.getAttribute(\"isfamily\")));\r\n perms.setId(permsElement.getAttribute(\"id\"));\r\n // I ignore the id attribute. should be the same as the given\r\n // photo id.\r\n return perms;\r\n }",
"protected static InstallationModificationImpl.InstallationState load(final InstalledIdentity installedIdentity) throws IOException {\n final InstallationModificationImpl.InstallationState state = new InstallationModificationImpl.InstallationState();\n for (final Layer layer : installedIdentity.getLayers()) {\n state.putLayer(layer);\n }\n for (final AddOn addOn : installedIdentity.getAddOns()) {\n state.putAddOn(addOn);\n }\n return state;\n }",
"protected AbstractColumn buildSimpleBarcodeColumn() {\n\t\tBarCodeColumn column = new BarCodeColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\tcolumn.setApplicationIdentifier(applicationIdentifier);\n\t\tcolumn.setBarcodeType(barcodeType);\n\t\tcolumn.setShowText(showText);\n\t\tcolumn.setCheckSum(checkSum);\n\t\treturn column;\n\t}",
"public void writeReferences() throws RDFHandlerException {\n\t\tIterator<Reference> referenceIterator = this.referenceQueue.iterator();\n\t\tfor (Resource resource : this.referenceSubjectQueue) {\n\t\t\tfinal Reference reference = referenceIterator.next();\n\t\t\tif (this.declaredReferences.add(resource)) {\n\t\t\t\twriteReference(reference, resource);\n\t\t\t}\n\t\t}\n\t\tthis.referenceSubjectQueue.clear();\n\t\tthis.referenceQueue.clear();\n\n\t\tthis.snakRdfConverter.writeAuxiliaryTriples();\n\t}",
"public void setDividerPadding(float padding, final Axis axis) {\n if (!equal(mDividerPadding.get(axis), padding)) {\n mDividerPadding.set(padding, axis);\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }",
"private void calculateSCL(double[] x) {\r\n //System.out.println(\"Checking at: \"+x[0]+\" \"+x[1]+\" \"+x[2]);\r\n value = 0.0;\r\n Arrays.fill(derivative, 0.0);\r\n double[] sums = new double[numClasses];\r\n double[] probs = new double[numClasses];\r\n double[] counts = new double[numClasses];\r\n Arrays.fill(counts, 0.0);\r\n for (int d = 0; d < data.length; d++) {\r\n // if (d == testMin) {\r\n // d = testMax - 1;\r\n // continue;\r\n // }\r\n int[] features = data[d];\r\n // activation\r\n Arrays.fill(sums, 0.0);\r\n for (int c = 0; c < numClasses; c++) {\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n sums[c] += x[i];\r\n }\r\n }\r\n // expectation (slower routine replaced by fast way)\r\n // double total = Double.NEGATIVE_INFINITY;\r\n // for (int c=0; c<numClasses; c++) {\r\n // total = SloppyMath.logAdd(total, sums[c]);\r\n // }\r\n double total = ArrayMath.logSum(sums);\r\n int ld = labels[d];\r\n for (int c = 0; c < numClasses; c++) {\r\n probs[c] = Math.exp(sums[c] - total);\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n derivative[i] += probs[ld] * probs[c];\r\n }\r\n }\r\n // observed\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], labels[d]);\r\n derivative[i] -= probs[ld];\r\n }\r\n value -= probs[ld];\r\n }\r\n // priors\r\n if (true) {\r\n for (int i = 0; i < x.length; i++) {\r\n double k = 1.0;\r\n double w = x[i];\r\n value += k * w * w / 2.0;\r\n derivative[i] += k * w;\r\n }\r\n }\r\n }",
"@Override\n public void postCrawling(CrawlSession session, ExitStatus exitStatus) {\n LOG.debug(\"postCrawling\");\n StateFlowGraph sfg = session.getStateFlowGraph();\n checkSFG(sfg);\n // TODO: call state abstraction function to get distance matrix and run rscript on it to\n // create clusters\n String[][] clusters = null;\n // generateClusters(session);\n\n result = outModelCache.close(session, exitStatus, clusters);\n\n outputBuilder.write(result, session.getConfig(), clusters);\n StateWriter writer =\n new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));\n for (State state : result.getStates().values()) {\n try {\n writer.writeHtmlForState(state);\n } catch (Exception Ex) {\n LOG.info(\"couldn't write state :\" + state.getName());\n }\n }\n LOG.info(\"Crawl overview plugin has finished\");\n }"
] |
Logs to Info if the debug level is greater than or equal to 1. | [
"static void i(String message){\n if (getStaticDebugLevel() >= CleverTapAPI.LogLevel.INFO.intValue()){\n Log.i(Constants.CLEVERTAP_LOG_TAG,message);\n }\n }"
] | [
"private void writeBufferedValsToStorage() {\n List<Versioned<byte[]>> obsoleteVals = storageEngine.multiVersionPut(currBufferedKey,\n currBufferedVals);\n // log Obsolete versions in debug mode\n if(logger.isDebugEnabled() && obsoleteVals.size() > 0) {\n logger.debug(\"updateEntries (Streaming multi-version-put) rejected these versions as obsolete : \"\n + StoreUtils.getVersions(obsoleteVals) + \" for key \" + currBufferedKey);\n }\n currBufferedVals = new ArrayList<Versioned<byte[]>>(VALS_BUFFER_EXPECTED_SIZE);\n }",
"public void setDefault() {\n try {\n TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);\n String phone = telephonyManager.getLine1Number();\n if (phone != null && !phone.isEmpty()) {\n this.setNumber(phone);\n } else {\n String iso = telephonyManager.getNetworkCountryIso();\n setEmptyDefault(iso);\n }\n } catch (SecurityException e) {\n setEmptyDefault();\n }\n }",
"private void _handleMultiValues(ArrayList<String> values, String key, String command) {\n if (key == null) return;\n\n if (values == null || values.isEmpty()) {\n _generateEmptyMultiValueError(key);\n return;\n }\n\n ValidationResult vr;\n\n // validate the key\n vr = validator.cleanMultiValuePropertyKey(key);\n\n // Check for an error\n if (vr.getErrorCode() != 0) {\n pushValidationResult(vr);\n }\n\n // reset the key\n Object _key = vr.getObject();\n String cleanKey = (_key != null) ? vr.getObject().toString() : null;\n\n // if key is empty generate an error and return\n if (cleanKey == null || cleanKey.isEmpty()) {\n _generateInvalidMultiValueKeyError(key);\n return;\n }\n\n key = cleanKey;\n\n try {\n JSONArray currentValues = _constructExistingMultiValue(key, command);\n JSONArray newValues = _cleanMultiValues(values, key);\n _validateAndPushMultiValue(currentValues, newValues, values, key, command);\n\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Error handling multi value operation for key \" + key, t);\n }\n }",
"@Deprecated\r\n private BufferedImage getOriginalImage(String suffix) throws IOException, FlickrException {\r\n StringBuffer buffer = getOriginalBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImage(buffer.toString());\r\n }",
"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 Build createBuild(String appName, Build build) {\n return connection.execute(new BuildCreate(appName, build), apiKey);\n }",
"public Token add( String word ) {\n Token t = new Token(word);\n push( t );\n return t;\n }",
"private Properties parseFile(File file) throws InvalidDeclarationFileException {\n Properties properties = new Properties();\n InputStream is = null;\n try {\n is = new FileInputStream(file);\n properties.load(is);\n } catch (Exception e) {\n throw new InvalidDeclarationFileException(String.format(\"Error reading declaration file %s\", file.getAbsoluteFile()), e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n LOG.error(\"IOException thrown while trying to close the declaration file.\", e);\n }\n }\n }\n\n if (!properties.containsKey(Constants.ID)) {\n throw new InvalidDeclarationFileException(String.format(\"File %s is not a correct declaration, needs to contains an id property\", file.getAbsoluteFile()));\n }\n return properties;\n }",
"public static void sendMimeMessage(MimeMessage mimeMessage) {\r\n try {\r\n Transport.send(mimeMessage);\r\n } catch (MessagingException e) {\r\n throw new IllegalStateException(\"Can not send message \" + mimeMessage, e);\r\n }\r\n }"
] |
Retrieves and validates the content length from the REST request.
@return true if has content length | [
"protected boolean hasContentLength() {\n boolean result = false;\n String contentLength = this.request.getHeader(RestMessageHeaders.CONTENT_LENGTH);\n if(contentLength != null) {\n try {\n Long.parseLong(contentLength);\n result = true;\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating put request. Incorrect content length parameter. Cannot parse this to long: \"\n + contentLength + \". Details: \" + nfe.getMessage(),\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect content length parameter. Cannot parse this to long: \"\n + contentLength + \". Details: \"\n + nfe.getMessage());\n }\n } else {\n logger.error(\"Error when validating put request. Missing Content-Length header.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Content-Length header\");\n }\n\n return result;\n }"
] | [
"private void allInput(List<FileModel> vertices, GraphRewrite event, ParameterStore store)\n {\n if (StringUtils.isBlank(getInputVariablesName()) && this.filenamePattern == null)\n {\n FileService fileModelService = new FileService(event.getGraphContext());\n for (FileModel fileModel : fileModelService.findAll())\n {\n vertices.add(fileModel);\n }\n }\n }",
"protected static <S extends IPAddressSegment> void normalizePrefixBoundary(\n\t\t\tint sectionPrefixBits,\n\t\t\tS segments[],\n\t\t\tint segmentBitCount,\n\t\t\tint segmentByteCount,\n\t\t\tBiFunction<S, Integer, S> segProducer) {\n\t\t//we've already verified segment prefixes in super constructor. We simply need to check the case where the prefix is at a segment boundary,\n\t\t//whether the network side has the correct prefix\n\t\tint networkSegmentIndex = getNetworkSegmentIndex(sectionPrefixBits, segmentByteCount, segmentBitCount);\n\t\tif(networkSegmentIndex >= 0) {\n\t\t\tS segment = segments[networkSegmentIndex];\n\t\t\tif(!segment.isPrefixed()) {\n\t\t\t\tsegments[networkSegmentIndex] = segProducer.apply(segment, segmentBitCount);\n\t\t\t}\n\t\t}\n\t}",
"public static lbmonitor_binding get(nitro_service service, String monitorname) throws Exception{\n\t\tlbmonitor_binding obj = new lbmonitor_binding();\n\t\tobj.set_monitorname(monitorname);\n\t\tlbmonitor_binding response = (lbmonitor_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static void transformChar(Reader self, Writer writer, @ClosureParams(value=SimpleType.class, options=\"java.lang.String\") Closure closure) throws IOException {\n int c;\n try {\n char[] chars = new char[1];\n while ((c = self.read()) != -1) {\n chars[0] = (char) c;\n writer.write((String) closure.call(new String(chars)));\n }\n writer.flush();\n\n Writer temp2 = writer;\n writer = null;\n temp2.close();\n Reader temp1 = self;\n self = null;\n temp1.close();\n } finally {\n closeWithWarning(self);\n closeWithWarning(writer);\n }\n }",
"private void addHours(ProjectCalendarDateRanges ranges, Record hoursRecord)\n {\n if (hoursRecord.getValue() != null)\n {\n String[] wh = hoursRecord.getValue().split(\"\\\\|\");\n try\n {\n String startText;\n String endText;\n\n if (wh[0].equals(\"s\"))\n {\n startText = wh[1];\n endText = wh[3];\n }\n else\n {\n startText = wh[3];\n endText = wh[1];\n }\n\n // for end time treat midnight as midnight next day\n if (endText.equals(\"00:00\"))\n {\n endText = \"24:00\";\n }\n Date start = m_calendarTimeFormat.parse(startText);\n Date end = m_calendarTimeFormat.parse(endText);\n\n ranges.addRange(new DateRange(start, end));\n }\n catch (ParseException e)\n {\n // silently ignore date parse exceptions\n }\n }\n }",
"public void initialize(FragmentManager fragmentManager) {\n AirMapInterface mapInterface = (AirMapInterface)\n fragmentManager.findFragmentById(R.id.map_frame);\n\n if (mapInterface != null) {\n initialize(fragmentManager, mapInterface);\n } else {\n initialize(fragmentManager, new DefaultAirMapViewBuilder(getContext()).builder().build());\n }\n }",
"public static Priority getInstance(Locale locale, String priority)\n {\n int index = DEFAULT_PRIORITY_INDEX;\n\n if (priority != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(locale, LocaleData.PRIORITY_TYPES);\n for (int loop = 0; loop < priorityTypes.length; loop++)\n {\n if (priorityTypes[loop].equalsIgnoreCase(priority) == true)\n {\n index = loop;\n break;\n }\n }\n }\n\n return (Priority.getInstance((index + 1) * 100));\n }",
"public CustomHeadersInterceptor addHeaderMap(Map<String, String> headers) {\n for (Map.Entry<String, String> header : headers.entrySet()) {\n this.headers.put(header.getKey(), Collections.singletonList(header.getValue()));\n }\n return this;\n }",
"public void setRotation(String rotation) {\r\n if (rotation != null) {\r\n try {\r\n setRotation(Integer.parseInt(rotation));\r\n } catch (NumberFormatException e) {\r\n setRotation(-1);\r\n }\r\n }\r\n }"
] |
Deal with streams attached to an operation response from a proxied domain process.
@param context the context of the operation
@param responseNode the DMR response from the proxied process
@param streams the streams associated with the response | [
"public static void handleDomainOperationResponseStreams(final OperationContext context,\n final ModelNode responseNode,\n final List<OperationResponse.StreamEntry> streams) {\n\n if (responseNode.hasDefined(RESPONSE_HEADERS)) {\n ModelNode responseHeaders = responseNode.get(RESPONSE_HEADERS);\n // Strip out any stream header as the header created by this process is what counts\n responseHeaders.remove(ATTACHED_STREAMS);\n if (responseHeaders.asInt() == 0) {\n responseNode.remove(RESPONSE_HEADERS);\n }\n }\n\n for (OperationResponse.StreamEntry streamEntry : streams) {\n context.attachResultStream(streamEntry.getUUID(), streamEntry.getMimeType(), streamEntry.getStream());\n }\n }"
] | [
"public static <T extends Publisher> T getPublisher(AbstractProject<?, ?> project, Class<T> type) {\n // Search for a publisher of the given type in the project and return it if found:\n T publisher = new PublisherFindImpl<T>().find(project, type);\n if (publisher != null) {\n return publisher;\n }\n // If not found, the publisher might be wrapped by a \"Flexible Publish\" publisher. The below searches for it inside the\n // Flexible Publisher:\n publisher = new PublisherFlexible<T>().find(project, type);\n return publisher;\n }",
"@Override\n public DMatrixRMaj getV(DMatrixRMaj V , boolean transpose , boolean compact ) {\n V = handleV(V, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(V);\n\n// UBV.print();\n\n // todo the very first multiplication can be avoided by setting to the rank1update output\n for( int j = min-1; j >= 0; j-- ) {\n u[j+1] = 1;\n for( int i = j+2; i < n; i++ ) {\n u[i] = UBV.get(j,i);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(V, u, gammasV[j], j + 1, j + 1, n);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(V, u, gammasV[j], j + 1, j + 1, n, this.b);\n }\n\n return V;\n }",
"protected void store(Object obj, Identity oid, ClassDescriptor cld, boolean insert)\n {\n store(obj, oid, cld, insert, false);\n }",
"public static void removeColumns( DMatrixRMaj A , int col0 , int col1 )\n {\n if( col1 < col0 ) {\n throw new IllegalArgumentException(\"col1 must be >= col0\");\n } else if( col0 >= A.numCols || col1 >= A.numCols ) {\n throw new IllegalArgumentException(\"Columns which are to be removed must be in bounds\");\n }\n\n int step = col1-col0+1;\n int offset = 0;\n for (int row = 0, idx=0; row < A.numRows; row++) {\n for (int i = 0; i < col0; i++,idx++) {\n A.data[idx] = A.data[idx+offset];\n }\n offset += step;\n for (int i = col1+1; i < A.numCols; i++,idx++) {\n A.data[idx] = A.data[idx+offset];\n }\n }\n A.numCols -= step;\n }",
"public ExtendedOutputStreamWriter append(double d) throws IOException {\n super.append(String.format(Locale.ROOT, doubleFormat, d));\n return this;\n }",
"public static String unexpandLine(CharSequence self, int tabStop) {\n StringBuilder builder = new StringBuilder(self.toString());\n int index = 0;\n while (index + tabStop < builder.length()) {\n // cut original string in tabstop-length pieces\n String piece = builder.substring(index, index + tabStop);\n // count trailing whitespace characters\n int count = 0;\n while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1)))))\n count++;\n // replace if whitespace was found\n if (count > 0) {\n piece = piece.substring(0, tabStop - count) + '\\t';\n builder.replace(index, index + tabStop, piece);\n index = index + tabStop - (count - 1);\n } else\n index = index + tabStop;\n }\n return builder.toString();\n }",
"public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }",
"public String renameApp(String appName, String newName) {\n return connection.execute(new AppRename(appName, newName), apiKey).getName();\n }",
"public void build(double[] coords, int nump) throws IllegalArgumentException {\n if (nump < 4) {\n throw new IllegalArgumentException(\"Less than four input points specified\");\n }\n if (coords.length / 3 < nump) {\n throw new IllegalArgumentException(\"Coordinate array too small for specified number of points\");\n }\n initBuffers(nump);\n setPoints(coords, nump);\n buildHull();\n }"
] |
Send a data to Incoming Webhook endpoint. | [
"public WebhookResponse send(String url, Payload payload) throws IOException {\n SlackHttpClient httpClient = getHttpClient();\n Response httpResponse = httpClient.postJsonPostRequest(url, payload);\n String body = httpResponse.body().string();\n httpClient.runHttpResponseListeners(httpResponse, body);\n\n return WebhookResponse.builder()\n .code(httpResponse.code())\n .message(httpResponse.message())\n .body(body)\n .build();\n }"
] | [
"private List<Integer> getNodeIdListForPartitionIdList(List<Integer> partitionIds)\n throws VoldemortException {\n List<Integer> nodeIds = new ArrayList<Integer>(partitionIds.size());\n for(Integer partitionId: partitionIds) {\n int nodeId = getNodeIdForPartitionId(partitionId);\n if(nodeIds.contains(nodeId)) {\n throw new VoldemortException(\"Node ID \" + nodeId + \" already in list of Node IDs.\");\n } else {\n nodeIds.add(nodeId);\n }\n }\n return nodeIds;\n }",
"public Query getPKQuery(Identity oid)\r\n {\r\n Object[] values = oid.getPrimaryKeyValues();\r\n ClassDescriptor cld = pb.getClassDescriptor(oid.getObjectsTopLevelClass());\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n Criteria criteria = new Criteria();\r\n\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fld = fields[i];\r\n criteria.addEqualTo(fld.getAttributeName(), values[i]);\r\n }\r\n return QueryFactory.newQuery(cld.getClassOfObject(), criteria);\r\n }",
"static void doDifference(\n Map<String, String> left,\n Map<String, String> right,\n Map<String, String> onlyOnLeft,\n Map<String, String> onlyOnRight,\n Map<String, String> updated\n ) {\n onlyOnRight.clear();\n onlyOnRight.putAll(right);\n for (Map.Entry<String, String> entry : left.entrySet()) {\n String leftKey = entry.getKey();\n String leftValue = entry.getValue();\n if (right.containsKey(leftKey)) {\n String rightValue = onlyOnRight.remove(leftKey);\n if (!leftValue.equals(rightValue)) {\n updated.put(leftKey, leftValue);\n }\n } else {\n onlyOnLeft.put(leftKey, leftValue);\n }\n }\n }",
"public static String paramMapToString(final Map<String, String[]> parameters) {\n\n final StringBuffer result = new StringBuffer();\n for (final String key : parameters.keySet()) {\n String[] values = parameters.get(key);\n if (null == values) {\n result.append(key).append('&');\n } else {\n for (final String value : parameters.get(key)) {\n result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');\n }\n }\n }\n // remove last '&'\n if (result.length() > 0) {\n result.setLength(result.length() - 1);\n }\n return result.toString();\n }",
"public Headers getAllHeaders() {\n Headers requestHeaders = getHeaders();\n requestHeaders = hasPayload() ? requestHeaders.withContentType(getPayload().get().getMimeType()) : requestHeaders;\n //We don't want to add headers more than once.\n return requestHeaders;\n }",
"private void processResponse(Response<ByteArray, Object> response, Pipeline pipeline) {\n if(response == null) {\n logger.warn(\"RoutingTimedout on waiting for async ops; parallelResponseToWait: \"\n + numNodesPendingResponse + \"; preferred-1: \" + (preferred - 1)\n + \"; quorumOK: \" + quorumSatisfied + \"; zoneOK: \" + zonesSatisfied);\n } else {\n numNodesPendingResponse = numNodesPendingResponse - 1;\n numResponsesGot = numResponsesGot + 1;\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handling async put error\");\n }\n if(response.getValue() instanceof QuotaExceededException) {\n /**\n * TODO Not sure if we need to count this Exception for\n * stats or silently ignore and just log a warning. While\n * QuotaExceededException thrown from other places mean the\n * operation failed, this one does not fail the operation\n * but instead stores slops. Introduce a new Exception in\n * client side to just monitor how mamy Async writes fail on\n * exceeding Quota?\n * \n */\n if(logger.isDebugEnabled()) {\n logger.debug(\"Received quota exceeded exception after a successful \"\n + pipeline.getOperation().getSimpleName() + \" call on node \"\n + response.getNode().getId() + \", store '\"\n + pipelineData.getStoreName() + \"', master-node '\"\n + pipelineData.getMaster().getId() + \"'\");\n }\n } else if(handleResponseError(response, pipeline, failureDetector)) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key\n + \"} severe async put error, exiting parallel put stage\");\n }\n\n return;\n }\n if(PipelineRoutedStore.isSlopableFailure(response.getValue())\n || response.getValue() instanceof QuotaExceededException) {\n /**\n * We want to slop ParallelPuts which fail due to\n * QuotaExceededException.\n * \n * TODO Though this is not the right way of doing things, in\n * order to avoid inconsistencies and data loss, we chose to\n * slop the quota failed parallel puts.\n * \n * As a long term solution - 1) either Quota management\n * should be hidden completely in a routing layer like\n * Coordinator or 2) the Server should be able to\n * distinguish between serial and parallel puts and should\n * only quota for serial puts\n * \n */\n pipelineData.getSynchronizer().tryDelegateSlop(response.getNode());\n }\n\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT {key:\" + key + \"} handled async put error\");\n }\n\n } else {\n pipelineData.incrementSuccesses();\n failureDetector.recordSuccess(response.getNode(), response.getRequestTime());\n pipelineData.getZoneResponses().add(response.getNode().getZoneId());\n }\n }\n }",
"Item newStringishItem(final int type, final String value) {\n key2.set(type, value, null, null);\n Item result = get(key2);\n if (result == null) {\n pool.put12(type, newUTF8(value));\n result = new Item(index++, key2);\n put(result);\n }\n return result;\n }",
"private String formatCurrency(Number value)\n {\n return (value == null ? null : m_formats.getCurrencyFormat().format(value));\n }",
"public static CountryList getCountries(Context context) {\n if (mCountries != null) {\n return mCountries;\n }\n mCountries = new CountryList();\n try {\n JSONArray countries = new JSONArray(getJsonFromRaw(context, R.raw.countries));\n for (int i = 0; i < countries.length(); i++) {\n try {\n JSONObject country = (JSONObject) countries.get(i);\n mCountries.add(new Country(country.getString(\"name\"), country.getString(\"iso2\"), country.getInt(\"dialCode\")));\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n return mCountries;\n }"
] |
Get the node that has been selected by the user, or null if
nothing is selected.
@return The node or <code>null</code> | [
"public ManagementModelNode getSelectedNode() {\n if (tree.getSelectionPath() == null) return null;\n return (ManagementModelNode)tree.getSelectionPath().getLastPathComponent();\n }"
] | [
"protected static Map<String, List<Statement>> addStatementToGroups(Statement statement, Map<String, List<Statement>> claims) {\n\t\tMap<String, List<Statement>> newGroups = new HashMap<>(claims);\n\t\tString pid = statement.getMainSnak().getPropertyId().getId();\n\t\tif(newGroups.containsKey(pid)) {\n\t\t\tList<Statement> newGroup = new ArrayList<>(newGroups.get(pid).size());\n\t\t\tboolean statementReplaced = false;\n\t\t\tfor(Statement existingStatement : newGroups.get(pid)) {\n\t\t\t\tif(existingStatement.getStatementId().equals(statement.getStatementId()) &&\n\t\t\t\t\t\t!existingStatement.getStatementId().isEmpty()) {\n\t\t\t\t\tstatementReplaced = true;\n\t\t\t\t\tnewGroup.add(statement);\n\t\t\t\t} else {\n\t\t\t\t\tnewGroup.add(existingStatement);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!statementReplaced) {\n\t\t\t\tnewGroup.add(statement);\n\t\t\t}\n\t\t\tnewGroups.put(pid, newGroup);\n\t\t} else {\n\t\t\tnewGroups.put(pid, Collections.singletonList(statement));\n\t\t}\n\t\treturn newGroups;\n\t}",
"public static Collection<Field> getAttributes(\n final Class<?> classToInspect, final Predicate<Field> filter) {\n Set<Field> allFields = new HashSet<>();\n getAllAttributes(classToInspect, allFields, Function.identity(), filter);\n return allFields;\n }",
"public void addRoute(String path, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(path, false), actorClass);\n }",
"@RequestMapping(value = \"api/edit/disable\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableResponses(Model model, int path_id, @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n OverrideService.getInstance().disableAllOverrides(path_id, clientUUID);\n //TODO also need to disable custom override if there is one of those\n editService.removeCustomOverride(path_id, clientUUID);\n\n return null;\n }",
"public static nsconfig diff(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig diffresource = new nsconfig();\n\t\tdiffresource.config1 = resource.config1;\n\t\tdiffresource.config2 = resource.config2;\n\t\tdiffresource.outtype = resource.outtype;\n\t\tdiffresource.template = resource.template;\n\t\tdiffresource.ignoredevicespecific = resource.ignoredevicespecific;\n\t\treturn (nsconfig)diffresource.perform_operationEx(client,\"diff\");\n\t}",
"public Credentials toGrgit() {\n if (username != null && password != null) {\n return new Credentials(username, password);\n } else {\n return null;\n }\n }",
"private void readResources(Storepoint phoenixProject)\n {\n Resources resources = phoenixProject.getResources();\n if (resources != null)\n {\n for (net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res : resources.getResource())\n {\n Resource resource = readResource(res);\n readAssignments(resource, res);\n }\n }\n }",
"void countNonZeroInV( int []parent ) {\n int []w = gwork.data;\n findMinElementIndexInRows(leftmost);\n createRowElementLinkedLists(leftmost,w);\n countNonZeroUsingLinkedList(parent,w);\n }",
"@Inline(value = \"$1.remove($2.getKey(), $2.getValue())\", statementExpression = true)\n\tpublic static <K, V> boolean operator_remove(Map<K, V> map, Pair<? extends K, ? extends V> entry) {\n\t\t//TODO use the JRE 1.8 API: map.remove(entry.getKey(), entry.getValue());\n\t\tfinal K key = entry.getKey();\n\t\tfinal V storedValue = map.get(entry.getKey());\n\t if (!Objects.equal(storedValue, entry.getValue())\n\t\t\t|| (storedValue == null && !map.containsKey(key))) {\n\t return false;\n \t}\n \tmap.remove(key);\n\t return true;\n\t}"
] |
Converts the given hash code into an index into the
hash table. | [
"private int indexFor(int hash)\r\n {\r\n // mix the bits to avoid bucket collisions...\r\n hash += ~(hash << 15);\r\n hash ^= (hash >>> 10);\r\n hash += (hash << 3);\r\n hash ^= (hash >>> 6);\r\n hash += ~(hash << 11);\r\n hash ^= (hash >>> 16);\r\n return hash & (table.length - 1);\r\n }"
] | [
"private void readRelationships(Storepoint phoenixProject)\n {\n for (Relationship relation : phoenixProject.getRelationships().getRelationship())\n {\n readRelation(relation);\n }\n }",
"public Headers toHeaders() {\n Headers headers = new Headers();\n if (!getMatch().isEmpty()) {\n headers = headers.add(new Header(HeaderConstants.IF_MATCH, buildTagHeaderValue(getMatch())));\n }\n if (!getNoneMatch().isEmpty()) {\n headers = headers.add(new Header(HeaderConstants.IF_NONE_MATCH, buildTagHeaderValue(getNoneMatch())));\n }\n if (modifiedSince.isPresent()) {\n headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_MODIFIED_SINCE, modifiedSince.get()));\n }\n if (unModifiedSince.isPresent()) {\n headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_UNMODIFIED_SINCE, unModifiedSince.get()));\n }\n\n return headers;\n }",
"protected void doPurge(Runnable afterPurgeAction) {\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\n org.opencms.flex.Messages.get().getBundle().key(\n org.opencms.flex.Messages.LOG_FLEXCACHE_WILL_PURGE_JSP_REPOSITORY_0));\n }\n\n File d;\n d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_ONLINE + File.separator);\n CmsFileUtil.purgeDirectory(d);\n\n d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_OFFLINE + File.separator);\n CmsFileUtil.purgeDirectory(d);\n if (afterPurgeAction != null) {\n afterPurgeAction.run();\n }\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\n org.opencms.flex.Messages.get().getBundle().key(\n org.opencms.flex.Messages.LOG_FLEXCACHE_PURGED_JSP_REPOSITORY_0));\n }\n\n }",
"public void addColumn(String columnName, boolean searchable, boolean orderable,\n String searchValue) {\n this.columns.add(new Column(columnName, \"\", searchable, orderable,\n new Search(searchValue, false)));\n }",
"public static String getDatatypeIriFromJsonDatatype(String jsonDatatype) {\n\t\tswitch (jsonDatatype) {\n\t\tcase JSON_DT_ITEM:\n\t\t\treturn DT_ITEM;\n\t\tcase JSON_DT_PROPERTY:\n\t\t\treturn DT_PROPERTY;\n\t\tcase JSON_DT_GLOBE_COORDINATES:\n\t\t\treturn DT_GLOBE_COORDINATES;\n\t\tcase JSON_DT_URL:\n\t\t\treturn DT_URL;\n\t\tcase JSON_DT_COMMONS_MEDIA:\n\t\t\treturn DT_COMMONS_MEDIA;\n\t\tcase JSON_DT_TIME:\n\t\t\treturn DT_TIME;\n\t\tcase JSON_DT_QUANTITY:\n\t\t\treturn DT_QUANTITY;\n\t\tcase JSON_DT_STRING:\n\t\t\treturn DT_STRING;\n\t\tcase JSON_DT_MONOLINGUAL_TEXT:\n\t\t\treturn DT_MONOLINGUAL_TEXT;\n\t\tdefault:\n\t\t\tif(!JSON_DATATYPE_PATTERN.matcher(jsonDatatype).matches()) {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid JSON datatype \\\"\" + jsonDatatype + \"\\\"\");\n\t\t\t}\n\n\t\t\tString[] parts = jsonDatatype.split(\"-\");\n\t\t\tfor(int i = 0; i < parts.length; i++) {\n\t\t\t\tparts[i] = StringUtils.capitalize(parts[i]);\n\t\t\t}\n\t\t\treturn \"http://wikiba.se/ontology#\" + StringUtils.join(parts);\n\t\t}\n\t}",
"public ProjectCalendarWeek getWorkWeek(Date date)\n {\n ProjectCalendarWeek week = null;\n if (!m_workWeeks.isEmpty())\n {\n sortWorkWeeks();\n\n int low = 0;\n int high = m_workWeeks.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarWeek midVal = m_workWeeks.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getDateRange().getStart(), midVal.getDateRange().getEnd(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n week = midVal;\n break;\n }\n }\n }\n }\n\n if (week == null && getParent() != null)\n {\n // Check base calendar as well for a work week.\n week = getParent().getWorkWeek(date);\n }\n return (week);\n }",
"protected AbstractColumn buildSimpleBarcodeColumn() {\n\t\tBarCodeColumn column = new BarCodeColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\tcolumn.setApplicationIdentifier(applicationIdentifier);\n\t\tcolumn.setBarcodeType(barcodeType);\n\t\tcolumn.setShowText(showText);\n\t\tcolumn.setCheckSum(checkSum);\n\t\treturn column;\n\t}",
"public void signOff(String key, Collection<WebSocketConnection> connections) {\n if (connections.isEmpty()) {\n return;\n }\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.keySet().removeAll(connections);\n }",
"Map<UUID, UUID> getActivityCodes(Activity activity)\n {\n Map<UUID, UUID> map = m_activityCodeCache.get(activity);\n if (map == null)\n {\n map = new HashMap<UUID, UUID>();\n m_activityCodeCache.put(activity, map);\n for (CodeAssignment ca : activity.getCodeAssignment())\n {\n UUID code = getUUID(ca.getCodeUuid(), ca.getCode());\n UUID value = getUUID(ca.getValueUuid(), ca.getValue());\n map.put(code, value);\n }\n }\n return map;\n }"
] |
Creates a ClassNode containing the wrapper of a ClassNode
of primitive type. Any ClassNode representing a primitive
type should be created using the predefined types used in
class. The method will check the parameter for known
references of ClassNode representing a primitive type. If
Reference is found, then a ClassNode will be contained that
represents the wrapper class. For example for boolean, the
wrapper class is java.lang.Boolean.
If the parameter is no primitive type, the redirected
ClassNode will be returned
@see #make(Class)
@see #make(String)
@param cn the ClassNode containing a possible primitive type | [
"public static ClassNode getWrapper(ClassNode cn) {\n cn = cn.redirect();\n if (!isPrimitiveType(cn)) return cn;\n if (cn==boolean_TYPE) {\n return Boolean_TYPE;\n } else if (cn==byte_TYPE) {\n return Byte_TYPE;\n } else if (cn==char_TYPE) {\n return Character_TYPE;\n } else if (cn==short_TYPE) {\n return Short_TYPE;\n } else if (cn==int_TYPE) {\n return Integer_TYPE;\n } else if (cn==long_TYPE) {\n return Long_TYPE;\n } else if (cn==float_TYPE) {\n return Float_TYPE;\n } else if (cn==double_TYPE) {\n return Double_TYPE;\n } else if (cn==VOID_TYPE) {\n return void_WRAPPER_TYPE;\n }\n else {\n return cn;\n }\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 Token add( Symbol symbol ) {\n Token t = new Token(symbol);\n push( t );\n return t;\n }",
"public static dospolicy get(nitro_service service, String name) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tobj.set_name(name);\n\t\tdospolicy response = (dospolicy) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private static void listCalendars(ProjectFile file)\n {\n for (ProjectCalendar cal : file.getCalendars())\n {\n System.out.println(cal.toString());\n }\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 }",
"@Pure\n\tpublic static <P1, P2, P3, P4, RESULT> Function3<P2, P3, P4, RESULT> curry(\n\t\t\tfinal Function4<? super P1, ? super P2, ? super P3, ? super P4, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function3<P2, P3, P4, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3, P4 p4) {\n\t\t\t\treturn function.apply(argument, p2, p3, p4);\n\t\t\t}\n\t\t};\n\t}",
"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 }",
"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 }",
"@Override\n public final int getInt(final String key) {\n Integer result = optInt(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }"
] |
Gets value of this function at the current point, computed on the given batch of examples.
@param batch A set of indices indicating the examples over which the gradient should be computed.
@return The value of the function at the point. | [
"public double getValue(int[] batch) {\n double value = 0.0;\n for (int i=0; i<batch.length; i++) {\n value += getValue(i);\n }\n return value;\n }"
] | [
"private void debugLogStart(String operationType,\n Long originTimeInMS,\n Long requestReceivedTimeInMs,\n String keyString) {\n long durationInMs = requestReceivedTimeInMs - originTimeInMS;\n logger.debug(\"Received a new request. Operation Type: \" + operationType + \" , key(s): \"\n + keyString + \" , Store: \" + this.storeName + \" , Origin time (in ms): \"\n + originTimeInMS + \" . Request received at time(in ms): \"\n + requestReceivedTimeInMs\n + \" , Duration from RESTClient to CoordinatorFatClient(in ms): \"\n + durationInMs);\n\n }",
"public RowColumn following() {\n if (row.equals(Bytes.EMPTY)) {\n return RowColumn.EMPTY;\n } else if (col.equals(Column.EMPTY)) {\n return new RowColumn(followingBytes(row));\n } else if (!col.isQualifierSet()) {\n return new RowColumn(row, new Column(followingBytes(col.getFamily())));\n } else if (!col.isVisibilitySet()) {\n return new RowColumn(row, new Column(col.getFamily(), followingBytes(col.getQualifier())));\n } else {\n return new RowColumn(row,\n new Column(col.getFamily(), col.getQualifier(), followingBytes(col.getVisibility())));\n }\n }",
"public String isChecked(String value1, String value2) {\n\n if ((value1 == null) || (value2 == null)) {\n return \"\";\n }\n\n if (value1.trim().equalsIgnoreCase(value2.trim())) {\n return \"checked\";\n }\n\n return \"\";\n }",
"private StitchUserT doLogin(final StitchCredential credential, final boolean asLinkRequest) {\n final Response response = doLoginRequest(credential, asLinkRequest);\n\n final StitchUserT previousUser = activeUser;\n final StitchUserT user = processLoginResponse(credential, response, asLinkRequest);\n\n if (asLinkRequest) {\n onUserLinked(user);\n } else {\n onUserLoggedIn(user);\n onActiveUserChanged(activeUser, previousUser);\n }\n\n return user;\n }",
"private static Class<?> extractTypeFromClass(Class<?> clazz, Class<?> source, int typeIndex,\n\t\t\tMap<TypeVariable, Type> typeVariableMap, Map<Integer, Integer> typeIndexesPerLevel,\n\t\t\tint nestingLevel, int currentLevel) {\n\n\t\tif (clazz.getName().startsWith(\"java.util.\")) {\n\t\t\treturn null;\n\t\t}\n\t\tif (clazz.getSuperclass() != null && isIntrospectionCandidate(clazz.getSuperclass())) {\n\t\t\ttry {\n\t\t\t\treturn extractType(clazz.getGenericSuperclass(), source, typeIndex, typeVariableMap,\n\t\t\t\t\t\ttypeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t}\n\t\t\tcatch (MalformedParameterizedTypeException ex) {\n\t\t\t\t// from getGenericSuperclass() - ignore and continue with interface introspection\n\t\t\t}\n\t\t}\n\t\tType[] ifcs = clazz.getGenericInterfaces();\n\t\tif (ifcs != null) {\n\t\t\tfor (Type ifc : ifcs) {\n\t\t\t\tType rawType = ifc;\n\t\t\t\tif (ifc instanceof ParameterizedType) {\n\t\t\t\t\trawType = ((ParameterizedType) ifc).getRawType();\n\t\t\t\t}\n\t\t\t\tif (rawType instanceof Class && isIntrospectionCandidate((Class) rawType)) {\n\t\t\t\t\treturn extractType(ifc, source, typeIndex, typeVariableMap, typeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"private static final void writeJson(Writer os, //\n Object object, //\n SerializeConfig config, //\n SerializeFilter[] filters, //\n DateFormat dateFormat, //\n int defaultFeatures, //\n SerializerFeature... features) {\n SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features);\n\n try {\n JSONSerializer serializer = new JSONSerializer(writer, config);\n\n if (dateFormat != null) {\n serializer.setDateFormat(dateFormat);\n serializer.config(SerializerFeature.WriteDateUseDateFormat, true);\n }\n\n if (filters != null) {\n for (SerializeFilter filter : filters) {\n serializer.addFilter(filter);\n }\n }\n serializer.write(object);\n } finally {\n writer.close();\n }\n }",
"private int deleteSegments(Log log, List<LogSegment> segments) {\n int total = 0;\n for (LogSegment segment : segments) {\n boolean deleted = false;\n try {\n try {\n segment.getMessageSet().close();\n } catch (IOException e) {\n logger.warn(e.getMessage(), e);\n }\n if (!segment.getFile().delete()) {\n deleted = true;\n } else {\n total += 1;\n }\n } finally {\n logger.warn(String.format(\"DELETE_LOG[%s] %s => %s\", log.name, segment.getFile().getAbsolutePath(),\n deleted));\n }\n }\n return total;\n }",
"public ReferrerList getPhotoReferrers(Date date, String domain, String photoId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTO_REFERRERS, domain, \"photo_id\", photoId, date, perPage, page);\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public TrackMetadata requestMetadataFrom(final DataReference track, final CdjStatus.TrackType trackType) {\n return requestMetadataInternal(track, trackType, false);\n }"
] |
Returns the docker version.
@param serverUrl
The serverUrl to use. | [
"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 DbConn getConn()\n {\n Connection cnx = null;\n try\n {\n Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.\n cnx = _ds.getConnection();\n if (cnx.getAutoCommit())\n {\n cnx.setAutoCommit(false);\n cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode\n }\n\n if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)\n {\n cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n }\n\n return new DbConn(this, cnx);\n }\n catch (SQLException e)\n {\n DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.\n throw new DatabaseException(e);\n }\n }",
"private static JSONObject parseTarget(Shape target) throws JSONException {\n JSONObject targetObject = new JSONObject();\n\n targetObject.put(\"resourceId\",\n target.getResourceId().toString());\n\n return targetObject;\n }",
"public List<GanttDesignerRemark.Task> getTask()\n {\n if (task == null)\n {\n task = new ArrayList<GanttDesignerRemark.Task>();\n }\n return this.task;\n }",
"public static double[][] diag(double[] vector){\n\n\t\t// Note: According to the Java Language spec, an array is initialized with the default value, here 0.\n\t\tdouble[][] diagonalMatrix = new double[vector.length][vector.length];\n\n\t\tfor(int index = 0; index < vector.length; index++) {\n\t\t\tdiagonalMatrix[index][index] = vector[index];\n\t\t}\n\n\t\treturn diagonalMatrix;\n\t}",
"public byte[] toArray() {\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return copy;\n }",
"public DescriptorRepository readDescriptorRepository(String fileName)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readDescriptorRepository(fileName);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository \" + fileName, e);\r\n }\r\n }",
"public static Class<?> loadClass(String className, ClassLoader cl) {\n try {\n return Class.forName(className, false, cl);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public static base_responses delete(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 deleteresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tdeleteresources[i] = new nsacl6();\n\t\t\t\tdeleteresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void writeResources() throws IOException\n {\n writeAttributeTypes(\"resource_types\", ResourceField.values());\n\n m_writer.writeStartList(\"resources\");\n for (Resource resource : m_projectFile.getResources())\n {\n writeFields(null, resource, ResourceField.values());\n }\n m_writer.writeEndList();\n }"
] |
Stop the drag action. | [
"public void stopDrag() {\n mPhysicsDragger.stopDrag();\n\n mPhysicsContext.runOnPhysicsThread(new Runnable() {\n @Override\n public void run() {\n if (mRigidBodyDragMe != null) {\n NativePhysics3DWorld.stopDrag(getNative());\n mRigidBodyDragMe = null;\n }\n }\n });\n }"
] | [
"public void close()\t{\n\t\tif (watchdog != null) {\n\t\t\twatchdog.cancel();\n\t\t\twatchdog = null;\n\t\t}\n\t\t\n\t\tdisconnect();\n\t\t\n\t\t// clear nodes collection and send queue\n\t\tfor (Object listener : this.zwaveEventListeners.toArray()) {\n\t\t\tif (!(listener instanceof ZWaveNode))\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tthis.zwaveEventListeners.remove(listener);\n\t\t}\n\t\t\n\t\tthis.zwaveNodes.clear();\n\t\tthis.sendQueue.clear();\n\t\t\n\t\tlogger.info(\"Stopped Z-Wave controller\");\n\t}",
"static ChangeEvent<BsonDocument> changeEventForLocalInsert(\n final MongoNamespace namespace,\n final BsonDocument document,\n final boolean writePending\n ) {\n final BsonValue docId = BsonUtils.getDocumentId(document);\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.INSERT,\n document,\n namespace,\n new BsonDocument(\"_id\", docId),\n null,\n writePending);\n }",
"public static String getCountryCodeAndCheckDigit(final String iban) {\n return iban.substring(COUNTRY_CODE_INDEX,\n COUNTRY_CODE_INDEX + COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH);\n }",
"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 static aaauser_auditsyslogpolicy_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_auditsyslogpolicy_binding obj = new aaauser_auditsyslogpolicy_binding();\n\t\tobj.set_username(username);\n\t\taaauser_auditsyslogpolicy_binding response[] = (aaauser_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private boolean activityIsMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"Milestone\") != -1;\n }",
"protected Declaration createDeclaration(String property, Term<?> term)\n {\n Declaration d = CSSFactory.getRuleFactory().createDeclaration();\n d.unlock();\n d.setProperty(property);\n d.add(term);\n return d;\n }",
"private Integer getIntegerTimeInMinutes(Date date)\n {\n Integer result = null;\n if (date != null)\n {\n Calendar cal = DateHelper.popCalendar(date);\n int time = cal.get(Calendar.HOUR_OF_DAY) * 60;\n time += cal.get(Calendar.MINUTE);\n DateHelper.pushCalendar(cal);\n result = Integer.valueOf(time); \n }\n return (result);\n }",
"private static boolean isAssignableFrom(Type from, ParameterizedType to,\n\t\t\tMap<String, Type> typeVarMap) {\n\n\t\tif (from == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (to.equals(from)) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// First figure out the class and any type information.\n\t\tClass<?> clazz = getRawType(from);\n\t\tParameterizedType ptype = null;\n\t\tif (from instanceof ParameterizedType) {\n\t\t\tptype = (ParameterizedType) from;\n\t\t}\n\n\t\t// Load up parameterized variable info if it was parameterized.\n\t\tif (ptype != null) {\n\t\t\tType[] tArgs = ptype.getActualTypeArguments();\n\t\t\tTypeVariable<?>[] tParams = clazz.getTypeParameters();\n\t\t\tfor (int i = 0; i < tArgs.length; i++) {\n\t\t\t\tType arg = tArgs[i];\n\t\t\t\tTypeVariable<?> var = tParams[i];\n\t\t\t\twhile (arg instanceof TypeVariable) {\n\t\t\t\t\tTypeVariable<?> v = (TypeVariable<?>) arg;\n\t\t\t\t\targ = typeVarMap.get(v.getName());\n\t\t\t\t}\n\t\t\t\ttypeVarMap.put(var.getName(), arg);\n\t\t\t}\n\n\t\t\t// check if they are equivalent under our current mapping.\n\t\t\tif (typeEquals(ptype, to, typeVarMap)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tfor (Type itype : clazz.getGenericInterfaces()) {\n\t\t\tif (isAssignableFrom(itype, to, new HashMap<String, Type>(\n\t\t\t\t\ttypeVarMap))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\t// Interfaces didn't work, try the superclass.\n\t\tType sType = clazz.getGenericSuperclass();\n\t\tif (isAssignableFrom(sType, to, new HashMap<String, Type>(typeVarMap))) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}"
] |
Add a "post-run" dependent for this model.
@param dependent the "post-run" dependent.
@return key to be used as parameter to taskResult(string) method to retrieve result of root
task in the given dependent task group | [
"protected String addPostRunDependent(TaskGroup.HasTaskGroup dependent) {\n Objects.requireNonNull(dependent);\n this.taskGroup.addPostRunDependentTaskGroup(dependent.taskGroup());\n return dependent.taskGroup().key();\n }"
] | [
"public void setShadow(float radius, float dx, float dy, int color) {\n\t\tshadowRadius = radius;\n\t\tshadowDx = dx;\n\t\tshadowDy = dy;\n\t\tshadowColor = color;\n\t\tupdateShadow();\n\t}",
"public void setWriteTimeout(int writeTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}",
"protected boolean isTransient(ClassDescriptor cld, Object obj, Identity oid)\r\n {\r\n // if the Identity is transient we assume a non-persistent object\r\n boolean isNew = oid != null && oid.isTransient();\r\n /*\r\n detection of new objects is costly (select of ID in DB to check if object\r\n already exists) we do:\r\n a. check if the object has nullified PK field\r\n b. check if the object is already registered\r\n c. lookup from cache and if not found, last option select on DB\r\n */\r\n if(!isNew)\r\n {\r\n final PersistenceBroker pb = getBroker();\r\n if(cld == null)\r\n {\r\n cld = pb.getClassDescriptor(obj.getClass());\r\n }\r\n isNew = pb.serviceBrokerHelper().hasNullPKField(cld, obj);\r\n if(!isNew)\r\n {\r\n if(oid == null)\r\n {\r\n oid = pb.serviceIdentity().buildIdentity(cld, obj);\r\n }\r\n final ObjectEnvelope mod = objectEnvelopeTable.getByIdentity(oid);\r\n if(mod != null)\r\n {\r\n // already registered object, use current state\r\n isNew = mod.needsInsert();\r\n }\r\n else\r\n {\r\n // if object was found cache, assume it's old\r\n // else make costly check against the DB\r\n isNew = pb.serviceObjectCache().lookup(oid) == null\r\n && !pb.serviceBrokerHelper().doesExist(cld, oid, obj);\r\n }\r\n }\r\n }\r\n return isNew;\r\n }",
"@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 }",
"public SelectStatement getPreparedSelectStatement(Query query, ClassDescriptor cld)\r\n {\r\n SelectStatement sql = new SqlSelectStatement(m_platform, cld, query, logger);\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n return sql;\r\n }",
"public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)\r\n throws SQLException\r\n {\r\n return getObjectFromColumn(rs, null, jdbcType, null, columnId);\r\n }",
"private Double getDouble(Number number)\n {\n Double result = null;\n\n if (number != null)\n {\n result = Double.valueOf(number.doubleValue());\n }\n\n return result;\n }",
"public Set<String> getTags() {\r\n Set<String> tags = new HashSet<String>(classIndex.objectsList());\r\n tags.remove(flags.backgroundSymbol);\r\n return tags;\r\n }",
"public static base_response delete(nitro_service client, String Dnssuffix) throws Exception {\n\t\tdnssuffix deleteresource = new dnssuffix();\n\t\tdeleteresource.Dnssuffix = Dnssuffix;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] |
Creates a Set out of the given keys
@param <K> the key type
@param keys
the keys
@return a Set containing the given keys | [
"@SafeVarargs\n public static <K> Set<K> set(final K... keys) {\n return new LinkedHashSet<K>(Arrays.asList(keys));\n }"
] | [
"public String userAgent() {\n return String.format(\"Azure-SDK-For-Java/%s OS:%s MacAddressHash:%s Java:%s\",\n getClass().getPackage().getImplementationVersion(),\n OS,\n MAC_ADDRESS_HASH,\n JAVA_VERSION);\n }",
"public Iterable<BoxRetentionPolicyAssignment.Info> getAllAssignments(int limit, String ... fields) {\r\n return this.getAssignments(null, limit, fields);\r\n }",
"public static String getValue(Element element) {\r\n if (element != null) {\r\n Node dataNode = element.getFirstChild();\r\n if (dataNode != null) {\r\n return ((Text) dataNode).getData();\r\n }\r\n }\r\n return null;\r\n }",
"private String getTimeString(Date value)\n {\n Calendar cal = DateHelper.popCalendar(value);\n int hours = cal.get(Calendar.HOUR_OF_DAY);\n int minutes = cal.get(Calendar.MINUTE);\n DateHelper.pushCalendar(cal);\n \n StringBuilder sb = new StringBuilder(4);\n sb.append(m_twoDigitFormat.format(hours));\n sb.append(m_twoDigitFormat.format(minutes));\n\n return (sb.toString());\n }",
"public static int lengthOfCodePoint(int codePoint)\n {\n if (codePoint < 0) {\n throw new InvalidCodePointException(codePoint);\n }\n if (codePoint < 0x80) {\n // normal ASCII\n // 0xxx_xxxx\n return 1;\n }\n if (codePoint < 0x800) {\n return 2;\n }\n if (codePoint < 0x1_0000) {\n return 3;\n }\n if (codePoint < 0x11_0000) {\n return 4;\n }\n // Per RFC3629, UTF-8 is limited to 4 bytes, so more bytes are illegal\n throw new InvalidCodePointException(codePoint);\n }",
"public void setProgressBackgroundColor(int colorRes) {\n mCircleView.setBackgroundColor(colorRes);\n mProgress.setBackgroundColor(getResources().getColor(colorRes));\n }",
"private void initBeanNameDefaulted(EnhancedAnnotation<T> annotatedAnnotation) {\n if (annotatedAnnotation.isAnnotationPresent(Named.class)) {\n if (!\"\".equals(annotatedAnnotation.getAnnotation(Named.class).value())) {\n throw MetadataLogger.LOG.valueOnNamedStereotype(annotatedAnnotation);\n }\n beanNameDefaulted = true;\n }\n }",
"public GVRMesh findMesh(GVRSceneObject model)\n {\n class MeshFinder implements GVRSceneObject.ComponentVisitor\n {\n private GVRMesh meshFound = null;\n public GVRMesh getMesh() { return meshFound; }\n public boolean visit(GVRComponent comp)\n {\n GVRRenderData rdata = (GVRRenderData) comp;\n meshFound = rdata.getMesh();\n return (meshFound == null);\n }\n };\n MeshFinder findMesh = new MeshFinder();\n model.forAllComponents(findMesh, GVRRenderData.getComponentType());\n return findMesh.getMesh();\n }",
"public ProxyAuthentication getProxyAuthentication() {\n\t\t// convert authentication to layerAuthentication so we only use one\n\t\t// TODO Remove when removing deprecated authentication field.\n\t\tif (layerAuthentication == null && authentication != null) {\n\t\t\tlayerAuthentication = new LayerAuthentication();\n\t\t\tlayerAuthentication.setAuthenticationMethod(LayerAuthenticationMethod.valueOf(authentication\n\t\t\t\t\t.getAuthenticationMethod().name()));\n\t\t\tlayerAuthentication.setPassword(authentication.getPassword());\n\t\t\tlayerAuthentication.setPasswordKey(authentication.getPasswordKey());\n\t\t\tlayerAuthentication.setRealm(authentication.getRealm());\n\t\t\tlayerAuthentication.setUser(authentication.getUser());\n\t\t\tlayerAuthentication.setUserKey(authentication.getUserKey());\n\t\t}\n\t\t// TODO Remove when removing deprecated authentication field.\n\t\treturn layerAuthentication;\n\t}"
] |
Issue the database statements to drop the table associated with a class.
<p>
<b>WARNING:</b> This is [obviously] very destructive and is unrecoverable.
</p>
@param connectionSource
Associated connection source.
@param dataClass
The class for which a table will be dropped.
@param ignoreErrors
If set to true then try each statement regardless of {@link SQLException} thrown previously.
@return The number of statements executed to do so. | [
"public static <T, ID> int dropTable(ConnectionSource connectionSource, Class<T> dataClass, boolean ignoreErrors)\n\t\t\tthrows SQLException {\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);\n\t\treturn dropTable(dao, ignoreErrors);\n\t}"
] | [
"public synchronized void stop() throws DatastoreEmulatorException {\n // We intentionally don't check the internal state. If people want to try and stop the server\n // multiple times that's fine.\n stopEmulatorInternal();\n if (state != State.STOPPED) {\n state = State.STOPPED;\n if (projectDirectory != null) {\n try {\n Process process =\n new ProcessBuilder(\"rm\", \"-r\", projectDirectory.getAbsolutePath()).start();\n if (process.waitFor() != 0) {\n throw new IOException(\n \"Temporary project directory deletion exited with \" + process.exitValue());\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n }\n }\n }\n }",
"public 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 }",
"public void setDefault() {\n try {\n TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);\n String phone = telephonyManager.getLine1Number();\n if (phone != null && !phone.isEmpty()) {\n this.setNumber(phone);\n } else {\n String iso = telephonyManager.getNetworkCountryIso();\n setEmptyDefault(iso);\n }\n } catch (SecurityException e) {\n setEmptyDefault();\n }\n }",
"public static long count(nitro_service service, String ciphergroupname) throws Exception{\n\t\tsslcipher_individualcipher_binding obj = new sslcipher_individualcipher_binding();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tsslcipher_individualcipher_binding response[] = (sslcipher_individualcipher_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 void close() {\n Closer.closeQuietly(acceptor);\n for (Processor processor : processors) {\n Closer.closeQuietly(processor);\n }\n }",
"private void updateBundleDescriptorContent() throws CmsXmlException {\n\n if (m_descContent.hasLocale(Descriptor.LOCALE)) {\n m_descContent.removeLocale(Descriptor.LOCALE);\n }\n m_descContent.addLocale(m_cms, Descriptor.LOCALE);\n\n int i = 0;\n Property<Object> descProp;\n String desc;\n Property<Object> defaultValueProp;\n String defaultValue;\n Map<String, Item> keyItemMap = getKeyItemMap();\n List<String> keys = new ArrayList<String>(keyItemMap.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n\n m_descContent.addValue(m_cms, Descriptor.N_MESSAGE, Descriptor.LOCALE, i);\n i++;\n String messagePrefix = Descriptor.N_MESSAGE + \"[\" + i + \"]/\";\n\n m_descContent.getValue(messagePrefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(\n m_cms,\n (String)key);\n descProp = keyItemMap.get(key).getItemProperty(TableProperty.DESCRIPTION);\n if ((null != descProp) && (null != descProp.getValue())) {\n desc = descProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).setStringValue(\n m_cms,\n desc);\n }\n\n defaultValueProp = keyItemMap.get(key).getItemProperty(TableProperty.DEFAULT);\n if ((null != defaultValueProp) && (null != defaultValueProp.getValue())) {\n defaultValue = defaultValueProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).setStringValue(\n m_cms,\n defaultValue);\n }\n\n }\n }\n\n }",
"private final boolean matchChildBlock(int bufferIndex)\n {\n //\n // Match the pattern we see at the start of the child block\n //\n int index = 0;\n for (byte b : CHILD_BLOCK_PATTERN)\n {\n if (b != m_buffer[bufferIndex + index])\n {\n return false;\n }\n ++index;\n }\n\n //\n // The first step will produce false positives. To handle this, we should find\n // the name of the block next, and check to ensure that the length\n // of the name makes sense.\n //\n int nameLength = FastTrackUtility.getInt(m_buffer, bufferIndex + index);\n\n// System.out.println(\"Name length: \" + nameLength);\n// \n// if (nameLength > 0 && nameLength < 100)\n// {\n// String name = new String(m_buffer, bufferIndex+index+4, nameLength, CharsetHelper.UTF16LE);\n// System.out.println(\"Name: \" + name);\n// }\n \n return nameLength > 0 && nameLength < 100;\n }",
"public static String getAt(CharSequence self, Collection indices) {\n StringBuilder answer = new StringBuilder();\n for (Object value : indices) {\n if (value instanceof Range) {\n answer.append(getAt(self, (Range) value));\n } else if (value instanceof Collection) {\n answer.append(getAt(self, (Collection) value));\n } else {\n int idx = DefaultTypeTransformation.intUnbox(value);\n answer.append(getAt(self, idx));\n }\n }\n return answer.toString();\n }",
"public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {\n calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);\n calendar.set(Calendar.MINUTE, minute);\n calendar.set(Calendar.SECOND, second);\n calendar.set(Calendar.MILLISECOND, millisecond);\n }"
] |
Removes trailing and leading whitespace, and also reduces each
sequence of internal whitespace to a single space. | [
"public static String normalizeWS(String value) {\n char[] tmp = new char[value.length()];\n int pos = 0;\n boolean prevws = false;\n for (int ix = 0; ix < tmp.length; ix++) {\n char ch = value.charAt(ix);\n if (ch != ' ' && ch != '\\t' && ch != '\\n' && ch != '\\r') {\n if (prevws && pos != 0)\n tmp[pos++] = ' ';\n\n tmp[pos++] = ch;\n prevws = false;\n } else\n prevws = true;\n }\n return new String(tmp, 0, pos);\n }"
] | [
"public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) {\n return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent);\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}",
"public BoxFolder.Info getFolderInfo(String folderID) {\n URL url = FOLDER_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFolder folder = new BoxFolder(this.api, jsonObject.get(\"id\").asString());\n return folder.new Info(response.getJSON());\n }",
"public void remove( Token token ) {\n if( token == first ) {\n first = first.next;\n }\n if( token == last ) {\n last = last.previous;\n }\n if( token.next != null ) {\n token.next.previous = token.previous;\n }\n if( token.previous != null ) {\n token.previous.next = token.next;\n }\n\n token.next = token.previous = null;\n size--;\n }",
"public static String trim(String s, int maxWidth) {\r\n if (s.length() <= maxWidth) {\r\n return (s);\r\n }\r\n return (s.substring(0, maxWidth));\r\n }",
"public void validate() throws PackagingException {\n if (control == null || !control.isDirectory()) {\n throw new PackagingException(\"The 'control' attribute doesn't point to a directory. \" + control);\n }\n\n if (changesIn != null) {\n\n if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) {\n throw new PackagingException(\"The 'changesIn' setting needs to point to a readable file. \" + changesIn + \" was not found/readable.\");\n }\n\n if (changesOut != null && !isWritableFile(changesOut)) {\n throw new PackagingException(\"Cannot write the output for 'changesOut' to \" + changesOut);\n }\n\n if (changesSave != null && !isWritableFile(changesSave)) {\n throw new PackagingException(\"Cannot write the output for 'changesSave' to \" + changesSave);\n }\n\n } else {\n if (changesOut != null || changesSave != null) {\n throw new PackagingException(\"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.\");\n }\n }\n\n if (Compression.toEnum(compression) == null) {\n throw new PackagingException(\"The compression method '\" + compression + \"' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')\");\n }\n\n if (deb == null) {\n throw new PackagingException(\"You need to specify where the deb file is supposed to be created.\");\n }\n\n getDigestCode(digest);\n }",
"public Gallery lookupGallery(String galleryId) throws FlickrException {\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GALLERY);\r\n parameters.put(\"url\", galleryId);\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 galleryElement = response.getPayload();\r\n Gallery gallery = new Gallery();\r\n gallery.setId(galleryElement.getAttribute(\"id\"));\r\n gallery.setUrl(galleryElement.getAttribute(\"url\"));\r\n\r\n User owner = new User();\r\n owner.setId(galleryElement.getAttribute(\"owner\"));\r\n gallery.setOwner(owner);\r\n gallery.setCreateDate(galleryElement.getAttribute(\"date_create\"));\r\n gallery.setUpdateDate(galleryElement.getAttribute(\"date_update\"));\r\n gallery.setPrimaryPhotoId(galleryElement.getAttribute(\"primary_photo_id\"));\r\n gallery.setPrimaryPhotoServer(galleryElement.getAttribute(\"primary_photo_server\"));\r\n gallery.setVideoCount(galleryElement.getAttribute(\"count_videos\"));\r\n gallery.setPhotoCount(galleryElement.getAttribute(\"count_photos\"));\r\n gallery.setPrimaryPhotoFarm(galleryElement.getAttribute(\"farm\"));\r\n gallery.setPrimaryPhotoSecret(galleryElement.getAttribute(\"secret\"));\r\n\r\n gallery.setTitle(XMLUtilities.getChildValue(galleryElement, \"title\"));\r\n gallery.setDesc(XMLUtilities.getChildValue(galleryElement, \"description\"));\r\n return gallery;\r\n }",
"private void writeIntegerField(String fieldName, Object value) throws IOException\n {\n int val = ((Number) value).intValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"private int calculateColor(float angle) {\n\t\tfloat unit = (float) (angle / (2 * Math.PI));\n\t\tif (unit < 0) {\n\t\t\tunit += 1;\n\t\t}\n\n\t\tif (unit <= 0) {\n\t\t\tmColor = COLORS[0];\n\t\t\treturn COLORS[0];\n\t\t}\n\t\tif (unit >= 1) {\n\t\t\tmColor = COLORS[COLORS.length - 1];\n\t\t\treturn COLORS[COLORS.length - 1];\n\t\t}\n\n\t\tfloat p = unit * (COLORS.length - 1);\n\t\tint i = (int) p;\n\t\tp -= i;\n\n\t\tint c0 = COLORS[i];\n\t\tint c1 = COLORS[i + 1];\n\t\tint a = ave(Color.alpha(c0), Color.alpha(c1), p);\n\t\tint r = ave(Color.red(c0), Color.red(c1), p);\n\t\tint g = ave(Color.green(c0), Color.green(c1), p);\n\t\tint b = ave(Color.blue(c0), Color.blue(c1), p);\n\n\t\tmColor = Color.argb(a, r, g, b);\n\t\treturn Color.argb(a, r, g, b);\n\t}"
] |
Update the background color of the mBgCircle image view. | [
"public void setBackgroundColor(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }"
] | [
"public static base_response update(nitro_service client, autoscaleaction resource) throws Exception {\n\t\tautoscaleaction updateresource = new autoscaleaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.parameters = resource.parameters;\n\t\tupdateresource.vmdestroygraceperiod = resource.vmdestroygraceperiod;\n\t\tupdateresource.quiettime = resource.quiettime;\n\t\tupdateresource.vserver = resource.vserver;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static String padLeft(String str, int totalChars, char ch) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n StringBuilder sb = new StringBuilder();\r\n for (int i = 0, num = totalChars - str.length(); i < num; i++) {\r\n sb.append(ch);\r\n }\r\n sb.append(str);\r\n return sb.toString();\r\n }",
"@Override\n public final boolean has(final String key) {\n String result = this.obj.optString(key, null);\n return result != null;\n }",
"public static base_responses delete(nitro_service client, String hostname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (hostname != null && hostname.length > 0) {\n\t\t\tdnsaaaarec deleteresources[] = new dnsaaaarec[hostname.length];\n\t\t\tfor (int i=0;i<hostname.length;i++){\n\t\t\t\tdeleteresources[i] = new dnsaaaarec();\n\t\t\t\tdeleteresources[i].hostname = hostname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void copyStructure( DMatrixSparseCSC orig ) {\n reshape(orig.numRows, orig.numCols, orig.nz_length);\n this.nz_length = orig.nz_length;\n System.arraycopy(orig.col_idx,0,col_idx,0,orig.numCols+1);\n System.arraycopy(orig.nz_rows,0,nz_rows,0,orig.nz_length);\n }",
"public void resetQuotaAndRecoverEnforcement() {\n for(Integer nodeId: nodeIds) {\n boolean quotaEnforcement = mapNodeToQuotaEnforcingEnabled.get(nodeId);\n adminClient.metadataMgmtOps.updateRemoteMetadata(Arrays.asList(nodeId),\n MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY,\n Boolean.toString(quotaEnforcement));\n }\n for(String storeName: storeNames) {\n adminClient.quotaMgmtOps.rebalanceQuota(storeName);\n }\n }",
"@Override public int getItemViewType(int position) {\n T content = getItem(position);\n return rendererBuilder.getItemViewType(content);\n }",
"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 }",
"private void handleFailedSendDataRequest(SerialMessage originalMessage) {\n\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\n\t\tif (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD)\n\t\t\treturn;\n\t\t\n\t\tif (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {\n\t\t\tZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);\n\t\t\t\n\t\t\tif (wakeUpCommandClass != null) {\n\t\t\t\twakeUpCommandClass.setAwake(false);\n\t\t\t\twakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue.\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)\n\t\t\treturn;\n\t\t\n\t\tnode.incrementResendCount();\n\t\t\n\t\tlogger.error(\"Got an error while sending data to node {}. Resending message.\", node.getNodeId());\n\t\tthis.sendData(originalMessage);\n\t}"
] |
Get a scalar value for the DOM diversity using the Robust Tree Edit Distance
@param dom1
@param dom2
@return | [
"public static double getRobustTreeEditDistance(String dom1, String dom2) {\n\n\t\tLblTree domTree1 = null, domTree2 = null;\n\t\ttry {\n\t\t\tdomTree1 = getDomTree(dom1);\n\t\t\tdomTree2 = getDomTree(dom2);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tdouble DD = 0.0;\n\t\tRTED_InfoTree_Opt rted;\n\t\tdouble ted;\n\n\t\trted = new RTED_InfoTree_Opt(1, 1, 1);\n\n\t\t// compute tree edit distance\n\t\trted.init(domTree1, domTree2);\n\n\t\tint maxSize = Math.max(domTree1.getNodeCount(), domTree2.getNodeCount());\n\n\t\trted.computeOptimalStrategy();\n\t\tted = rted.nonNormalizedTreeDist();\n\t\tted /= (double) maxSize;\n\n\t\tDD = ted;\n\t\treturn DD;\n\t}"
] | [
"public String getModuleJenkinsJobInfo(final DbArtifact dbArtifact) {\n\t\tfinal DbModule module = getModule(dbArtifact);\n\t\tif(module == null){\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\tfinal String jenkinsJobUrl = module.getBuildInfo().get(\"jenkins-job-url\");\n\t\t\n\t\tif(jenkinsJobUrl == null){\n\t\t\treturn \"\";\t\t\t\n\t\t}\n\n\t\treturn jenkinsJobUrl;\n\t}",
"private Map<String, String> parseAttributes(I_CmsXmlContentLocation formatterLoc) {\n\n Map<String, String> result = new LinkedHashMap<>();\n for (I_CmsXmlContentValueLocation mappingLoc : formatterLoc.getSubValues(N_ATTRIBUTE)) {\n String key = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_KEY));\n String value = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_VALUE));\n result.put(key, value);\n }\n return Collections.unmodifiableMap(result);\n }",
"public static String getPrefix(String column) {\n\t\treturn column.contains( \".\" ) ? DOT_SEPARATOR_PATTERN.split( column )[0] : null;\n\t}",
"public double d(double x){\n\t\tint intervalNumber =getIntervalNumber(x);\n\t\tif (intervalNumber==0 || intervalNumber==points.length) {\n\t\t\treturn x;\n\t\t}\n\t\treturn getIntervalReferencePoint(intervalNumber-1);\n\t}",
"protected AbstractElement getEnclosingSingleElementGroup(AbstractElement elementToParse) {\n\t\tEObject container = elementToParse.eContainer();\n\t\tif (container instanceof Group) {\n\t\t\tif (((Group) container).getElements().size() == 1) {\n\t\t\t\treturn (AbstractElement) container;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public FieldType getField()\n {\n FieldType result = null;\n if (m_index < m_fields.length)\n {\n result = m_fields[m_index++];\n }\n\n return result;\n }",
"public void remove(Identity oid)\r\n {\r\n try\r\n {\r\n jcsCache.remove(oid.toString());\r\n }\r\n catch (CacheException e)\r\n {\r\n throw new RuntimeCacheException(e.getMessage());\r\n }\r\n }",
"public static boolean intArrayContains(int[] array, int numToCheck) {\n for (int i = 0; i < array.length; i++) {\n if (array[i] == numToCheck) {\n return true;\n }\n }\n return false;\n }",
"public final int getJdbcType()\r\n {\r\n switch (this.fieldSource)\r\n {\r\n case SOURCE_FIELD :\r\n return this.getFieldRef().getJdbcType().getType();\r\n case SOURCE_NULL :\r\n return java.sql.Types.NULL;\r\n case SOURCE_VALUE :\r\n return java.sql.Types.VARCHAR;\r\n default :\r\n return java.sql.Types.NULL;\r\n }\r\n }"
] |
Removes the value connected to the given key
from all levels of the cache. Will not throw an
exception on fail.
@param cacheKey | [
"public void purge(String cacheKey) {\n try {\n if (useMemoryCache) {\n if (memoryCache != null) {\n memoryCache.remove(cacheKey);\n }\n }\n\n if (useDiskCache) {\n if (diskLruCache != null) {\n diskLruCache.remove(cacheKey);\n }\n }\n } catch (Exception e) {\n Log.w(TAG, \"Could not remove entry in cache purge\", e);\n }\n }"
] | [
"public WindupConfiguration setOptionValue(String name, Object value)\n {\n configurationOptions.put(name, value);\n return this;\n }",
"protected void bindHelper(GVRScriptBundle scriptBundle, GVRSceneObject rootSceneObject, int bindMask)\n throws IOException, GVRScriptException\n {\n for (GVRScriptBindingEntry entry : scriptBundle.file.binding) {\n GVRAndroidResource rc;\n if (entry.volumeType == null || entry.volumeType.isEmpty()) {\n rc = scriptBundle.volume.openResource(entry.script);\n } else {\n GVRResourceVolume.VolumeType volumeType = GVRResourceVolume.VolumeType.fromString(entry.volumeType);\n if (volumeType == null) {\n throw new GVRScriptException(String.format(\"Volume type %s is not recognized, script=%s\",\n entry.volumeType, entry.script));\n }\n rc = new GVRResourceVolume(mGvrContext, volumeType).openResource(entry.script);\n }\n\n GVRScriptFile scriptFile = (GVRScriptFile)loadScript(rc, entry.language);\n\n String targetName = entry.target;\n if (targetName.startsWith(TARGET_PREFIX)) {\n TargetResolver resolver = sBuiltinTargetMap.get(targetName);\n IScriptable target = resolver.getTarget(mGvrContext, targetName);\n\n // Apply mask\n boolean toBind = false;\n if ((bindMask & BIND_MASK_GVRSCRIPT) != 0 && targetName.equalsIgnoreCase(TARGET_GVRMAIN)) {\n toBind = true;\n }\n\n if ((bindMask & BIND_MASK_GVRACTIVITY) != 0 && targetName.equalsIgnoreCase(TARGET_GVRAPPLICATION)) {\n toBind = true;\n }\n\n if (toBind) {\n attachScriptFile(target, scriptFile);\n }\n } else {\n if ((bindMask & BIND_MASK_SCENE_OBJECTS) != 0) {\n if (targetName.equals(rootSceneObject.getName())) {\n attachScriptFile(rootSceneObject, scriptFile);\n }\n\n // Search in children\n GVRSceneObject[] sceneObjects = rootSceneObject.getSceneObjectsByName(targetName);\n if (sceneObjects != null) {\n for (GVRSceneObject sceneObject : sceneObjects) {\n GVRScriptBehavior b = new GVRScriptBehavior(sceneObject.getGVRContext());\n b.setScriptFile(scriptFile);\n sceneObject.attachComponent(b);\n }\n }\n }\n }\n }\n }",
"public static base_response delete(nitro_service client, String sitename) throws Exception {\n\t\tgslbsite deleteresource = new gslbsite();\n\t\tdeleteresource.sitename = sitename;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"protected void writeBody(HttpURLConnection connection, ProgressListener listener) {\n if (this.body == null) {\n return;\n }\n\n connection.setDoOutput(true);\n try {\n OutputStream output = connection.getOutputStream();\n if (listener != null) {\n output = new ProgressOutputStream(output, listener, this.bodyLength);\n }\n int b = this.body.read();\n while (b != -1) {\n output.write(b);\n b = this.body.read();\n }\n output.close();\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n }",
"public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {\r\n return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);\r\n }",
"@AsParameterConverter\n\tpublic Trader retrieveTrader(String name) {\n\t\tfor (Trader trader : traders) {\n\t\t\tif (trader.getName().equals(name)) {\n\t\t\t\treturn trader;\n\t\t\t}\n\t\t}\n\t\treturn mockTradePersister().retrieveTrader(name);\n\t}",
"private String dumpZoneNAryDetails(StoreRoutingPlan storeRoutingPlan) {\n StringBuilder sb = new StringBuilder();\n\n sb.append(\"\\tDetailed Dump (Zone N-Aries):\").append(Utils.NEWLINE);\n for(Node node: storeRoutingPlan.getCluster().getNodes()) {\n int zoneId = node.getZoneId();\n int nodeId = node.getId();\n sb.append(\"\\tNode ID: \" + nodeId + \" in zone \" + zoneId).append(Utils.NEWLINE);\n List<Integer> naries = storeRoutingPlan.getZoneNAryPartitionIds(nodeId);\n Map<Integer, List<Integer>> zoneNaryTypeToPartitionIds = new HashMap<Integer, List<Integer>>();\n for(int nary: naries) {\n int zoneReplicaType = storeRoutingPlan.getZoneNaryForNodesPartition(zoneId,\n nodeId,\n nary);\n if(!zoneNaryTypeToPartitionIds.containsKey(zoneReplicaType)) {\n zoneNaryTypeToPartitionIds.put(zoneReplicaType, new ArrayList<Integer>());\n }\n zoneNaryTypeToPartitionIds.get(zoneReplicaType).add(nary);\n }\n\n for(int replicaType: new TreeSet<Integer>(zoneNaryTypeToPartitionIds.keySet())) {\n sb.append(\"\\t\\t\" + replicaType + \" : \");\n sb.append(zoneNaryTypeToPartitionIds.get(replicaType).toString());\n sb.append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }",
"private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }",
"protected Class getPrototypeClass(T content) {\n if (prototypes.size() == 1) {\n return prototypes.get(0).getClass();\n } else {\n return binding.get(content.getClass());\n }\n }"
] |
Return the value from the field in the object that is defined by this FieldType. If the field is a foreign object
then the ID of the field is returned instead. | [
"public Object extractJavaFieldValue(Object object) throws SQLException {\n\n\t\tObject val = extractRawJavaFieldValue(object);\n\n\t\t// if this is a foreign object then we want its reference field\n\t\tif (foreignRefField != null && val != null) {\n\t\t\tval = foreignRefField.extractRawJavaFieldValue(val);\n\t\t}\n\n\t\treturn val;\n\t}"
] | [
"private static int getBinaryLength(int version, QrMode[] inputModeUnoptimized, int[] inputData, boolean gs1, int eciMode) {\n\n int i, j;\n QrMode currentMode;\n int inputLength = inputModeUnoptimized.length;\n int count = 0;\n int alphaLength;\n int percent = 0;\n\n // ZINT NOTE: in Zint, this call modifies the input mode array directly; here, we leave\n // the original array alone so that subsequent binary length checks don't irrevocably\n // optimize the mode array for the wrong QR Code version\n QrMode[] inputMode = applyOptimisation(version, inputModeUnoptimized);\n\n currentMode = QrMode.NULL;\n\n if (gs1) {\n count += 4;\n }\n\n if (eciMode != 3) {\n count += 12;\n }\n\n for (i = 0; i < inputLength; i++) {\n if (inputMode[i] != currentMode) {\n count += 4;\n switch (inputMode[i]) {\n case KANJI:\n count += tribus(version, 8, 10, 12);\n count += (blockLength(i, inputMode) * 13);\n break;\n case BINARY:\n count += tribus(version, 8, 16, 16);\n for (j = i; j < (i + blockLength(i, inputMode)); j++) {\n if (inputData[j] > 0xff) {\n count += 16;\n } else {\n count += 8;\n }\n }\n break;\n case ALPHANUM:\n count += tribus(version, 9, 11, 13);\n alphaLength = blockLength(i, inputMode);\n // In alphanumeric mode % becomes %%\n if (gs1) {\n for (j = i; j < (i + alphaLength); j++) { // TODO: need to do this only if in GS1 mode? or is the other code wrong? https://sourceforge.net/p/zint/tickets/104/#227b\n if (inputData[j] == '%') {\n percent++;\n }\n }\n }\n alphaLength += percent;\n switch (alphaLength % 2) {\n case 0:\n count += (alphaLength / 2) * 11;\n break;\n case 1:\n count += ((alphaLength - 1) / 2) * 11;\n count += 6;\n break;\n }\n break;\n case NUMERIC:\n count += tribus(version, 10, 12, 14);\n switch (blockLength(i, inputMode) % 3) {\n case 0:\n count += (blockLength(i, inputMode) / 3) * 10;\n break;\n case 1:\n count += ((blockLength(i, inputMode) - 1) / 3) * 10;\n count += 4;\n break;\n case 2:\n count += ((blockLength(i, inputMode) - 2) / 3) * 10;\n count += 7;\n break;\n }\n break;\n }\n currentMode = inputMode[i];\n }\n }\n\n return count;\n }",
"public void setList(List<T> list) {\n if (list != mList) {\n mList = list;\n if (mList == null) {\n notifyInvalidated();\n } else {\n notifyChanged();\n }\n }\n }",
"public String get(final long index) {\n return doWithJedis(new JedisCallable<String>() {\n @Override\n public String call(Jedis jedis) {\n return jedis.lindex(getKey(), index);\n }\n });\n }",
"public void setKeywords(final List<String> keywords) {\n StringBuilder builder = new StringBuilder();\n for (String keyword: keywords) {\n if (builder.length() > 0) {\n builder.append(',');\n }\n builder.append(keyword.trim());\n }\n this.keywords = Optional.of(builder.toString());\n }",
"public void initialize(FragmentManager fragmentManager) {\n AirMapInterface mapInterface = (AirMapInterface)\n fragmentManager.findFragmentById(R.id.map_frame);\n\n if (mapInterface != null) {\n initialize(fragmentManager, mapInterface);\n } else {\n initialize(fragmentManager, new DefaultAirMapViewBuilder(getContext()).builder().build());\n }\n }",
"private ProjectFile readDatabaseFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaDatabaseFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }",
"@Override\n public boolean setA(DMatrixRBlock A) {\n if( A.numRows < A.numCols )\n throw new IllegalArgumentException(\"Number of rows must be more than or equal to the number of columns. \" +\n \"Can't solve an underdetermined system.\");\n\n if( !decomposer.decompose(A))\n return false;\n\n this.QR = decomposer.getQR();\n\n return true;\n }",
"public int getCurrentMethodOrdinal(int overrideId, int pathId, String clientUUID, String[] filters) throws Exception {\n int currentOrdinal = 0;\n List<EnabledEndpoint> enabledEndpoints = getEnabledEndpoints(pathId, clientUUID, filters);\n for (EnabledEndpoint enabledEndpoint : enabledEndpoints) {\n if (enabledEndpoint.getOverrideId() == overrideId) {\n currentOrdinal++;\n }\n }\n return currentOrdinal;\n }",
"public Where<T, ID> in(String columnName, Object... objects) throws SQLException {\n\t\treturn in(true, columnName, objects);\n\t}"
] |
Finish service initialization.
@throws GeomajasException oops | [
"@PostConstruct\n\tprotected void postConstruct() throws GeomajasException {\n\t\tif (null != crsDefinitions) {\n\t\t\tfor (CrsInfo crsInfo : crsDefinitions.values()) {\n\t\t\t\ttry {\n\t\t\t\t\tCoordinateReferenceSystem crs = CRS.parseWKT(crsInfo.getCrsWkt());\n\t\t\t\t\tString code = crsInfo.getKey();\n\t\t\t\t\tcrsCache.put(code, CrsFactory.getCrs(code, crs));\n\t\t\t\t} catch (FactoryException e) {\n\t\t\t\t\tthrow new GeomajasException(e, ExceptionCode.CRS_DECODE_FAILURE_FOR_MAP, crsInfo.getKey());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (null != crsTransformDefinitions) {\n\t\t\tfor (CrsTransformInfo crsTransformInfo : crsTransformDefinitions.values()) {\n\t\t\t\tString key = getTransformKey(crsTransformInfo);\n\t\t\t\ttransformCache.put(key, getCrsTransform(key, crsTransformInfo));\n\t\t\t}\n\t\t}\n\t\tGeometryFactory factory = new GeometryFactory();\n\t\tEMPTY_GEOMETRIES.put(Point.class, factory.createPoint((Coordinate) null));\n\t\tEMPTY_GEOMETRIES.put(LineString.class, factory.createLineString((Coordinate[]) null));\n\t\tEMPTY_GEOMETRIES.put(Polygon.class, factory.createPolygon(null, null));\n\t\tEMPTY_GEOMETRIES.put(MultiPoint.class, factory.createMultiPoint((Coordinate[]) null));\n\t\tEMPTY_GEOMETRIES.put(MultiLineString.class, factory.createMultiLineString((LineString[]) null)); // cast needed!\n\t\tEMPTY_GEOMETRIES.put(MultiPolygon.class, factory.createMultiPolygon((Polygon[]) null)); // cast needed!\n\t\tEMPTY_GEOMETRIES.put(Geometry.class, factory.createGeometryCollection(null));\n\t}"
] | [
"private String getPropertyName(Expression expression) {\n\t\tif (!(expression instanceof PropertyName)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a PropertyName.\");\n\t\t}\n\t\tString name = ((PropertyName) expression).getPropertyName();\n\t\tif (name.endsWith(FilterService.ATTRIBUTE_ID)) {\n\t\t\t// replace by Hibernate id property, always refers to the id, even if named differently\n\t\t\tname = name.substring(0, name.length() - FilterService.ATTRIBUTE_ID.length()) + HIBERNATE_ID;\n\t\t}\n\t\treturn name;\n\t}",
"public static <K,V> SortedMap<K,V> asImmutable(SortedMap<K, ? extends V> self) {\n return Collections.unmodifiableSortedMap(self);\n }",
"public static GVRVideoSceneObjectPlayer<MediaPlayer> makePlayerInstance(final MediaPlayer mediaPlayer) {\n return new GVRVideoSceneObjectPlayer<MediaPlayer>() {\n @Override\n public MediaPlayer getPlayer() {\n return mediaPlayer;\n }\n\n @Override\n public void setSurface(Surface surface) {\n mediaPlayer.setSurface(surface);\n }\n\n @Override\n public void release() {\n mediaPlayer.release();\n }\n\n @Override\n public boolean canReleaseSurfaceImmediately() {\n return true;\n }\n\n @Override\n public void pause() {\n try {\n mediaPlayer.pause();\n } catch (final IllegalStateException exc) {\n //intentionally ignored; might have been released already or never got to be\n //initialized\n }\n }\n\n @Override\n public void start() {\n mediaPlayer.start();\n }\n\n @Override\n public boolean isPlaying() {\n return mediaPlayer.isPlaying();\n }\n };\n }",
"private void writeImages() {\n\t\tfor (ValueMap gv : this.valueMaps) {\n\t\t\tgv.writeImage();\n\t\t}\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"map-site-count.csv\"))) {\n\t\t\tout.println(\"Site key,Number of geo items\");\n\t\t\tout.println(\"wikidata total,\" + this.count);\n\t\t\tfor (Entry<String, Integer> entry : this.siteCounts.entrySet()) {\n\t\t\t\tout.println(entry.getKey() + \",\" + entry.getValue());\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}",
"protected Renderer build() {\n validateAttributes();\n\n Renderer renderer;\n if (isRecyclable(convertView, content)) {\n renderer = recycle(convertView, content);\n } else {\n renderer = createRenderer(content, parent);\n }\n return renderer;\n }",
"public static base_responses restore(nitro_service client, appfwprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwprofile restoreresources[] = new appfwprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trestoreresources[i] = new appfwprofile();\n\t\t\t\trestoreresources[i].archivename = resources[i].archivename;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, restoreresources,\"restore\");\n\t\t}\n\t\treturn result;\n\t}",
"public QueryStringBuilder getQueryParameters() {\n QueryStringBuilder builder = new QueryStringBuilder();\n\n if (this.isNullOrEmpty(this.query) && this.metadataFilter == null) {\n throw new BoxAPIException(\n \"BoxSearchParameters requires either a search query or Metadata filter to be set.\"\n );\n }\n\n //Set the query of the search\n if (!this.isNullOrEmpty(this.query)) {\n builder.appendParam(\"query\", this.query);\n }\n //Set the scope of the search\n if (!this.isNullOrEmpty(this.scope)) {\n builder.appendParam(\"scope\", this.scope);\n }\n //Acceptable Value: \"jpg,png\"\n if (!this.isNullOrEmpty(this.fileExtensions)) {\n builder.appendParam(\"file_extensions\", this.listToCSV(this.fileExtensions));\n }\n //Created Date Range: From Date - To Date\n if ((this.createdRange != null)) {\n builder.appendParam(\"created_at_range\", this.createdRange.buildRangeString());\n }\n //Updated Date Range: From Date - To Date\n if ((this.updatedRange != null)) {\n builder.appendParam(\"updated_at_range\", this.updatedRange.buildRangeString());\n }\n //Filesize Range\n if ((this.sizeRange != null)) {\n builder.appendParam(\"size_range\", this.sizeRange.buildRangeString());\n }\n //Owner Id's\n if (!this.isNullOrEmpty(this.ownerUserIds)) {\n builder.appendParam(\"owner_user_ids\", this.listToCSV(this.ownerUserIds));\n }\n //Ancestor ID's\n if (!this.isNullOrEmpty(this.ancestorFolderIds)) {\n builder.appendParam(\"ancestor_folder_ids\", this.listToCSV(this.ancestorFolderIds));\n }\n //Content Types: \"name, description\"\n if (!this.isNullOrEmpty(this.contentTypes)) {\n builder.appendParam(\"content_types\", this.listToCSV(this.contentTypes));\n }\n //Type of File: \"file,folder,web_link\"\n if (this.type != null) {\n builder.appendParam(\"type\", this.type);\n }\n //Trash Content\n if (!this.isNullOrEmpty(this.trashContent)) {\n builder.appendParam(\"trash_content\", this.trashContent);\n }\n //Metadata filters\n if (this.metadataFilter != null) {\n builder.appendParam(\"mdfilters\", this.formatBoxMetadataFilterRequest().toString());\n }\n //Fields\n if (!this.isNullOrEmpty(this.fields)) {\n builder.appendParam(\"fields\", this.listToCSV(this.fields));\n }\n //Sort\n if (!this.isNullOrEmpty(this.sort)) {\n builder.appendParam(\"sort\", this.sort);\n }\n //Direction\n if (!this.isNullOrEmpty(this.direction)) {\n builder.appendParam(\"direction\", this.direction);\n }\n return builder;\n }",
"private Properties parseFile(File file) throws InvalidDeclarationFileException {\n Properties properties = new Properties();\n InputStream is = null;\n try {\n is = new FileInputStream(file);\n properties.load(is);\n } catch (Exception e) {\n throw new InvalidDeclarationFileException(String.format(\"Error reading declaration file %s\", file.getAbsoluteFile()), e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n LOG.error(\"IOException thrown while trying to close the declaration file.\", e);\n }\n }\n }\n\n if (!properties.containsKey(Constants.ID)) {\n throw new InvalidDeclarationFileException(String.format(\"File %s is not a correct declaration, needs to contains an id property\", file.getAbsoluteFile()));\n }\n return properties;\n }",
"public static cmpparameter get(nitro_service service) throws Exception{\n\t\tcmpparameter obj = new cmpparameter();\n\t\tcmpparameter[] response = (cmpparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] |
Use this API to fetch all the tmsessionparameter resources that are configured on netscaler. | [
"public static tmsessionparameter get(nitro_service service) throws Exception{\n\t\ttmsessionparameter obj = new tmsessionparameter();\n\t\ttmsessionparameter[] response = (tmsessionparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] | [
"public static base_response reset(nitro_service client) throws Exception {\n\t\tappfwlearningdata resetresource = new appfwlearningdata();\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}",
"private boolean hidden(String className) {\n\tclassName = removeTemplate(className);\n\tClassInfo ci = classnames.get(className);\n\treturn ci != null ? ci.hidden : optionProvider.getOptionsFor(className).matchesHideExpression(className);\n }",
"public LuaScriptBlock endBlockReturn(LuaValue value) {\n add(new LuaAstReturnStatement(argument(value)));\n return new LuaScriptBlock(script);\n }",
"public Iterable<? extends WindupVertexFrame> findVariable(String name, int maxDepth)\n {\n int currentDepth = 0;\n Iterable<? extends WindupVertexFrame> result = null;\n for (Map<String, Iterable<? extends WindupVertexFrame>> frame : deque)\n {\n result = frame.get(name);\n if (result != null)\n {\n break;\n }\n currentDepth++;\n if (currentDepth >= maxDepth)\n break;\n }\n return result;\n }",
"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 }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushNotificationViewedEvent(Bundle extras){\n\n if (extras == null || extras.isEmpty() || extras.get(Constants.NOTIFICATION_TAG) == null) {\n getConfigLogger().debug(getAccountId(), \"Push notification: \" + (extras == null ? \"NULL\" : extras.toString()) + \" not from CleverTap - will not process Notification Viewed event.\");\n return;\n }\n\n if (!extras.containsKey(Constants.NOTIFICATION_ID_TAG) || (extras.getString(Constants.NOTIFICATION_ID_TAG) == null)) {\n getConfigLogger().debug(getAccountId(), \"Push notification ID Tag is null, not processing Notification Viewed event for: \" + extras.toString());\n return;\n }\n\n // Check for dupe notification views; if same notficationdId within specified time interval (2 secs) don't process\n boolean isDuplicate = checkDuplicateNotificationIds(extras, notificationViewedIdTagMap, Constants.NOTIFICATION_VIEWED_ID_TAG_INTERVAL);\n if (isDuplicate) {\n getConfigLogger().debug(getAccountId(), \"Already processed Notification Viewed event for \" + extras.toString() + \", dropping duplicate.\");\n return;\n }\n\n JSONObject event = new JSONObject();\n try {\n JSONObject notif = getWzrkFields(extras);\n event.put(\"evtName\", Constants.NOTIFICATION_VIEWED_EVENT_NAME);\n event.put(\"evtData\", notif);\n } catch (Throwable ignored) {\n //no-op\n }\n queueEvent(context, event, Constants.RAISED_EVENT);\n }",
"public void put(String key, Object object, Envelope envelope) {\n\t\tindex.put(key, envelope);\n\t\tcache.put(key, object);\n\t}",
"public static String getPrefix(String column) {\n\t\treturn column.contains( \".\" ) ? DOT_SEPARATOR_PATTERN.split( column )[0] : null;\n\t}",
"public InputStream sendRequest(String requestMethod,\n\t\t\tMap<String, String> parameters) throws IOException {\n\t\tString queryString = getQueryString(parameters);\n\t\tURL url = new URL(this.apiBaseUrl);\n\t\tHttpURLConnection connection = (HttpURLConnection) WebResourceFetcherImpl\n\t\t\t\t.getUrlConnection(url);\n\n\t\tsetupConnection(requestMethod, queryString, connection);\n\t\tOutputStreamWriter writer = new OutputStreamWriter(\n\t\t\t\tconnection.getOutputStream());\n\t\twriter.write(queryString);\n\t\twriter.flush();\n\t\twriter.close();\n\n\t\tint rc = connection.getResponseCode();\n\t\tif (rc != 200) {\n\t\t\tlogger.warn(\"Error: API request returned response code \" + rc);\n\t\t}\n\n\t\tInputStream iStream = connection.getInputStream();\n\t\tfillCookies(connection.getHeaderFields());\n\t\treturn iStream;\n\t}"
] |
Returns the corresponding ModuleSpec service name for the given module.
@param identifier The module identifier
@return The service name of the ModuleSpec service | [
"public static ServiceName moduleSpecServiceName(ModuleIdentifier identifier) {\n if (!isDynamicModule(identifier)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_SPEC_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }"
] | [
"private static void processTaskFilter(ProjectFile project, Filter filter)\n {\n for (Task task : project.getTasks())\n {\n if (filter.evaluate(task, null))\n {\n System.out.println(task.getID() + \",\" + task.getUniqueID() + \",\" + task.getName());\n }\n }\n }",
"@VisibleForTesting\n protected static Dimension getSize(\n final ScalebarAttributeValues scalebarParams,\n final ScaleBarRenderSettings settings, final Dimension maxLabelSize) {\n final float width;\n final float height;\n if (scalebarParams.getOrientation().isHorizontal()) {\n width = 2 * settings.getPadding()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getLeftLabelMargin() + settings.getRightLabelMargin();\n height = 2 * settings.getPadding()\n + settings.getBarSize() + settings.getLabelDistance()\n + Label.getRotatedHeight(maxLabelSize, scalebarParams.getLabelRotation());\n } else {\n width = 2 * settings.getPadding()\n + settings.getLabelDistance() + settings.getBarSize()\n + Label.getRotatedWidth(maxLabelSize, scalebarParams.getLabelRotation());\n height = 2 * settings.getPadding()\n + settings.getTopLabelMargin()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getBottomLabelMargin();\n }\n return new Dimension((int) Math.ceil(width), (int) Math.ceil(height));\n }",
"int getItemViewType(T content) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n return getItemViewType(prototypeClass);\n }",
"public ProjectCalendar getDefaultCalendar()\n {\n String calendarName = m_properties.getDefaultCalendarName();\n ProjectCalendar calendar = getCalendarByName(calendarName);\n if (calendar == null)\n {\n if (m_calendars.isEmpty())\n {\n calendar = addDefaultBaseCalendar();\n }\n else\n {\n calendar = m_calendars.get(0);\n }\n }\n return calendar;\n }",
"public void deleteEmailAlias(String emailAliasID) {\n URL url = EMAIL_ALIAS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), emailAliasID);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"public static base_response add(nitro_service client, vpnsessionaction resource) throws Exception {\n\t\tvpnsessionaction addresource = new vpnsessionaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.httpport = resource.httpport;\n\t\taddresource.winsip = resource.winsip;\n\t\taddresource.dnsvservername = resource.dnsvservername;\n\t\taddresource.splitdns = resource.splitdns;\n\t\taddresource.sesstimeout = resource.sesstimeout;\n\t\taddresource.clientsecurity = resource.clientsecurity;\n\t\taddresource.clientsecuritygroup = resource.clientsecuritygroup;\n\t\taddresource.clientsecuritymessage = resource.clientsecuritymessage;\n\t\taddresource.clientsecuritylog = resource.clientsecuritylog;\n\t\taddresource.splittunnel = resource.splittunnel;\n\t\taddresource.locallanaccess = resource.locallanaccess;\n\t\taddresource.rfc1918 = resource.rfc1918;\n\t\taddresource.spoofiip = resource.spoofiip;\n\t\taddresource.killconnections = resource.killconnections;\n\t\taddresource.transparentinterception = resource.transparentinterception;\n\t\taddresource.windowsclienttype = resource.windowsclienttype;\n\t\taddresource.defaultauthorizationaction = resource.defaultauthorizationaction;\n\t\taddresource.authorizationgroup = resource.authorizationgroup;\n\t\taddresource.clientidletimeout = resource.clientidletimeout;\n\t\taddresource.proxy = resource.proxy;\n\t\taddresource.allprotocolproxy = resource.allprotocolproxy;\n\t\taddresource.httpproxy = resource.httpproxy;\n\t\taddresource.ftpproxy = resource.ftpproxy;\n\t\taddresource.socksproxy = resource.socksproxy;\n\t\taddresource.gopherproxy = resource.gopherproxy;\n\t\taddresource.sslproxy = resource.sslproxy;\n\t\taddresource.proxyexception = resource.proxyexception;\n\t\taddresource.proxylocalbypass = resource.proxylocalbypass;\n\t\taddresource.clientcleanupprompt = resource.clientcleanupprompt;\n\t\taddresource.forcecleanup = resource.forcecleanup;\n\t\taddresource.clientoptions = resource.clientoptions;\n\t\taddresource.clientconfiguration = resource.clientconfiguration;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.ssocredential = resource.ssocredential;\n\t\taddresource.windowsautologon = resource.windowsautologon;\n\t\taddresource.usemip = resource.usemip;\n\t\taddresource.useiip = resource.useiip;\n\t\taddresource.clientdebug = resource.clientdebug;\n\t\taddresource.loginscript = resource.loginscript;\n\t\taddresource.logoutscript = resource.logoutscript;\n\t\taddresource.homepage = resource.homepage;\n\t\taddresource.icaproxy = resource.icaproxy;\n\t\taddresource.wihome = resource.wihome;\n\t\taddresource.citrixreceiverhome = resource.citrixreceiverhome;\n\t\taddresource.wiportalmode = resource.wiportalmode;\n\t\taddresource.clientchoices = resource.clientchoices;\n\t\taddresource.epaclienttype = resource.epaclienttype;\n\t\taddresource.iipdnssuffix = resource.iipdnssuffix;\n\t\taddresource.forcedtimeout = resource.forcedtimeout;\n\t\taddresource.forcedtimeoutwarning = resource.forcedtimeoutwarning;\n\t\taddresource.ntdomain = resource.ntdomain;\n\t\taddresource.clientlessvpnmode = resource.clientlessvpnmode;\n\t\taddresource.emailhome = resource.emailhome;\n\t\taddresource.clientlessmodeurlencoding = resource.clientlessmodeurlencoding;\n\t\taddresource.clientlesspersistentcookie = resource.clientlesspersistentcookie;\n\t\taddresource.allowedlogingroups = resource.allowedlogingroups;\n\t\taddresource.securebrowse = resource.securebrowse;\n\t\taddresource.storefronturl = resource.storefronturl;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\treturn addresource.add_resource(client);\n\t}",
"public void deletePersistent(Object object)\r\n {\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open\");\r\n }\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"No transaction in progress, cannot delete persistent\");\r\n }\r\n RuntimeObject rt = new RuntimeObject(object, tx);\r\n tx.deletePersistent(rt);\r\n// tx.moveToLastInOrderList(rt.getIdentity());\r\n }",
"@Override\n public void onRotationSensor(long timeStamp, float rotationW, float rotationX, float rotationY, float rotationZ,\n float gyroX, float gyroY, float gyroZ) {\n GVRCameraRig cameraRig = null;\n if (mMainScene != null) {\n cameraRig = mMainScene.getMainCameraRig();\n }\n\n if (cameraRig != null) {\n cameraRig.setRotationSensorData(timeStamp, rotationW, rotationX, rotationY, rotationZ, gyroX, gyroY, gyroZ);\n updateSensoredScene();\n }\n }",
"public static base_response update(nitro_service client, protocolhttpband resource) throws Exception {\n\t\tprotocolhttpband updateresource = new protocolhttpband();\n\t\tupdateresource.reqbandsize = resource.reqbandsize;\n\t\tupdateresource.respbandsize = resource.respbandsize;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Reads a data block and adds it to the list of blocks.
@param text RTF data
@param offset current offset
@param length next block length
@param blocks list of blocks
@return next offset | [
"private static int readDataBlock(String text, int offset, int length, List<byte[]> blocks)\n {\n int bytes = length / 2;\n byte[] data = new byte[bytes];\n\n for (int index = 0; index < bytes; index++)\n {\n data[index] = (byte) Integer.parseInt(text.substring(offset, offset + 2), 16);\n offset += 2;\n }\n\n blocks.add(data);\n return (offset);\n }"
] | [
"public static Type boxedType(Type type) {\n if (type instanceof Class<?>) {\n return boxedClass((Class<?>) type);\n } else {\n return type;\n }\n }",
"public static boolean compareAnnotatedParameters(AnnotatedParameter<?> p1, AnnotatedParameter<?> p2) {\n return compareAnnotatedCallable(p1.getDeclaringCallable(), p2.getDeclaringCallable()) && p1.getPosition() == p2.getPosition() && compareAnnotated(p1, p2);\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 static Bitmap crop(Bitmap srcBmp, View canvasView, int downsampling) {\n float scale = 1f / downsampling;\n return Bitmap.createBitmap(\n srcBmp,\n (int) Math.floor((ViewCompat.getX(canvasView)) * scale),\n (int) Math.floor((ViewCompat.getY(canvasView)) * scale),\n (int) Math.floor((canvasView.getWidth()) * scale),\n (int) Math.floor((canvasView.getHeight()) * scale)\n );\n }",
"private DefBase getDefForLevel(String level)\r\n {\r\n if (LEVEL_CLASS.equals(level))\r\n {\r\n return _curClassDef;\r\n }\r\n else if (LEVEL_FIELD.equals(level))\r\n {\r\n return _curFieldDef;\r\n }\r\n else if (LEVEL_REFERENCE.equals(level))\r\n {\r\n return _curReferenceDef;\r\n }\r\n else if (LEVEL_COLLECTION.equals(level))\r\n {\r\n return _curCollectionDef;\r\n }\r\n else if (LEVEL_OBJECT_CACHE.equals(level))\r\n {\r\n return _curObjectCacheDef;\r\n }\r\n else if (LEVEL_INDEX_DESC.equals(level))\r\n {\r\n return _curIndexDescriptorDef;\r\n }\r\n else if (LEVEL_TABLE.equals(level))\r\n {\r\n return _curTableDef;\r\n }\r\n else if (LEVEL_COLUMN.equals(level))\r\n {\r\n return _curColumnDef;\r\n }\r\n else if (LEVEL_FOREIGNKEY.equals(level))\r\n {\r\n return _curForeignkeyDef;\r\n }\r\n else if (LEVEL_INDEX.equals(level))\r\n {\r\n return _curIndexDef;\r\n }\r\n else if (LEVEL_PROCEDURE.equals(level))\r\n {\r\n return _curProcedureDef;\r\n }\r\n else if (LEVEL_PROCEDURE_ARGUMENT.equals(level))\r\n {\r\n return _curProcedureArgumentDef;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }",
"public static onlinkipv6prefix[] get(nitro_service service) throws Exception{\n\t\tonlinkipv6prefix obj = new onlinkipv6prefix();\n\t\tonlinkipv6prefix[] response = (onlinkipv6prefix[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void setProxy(String proxyHost, int proxyPort) {\n System.setProperty(\"http.proxySet\", \"true\");\n System.setProperty(\"http.proxyHost\", proxyHost);\n System.setProperty(\"http.proxyPort\", \"\" + proxyPort);\n System.setProperty(\"https.proxyHost\", proxyHost);\n System.setProperty(\"https.proxyPort\", \"\" + proxyPort);\n }",
"public static Object newInstance(String className, Class[] types, Object[] args) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(getClass(className), types, args);\r\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 }"
] |
Given a resource field number, this method returns the resource field name.
@param key resource field number
@return resource field name | [
"private String getResourceField(int key)\n {\n String result = null;\n\n if (key > 0 && key < m_resourceNames.length)\n {\n result = m_resourceNames[key];\n }\n\n return (result);\n }"
] | [
"private boolean verify(String key, BoxSignatureAlgorithm actualAlgorithm, String actualSignature,\n String webHookPayload, String deliveryTimestamp) {\n if (actualSignature == null) {\n return false;\n }\n\n byte[] actual = Base64.decode(actualSignature);\n byte[] expected = this.signRaw(actualAlgorithm, key, webHookPayload, deliveryTimestamp);\n\n return Arrays.equals(expected, actual);\n }",
"public void useNewSOAPServiceWithOldClientAndRedirection() throws Exception {\n URL wsdlURL = getClass().getResource(\"/CustomerService.wsdl\");\n com.example.customerservice.CustomerServiceService service = \n new com.example.customerservice.CustomerServiceService(wsdlURL);\n \n com.example.customerservice.CustomerService customerService = \n service.getCustomerServiceRedirectPort();\n\n System.out.println(\"Using new SOAP CustomerService with old client and the redirection\");\n \n customer.v1.Customer customer = createOldCustomer(\"Barry Old to New SOAP With Redirection\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry Old to New SOAP With Redirection\");\n printOldCustomerDetails(customer);\n }",
"public void logout() {\n String userIdentifier = session.get(config().sessionKeyUsername());\n SessionManager sessionManager = app().sessionManager();\n sessionManager.logout(session);\n if (S.notBlank(userIdentifier)) {\n app().eventBus().trigger(new LogoutEvent(userIdentifier));\n }\n }",
"public SelectStatement getPreparedSelectByPkStatement(ClassDescriptor cld)\r\n {\r\n SelectStatement sql;\r\n SqlForClass sfc = getSqlForClass(cld);\r\n sql = sfc.getSelectByPKSql();\r\n if(sql == null)\r\n {\r\n sql = new SqlSelectByPkStatement(m_platform, cld, logger);\r\n\r\n // set the sql string\r\n sfc.setSelectByPKSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }",
"public static Timespan create(Timespan... timespans) {\n if (timespans == null) {\n return null;\n }\n\n if (timespans.length == 0) {\n return ZERO_MILLISECONDS;\n }\n\n Timespan res = timespans[0];\n\n for (int i = 1; i < timespans.length; i++) {\n Timespan timespan = timespans[i];\n res = res.add(timespan);\n }\n\n return res;\n }",
"static void processServerConfig(final Resource root, final RequiredConfigurationHolder requiredConfigurationHolder, final IgnoredNonAffectedServerGroupsUtil.ServerConfigInfo serverConfig, final ExtensionRegistry extensionRegistry) {\n\n final Set<String> serverGroups = requiredConfigurationHolder.serverGroups;\n final Set<String> socketBindings = requiredConfigurationHolder.socketBindings;\n\n String sbg = serverConfig.getSocketBindingGroup();\n if (sbg != null && !socketBindings.contains(sbg)) {\n processSocketBindingGroup(root, sbg, requiredConfigurationHolder);\n }\n\n final String groupName = serverConfig.getServerGroup();\n final PathElement groupElement = PathElement.pathElement(SERVER_GROUP, groupName);\n // Also check the root, since this also gets executed on the slave which may not have the server-group configured yet\n if (!serverGroups.contains(groupName) && root.hasChild(groupElement)) {\n\n final Resource serverGroup = root.getChild(groupElement);\n final ModelNode groupModel = serverGroup.getModel();\n serverGroups.add(groupName);\n\n // Include the socket binding groups\n if (groupModel.hasDefined(SOCKET_BINDING_GROUP)) {\n final String socketBindingGroup = groupModel.get(SOCKET_BINDING_GROUP).asString();\n processSocketBindingGroup(root, socketBindingGroup, requiredConfigurationHolder);\n }\n\n final String profileName = groupModel.get(PROFILE).asString();\n processProfile(root, profileName, requiredConfigurationHolder, extensionRegistry);\n }\n }",
"@GuardedBy(\"elementsLock\")\n\t@Override\n\tpublic boolean markChecked(CandidateElement element) {\n\t\tString generalString = element.getGeneralString();\n\t\tString uniqueString = element.getUniqueString();\n\t\tsynchronized (elementsLock) {\n\t\t\tif (elements.contains(uniqueString)) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\telements.add(generalString);\n\t\t\t\telements.add(uniqueString);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}",
"protected org.apache.log4j.helpers.PatternParser createPatternParser(final String pattern) {\n\t\treturn new FoundationLoggingPatternParser(pattern);\n\t}",
"public static base_response unset(nitro_service client, sslservice resource, String[] args) throws Exception{\n\t\tsslservice unsetresource = new sslservice();\n\t\tunsetresource.servicename = resource.servicename;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] |
makes object obj persistent to the Objectcache under the key oid. | [
"public void cache(Identity oid, Object obj)\r\n {\r\n try\r\n {\r\n jcsCache.put(oid.toString(), obj);\r\n }\r\n catch (CacheException e)\r\n {\r\n throw new RuntimeCacheException(e);\r\n }\r\n }"
] | [
"private void addReverse(final File[] files) {\n for (int i = files.length - 1; i >= 0; --i) {\n stack.add(files[i]);\n }\n }",
"List<CmsResource> getBundleResources() {\n\n List<CmsResource> resources = new ArrayList<>(m_bundleFiles.values());\n if (m_desc != null) {\n resources.add(m_desc);\n }\n return resources;\n\n }",
"@Override\n\tpublic boolean retainAll(Collection<?> collection) {\n\t\tif (dao == null) {\n\t\t\treturn false;\n\t\t}\n\t\tboolean changed = false;\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\tT data = iterator.next();\n\t\t\t\tif (!collection.contains(data)) {\n\t\t\t\t\titerator.remove();\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn changed;\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}",
"private boolean applyRemoteDomainModel(final List<ModelNode> bootOperations, final HostInfo hostInfo) {\n try {\n HostControllerLogger.ROOT_LOGGER.debug(\"Applying domain level boot operations provided by master\");\n SyncModelParameters parameters =\n new SyncModelParameters(domainController, ignoredDomainResourceRegistry,\n hostControllerEnvironment, extensionRegistry, operationExecutor, true, serverProxies, remoteFileRepository, contentRepository);\n final SyncDomainModelOperationHandler handler =\n new SyncDomainModelOperationHandler(hostInfo, parameters);\n final ModelNode operation = APPLY_DOMAIN_MODEL.clone();\n operation.get(DOMAIN_MODEL).set(bootOperations);\n\n final ModelNode result = operationExecutor.execute(OperationBuilder.create(operation).build(), OperationMessageHandler.DISCARD, ModelController.OperationTransactionControl.COMMIT, handler);\n\n final String outcome = result.get(OUTCOME).asString();\n final boolean success = SUCCESS.equals(outcome);\n\n // check if anything we synced triggered reload-required or restart-required.\n // if they did we log a warning on the synced slave.\n if (result.has(RESPONSE_HEADERS)) {\n final ModelNode headers = result.get(RESPONSE_HEADERS);\n if (headers.hasDefined(OPERATION_REQUIRES_RELOAD) && headers.get(OPERATION_REQUIRES_RELOAD).asBoolean()) {\n HostControllerLogger.ROOT_LOGGER.domainModelAppliedButReloadIsRequired();\n }\n if (headers.hasDefined(OPERATION_REQUIRES_RESTART) && headers.get(OPERATION_REQUIRES_RESTART).asBoolean()) {\n HostControllerLogger.ROOT_LOGGER.domainModelAppliedButRestartIsRequired();\n }\n }\n if (!success) {\n ModelNode failureDesc = result.hasDefined(FAILURE_DESCRIPTION) ? result.get(FAILURE_DESCRIPTION) : new ModelNode();\n HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(outcome, failureDesc);\n return false;\n } else {\n return true;\n }\n } catch (Exception e) {\n HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(e);\n return false;\n }\n }",
"private void instanceAlreadyLoaded(\n\t\tfinal Tuple resultset,\n\t\tfinal int i,\n\t\t\t//TODO create an interface for this usage\n\t\tfinal OgmEntityPersister persister,\n\t\tfinal org.hibernate.engine.spi.EntityKey key,\n\t\tfinal Object object,\n\t\tfinal LockMode lockMode,\n\t\tfinal SharedSessionContractImplementor session)\n\tthrows HibernateException {\n\t\tif ( !persister.isInstance( object ) ) {\n\t\t\tthrow new WrongClassException(\n\t\t\t\t\t\"loaded object was of wrong class \" + object.getClass(),\n\t\t\t\t\tkey.getIdentifier(),\n\t\t\t\t\tpersister.getEntityName()\n\t\t\t\t);\n\t\t}\n\n\t\tif ( LockMode.NONE != lockMode && upgradeLocks() ) { // no point doing this if NONE was requested\n\n\t\t\tfinal boolean isVersionCheckNeeded = persister.isVersioned() &&\n\t\t\t\t\tsession.getPersistenceContext().getEntry( object )\n\t\t\t\t\t\t\t.getLockMode().lessThan( lockMode );\n\t\t\t// we don't need to worry about existing version being uninitialized\n\t\t\t// because this block isn't called by a re-entrant load (re-entrant\n\t\t\t// loads _always_ have lock mode NONE)\n\t\t\tif ( isVersionCheckNeeded ) {\n\t\t\t\t//we only check the version when _upgrading_ lock modes\n\t\t\t\tObject oldVersion = session.getPersistenceContext().getEntry( object ).getVersion();\n\t\t\t\tpersister.checkVersionAndRaiseSOSE( key.getIdentifier(), oldVersion, session, resultset );\n\t\t\t\t//we need to upgrade the lock mode to the mode requested\n\t\t\t\tsession.getPersistenceContext().getEntry( object )\n\t\t\t\t\t\t.setLockMode( lockMode );\n\t\t\t}\n\t\t}\n\t}",
"public boolean hasValue(String fieldName) {\n\t\treturn resultMap.containsKey(fieldName) && resultMap.get(fieldName) != null;\n\t}",
"private void checkInitializationMethod(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String initMethodName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_INITIALIZATION_METHOD);\r\n\r\n if (initMethodName == null)\r\n {\r\n return;\r\n }\r\n\r\n Class initClass;\r\n Method initMethod;\r\n\r\n try\r\n {\r\n initClass = InheritanceHelper.getClass(classDef.getName());\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" was not found on the classpath\");\r\n }\r\n try\r\n {\r\n initMethod = initClass.getDeclaredMethod(initMethodName, new Class[0]);\r\n }\r\n catch (NoSuchMethodException ex)\r\n {\r\n initMethod = null;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new ConstraintException(\"Exception while checking the class \"+classDef.getName()+\": \"+ex.getMessage());\r\n }\r\n if (initMethod == null)\r\n { \r\n try\r\n {\r\n initMethod = initClass.getMethod(initMethodName, new Class[0]);\r\n }\r\n catch (NoSuchMethodException ex)\r\n {\r\n throw new ConstraintException(\"No suitable initialization-method \"+initMethodName+\" found in class \"+classDef.getName());\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new ConstraintException(\"Exception while checking the class \"+classDef.getName()+\": \"+ex.getMessage());\r\n }\r\n }\r\n\r\n // checking modifiers\r\n int mods = initMethod.getModifiers();\r\n\r\n if (Modifier.isStatic(mods) || Modifier.isAbstract(mods))\r\n {\r\n throw new ConstraintException(\"The initialization-method \"+initMethodName+\" in class \"+classDef.getName()+\" must be a concrete instance method\");\r\n }\r\n }",
"private GridLines getGridLines(byte[] data, int offset)\n {\n Color normalLineColor = ColorType.getInstance(data[offset]).getColor();\n LineStyle normalLineStyle = LineStyle.getInstance(data[offset + 3]);\n int intervalNumber = data[offset + 4];\n LineStyle intervalLineStyle = LineStyle.getInstance(data[offset + 5]);\n Color intervalLineColor = ColorType.getInstance(data[offset + 6]).getColor();\n return new GridLines(normalLineColor, normalLineStyle, intervalNumber, intervalLineStyle, intervalLineColor);\n }",
"public void updateActive(int profileId, String clientUUID, Boolean active) throws Exception {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_CLIENT +\n \" SET \" + Constants.CLIENT_IS_ACTIVE + \"= ?\" +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n statement.setBoolean(1, active);\n statement.setString(2, clientUUID);\n statement.setInt(3, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n // ok to swallow this.. just means there wasn't any\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }"
] |
Given a RendererViewHolder passed as argument and a position renders the view using the
Renderer previously stored into the RendererViewHolder.
@param viewHolder with a Renderer class inside.
@param position to render. | [
"@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 }"
] | [
"public double getBearing(LatLong end) {\n if (this.equals(end)) {\n return 0;\n }\n\n double lat1 = latToRadians();\n double lon1 = longToRadians();\n double lat2 = end.latToRadians();\n double lon2 = end.longToRadians();\n\n double angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2),\n Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)\n * Math.cos(lat2) * Math.cos(lon1 - lon2));\n\n if (angle < 0.0) {\n angle += Math.PI * 2.0;\n }\n if (angle > Math.PI) {\n angle -= Math.PI * 2.0;\n }\n\n return Math.toDegrees(angle);\n }",
"public BoxLock lock(Date expiresAt, boolean isDownloadPrevented) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", \"lock\").toString();\n URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject lockConfig = new JsonObject();\n lockConfig.add(\"type\", \"lock\");\n if (expiresAt != null) {\n lockConfig.add(\"expires_at\", BoxDateFormat.format(expiresAt));\n }\n lockConfig.add(\"is_download_prevented\", isDownloadPrevented);\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"lock\", lockConfig);\n request.setBody(requestJSON.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n JsonValue lockValue = responseJSON.get(\"lock\");\n JsonObject lockJSON = JsonObject.readFrom(lockValue.toString());\n\n return new BoxLock(lockJSON, this.getAPI());\n }",
"public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException {\n\n final Set<String> keys = request.keys();\n if (keys.size() == 2) { // no props\n return null;\n }\n ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPONSE);\n if (outcome == null) {\n outcome = retrieveDescription(ctx, request, true);\n if (outcome == null) {\n return null;\n } else {\n ctx.set(Scope.REQUEST, DESCRIPTION_RESPONSE, outcome);\n }\n }\n if(!outcome.has(Util.RESULT)) {\n throw new CommandFormatException(\"Failed to perform \" + Util.READ_OPERATION_DESCRIPTION + \" to validate the request: result is not available.\");\n }\n\n final String operationName = request.get(Util.OPERATION).asString();\n\n final ModelNode result = outcome.get(Util.RESULT);\n final Set<String> definedProps = result.hasDefined(Util.REQUEST_PROPERTIES) ? result.get(Util.REQUEST_PROPERTIES).keys() : Collections.emptySet();\n if(definedProps.isEmpty()) {\n if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) {\n throw new CommandFormatException(\"Operation '\" + operationName + \"' does not expect any property.\");\n }\n } else {\n int skipped = 0;\n for(String prop : keys) {\n if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) {\n ++skipped;\n continue;\n }\n if(!definedProps.contains(prop)) {\n if(!Util.OPERATION_HEADERS.equals(prop)) {\n throw new CommandFormatException(\"'\" + prop + \"' is not found among the supported properties: \" + definedProps);\n }\n }\n }\n }\n return outcome;\n }",
"private void queryDatabaseMetaData()\n {\n ResultSet rs = null;\n\n try\n {\n Set<String> tables = new HashSet<String>();\n DatabaseMetaData dmd = m_connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tables.add(rs.getString(\"TABLE_NAME\"));\n }\n\n m_hasResourceBaselines = tables.contains(\"MSP_RESOURCE_BASELINES\");\n m_hasTaskBaselines = tables.contains(\"MSP_TASK_BASELINES\");\n m_hasAssignmentBaselines = tables.contains(\"MSP_ASSIGNMENT_BASELINES\");\n }\n\n catch (Exception ex)\n {\n // Ignore errors when reading meta data\n }\n\n finally\n {\n if (rs != null)\n {\n try\n {\n rs.close();\n }\n\n catch (SQLException ex)\n {\n // Ignore errors when closing result set\n }\n rs = null;\n }\n }\n }",
"public Map<String, CmsJspCategoryAccessBean> getReadAllSubCategories() {\n\n if (null == m_allSubCategories) {\n m_allSubCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n @Override\n public Object transform(Object categoryPath) {\n\n try {\n List<CmsCategory> categories = CmsCategoryService.getInstance().readCategories(\n m_cms,\n (String)categoryPath,\n true,\n m_cms.getRequestContext().getUri());\n CmsJspCategoryAccessBean result = new CmsJspCategoryAccessBean(\n m_cms,\n categories,\n (String)categoryPath);\n return result;\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n\n });\n }\n return m_allSubCategories;\n }",
"@JsonProperty(\"aliases\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, List<TermImpl>> getAliasUpdates() {\n \t\n \tMap<String, List<TermImpl>> updatedValues = new HashMap<>();\n \tfor(Map.Entry<String,AliasesWithUpdate> entry : newAliases.entrySet()) {\n \t\tAliasesWithUpdate update = entry.getValue();\n \t\tif (!update.write) {\n \t\t\tcontinue;\n \t\t}\n \t\tList<TermImpl> convertedAliases = new ArrayList<>();\n \t\tfor(MonolingualTextValue alias : update.aliases) {\n \t\t\tconvertedAliases.add(monolingualToJackson(alias));\n \t\t}\n \t\tupdatedValues.put(entry.getKey(), convertedAliases);\n \t}\n \treturn updatedValues;\n }",
"public static base_responses add(nitro_service client, dnsview resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsview addresources[] = new dnsview[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnsview();\n\t\t\t\taddresources[i].viewname = resources[i].viewname;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"void handleFacebookError(HttpStatus statusCode, FacebookError error) {\n\t\tif (error != null && error.getCode() != null) {\n\t\t\tint code = error.getCode();\n\t\t\t\n\t\t\tif (code == UNKNOWN) {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t} else if (code == SERVICE) {\n\t\t\t\tthrow new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) {\n\t\t\t\tthrow new RateLimitExceededException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PERMISSION_DENIED || isUserPermissionError(code)) {\n\t\t\t\tthrow new InsufficientPermissionException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) {\n\t\t\t\tthrow new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN) {\n\t\t\t\tthrow new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == MESG_DUPLICATE) { \n\t\t\t\tthrow new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) {\n\t\t\t\tthrow new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t}\n\t\t}\n\n\t}",
"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}"
] |
Prepares a Jetty server for communicating with consumers. | [
"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 static void main(String[] args) {\n DirectoryIterator iter = new DirectoryIterator(args);\n while(iter.hasNext())\n System.out.println(iter.next().getAbsolutePath());\n }",
"private void recoverNamespace(final NamespaceSynchronizationConfig nsConfig) {\n final MongoCollection<BsonDocument> undoCollection =\n getUndoCollection(nsConfig.getNamespace());\n final MongoCollection<BsonDocument> localCollection =\n getLocalCollection(nsConfig.getNamespace());\n final List<BsonDocument> undoDocs = undoCollection.find().into(new ArrayList<>());\n final Set<BsonValue> recoveredIds = new HashSet<>();\n\n\n // Replace local docs with undo docs. Presence of an undo doc implies we had a system failure\n // during a write. This covers updates and deletes.\n for (final BsonDocument undoDoc : undoDocs) {\n final BsonValue documentId = BsonUtils.getDocumentId(undoDoc);\n final BsonDocument filter = getDocumentIdFilter(documentId);\n localCollection.findOneAndReplace(\n filter, undoDoc, new FindOneAndReplaceOptions().upsert(true));\n recoveredIds.add(documentId);\n }\n\n // If we recovered a document, but its pending writes are set to do something else, then the\n // failure occurred after the pending writes were set, but before the undo document was\n // deleted. In this case, we should restore the document to the state that the pending\n // write indicates. There is a possibility that the pending write is from before the failed\n // operation, but in that case, the findOneAndReplace or delete is a no-op since restoring\n // the document to the state of the change event would be the same as recovering the undo\n // document.\n for (final CoreDocumentSynchronizationConfig docConfig : nsConfig.getSynchronizedDocuments()) {\n final BsonValue documentId = docConfig.getDocumentId();\n final BsonDocument filter = getDocumentIdFilter(documentId);\n\n if (recoveredIds.contains(docConfig.getDocumentId())) {\n final ChangeEvent<BsonDocument> pendingWrite = docConfig.getLastUncommittedChangeEvent();\n if (pendingWrite != null) {\n switch (pendingWrite.getOperationType()) {\n case INSERT:\n case UPDATE:\n case REPLACE:\n localCollection.findOneAndReplace(\n filter,\n pendingWrite.getFullDocument(),\n new FindOneAndReplaceOptions().upsert(true)\n );\n break;\n case DELETE:\n localCollection.deleteOne(filter);\n break;\n default:\n // There should never be pending writes with an unknown event type, but if someone\n // is messing with the config collection we want to stop the synchronizer to prevent\n // further data corruption.\n throw new IllegalStateException(\n \"there should not be a pending write with an unknown event type\"\n );\n }\n }\n }\n }\n\n // Delete all of our undo documents. If we've reached this point, we've recovered the local\n // collection to the state we want with respect to all of our undo documents. If we fail before\n // these deletes or while carrying out the deletes, but after recovering the documents to\n // their desired state, that's okay because the next recovery pass will be effectively a no-op\n // up to this point.\n for (final BsonValue recoveredId : recoveredIds) {\n undoCollection.deleteOne(getDocumentIdFilter(recoveredId));\n }\n\n // Find local documents for which there are no document configs and delete them. This covers\n // inserts, upserts, and desync deletes. This will occur on any recovery pass regardless of\n // the documents in the undo collection, so it's fine that we do this after deleting the undo\n // documents.\n localCollection.deleteMany(new BsonDocument(\n \"_id\",\n new BsonDocument(\n \"$nin\",\n new BsonArray(new ArrayList<>(\n this.syncConfig.getSynchronizedDocumentIds(nsConfig.getNamespace()))))));\n }",
"private boolean isDepOfIdlArtifact(Artifact artifact, Map<String, Artifact> depsMap) {\n List<String> depTrail = artifact.getDependencyTrail();\n // depTrail can be null sometimes, which seems like a maven bug\n if (depTrail != null) {\n for (String name : depTrail) {\n Artifact dep = depsMap.get(name);\n if (dep != null && isIdlCalssifier(dep, classifier)) {\n return true;\n }\n }\n }\n return false;\n }",
"public boolean mapsCell(String cell) {\n return mappedCells.stream().anyMatch(x -> x.equals(cell));\n }",
"public static Message create( String text, Object data, ProcessingUnit owner )\n {\n return new SimpleMessage( text, data, owner);\n }",
"public static int randomIntBetween(int min, int max) {\n Random rand = new Random();\n return rand.nextInt((max - min) + 1) + min;\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}",
"public static void checkFloatNotNaNOrInfinity(String parameterName,\n float data) {\n if (Float.isNaN(data) || Float.isInfinite(data)) {\n throw Exceptions.IllegalArgument(\n \"%s should never be NaN or Infinite.\", parameterName);\n }\n }",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerWidget(View widget) {\n prepareWidget(widget);\n\n if (widget instanceof AlgoliaResultsListener) {\n AlgoliaResultsListener listener = (AlgoliaResultsListener) widget;\n if (!this.resultListeners.contains(listener)) {\n this.resultListeners.add(listener);\n }\n searcher.registerResultListener(listener);\n }\n if (widget instanceof AlgoliaErrorListener) {\n AlgoliaErrorListener listener = (AlgoliaErrorListener) widget;\n if (!this.errorListeners.contains(listener)) {\n this.errorListeners.add(listener);\n }\n searcher.registerErrorListener(listener);\n }\n if (widget instanceof AlgoliaSearcherListener) {\n AlgoliaSearcherListener listener = (AlgoliaSearcherListener) widget;\n listener.initWithSearcher(searcher);\n }\n }"
] |
Returns the expected name of a workspace for a given suffix
@param suffix
@return | [
"private static String formatDirName(final String prefix, final String suffix) {\n // Replace all invalid characters with '-'\n final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate();\n return String.format(\"%s-%s\", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-'));\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}",
"@Override\n\tpublic RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException {\n\t\tif(exerciseMethod == ExerciseMethod.UPPER_BOUND_METHOD) {\n\t\t\t// Find optimal lambda\n\t\t\tGoldenSectionSearch optimizer = new GoldenSectionSearch(-1.0, 1.0);\n\t\t\twhile(!optimizer.isDone()) {\n\t\t\t\tdouble lambda = optimizer.getNextPoint();\n\t\t\t\tdouble value = this.getValues(evaluationTime, model, lambda).getAverage();\n\t\t\t\toptimizer.setValue(value);\n\t\t\t}\n\t\t\treturn getValues(evaluationTime, model, optimizer.getBestPoint());\n\t\t}\n\t\telse {\n\t\t\treturn getValues(evaluationTime, model, 0.0);\n\t\t}\n\t}",
"public Token add( Function function ) {\n Token t = new Token(function);\n push( t );\n return t;\n }",
"public String join(List<String> list) {\n\n if (list == null) {\n return null;\n }\n\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for (String s : list) {\n\n if (s == null) {\n if (convertEmptyToNull) {\n s = \"\";\n } else {\n throw new IllegalArgumentException(\"StringListFlattener does not support null strings in the list. Consider calling setConvertEmptyToNull(true).\");\n }\n }\n\n if (!first) {\n sb.append(separator);\n }\n\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c == escapeChar || c == separator) {\n sb.append(escapeChar);\n }\n sb.append(c);\n }\n\n first = false;\n }\n return sb.toString();\n }",
"private static boolean containsGreekLetter(String s) {\r\n Matcher m = biogreek.matcher(s);\r\n return m.find();\r\n }",
"public void delete(final String referenceId) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaDelete<PrintJobStatusExtImpl> delete =\n builder.createCriteriaDelete(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = delete.from(PrintJobStatusExtImpl.class);\n delete.where(builder.equal(root.get(\"referenceId\"), referenceId));\n getSession().createQuery(delete).executeUpdate();\n }",
"public <T extends Widget & Checkable> List<T> getCheckedWidgets() {\n List<T> checked = new ArrayList<>();\n\n for (Widget c : getChildren()) {\n if (c instanceof Checkable && ((Checkable) c).isChecked()) {\n checked.add((T) c);\n }\n }\n\n return checked;\n }",
"public Set<Class> entityClasses() {\n EntityMetaInfoRepo repo = app().entityMetaInfoRepo().forDb(id);\n return null == repo ? C.<Class>set() : repo.entityClasses();\n }",
"public static Cluster swapRandomPartitionsWithinZone(final Cluster nextCandidateCluster,\n final int zoneId) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n Random r = new Random();\n\n List<Integer> nodeIdsInZone = new ArrayList<Integer>(nextCandidateCluster.getNodeIdsInZone(zoneId));\n\n if(nodeIdsInZone.size() == 0) {\n return returnCluster;\n }\n\n // Select random stealer node\n int stealerNodeOffset = r.nextInt(nodeIdsInZone.size());\n Integer stealerNodeId = nodeIdsInZone.get(stealerNodeOffset);\n\n // Select random stealer partition\n List<Integer> stealerPartitions = returnCluster.getNodeById(stealerNodeId)\n .getPartitionIds();\n if(stealerPartitions.size() == 0) {\n return nextCandidateCluster;\n }\n int stealerPartitionOffset = r.nextInt(stealerPartitions.size());\n int stealerPartitionId = stealerPartitions.get(stealerPartitionOffset);\n\n // Select random donor node\n List<Integer> donorNodeIds = new ArrayList<Integer>();\n donorNodeIds.addAll(nodeIdsInZone);\n donorNodeIds.remove(stealerNodeId);\n\n if(donorNodeIds.isEmpty()) { // No donor nodes!\n return returnCluster;\n }\n int donorIdOffset = r.nextInt(donorNodeIds.size());\n Integer donorNodeId = donorNodeIds.get(donorIdOffset);\n\n // Select random donor partition\n List<Integer> donorPartitions = returnCluster.getNodeById(donorNodeId).getPartitionIds();\n int donorPartitionOffset = r.nextInt(donorPartitions.size());\n int donorPartitionId = donorPartitions.get(donorPartitionOffset);\n\n return swapPartitions(returnCluster,\n stealerNodeId,\n stealerPartitionId,\n donorNodeId,\n donorPartitionId);\n }"
] |
Release a connection by placing the connection back in the pool.
@param connectionHandle Connection being released.
@throws SQLException | [
"protected void internalReleaseConnection(ConnectionHandle connectionHandle) throws SQLException {\r\n\t\tif (!this.cachedPoolStrategy){\r\n\t\t\tconnectionHandle.clearStatementCaches(false);\r\n\t\t}\r\n\r\n\t\tif (connectionHandle.getReplayLog() != null){\r\n\t\t\tconnectionHandle.getReplayLog().clear();\r\n\t\t\tconnectionHandle.recoveryResult.getReplaceTarget().clear();\r\n\t\t}\r\n\r\n\t\tif (connectionHandle.isExpired() || \r\n\t\t\t\t(!this.poolShuttingDown \r\n\t\t\t\t\t\t&& connectionHandle.isPossiblyBroken()\r\n\t\t\t\t&& !isConnectionHandleAlive(connectionHandle))){\r\n\r\n if (connectionHandle.isExpired()) {\r\n connectionHandle.internalClose();\r\n }\r\n\r\n\t\t\tConnectionPartition connectionPartition = connectionHandle.getOriginatingPartition();\r\n\t\t\tpostDestroyConnection(connectionHandle);\r\n\r\n\t\t\tmaybeSignalForMoreConnections(connectionPartition);\r\n\t\t\tconnectionHandle.clearStatementCaches(true);\r\n\t\t\treturn; // don't place back in queue - connection is broken or expired.\r\n\t\t}\r\n\r\n\r\n\t\tconnectionHandle.setConnectionLastUsedInMs(System.currentTimeMillis());\r\n\t\tif (!this.poolShuttingDown){\r\n\t\t\tputConnectionBackInPartition(connectionHandle);\r\n\t\t} else {\r\n\t\t\tconnectionHandle.internalClose();\r\n\t\t}\r\n\t}"
] | [
"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 }",
"private void deselectChildren(CmsTreeItem item) {\r\n\r\n for (String childId : m_childrens.get(item.getId())) {\r\n CmsTreeItem child = m_categories.get(childId);\r\n deselectChildren(child);\r\n child.getCheckBox().setChecked(false);\r\n if (m_selectedCategories.contains(childId)) {\r\n m_selectedCategories.remove(childId);\r\n }\r\n }\r\n }",
"protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {\n for (MethodNode method : mopCalls) {\n String name = getMopMethodName(method, useThis);\n Parameter[] parameters = method.getParameters();\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());\n MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);\n controller.setMethodVisitor(mv);\n mv.visitVarInsn(ALOAD, 0);\n int newRegister = 1;\n OperandStack operandStack = controller.getOperandStack();\n for (Parameter parameter : parameters) {\n ClassNode type = parameter.getType();\n operandStack.load(parameter.getType(), newRegister);\n // increment to next register, double/long are using two places\n newRegister++;\n if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++;\n }\n operandStack.remove(parameters.length);\n ClassNode declaringClass = method.getDeclaringClass();\n // JDK 8 support for default methods in interfaces\n // this should probably be strenghtened when we support the A.super.foo() syntax\n int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL;\n mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE);\n BytecodeHelper.doReturn(mv, method.getReturnType());\n mv.visitMaxs(0, 0);\n mv.visitEnd();\n controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);\n }\n }",
"public void updateAnimation()\n {\n Date time = new Date();\n long currentTime = time.getTime() - this.beginAnimation;\n if (currentTime > animationTime)\n {\n this.currentQuaternion.set(endQuaternion);\n for (int i = 0; i < 3; i++)\n {\n\n this.currentPos[i] = this.endPos[i];\n }\n this.animate = false;\n }\n\n else\n {\n float t = (float) currentTime / animationTime;\n this.currentQuaternion = this.beginQuaternion.slerp(this.endQuaternion,\n t);\n for (int i = 0; i < 3; i++)\n {\n this.currentPos[i] = this.beginPos[i] + totalTranslation[i] * t;\n }\n\n }\n }",
"private ProjectFile readProjectFile(ProjectReader reader, InputStream stream) throws MPXJException\n {\n addListeners(reader);\n return reader.read(stream);\n }",
"void init( DMatrixSparseCSC A ) {\n this.A = A;\n this.m = A.numRows;\n this.n = A.numCols;\n\n this.next = 0;\n this.head = m;\n this.tail = m + n;\n this.nque = m + 2*n;\n\n if( parent.length < n || leftmost.length < m) {\n parent = new int[n];\n post = new int[n];\n pinv = new int[m+n];\n countsR = new int[n];\n leftmost = new int[m];\n }\n gwork.reshape(m+3*n);\n }",
"public static <K, V> HashMap<K, V> newEmptyHashMap(Iterable<?> iterable) {\n if(iterable instanceof Collection<?>)\n return Maps.newHashMapWithExpectedSize(((Collection<?>) iterable).size());\n return Maps.newHashMap();\n }",
"public int setPageCount(final int num) {\n int diff = num - getCheckableCount();\n if (diff > 0) {\n addIndicatorChildren(diff);\n } else if (diff < 0) {\n removeIndicatorChildren(-diff);\n }\n if (mCurrentPage >=num ) {\n mCurrentPage = 0;\n }\n setCurrentPage(mCurrentPage);\n return diff;\n }",
"public ArrayList<Duration> segmentBaselineWork(ProjectFile file, List<TimephasedWork> work, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n return segmentWork(file.getBaselineCalendar(), work, rangeUnits, dateList);\n }"
] |
Reads a PEP file from the input stream.
@param is input stream representing a PEP file | [
"private void readFile(InputStream is) throws IOException\n {\n StreamHelper.skip(is, 64);\n int index = 64;\n\n ArrayList<Integer> offsetList = new ArrayList<Integer>();\n List<String> nameList = new ArrayList<String>();\n\n while (true)\n {\n byte[] table = new byte[32];\n is.read(table);\n index += 32;\n\n int offset = PEPUtility.getInt(table, 0);\n offsetList.add(Integer.valueOf(offset));\n if (offset == 0)\n {\n break;\n }\n\n nameList.add(PEPUtility.getString(table, 5).toUpperCase());\n }\n\n StreamHelper.skip(is, offsetList.get(0).intValue() - index);\n\n for (int offsetIndex = 1; offsetIndex < offsetList.size() - 1; offsetIndex++)\n {\n String name = nameList.get(offsetIndex - 1);\n Class<? extends Table> tableClass = TABLE_CLASSES.get(name);\n if (tableClass == null)\n {\n tableClass = Table.class;\n }\n\n Table table;\n try\n {\n table = tableClass.newInstance();\n }\n\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n m_tables.put(name, table);\n table.read(is);\n }\n }"
] | [
"private EventTypeEnum getEventType(Message message) {\n boolean isRequestor = MessageUtils.isRequestor(message);\n boolean isFault = MessageUtils.isFault(message);\n boolean isOutbound = MessageUtils.isOutbound(message);\n\n //Needed because if it is rest request and method does not exists had better to return Fault\n if(!isFault && isRestMessage(message)) {\n isFault = (message.getExchange().get(\"org.apache.cxf.resource.operation.name\") == null);\n if (!isFault) {\n Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE);\n if (null != responseCode) {\n isFault = (responseCode >= 400);\n }\n }\n }\n if (isOutbound) {\n if (isFault) {\n return EventTypeEnum.FAULT_OUT;\n } else {\n return isRequestor ? EventTypeEnum.REQ_OUT : EventTypeEnum.RESP_OUT;\n }\n } else {\n if (isFault) {\n return EventTypeEnum.FAULT_IN;\n } else {\n return isRequestor ? EventTypeEnum.RESP_IN : EventTypeEnum.REQ_IN;\n }\n }\n }",
"public static gslbldnsentries[] get(nitro_service service) throws Exception{\n\t\tgslbldnsentries obj = new gslbldnsentries();\n\t\tgslbldnsentries[] response = (gslbldnsentries[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void setOccurence(int min, int max) throws ParseException {\n if (!simplified) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n optional = true;\n }\n minimumOccurence = Math.max(1, min);\n maximumOccurence = max;\n } else {\n throw new ParseException(\"already simplified\");\n }\n }",
"public byte[] getByteArrayValue(int index)\n {\n byte[] result = null;\n\n if (m_array[index] != null)\n {\n result = (byte[]) m_array[index];\n }\n\n return (result);\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 }",
"public static String readDesignerVersion(ServletContext context) {\n String retStr = \"\";\n BufferedReader br = null;\n try {\n InputStream inputStream = context.getResourceAsStream(\"/META-INF/MANIFEST.MF\");\n br = new BufferedReader(new InputStreamReader(inputStream,\n \"UTF-8\"));\n String line;\n while ((line = br.readLine()) != null) {\n if (line.startsWith(BUNDLE_VERSION)) {\n retStr = line.substring(BUNDLE_VERSION.length() + 1);\n retStr = retStr.trim();\n }\n }\n inputStream.close();\n } catch (Exception e) {\n logger.error(e.getMessage(),\n e);\n } finally {\n if (br != null) {\n IOUtils.closeQuietly(br);\n }\n }\n return retStr;\n }",
"public Tree determineHead(Tree t, Tree parent) {\r\n if (nonTerminalInfo == null) {\r\n throw new RuntimeException(\"Classes derived from AbstractCollinsHeadFinder must\" + \" create and fill HashMap nonTerminalInfo.\");\r\n }\r\n if (t == null || t.isLeaf()) {\r\n return null;\r\n }\r\n if (DEBUG) {\r\n System.err.println(\"determineHead for \" + t.value());\r\n }\r\n \r\n Tree[] kids = t.children();\r\n\r\n Tree theHead;\r\n // first check if subclass found explicitly marked head\r\n if ((theHead = findMarkedHead(t)) != null) {\r\n if (DEBUG) {\r\n System.err.println(\"Find marked head method returned \" +\r\n theHead.label() + \" as head of \" + t.label());\r\n }\r\n return theHead;\r\n }\r\n\r\n // if the node is a unary, then that kid must be the head\r\n // it used to special case preterminal and ROOT/TOP case\r\n // but that seemed bad (especially hardcoding string \"ROOT\")\r\n if (kids.length == 1) {\r\n if (DEBUG) {\r\n System.err.println(\"Only one child determines \" +\r\n kids[0].label() + \" as head of \" + t.label());\r\n }\r\n return kids[0];\r\n }\r\n\r\n return determineNonTrivialHead(t, parent);\r\n }",
"public static List<String> getNodeListFromStringLineSeperateOrSpaceSeperate(\n String listStr, boolean removeDuplicate) {\n\n List<String> nodes = new ArrayList<String>();\n\n for (String token : listStr.split(\"[\\\\r?\\\\n| +]+\")) {\n\n // 20131025: fix if fqdn has space in the end.\n if (token != null && !token.trim().isEmpty()) {\n nodes.add(token.trim());\n\n }\n }\n\n if (removeDuplicate) {\n removeDuplicateNodeList(nodes);\n }\n logger.info(\"Target hosts size : \" + nodes.size());\n\n return nodes;\n\n }",
"public static authenticationradiusaction get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tobj.set_name(name);\n\t\tauthenticationradiusaction response = (authenticationradiusaction) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Call the no-arg constructor for the given class
@param <T> The type of the thing to construct
@param klass The class
@return The constructed thing | [
"public static <T> T callConstructor(Class<T> klass) {\n return callConstructor(klass, new Class<?>[0], new Object[0]);\n }"
] | [
"@Override\n\tpublic <T> T get(Object key, Resource resource, Provider<T> provider) {\n\t\tif(resource == null) {\n\t\t\treturn provider.get();\n\t\t}\n\t\tCacheAdapter adapter = getOrCreate(resource);\n\t\tT element = adapter.<T>internalGet(key);\n\t\tif (element==null) {\n\t\t\telement = provider.get();\n\t\t\tcacheMiss(adapter);\n\t\t\tadapter.set(key, element);\n\t\t} else {\n\t\t\tcacheHit(adapter);\n\t\t}\n\t\tif (element == CacheAdapter.NULL) {\n\t\t\treturn null;\n\t\t}\n\t\treturn element;\n\t}",
"public Column getColumn(String columnName) {\n if (columnName == null) {\n return null;\n }\n for (Column column : columns) {\n if (columnName.equals(column.getData())) {\n return column;\n }\n }\n return null;\n }",
"protected void putConnectionBackInPartition(ConnectionHandle connectionHandle) throws SQLException {\r\n\r\n\t\tif (this.cachedPoolStrategy && ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.dumbGet().getValue()){\r\n\t\t\tconnectionHandle.logicallyClosed.set(true);\r\n\t\t\t((CachedConnectionStrategy)this.connectionStrategy).tlConnections.set(new AbstractMap.SimpleEntry<ConnectionHandle, Boolean>(connectionHandle, false));\r\n\t\t} else {\r\n\t\t\tBlockingQueue<ConnectionHandle> queue = connectionHandle.getOriginatingPartition().getFreeConnections();\r\n\t\t\t\tif (!queue.offer(connectionHandle)){ // this shouldn't fail\r\n\t\t\t\t\tconnectionHandle.internalClose();\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t}",
"private boolean isAcceptingNewJobs() {\n if (this.requestedToStop) {\n return false;\n } else if (new File(this.workingDirectories.getWorking(), \"stop\").exists()) {\n LOGGER.info(\"The print has been requested to stop\");\n this.requestedToStop = true;\n notifyIfStopped();\n return false;\n } else {\n return true;\n }\n }",
"@SuppressWarnings(\"unused\")\n\t@XmlID\n @XmlAttribute(name = \"id\")\n private String getXmlID(){\n return String.format(\"%s-%s\", this.getClass().getSimpleName(), Long.valueOf(id));\n }",
"public ResourceAssignment addResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = getExistingResourceAssignment(resource);\n\n if (assignment == null)\n {\n assignment = new ResourceAssignment(getParentFile(), this);\n m_assignments.add(assignment);\n getParentFile().getResourceAssignments().add(assignment);\n\n assignment.setTaskUniqueID(getUniqueID());\n assignment.setWork(getDuration());\n assignment.setUnits(ResourceAssignment.DEFAULT_UNITS);\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n }\n\n return (assignment);\n }",
"public void strokeEllipse(Rectangle rect, Color color, float linewidth) {\n\t\ttemplate.saveState();\n\t\tsetStroke(color, linewidth, null);\n\t\ttemplate.ellipse(origX + rect.getLeft(), origY + rect.getBottom(), origX + rect.getRight(),\n\t\t\t\torigY + rect.getTop());\n\t\ttemplate.stroke();\n\t\ttemplate.restoreState();\n\t}",
"@PostConstruct\n public void checkUniqueSchemes() {\n Multimap<String, ConfigFileLoaderPlugin> schemeToPluginMap = HashMultimap.create();\n\n for (ConfigFileLoaderPlugin plugin: getLoaderPlugins()) {\n schemeToPluginMap.put(plugin.getUriScheme(), plugin);\n }\n\n StringBuilder violations = new StringBuilder();\n for (String scheme: schemeToPluginMap.keySet()) {\n final Collection<ConfigFileLoaderPlugin> plugins = schemeToPluginMap.get(scheme);\n if (plugins.size() > 1) {\n violations.append(\"\\n\\n* \").append(\"There are has multiple \")\n .append(ConfigFileLoaderPlugin.class.getSimpleName())\n .append(\" plugins that support the scheme: '\").append(scheme).append('\\'')\n .append(\":\\n\\t\").append(plugins);\n }\n }\n\n if (violations.length() > 0) {\n throw new IllegalStateException(violations.toString());\n }\n }",
"public static BoxLegalHoldAssignment.Info create(BoxAPIConnection api,\n String policyID, String resourceType, String resourceID) {\n URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n JsonObject requestJSON = new JsonObject()\n .add(\"policy_id\", policyID)\n .add(\"assign_to\", new JsonObject()\n .add(\"type\", resourceType)\n .add(\"id\", resourceID));\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxLegalHoldAssignment createdAssignment = new BoxLegalHoldAssignment(api, responseJSON.get(\"id\").asString());\n return createdAssignment.new Info(responseJSON);\n }"
] |
Check if the provided manifestPath is correct.
Set the manifest and imagePath in case of the correct manifest.
@param manifestPath
@param candidateImagePath
@param dependenciesClient
@param listener
@return true if found the correct manifest
@throws IOException | [
"private boolean checkAndSetManifestAndImagePathCandidates(String manifestPath, String candidateImagePath, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateManifest = getManifestFromArtifactory(dependenciesClient, manifestPath);\n if (candidateManifest == null) {\n return false;\n }\n\n String imageDigest = DockerUtils.getConfigDigest(candidateManifest);\n if (imageDigest.equals(imageId)) {\n manifest = candidateManifest;\n imagePath = candidateImagePath;\n return true;\n }\n\n listener.getLogger().println(String.format(\"Found incorrect manifest.json file in Artifactory in the following path: %s\\nExpecting: %s got: %s\", manifestPath, imageId, imageDigest));\n return false;\n }"
] | [
"public static appflowpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_binding obj = new appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_binding response = (appflowpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"protected EObject forceCreateModelElementAndSet(Action action, EObject value) {\n \tEObject result = semanticModelBuilder.create(action.getType().getClassifier());\n \tsemanticModelBuilder.set(result, action.getFeature(), value, null /* ParserRule */, currentNode);\n \tinsertCompositeNode(action);\n \tassociateNodeWithAstElement(currentNode, result);\n \treturn result;\n }",
"private ColorItem buildColorItem(Message menuItem) {\n final int colorId = (int) ((NumberField) menuItem.arguments.get(1)).getValue();\n final String label = ((StringField) menuItem.arguments.get(3)).getValue();\n return buildColorItem(colorId, label);\n }",
"private void readProjectProperties(Project ganttProject)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(ganttProject.getName());\n mpxjProperties.setCompany(ganttProject.getCompany());\n mpxjProperties.setDefaultDurationUnits(TimeUnit.DAYS);\n\n String locale = ganttProject.getLocale();\n if (locale == null)\n {\n locale = \"en_US\";\n }\n m_localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(locale));\n }",
"protected boolean isSecureLink(CmsObject cms, String vfsName, CmsSite targetSite, boolean secureRequest) {\n\n return OpenCms.getStaticExportManager().isSecureLink(cms, vfsName, targetSite.getSiteRoot(), secureRequest);\n }",
"public void endRecord_() {\n // this is where we actually update the link database. basically,\n // all we need to do is to retract those links which weren't seen\n // this time around, and that can be done via assertLink, since it\n // can override existing links.\n\n // get all the existing links\n Collection<Link> oldlinks = linkdb.getAllLinksFor(getIdentity(current));\n\n // build a hashmap so we can look up corresponding old links from\n // new links\n if (oldlinks != null) {\n Map<String, Link> oldmap = new HashMap(oldlinks.size());\n for (Link l : oldlinks)\n oldmap.put(makeKey(l), l);\n\n // removing all the links we found this time around from the set of\n // old links. any links remaining after this will be stale, and need\n // to be retracted\n for (Link newl : new ArrayList<Link>(curlinks)) {\n String key = makeKey(newl);\n Link oldl = oldmap.get(key);\n if (oldl == null)\n continue;\n\n if (oldl.overrides(newl))\n // previous information overrides this link, so ignore\n curlinks.remove(newl);\n else if (sameAs(oldl, newl)) {\n // there's no new information here, so just ignore this\n curlinks.remove(newl);\n oldmap.remove(key); // we don't want to retract the old one\n } else\n // the link is out of date, but will be overwritten, so remove\n oldmap.remove(key);\n }\n\n // all the inferred links left in oldmap are now old links we\n // didn't find on this pass. there is no longer any evidence\n // supporting them, and so we can retract them.\n for (Link oldl : oldmap.values())\n if (oldl.getStatus() == LinkStatus.INFERRED) {\n oldl.retract(); // changes to retracted, updates timestamp\n curlinks.add(oldl);\n }\n }\n\n // okay, now we write it all to the database\n for (Link l : curlinks)\n linkdb.assertLink(l);\n }",
"public final PJsonObject getJSONObject(final int i) {\n JSONObject val = this.array.optJSONObject(i);\n final String context = \"[\" + i + \"]\";\n if (val == null) {\n throw new ObjectMissingException(this, context);\n }\n return new PJsonObject(this, val, context);\n }",
"public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) {\n\n if (clazz.isPrimitive()) {\n throw new IllegalArgumentException(\"Primitive types not supported.\");\n }\n\n List<Field> result = new ArrayList<Field>();\n\n while (true) {\n\n if (clazz == Object.class) {\n break;\n }\n\n result.addAll(Arrays.asList(clazz.getDeclaredFields()));\n clazz = clazz.getSuperclass();\n }\n\n return result.toArray(new Field[result.size()]);\n }",
"public PhotoList<Photo> getClusterPhotos(String tag, String clusterId) throws FlickrException {\n\n PhotoList<Photo> photos = new PhotoList<Photo>();\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_CLUSTER_PHOTOS);\n\n parameters.put(\"tag\", tag);\n parameters.put(\"cluster_id\", clusterId);\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 photosElement = response.getPayload();\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\n photos.setPage(\"1\");\n photos.setPages(\"1\");\n photos.setPerPage(\"\" + photoNodes.getLength());\n photos.setTotal(\"\" + photoNodes.getLength());\n for (int i = 0; i < photoNodes.getLength(); i++) {\n Element photoElement = (Element) photoNodes.item(i);\n photos.add(PhotoUtils.createPhoto(photoElement));\n }\n return photos;\n }"
] |
Returns the next object in the table.
@throws IllegalStateException
If there was a problem extracting the object from SQL. | [
"@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 synchronized RegistrationPoint getOldestRegistrationPoint() {\n return registrationPoints.size() == 0 ? null : registrationPoints.values().iterator().next().get(0);\n }",
"private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) {\n\t\tdouble interpolationEntitiyTime;\n\t\tRandomVariable interpolationEntityForwardValue;\n\t\tswitch(interpolationEntityForward) {\n\t\tcase FORWARD:\n\t\tdefault:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward;\n\t\t\tbreak;\n\t\tcase FORWARD_TIMES_DISCOUNTFACTOR:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime)));\n\t\t\tbreak;\n\t\tcase ZERO:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime = fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset);\n\t\t\tbreak;\n\t\t}\n\t\tcase DISCOUNTFACTOR:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime\t\t= fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0));\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t\tsuper.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter);\n\t}",
"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 double normP(DMatrixRMaj A , double p ) {\n if( p == 1 ) {\n return normP1(A);\n } else if( p == 2 ) {\n return normP2(A);\n } else if( Double.isInfinite(p)) {\n return normPInf(A);\n }\n if( MatrixFeatures_DDRM.isVector(A) ) {\n return elementP(A,p);\n } else {\n throw new IllegalArgumentException(\"Doesn't support induced norms yet.\");\n }\n }",
"private Auth constructAuth(String authToken, String tokenSecret, String username) throws IOException {\n\n Auth auth = new Auth();\n auth.setToken(authToken);\n auth.setTokenSecret(tokenSecret);\n\n // Prompt to ask what permission is needed: read, update or delete.\n auth.setPermission(Permission.fromString(\"delete\"));\n\n User user = new User();\n // Later change the following 3. Either ask user to pass on command line or read\n // from saved file.\n user.setId(nsid);\n user.setUsername((username));\n user.setRealName(\"\");\n auth.setUser(user);\n this.authStore.store(auth);\n return auth;\n }",
"public Set<S> getMatchedDeclarationBinder() {\n Set<S> bindedSet = new HashSet<S>();\n for (Map.Entry<ServiceReference<S>, BinderDescriptor> e : declarationBinders.entrySet()) {\n if (e.getValue().match) {\n bindedSet.add(getDeclarationBinder(e.getKey()));\n }\n }\n return bindedSet;\n }",
"public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }",
"@Override\n public final String optString(final String key, final String defaultValue) {\n String result = optString(key);\n return result == null ? defaultValue : result;\n }",
"public String stripUnnecessaryComments(String javaContent, AntlrOptions options) {\n\t\tif (!options.isOptimizeCodeQuality()) {\n\t\t\treturn javaContent;\n\t\t}\n\t\tjavaContent = stripMachineDependentPaths(javaContent);\n\t\tif (options.isStripAllComments()) {\n\t\t\tjavaContent = stripAllComments(javaContent);\n\t\t}\n\t\treturn javaContent;\n\t}"
] |
Checks if a given number is in the range of a short.
@param number
a number which should be in the range of a short (positive or negative)
@see java.lang.Short#MIN_VALUE
@see java.lang.Short#MAX_VALUE
@return number as a short (rounding might occur) | [
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static short checkShort(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInShortRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), SHORT_MIN, SHORT_MAX);\n\t\t}\n\n\t\treturn number.shortValue();\n\t}"
] | [
"final protected char next(final ByteBuffer buffer, boolean allow8859) throws BaseExceptions.BadMessage {\n\n if (!buffer.hasRemaining()) return HttpTokens.EMPTY_BUFF;\n\n if (_segmentByteLimit <= _segmentBytePosition) {\n shutdownParser();\n throw new BaseExceptions.BadMessage(\"Request length limit exceeded: \" + _segmentByteLimit);\n }\n\n final byte b = buffer.get();\n _segmentBytePosition++;\n\n // If we ended on a CR, make sure we are\n if (_cr) {\n if (b != HttpTokens.LF) {\n throw new BadCharacter(\"Invalid sequence: LF didn't follow CR: \" + b);\n }\n _cr = false;\n return (char)b; // must be LF\n }\n\n // Make sure its a valid character\n if (b < HttpTokens.SPACE) {\n if (b == HttpTokens.CR) { // Set the flag to check for _cr and just run again\n _cr = true;\n return next(buffer, allow8859);\n }\n else if (b == HttpTokens.TAB || allow8859 && b < 0) {\n return (char)(b & 0xff);\n }\n else if (b == HttpTokens.LF) {\n return (char)b; // A backend should accept a bare linefeed. http://tools.ietf.org/html/rfc2616#section-19.3\n }\n else if (isLenient()) {\n return HttpTokens.REPLACEMENT;\n }\n else {\n shutdownParser();\n throw new BadCharacter(\"Invalid char: '\" + (char)(b & 0xff) + \"', 0x\" + Integer.toHexString(b));\n }\n }\n\n // valid ascii char\n return (char)b;\n }",
"public synchronized Response doCommandFullResponse(String command) throws CommandFormatException, IOException {\n ModelNode request = cmdCtx.buildRequest(command);\n boolean replacedBytes = replaceFilePathsWithBytes(request);\n OperationResponse response = execute(request, isSlowCommand(command) || replacedBytes);\n return new Response(command, request, response);\n }",
"private GraphicalIndicatorCriteria processCriteria(FieldType type)\n {\n GraphicalIndicatorCriteria criteria = new GraphicalIndicatorCriteria(m_properties);\n criteria.setLeftValue(type);\n\n int indicatorType = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n criteria.setIndicator(indicatorType);\n\n if (m_dataOffset + 4 < m_data.length)\n {\n int operatorValue = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n TestOperator operator = (operatorValue == 0 ? TestOperator.IS_ANY_VALUE : TestOperator.getInstance(operatorValue - 0x3E7));\n criteria.setOperator(operator);\n\n if (operator != TestOperator.IS_ANY_VALUE)\n {\n processOperandValue(0, type, criteria);\n\n if (operator == TestOperator.IS_WITHIN || operator == TestOperator.IS_NOT_WITHIN)\n {\n processOperandValue(1, type, criteria);\n }\n }\n }\n\n return (criteria);\n }",
"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 }",
"public static tmtrafficpolicy_tmglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficpolicy_tmglobal_binding obj = new tmtrafficpolicy_tmglobal_binding();\n\t\tobj.set_name(name);\n\t\ttmtrafficpolicy_tmglobal_binding response[] = (tmtrafficpolicy_tmglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Override\n\tpublic void close() {\n\t\tlogger.info(\"Finished processing.\");\n\t\tthis.timer.stop();\n\t\tthis.lastSeconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\tprintStatus();\n\t}",
"public Collection<V> put(K key, Collection<V> collection) {\r\n return map.put(key, collection);\r\n }",
"public static base_responses add(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 addresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new clusterinstance();\n\t\t\t\taddresources[i].clid = resources[i].clid;\n\t\t\t\taddresources[i].deadinterval = resources[i].deadinterval;\n\t\t\t\taddresources[i].hellointerval = resources[i].hellointerval;\n\t\t\t\taddresources[i].preemption = resources[i].preemption;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Integer getVarDataKey(FieldType type)\n {\n Integer result = null;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getVarDataKey();\n }\n return result;\n }"
] |
Painter the tile, by building a URL where the image can be found.
@param tile
Must be an instance of {@link InternalTile}, and must have a non-null {@link RasterUrlBuilder}.
@return Returns a {@link InternalTile}. | [
"public InternalTile paint(InternalTile tile) throws RenderException {\n\t\tif (tile.getContentType().equals(VectorTileContentType.URL_CONTENT)) {\n\t\t\tif (urlBuilder != null) {\n\t\t\t\tif (paintGeometries) {\n\t\t\t\t\turlBuilder.paintGeometries(paintGeometries);\n\t\t\t\t\turlBuilder.paintLabels(false);\n\t\t\t\t\ttile.setFeatureContent(urlBuilder.getImageUrl());\n\t\t\t\t}\n\t\t\t\tif (paintLabels) {\n\t\t\t\t\turlBuilder.paintGeometries(false);\n\t\t\t\t\turlBuilder.paintLabels(paintLabels);\n\t\t\t\t\ttile.setLabelContent(urlBuilder.getImageUrl());\n\t\t\t\t}\n\t\t\t\treturn tile;\n\t\t\t}\n\t\t}\n\t\treturn tile;\n\t}"
] | [
"public static Cluster swapPartitions(final Cluster nextCandidateCluster,\n final int nodeIdA,\n final int partitionIdA,\n final int nodeIdB,\n final int partitionIdB) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n\n // Swap partitions between nodes!\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n nodeIdA,\n Lists.newArrayList(partitionIdB));\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n nodeIdB,\n Lists.newArrayList(partitionIdA));\n\n return returnCluster;\n }",
"public String getShortMessage(Locale locale) {\n\t\tString message;\n\t\tmessage = translate(Integer.toString(exceptionCode), locale);\n\t\tif (message != null && msgParameters != null && msgParameters.length > 0) {\n\t\t\tfor (int i = 0; i < msgParameters.length; i++) {\n\t\t\t\tboolean isIncluded = false;\n\t\t\t\tString needTranslationParam = \"$${\" + i + \"}\";\n\t\t\t\tif (message.contains(needTranslationParam)) {\n\t\t\t\t\tString translation = translate(msgParameters[i], locale);\n\t\t\t\t\tif (null == translation && null != msgParameters[i]) {\n\t\t\t\t\t\ttranslation = msgParameters[i].toString();\n\t\t\t\t\t}\n\t\t\t\t\tif (null == translation) {\n\t\t\t\t\t\ttranslation = \"[null]\";\n\t\t\t\t\t}\n\t\t\t\t\tmessage = message.replace(needTranslationParam, translation);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tString verbatimParam = \"${\" + i + \"}\";\n\t\t\t\tString rs = null == msgParameters[i] ? \"[null]\" : msgParameters[i].toString();\n\t\t\t\tif (message.contains(verbatimParam)) {\n\t\t\t\t\tmessage = message.replace(verbatimParam, rs);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tif (!isIncluded) {\n\t\t\t\t\tmessage = message + \" (\" + rs + \")\"; // NOSONAR replace/contains makes StringBuilder use difficult\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn message;\n\t}",
"private void readResources(Project project, HashMap<BigInteger, ProjectCalendar> calendarMap)\n {\n Project.Resources resources = project.getResources();\n if (resources != null)\n {\n for (Project.Resources.Resource resource : resources.getResource())\n {\n readResource(resource, calendarMap);\n }\n }\n }",
"public static rnat6_nsip6_binding[] get(nitro_service service, String name) throws Exception{\n\t\trnat6_nsip6_binding obj = new rnat6_nsip6_binding();\n\t\tobj.set_name(name);\n\t\trnat6_nsip6_binding response[] = (rnat6_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"@Deprecated\n\tpublic void setResolutions(List<Double> resolutions) {\n\t\tgetZoomLevels().clear();\n\t\tfor (Double resolution : resolutions) {\n\t\t\tgetZoomLevels().add(new ScaleInfo(1. / resolution));\n\t\t}\n\t}",
"public IndirectionHandler createIndirectionHandler(PBKey brokerKey, Identity id)\r\n {\r\n Object args[] = {brokerKey, id};\r\n\r\n try\r\n {\r\n return (IndirectionHandler) getIndirectionHandlerConstructor().newInstance(args);\r\n }\r\n catch(InvocationTargetException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n catch(InstantiationException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n catch(IllegalAccessException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new indirection handler instance\", ex);\r\n }\r\n }",
"public static I_CmsMacroResolver newWorkplaceLocaleResolver(final CmsObject cms) {\n\n // Resolve macros in the property configuration\n CmsMacroResolver resolver = new CmsMacroResolver();\n resolver.setCmsObject(cms);\n CmsUserSettings userSettings = new CmsUserSettings(cms.getRequestContext().getCurrentUser());\n CmsMultiMessages multimessages = new CmsMultiMessages(userSettings.getLocale());\n multimessages.addMessages(OpenCms.getWorkplaceManager().getMessages(userSettings.getLocale()));\n resolver.setMessages(multimessages);\n resolver.setKeepEmptyMacros(true);\n\n return resolver;\n }",
"public void useSimpleProxy() {\n String webAppAddress = \"http://localhost:\" + port + \"/services/personservice\";\n PersonService proxy = JAXRSClientFactory.create(webAppAddress, PersonService.class);\n\n new PersonServiceProxyClient(proxy).useService();\n }",
"public void unbind(String name) throws ObjectNameNotFoundException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call unbind.\r\n */\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open. Must have an open DB to call unbind\");\r\n }\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"Tx is not open. Must have an open TX to call lookup.\");\r\n }\r\n\r\n tx.getNamedRootsMap().unbind(name);\r\n }"
] |
Use this API to update spilloverpolicy. | [
"public static base_response update(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy updateresource = new spilloverpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.action = resource.action;\n\t\tupdateresource.comment = resource.comment;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"private void deliverMasterYieldResponse(int fromPlayer, boolean yielded) {\n for (final MasterHandoffListener listener : getMasterHandoffListeners()) {\n try {\n listener.yieldResponse(fromPlayer, yielded);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master yield response to listener\", t);\n }\n }\n }",
"public Set<Class<?>> getPrevented() {\n if (this.prevent == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(this.prevent);\n }",
"static File getTargetFile(final File root, final MiscContentItem item) {\n return PatchContentLoader.getMiscPath(root, item);\n }",
"protected String format(String key, String defaultPattern, Object... args) {\n String escape = escape(defaultPattern);\n String s = lookupPattern(key, escape);\n Object[] objects = escapeAll(args);\n return MessageFormat.format(s, objects);\n }",
"private String[] getColumnNames(ResultSetMetaData rsmd) throws Exception {\n ArrayList<String> names = new ArrayList<String>();\n\n // Get result set meta data\n int numColumns = rsmd.getColumnCount();\n\n // Get the column names; column indices start from 1\n for (int i = 1; i < numColumns + 1; i++) {\n String columnName = rsmd.getColumnName(i);\n\n names.add(columnName);\n }\n\n return names.toArray(new String[0]);\n }",
"public void map(Story story, MetaFilter metaFilter) {\n if (metaFilter.allow(story.getMeta())) {\n boolean allowed = false;\n for (Scenario scenario : story.getScenarios()) {\n // scenario also inherits meta from story\n Meta inherited = scenario.getMeta().inheritFrom(story.getMeta());\n if (metaFilter.allow(inherited)) {\n allowed = true;\n break;\n }\n }\n if (allowed) {\n add(metaFilter.asString(), story);\n }\n }\n }",
"public T withStatement(Statement statement) {\n\t\tPropertyIdValue pid = statement.getMainSnak()\n\t\t\t\t.getPropertyId();\n\t\tArrayList<Statement> pidStatements = this.statements.get(pid);\n\t\tif (pidStatements == null) {\n\t\t\tpidStatements = new ArrayList<Statement>();\n\t\t\tthis.statements.put(pid, pidStatements);\n\t\t}\n\n\t\tpidStatements.add(statement);\n\t\treturn getThis();\n\t}",
"protected void generateRoutes()\n {\n try {\n\n//\t\t\tOptional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\n//\t\t\ttypeLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t \n//\t\t\t\tio.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();\n//\n//\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\n//\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t{\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\n//\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\n//\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t}\n//\t\t\t\t\n//\t\t\t});\n//\t\t\t\n//\t\t\tfor(Method m : this.controllerClass.getDeclaredMethods())\n//\t\t\t{\n//\t\t\t\n//\t\t\t\tOptional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));\n//\t\t\t\t\n//\t\t\t\tmethodLevelWrapAnnotation.ifPresent( a -> {\n//\t\t\t\t\t \n//\t\t\t\t\tio.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();\n//\t\n//\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClasses[] = w.value();\n//\t\n//\t\t\t\t\tfor (int i = 0; i < wrapperClasses.length; i++)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tClass<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];\n//\t\n//\t\t\t\t\t\tString wrapperName = generateFieldName(wrapperClass.getCanonicalName());\n//\t\n//\t\t\t\t\t\thandlerWrapperMap.put(wrapperClass, wrapperName);\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t});\n//\n//\t\t\t}\n//\t\t\t\n//\t\t\tlog.info(\"handlerWrapperMap: \" + handlerWrapperMap);\n\n TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)\n .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));\n\n ClassName extractorClass = ClassName.get(\"io.sinistral.proteus.server\", \"Extractors\");\n\n ClassName injectClass = ClassName.get(\"com.google.inject\", \"Inject\");\n\n\n MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);\n\n String className = this.controllerClass.getSimpleName().toLowerCase() + \"Controller\";\n\n typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);\n\n ClassName wrapperClass = ClassName.get(\"io.undertow.server\", \"HandlerWrapper\");\n ClassName stringClass = ClassName.get(\"java.lang\", \"String\");\n ClassName mapClass = ClassName.get(\"java.util\", \"Map\");\n\n TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);\n\n TypeName annotatedMapOfWrappers = mapOfWrappers\n .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember(\"value\", \"$S\", \"registeredHandlerWrappers\").build());\n\n typeBuilder.addField(mapOfWrappers, \"registeredHandlerWrappers\", Modifier.PROTECTED, Modifier.FINAL);\n\n\n constructor.addParameter(this.controllerClass, className);\n constructor.addParameter(annotatedMapOfWrappers, \"registeredHandlerWrappers\");\n\n constructor.addStatement(\"this.$N = $N\", className, className);\n constructor.addStatement(\"this.$N = $N\", \"registeredHandlerWrappers\", \"registeredHandlerWrappers\");\n\n addClassMethodHandlers(typeBuilder, this.controllerClass);\n\n typeBuilder.addMethod(constructor.build());\n\n JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, \"*\").build();\n\n StringBuilder sb = new StringBuilder();\n\n javaFile.writeTo(sb);\n\n this.sourceString = sb.toString();\n\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n }",
"protected boolean hasVectorClock(boolean isVectorClockOptional) {\n boolean result = false;\n\n String vectorClockHeader = this.request.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK);\n if(vectorClockHeader != null) {\n ObjectMapper mapper = new ObjectMapper();\n try {\n VectorClockWrapper vcWrapper = mapper.readValue(vectorClockHeader,\n VectorClockWrapper.class);\n this.parsedVectorClock = new VectorClock(vcWrapper.getVersions(),\n vcWrapper.getTimestamp());\n result = true;\n } catch(Exception e) {\n logger.error(\"Exception while parsing and constructing vector clock\", e);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Invalid Vector Clock\");\n }\n } else if(!isVectorClockOptional) {\n logger.error(\"Error when validating request. Missing Vector Clock\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing Vector Clock\");\n } else {\n result = true;\n }\n\n return result;\n }"
] |
Returns the names of the bundles configured as workplace bundles in any module configuration.
@return the names of the bundles configured as workplace bundles in any module configuration. | [
"public Set<String> getConfiguredWorkplaceBundles() {\n\n CmsADEConfigData configData = internalLookupConfiguration(null, null);\n return configData.getConfiguredWorkplaceBundles();\n }"
] | [
"private void fireTreeStructureChanged()\n {\n // Guaranteed to return a non-null array\n Object[] listeners = m_listenerList.getListenerList();\n TreeModelEvent e = null;\n // Process the listeners last to first, notifying\n // those that are interested in this event\n for (int i = listeners.length - 2; i >= 0; i -= 2)\n {\n if (listeners[i] == TreeModelListener.class)\n {\n // Lazily create the event:\n if (e == null)\n {\n e = new TreeModelEvent(getRoot(), new Object[]\n {\n getRoot()\n }, null, null);\n }\n ((TreeModelListener) listeners[i + 1]).treeStructureChanged(e);\n }\n }\n }",
"public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }",
"private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure,\n final boolean initial) throws OperationFailedException {\n ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure);\n if (resolved.recursive) {\n // Some part of expressionString resolved into a different expression.\n // So, start over, ignoring failures. Ignore failures because we don't require\n // that expressions must not resolve to something that *looks like* an expression but isn't\n return resolveExpressionStringRecursively(resolved.result, true, false);\n } else if (resolved.modified) {\n // Typical case\n return new ModelNode(resolved.result);\n } else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) {\n // We should only get an unmodified expression string back if there was a resolution\n // failure that we ignored.\n assert ignoreDMRResolutionFailure;\n // expressionString came from a node of type expression, so since we did nothing send it back in the same type\n return new ModelNode(new ValueExpression(expressionString));\n } else {\n // The string wasn't really an expression. Two possible cases:\n // 1) if initial == true, someone created a expression node with a non-expression string, which is legal\n // 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an\n // expression but can't be resolved. We don't require that expressions must not resolve to something that\n // *looks like* an expression but isn't, so we'll just treat this as a string\n return new ModelNode(expressionString);\n }\n }",
"public IPlan[] getAgentPlans(final String agent_name, Connector connector) {\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Plan>() {\n\n public IFuture<Plan> execute(IInternalAccess ia) {\n\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n plans = bia.getPlanbase().getPlans();\n return null;\n }\n }).get(new ThreadSuspendable());\n\n return plans;\n }",
"@SuppressWarnings(\"unchecked\")\n\tpublic Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException {\n\t\treturn decodeSignedRequest(signedRequest, Map.class);\n\t}",
"protected static InstallationModificationImpl.InstallationState load(final InstalledIdentity installedIdentity) throws IOException {\n final InstallationModificationImpl.InstallationState state = new InstallationModificationImpl.InstallationState();\n for (final Layer layer : installedIdentity.getLayers()) {\n state.putLayer(layer);\n }\n for (final AddOn addOn : installedIdentity.getAddOns()) {\n state.putAddOn(addOn);\n }\n return state;\n }",
"private void setProperties(Properties properties) {\n Props props = new Props(properties);\n if(props.containsKey(BOOTSTRAP_URLS_PROPERTY)) {\n setBootstrapURLs(props.getList(BOOTSTRAP_URLS_PROPERTY));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_SOURCE)) {\n setFatClientConfigSource(StoreClientConfigSource.get(props.getString(FAT_CLIENTS_CONFIG_SOURCE)));\n }\n\n if(props.containsKey(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY)) {\n setFatClientConfigPath(props.getString(FAT_CLIENTS_CONFIG_FILE_PATH_PROPERTY));\n }\n\n if(props.containsKey(METADATA_CHECK_INTERVAL_IN_MS)) {\n setMetadataCheckIntervalInMs(props.getInt(METADATA_CHECK_INTERVAL_IN_MS));\n }\n\n if(props.containsKey(NETTY_SERVER_PORT)) {\n setServerPort(props.getInt(NETTY_SERVER_PORT));\n }\n\n if(props.containsKey(NETTY_SERVER_BACKLOG)) {\n setNettyServerBacklog(props.getInt(NETTY_SERVER_BACKLOG));\n }\n\n if(props.containsKey(COORDINATOR_CORE_THREADS)) {\n setCoordinatorCoreThreads(props.getInt(COORDINATOR_CORE_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_MAX_THREADS)) {\n setCoordinatorMaxThreads(props.getInt(COORDINATOR_MAX_THREADS));\n }\n\n if(props.containsKey(COORDINATOR_QUEUED_REQUESTS)) {\n setCoordinatorQueuedRequestsSize(props.getInt(COORDINATOR_QUEUED_REQUESTS));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH)) {\n setHttpMessageDecoderMaxInitialLength(props.getInt(HTTP_MESSAGE_DECODER_MAX_INITIAL_LINE_LENGTH));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE)) {\n setHttpMessageDecoderMaxHeaderSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_HEADER_SIZE));\n }\n\n if(props.containsKey(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE)) {\n setHttpMessageDecoderMaxChunkSize(props.getInt(HTTP_MESSAGE_DECODER_MAX_CHUNK_SIZE));\n }\n\n if(props.containsKey(ADMIN_ENABLE)) {\n setAdminServiceEnabled(props.getBoolean(ADMIN_ENABLE));\n }\n\n if(props.containsKey(ADMIN_PORT)) {\n setAdminPort(props.getInt(ADMIN_PORT));\n }\n\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 }",
"private void onConnectionClose(final Connection closed) {\n synchronized (this) {\n if(connection == closed) {\n connection = null;\n if(shutdown) {\n connectTask = DISCONNECTED;\n return;\n }\n final ConnectTask previous = connectTask;\n connectTask = previous.connectionClosed();\n }\n }\n }"
] |
Returns the locale specified by the named scoped attribute or context
configuration parameter.
<p> The named scoped attribute is searched in the page, request,
session (if valid), and application scope(s) (in this order). If no such
attribute exists in any of the scopes, the locale is taken from the
named context configuration parameter.
@param pageContext the page in which to search for the named scoped
attribute or context configuration parameter
@param name the name of the scoped attribute or context configuration
parameter
@return the locale specified by the named scoped attribute or context
configuration parameter, or <tt>null</tt> if no scoped attribute or
configuration parameter with the given name exists | [
"static Locale getLocale(PageContext pageContext, String name) {\r\n\r\n Locale loc = null;\r\n\r\n Object obj = javax.servlet.jsp.jstl.core.Config.find(pageContext, name);\r\n if (obj != null) {\r\n if (obj instanceof Locale) {\r\n loc = (Locale)obj;\r\n } else {\r\n loc = SetLocaleSupport.parseLocale((String)obj);\r\n }\r\n }\r\n\r\n return loc;\r\n }"
] | [
"private org.apache.tools.ant.types.Path addSlaveClasspath() {\n org.apache.tools.ant.types.Path path = new org.apache.tools.ant.types.Path(getProject());\n\n String [] REQUIRED_SLAVE_CLASSES = {\n SlaveMain.class.getName(),\n Strings.class.getName(),\n MethodGlobFilter.class.getName(),\n TeeOutputStream.class.getName()\n };\n\n for (String clazz : Arrays.asList(REQUIRED_SLAVE_CLASSES)) {\n String resource = clazz.replace(\".\", \"/\") + \".class\";\n File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource);\n if (f != null) {\n path.createPath().setLocation(f);\n } else {\n throw new BuildException(\"Could not locate classpath for resource: \" + resource);\n }\n }\n return path;\n }",
"public static List<CompiledAutomaton> createAutomata(String prefix,\n String regexp, Map<String, Automaton> automatonMap) throws IOException {\n List<CompiledAutomaton> list = new ArrayList<>();\n Automaton automatonRegexp = null;\n if (regexp != null) {\n RegExp re = new RegExp(prefix + MtasToken.DELIMITER + regexp + \"\\u0000*\");\n automatonRegexp = re.toAutomaton();\n }\n int step = 500;\n List<String> keyList = new ArrayList<>(automatonMap.keySet());\n for (int i = 0; i < keyList.size(); i += step) {\n int localStep = step;\n boolean success = false;\n CompiledAutomaton compiledAutomaton = null;\n while (!success) {\n success = true;\n int next = Math.min(keyList.size(), i + localStep);\n List<Automaton> listAutomaton = new ArrayList<>();\n for (int j = i; j < next; j++) {\n listAutomaton.add(automatonMap.get(keyList.get(j)));\n }\n Automaton automatonList = Operations.union(listAutomaton);\n Automaton automaton;\n if (automatonRegexp != null) {\n automaton = Operations.intersection(automatonList, automatonRegexp);\n } else {\n automaton = automatonList;\n }\n try {\n compiledAutomaton = new CompiledAutomaton(automaton);\n } catch (TooComplexToDeterminizeException e) {\n log.debug(e);\n success = false;\n if (localStep > 1) {\n localStep /= 2;\n } else {\n throw new IOException(\"TooComplexToDeterminizeException\");\n }\n }\n }\n list.add(compiledAutomaton);\n }\n return list;\n }",
"public int execute(DatabaseConnection databaseConnection, T data, ID newId, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\ttry {\n\t\t\t// the arguments are the new-id and old-id\n\t\t\tObject[] args = new Object[] { convertIdToFieldObject(newId), extractIdToFieldObject(data) };\n\t\t\tint rowC = databaseConnection.update(statement, args, argFieldTypes);\n\t\t\tif (rowC > 0) {\n\t\t\t\tif (objectCache != null) {\n\t\t\t\t\tObject oldId = idField.extractJavaFieldValue(data);\n\t\t\t\t\tT obj = objectCache.updateId(clazz, oldId, newId);\n\t\t\t\t\tif (obj != null && obj != data) {\n\t\t\t\t\t\t// if our cached value is not the data that will be updated then we need to update it specially\n\t\t\t\t\t\tidField.assignField(connectionSource, obj, newId, false, objectCache);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// adjust the object to assign the new id\n\t\t\t\tidField.assignField(connectionSource, data, newId, false, objectCache);\n\t\t\t}\n\t\t\tlogger.debug(\"updating-id with statement '{}' and {} args, changed {} rows\", statement, args.length, rowC);\n\t\t\tif (args.length > 0) {\n\t\t\t\t// need to do the cast otherwise we only print the first object in args\n\t\t\t\tlogger.trace(\"updating-id arguments: {}\", (Object) args);\n\t\t\t}\n\t\t\treturn rowC;\n\t\t} catch (SQLException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Unable to run update-id stmt on object \" + data + \": \" + statement, e);\n\t\t}\n\t}",
"private RekordboxAnlz.BeatGridTag findTag(RekordboxAnlz anlzFile) {\n for (RekordboxAnlz.TaggedSection section : anlzFile.sections()) {\n if (section.body() instanceof RekordboxAnlz.BeatGridTag) {\n return (RekordboxAnlz.BeatGridTag) section.body();\n }\n }\n throw new IllegalArgumentException(\"No beat grid found inside analysis file \" + anlzFile);\n }",
"public static responderparam get(nitro_service service) throws Exception{\n\t\tresponderparam obj = new responderparam();\n\t\tresponderparam[] response = (responderparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public Set<String> getConfiguredWorkplaceBundles() {\n\n CmsADEConfigData configData = internalLookupConfiguration(null, null);\n return configData.getConfiguredWorkplaceBundles();\n }",
"@Override\n\tpublic void set(String headerName, String headerValue) {\n\t\tList<String> headerValues = new LinkedList<String>();\n\t\theaderValues.add(headerValue);\n\t\theaders.put(headerName, headerValues);\n\t}",
"private void sendCloseMessage() {\n\n this.lock(() -> {\n\n TcpChannelHub.this.writeMetaDataForKnownTID(0, outWire, null, 0);\n\n TcpChannelHub.this.outWire.writeDocument(false, w ->\n w.writeEventName(EventId.onClientClosing).text(\"\"));\n\n }, TryLock.LOCK);\n\n // wait up to 1 seconds to receive an close request acknowledgment from the server\n try {\n final boolean await = receivedClosedAcknowledgement.await(1, TimeUnit.SECONDS);\n if (!await)\n if (Jvm.isDebugEnabled(getClass()))\n Jvm.debug().on(getClass(), \"SERVER IGNORED CLOSE REQUEST: shutting down the client anyway as the \" +\n \"server did not respond to the close() request.\");\n } catch (InterruptedException ignore) {\n Thread.currentThread().interrupt();\n }\n }",
"protected void beforeLoading()\r\n {\r\n if (_listeners != null)\r\n {\r\n CollectionProxyListener listener;\r\n\r\n if (_perThreadDescriptorsEnabled) {\r\n loadProfileIfNeeded();\r\n }\r\n for (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n {\r\n listener = (CollectionProxyListener)_listeners.get(idx);\r\n listener.beforeLoading(this);\r\n }\r\n }\r\n }"
] |
Creates a scatter query from the given user query
@param query the user's query.
@param numSplits the number of splits to create. | [
"private Query.Builder createScatterQuery(Query query, int numSplits) {\n // TODO(pcostello): We can potentially support better splits with equality filters in our query\n // if there exists a composite index on property, __scatter__, __key__. Until an API for\n // metadata exists, this isn't possible. Note that ancestor and inequality queries fall into\n // the same category.\n Query.Builder scatterPointQuery = Query.newBuilder();\n scatterPointQuery.addAllKind(query.getKindList());\n scatterPointQuery.addOrder(DatastoreHelper.makeOrder(\n DatastoreHelper.SCATTER_PROPERTY_NAME, Direction.ASCENDING));\n // There is a split containing entities before and after each scatter entity:\n // ||---*------*------*------*------*------*------*---|| = scatter entity\n // If we represent each split as a region before a scatter entity, there is an extra region\n // following the last scatter point. Thus, we do not need the scatter entities for the last\n // region.\n scatterPointQuery.getLimitBuilder().setValue((numSplits - 1) * KEYS_PER_SPLIT);\n scatterPointQuery.addProjection(Projection.newBuilder().setProperty(\n PropertyReference.newBuilder().setName(\"__key__\")));\n return scatterPointQuery;\n }"
] | [
"public AT_Row setPaddingTop(int paddingTop) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private void setTableAliasForClassDescriptor(ClassDescriptor aCld, TableAlias anAlias)\r\n {\r\n if (m_cldToAlias.get(aCld) == null)\r\n {\r\n m_cldToAlias.put(aCld, anAlias);\r\n } \r\n }",
"public static SimpleDeploymentDescription of(final String name, @SuppressWarnings(\"TypeMayBeWeakened\") final Set<String> serverGroups) {\n final SimpleDeploymentDescription result = of(name);\n if (serverGroups != null) {\n result.addServerGroups(serverGroups);\n }\n return result;\n }",
"private static BoxRetentionPolicyAssignment.Info createAssignment(BoxAPIConnection api, String policyID,\r\n JsonObject assignTo, JsonArray filter) {\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL());\r\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\r\n\r\n JsonObject requestJSON = new JsonObject()\r\n .add(\"policy_id\", policyID)\r\n .add(\"assign_to\", assignTo);\r\n\r\n if (filter != null) {\r\n requestJSON.add(\"filter_fields\", filter);\r\n }\r\n\r\n request.setBody(requestJSON.toString());\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n BoxRetentionPolicyAssignment createdAssignment\r\n = new BoxRetentionPolicyAssignment(api, responseJSON.get(\"id\").asString());\r\n return createdAssignment.new Info(responseJSON);\r\n }",
"public static boolean isBadXmlCharacter(char c) {\n boolean cDataCharacter = c < '\\u0020' && c != '\\t' && c != '\\r' && c != '\\n';\n cDataCharacter |= (c >= '\\uD800' && c < '\\uE000');\n cDataCharacter |= (c == '\\uFFFE' || c == '\\uFFFF');\n return cDataCharacter;\n }",
"public List<WbSearchEntitiesResult> wbSearchEntities(String search, String language,\n Boolean strictLanguage, String type, Long limit, Long offset)\n throws MediaWikiApiErrorException {\n\n Map<String, String> parameters = new HashMap<String, String>();\n parameters.put(ApiConnection.PARAM_ACTION, \"wbsearchentities\");\n\n if (search != null) {\n parameters.put(\"search\", search);\n } else {\n throw new IllegalArgumentException(\n \"Search parameter must be specified for this action.\");\n }\n\n if (language != null) {\n parameters.put(\"language\", language);\n } else {\n throw new IllegalArgumentException(\n \"Language parameter must be specified for this action.\");\n }\n if (strictLanguage != null) {\n parameters.put(\"strictlanguage\", Boolean.toString(strictLanguage));\n }\n\n if (type != null) {\n parameters.put(\"type\", type);\n }\n\n if (limit != null) {\n parameters.put(\"limit\", Long.toString(limit));\n }\n\n if (offset != null) {\n parameters.put(\"continue\", Long.toString(offset));\n }\n\n List<WbSearchEntitiesResult> results = new ArrayList<>();\n\n try {\n JsonNode root = this.connection.sendJsonRequest(\"POST\", parameters);\n JsonNode entities = root.path(\"search\");\n for (JsonNode entityNode : entities) {\n try {\n JacksonWbSearchEntitiesResult ed = mapper.treeToValue(entityNode,\n JacksonWbSearchEntitiesResult.class);\n results.add(ed);\n } catch (JsonProcessingException e) {\n LOGGER.error(\"Error when reading JSON for entity \"\n + entityNode.path(\"id\").asText(\"UNKNOWN\") + \": \"\n + e.toString());\n }\n }\n } catch (IOException e) {\n LOGGER.error(\"Could not retrive data: \" + e.toString());\n }\n\n return results;\n }",
"public MaterializeBuilder withContainer(ViewGroup container, ViewGroup.LayoutParams layoutParams) {\n this.mContainer = container;\n this.mContainerLayoutParams = layoutParams;\n return this;\n }",
"public void setAngularLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setAngularLowerLimits(getNative(), limitX, limitY, limitZ);\n }",
"public ThumborUrlBuilder crop(int top, int left, int bottom, int right) {\n if (top < 0) {\n throw new IllegalArgumentException(\"Top must be greater or equal to zero.\");\n }\n if (left < 0) {\n throw new IllegalArgumentException(\"Left must be greater or equal to zero.\");\n }\n if (bottom < 1 || bottom <= top) {\n throw new IllegalArgumentException(\"Bottom must be greater than zero and top.\");\n }\n if (right < 1 || right <= left) {\n throw new IllegalArgumentException(\"Right must be greater than zero and left.\");\n }\n hasCrop = true;\n cropTop = top;\n cropLeft = left;\n cropBottom = bottom;\n cropRight = right;\n return this;\n }"
] |
to do with XmlId value being strictly of type 'String' | [
"@SuppressWarnings(\"unused\")\n\t@XmlID\n @XmlAttribute(name = \"id\")\n private String getXmlID(){\n return String.format(\"%s-%s\", this.getClass().getSimpleName(), Long.valueOf(id));\n }"
] | [
"private String hibcProcess(String source) {\n\n // HIBC 2.6 allows up to 110 characters, not including the \"+\" prefix or the check digit\n if (source.length() > 110) {\n throw new OkapiException(\"Data too long for HIBC LIC\");\n }\n\n source = source.toUpperCase();\n if (!source.matches(\"[A-Z0-9-\\\\. \\\\$/+\\\\%]+?\")) {\n throw new OkapiException(\"Invalid characters in input\");\n }\n\n int counter = 41;\n for (int i = 0; i < source.length(); i++) {\n counter += positionOf(source.charAt(i), HIBC_CHAR_TABLE);\n }\n counter = counter % 43;\n\n char checkDigit = HIBC_CHAR_TABLE[counter];\n\n encodeInfo += \"HIBC Check Digit Counter: \" + counter + \"\\n\";\n encodeInfo += \"HIBC Check Digit: \" + checkDigit + \"\\n\";\n\n return \"+\" + source + checkDigit;\n }",
"public void set( int index , double value ) {\n if( mat.getType() == MatrixType.DDRM ) {\n ((DMatrixRMaj) mat).set(index, value);\n } else if( mat.getType() == MatrixType.FDRM ) {\n ((FMatrixRMaj) mat).set(index, (float)value);\n } else {\n throw new RuntimeException(\"Not supported yet for this matrix type\");\n }\n }",
"public double response( double[] sample ) {\n if( sample.length != A.numCols )\n throw new IllegalArgumentException(\"Expected input vector to be in sample space\");\n\n DMatrixRMaj dots = new DMatrixRMaj(numComponents,1);\n DMatrixRMaj s = DMatrixRMaj.wrap(A.numCols,1,sample);\n\n CommonOps_DDRM.mult(V_t,s,dots);\n\n return NormOps_DDRM.normF(dots);\n }",
"protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }",
"public final void printClientConfig(final JSONWriter json) throws JSONException {\n json.key(\"attributes\");\n json.array();\n for (Map.Entry<String, Attribute> entry: this.attributes.entrySet()) {\n Attribute attribute = entry.getValue();\n if (attribute.getClass().getAnnotation(InternalAttribute.class) == null) {\n json.object();\n attribute.printClientConfig(json, this);\n json.endObject();\n }\n }\n json.endArray();\n }",
"private void readCalendars()\n {\n //\n // Create the calendars\n //\n for (MapRow row : getTable(\"NCALTAB\"))\n {\n ProjectCalendar calendar = m_projectFile.addCalendar();\n calendar.setUniqueID(row.getInteger(\"UNIQUE_ID\"));\n calendar.setName(row.getString(\"NAME\"));\n calendar.setWorkingDay(Day.SUNDAY, row.getBoolean(\"SUNDAY\"));\n calendar.setWorkingDay(Day.MONDAY, row.getBoolean(\"MONDAY\"));\n calendar.setWorkingDay(Day.TUESDAY, row.getBoolean(\"TUESDAY\"));\n calendar.setWorkingDay(Day.WEDNESDAY, row.getBoolean(\"WEDNESDAY\"));\n calendar.setWorkingDay(Day.THURSDAY, row.getBoolean(\"THURSDAY\"));\n calendar.setWorkingDay(Day.FRIDAY, row.getBoolean(\"FRIDAY\"));\n calendar.setWorkingDay(Day.SATURDAY, row.getBoolean(\"SATURDAY\"));\n\n for (Day day : Day.values())\n {\n if (calendar.isWorkingDay(day))\n {\n // TODO: this is an approximation\n calendar.addDefaultCalendarHours(day);\n }\n }\n }\n\n //\n // Set up the hierarchy and add exceptions\n //\n Table exceptionsTable = getTable(\"CALXTAB\");\n for (MapRow row : getTable(\"NCALTAB\"))\n {\n ProjectCalendar child = m_projectFile.getCalendarByUniqueID(row.getInteger(\"UNIQUE_ID\"));\n ProjectCalendar parent = m_projectFile.getCalendarByUniqueID(row.getInteger(\"BASE_CALENDAR_ID\"));\n if (child != null && parent != null)\n {\n child.setParent(parent);\n }\n\n addCalendarExceptions(exceptionsTable, child, row.getInteger(\"FIRST_CALENDAR_EXCEPTION_ID\"));\n\n m_eventManager.fireCalendarReadEvent(child);\n }\n }",
"protected List<I_CmsSearchConfigurationSortOption> getSortOptions() {\n\n List<I_CmsSearchConfigurationSortOption> options = new LinkedList<I_CmsSearchConfigurationSortOption>();\n try {\n JSONArray sortOptions = m_configObject.getJSONArray(JSON_KEY_SORTOPTIONS);\n for (int i = 0; i < sortOptions.length(); i++) {\n I_CmsSearchConfigurationSortOption option = parseSortOption(sortOptions.getJSONObject(i));\n if (option != null) {\n options.add(option);\n }\n }\n } catch (JSONException e) {\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_SORT_CONFIG_0), e);\n }\n } else {\n options = m_baseConfig.getSortConfig().getSortOptions();\n }\n }\n return options;\n }",
"@Override\n public final Double optDouble(final String key, final Double defaultValue) {\n Double result = optDouble(key);\n return result == null ? defaultValue : result;\n }",
"public void performImplicitDoubleStep(int x1, int x2 , double real , double img ) {\n double a11 = A.get(x1,x1);\n double a21 = A.get(x1+1,x1);\n double a12 = A.get(x1,x1+1);\n double a22 = A.get(x1+1,x1+1);\n double a32 = A.get(x1+2,x1+1);\n\n double p_plus_t = 2.0*real;\n double p_times_t = real*real + img*img;\n\n double b11,b21,b31;\n if( useStandardEq ) {\n b11 = (a11*a11 - p_plus_t*a11+p_times_t)/a21 + a12;\n b21 = a11+a22-p_plus_t;\n b31 = a32;\n } else {\n // this is different from the version in the book and seems in my testing to be more resilient to\n // over flow issues\n b11 = (a11*a11 - p_plus_t*a11+p_times_t) + a12*a21;\n b21 = (a11+a22-p_plus_t)*a21;\n b31 = a32*a21;\n }\n\n performImplicitDoubleStep(x1, x2, b11, b21, b31);\n }"
] |
Notification that the process has become unstable.
@return {@code true} if this is a change in status | [
"boolean processUnstable() {\n boolean change = !unstable;\n if (change) { // Only once until the process is removed. A process is unstable until removed.\n unstable = true;\n HostControllerLogger.ROOT_LOGGER.managedServerUnstable(serverName);\n }\n return change;\n }"
] | [
"public Bundler put(String key, Parcelable value) {\n delegate.putParcelable(key, value);\n return this;\n }",
"public Date getNextWorkStart(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToNextWorkStart(cal);\n return cal.getTime();\n }",
"public static appfwpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_binding obj = new appfwpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_binding response = (appfwpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public Build getBuildInfo(String appName, String buildId) {\n return connection.execute(new BuildInfo(appName, buildId), apiKey);\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 }",
"private FieldConversion[] getPkFieldConversion(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pks = cld.getPkFields();\r\n FieldConversion[] fc = new FieldConversion[pks.length]; \r\n \r\n for (int i= 0; i < pks.length; i++)\r\n {\r\n fc[i] = pks[i].getFieldConversion();\r\n }\r\n \r\n return fc;\r\n }",
"public static responderpolicy get(nitro_service service, String name) throws Exception{\n\t\tresponderpolicy obj = new responderpolicy();\n\t\tobj.set_name(name);\n\t\tresponderpolicy response = (responderpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public Method getGetMethod(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\tMethod method = getCache.get(object.getClass().getName(), fieldName);\n\t\tif( method == null ) {\n\t\t\tmethod = ReflectionUtils.findGetter(object, fieldName);\n\t\t\tgetCache.set(object.getClass().getName(), fieldName, method);\n\t\t}\n\t\treturn method;\n\t}",
"protected LayoutManager getLayOutManagerObj(ActionInvocation _invocation) {\n\t\tif (layoutManager == null || \"\".equals(layoutManager)){\n\t\t\tLOG.warn(\"No valid LayoutManager, using ClassicLayoutManager\");\n\t\t\treturn new ClassicLayoutManager();\n\t\t}\n\n\t\tObject los = conditionalParse(layoutManager, _invocation);\n\n\t\tif (los instanceof LayoutManager){\n\t\t\treturn (LayoutManager) los;\n\t\t}\n\n\t\tLayoutManager lo = null;\n\t\tif (los instanceof String){\n\t\t\tif (LAYOUT_CLASSIC.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ClassicLayoutManager();\n\t\t\telse if (LAYOUT_LIST.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ListLayoutManager();\n\t\t\telse {\n\t\t\t\ttry {\n\t\t\t\t\tlo = (LayoutManager) Class.forName((String) los).newInstance();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.warn(\"No valid LayoutManager: \" + e.getMessage(),e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lo;\n\t}"
] |
Sets allowed values for attribute
@param allowedValues values that are legal as part in this attribute
@return a builder that can be used to continue building the attribute definition | [
"@SuppressWarnings(\"deprecation\")\n public BUILDER setAllowedValues(String ... allowedValues) {\n assert allowedValues!= null;\n this.allowedValues = new ModelNode[allowedValues.length];\n for (int i = 0; i < allowedValues.length; i++) {\n this.allowedValues[i] = new ModelNode(allowedValues[i]);\n }\n return (BUILDER) this;\n }"
] | [
"public static void setQuota(final GreenMailUser user, final Quota quota) {\r\n Session session = GreenMailUtil.getSession(ServerSetupTest.IMAP);\r\n try {\r\n Store store = session.getStore(\"imap\");\r\n store.connect(user.getEmail(), user.getPassword());\r\n try {\r\n ((QuotaAwareStore) store).setQuota(quota);\r\n } finally {\r\n store.close();\r\n }\r\n } catch (Exception ex) {\r\n throw new IllegalStateException(\"Can not set quota \" + quota\r\n + \" for user \" + user, ex);\r\n }\r\n }",
"public static String frame(String imageUrl) {\n if (imageUrl == null || imageUrl.length() == 0) {\n throw new IllegalArgumentException(\"Image URL must not be blank.\");\n }\n return FILTER_FRAME + \"(\" + imageUrl + \")\";\n }",
"protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }",
"protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n \r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n \r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading schemas for catalog \" \r\n + this.getAttribute(ATT_CATALOG_NAME));\r\n rs = getDbMeta().getSchemas();\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n int count = 0;\r\n while (rs.next())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Creating schema \" + getCatalogName() + \".\" + rs.getString(\"TABLE_SCHEM\"));\r\n alNew.add(new DBMetaSchemaNode(getDbMeta(),\r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, \r\n rs.getString(\"TABLE_SCHEM\")));\r\n count++;\r\n }\r\n if (count == 0) \r\n alNew.add(new DBMetaSchemaNode(getDbMeta(), \r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, null));\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaCatalogNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx2);\r\n } \r\n return false;\r\n }\r\n return true;\r\n }",
"public static TextEncryptor queryableText(CharSequence password, CharSequence salt) {\n\t\treturn new HexEncodingTextEncryptor(new AndroidAesBytesEncryptor(password.toString(), salt, AndroidKeyGenerators.shared(16)));\n\t}",
"public static void unregisterMbean(ObjectName name) {\n try {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\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}",
"public List<ResourceRequestType.ResourceRequestCriterion> getResourceRequestCriterion()\n {\n if (resourceRequestCriterion == null)\n {\n resourceRequestCriterion = new ArrayList<ResourceRequestType.ResourceRequestCriterion>();\n }\n return this.resourceRequestCriterion;\n }",
"static void apply(final String patchId, final Collection<ContentModification> modifications, final PatchEntry patchEntry, final ContentItemFilter filter) {\n for (final ContentModification modification : modifications) {\n\n final ContentItem item = modification.getItem();\n // Check if we accept the item\n if (!filter.accepts(item)) {\n continue;\n }\n\n final Location location = new Location(item);\n final ContentEntry contentEntry = new ContentEntry(patchId, modification);\n ContentTaskDefinition definition = patchEntry.get(location);\n if (definition == null) {\n definition = new ContentTaskDefinition(location, contentEntry, false);\n patchEntry.put(location, definition);\n } else {\n definition.setTarget(contentEntry);\n }\n }\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.