query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
returns a sorted array of fields
[ "public GroovyFieldDoc[] fields() {\n Collections.sort(fields);\n return fields.toArray(new GroovyFieldDoc[fields.size()]);\n }" ]
[ "public static base_response delete(nitro_service client, route6 resource) throws Exception {\n\t\troute6 deleteresource = new route6();\n\t\tdeleteresource.network = resource.network;\n\t\tdeleteresource.gateway = resource.gateway;\n\t\tdeleteresource.vlan = resource.vlan;\n\t\tdeleteresource.td = resource.td;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public final void notifyFooterItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= footerItemCount || toPosition >= footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition\n + \" or toPosition \" + toPosition + \" is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition + headerItemCount + contentItemCount, toPosition + headerItemCount + contentItemCount);\n }", "public void propagateAsErrorIfCancelException(final Throwable t) {\n if ((t instanceof OperationCanceledError)) {\n throw ((OperationCanceledError)t);\n }\n final RuntimeException opCanceledException = this.getPlatformOperationCanceledException(t);\n if ((opCanceledException != null)) {\n throw new OperationCanceledError(opCanceledException);\n }\n }", "public void setPrefix(String prefix) {\n if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_PREFIX()))) {\n log(\"Ignoring prefix attribute because it is overridden by user properties.\", Project.MSG_WARN);\n } else {\n SysGlobals.initializeWith(prefix);\n }\n }", "protected void splitCriteria()\r\n {\r\n Criteria whereCrit = getQuery().getCriteria();\r\n Criteria havingCrit = getQuery().getHavingCriteria();\r\n\r\n if (whereCrit == null || whereCrit.isEmpty())\r\n {\r\n getJoinTreeToCriteria().put(getRoot(), null);\r\n }\r\n else\r\n {\r\n // TODO: parameters list shold be modified when the form is reduced to DNF.\r\n getJoinTreeToCriteria().put(getRoot(), whereCrit);\r\n buildJoinTree(whereCrit);\r\n }\r\n\r\n if (havingCrit != null && !havingCrit.isEmpty())\r\n {\r\n buildJoinTree(havingCrit);\r\n }\r\n\r\n }", "public static base_responses add(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction addresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].profilename = resources[i].profilename;\n\t\t\t\taddresources[i].parameters = resources[i].parameters;\n\t\t\t\taddresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\taddresources[i].quiettime = resources[i].quiettime;\n\t\t\t\taddresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "protected List<Integer> getPageSizes() {\n\n try {\n return Collections.singletonList(Integer.valueOf(m_configObject.getInt(JSON_KEY_PAGESIZE)));\n } catch (JSONException e) {\n List<Integer> result = null;\n String pageSizesString = null;\n try {\n pageSizesString = m_configObject.getString(JSON_KEY_PAGESIZE);\n String[] pageSizesArray = pageSizesString.split(\"-\");\n if (pageSizesArray.length > 0) {\n result = new ArrayList<>(pageSizesArray.length);\n for (int i = 0; i < pageSizesArray.length; i++) {\n result.add(Integer.valueOf(pageSizesArray[i]));\n }\n }\n return result;\n } catch (NumberFormatException | JSONException e1) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_PARSING_PAGE_SIZES_FAILED_1, pageSizesString), e);\n }\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_PAGESIZE_SPECIFIED_0), e);\n }\n return null;\n } else {\n return m_baseConfig.getPaginationConfig().getPageSizes();\n }\n }\n }", "private void addAllWithFilter(Map<String, String> toMap, Map<String, String> fromMap, IncludeExcludePatterns pattern) {\n for (Object o : fromMap.entrySet()) {\n Map.Entry entry = (Map.Entry) o;\n String key = (String) entry.getKey();\n if (PatternMatcher.pathConflicts(key, pattern)) {\n continue;\n }\n toMap.put(key, (String) entry.getValue());\n }\n }", "public static String plus(Number value, String right) {\n return DefaultGroovyMethods.toString(value) + right;\n }" ]
Layout which gets displayed if table is empty. @see org.opencms.ui.apps.user.I_CmsFilterableTable#getEmptyLayout()
[ "public VerticalLayout getEmptyLayout() {\n\n m_emptyLayout = CmsVaadinUtils.getInfoLayout(CmsOuTreeType.USER.getEmptyMessageKey());\n setVisible(size() > 0);\n m_emptyLayout.setVisible(size() == 0);\n return m_emptyLayout;\n }" ]
[ "private Map<Integer, List<Row>> createExceptionAssignmentMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"ID\");\n String exceptions = row.getString(\"EXCEPTIONS\");\n map.put(calendarID, createExceptionAssignmentRowList(exceptions));\n }\n return map;\n }", "public static Drawable decideIcon(ImageHolder imageHolder, Context ctx, int iconColor, boolean tint) {\n if (imageHolder == null) {\n return null;\n } else {\n return imageHolder.decideIcon(ctx, iconColor, tint);\n }\n }", "public static int getScreenWidth(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.widthPixels;\n }", "public static void mainInternal(String[] args) throws Exception {\n\n Options options = new Options();\n CmdLineParser parser = new CmdLineParser(options);\n try {\n parser.parseArgument(args);\n } catch (CmdLineException e) {\n helpScreen(parser);\n return;\n }\n\n try {\n List<String> configs = new ArrayList<>();\n if (options.configs != null) {\n configs.addAll(Arrays.asList(options.configs.split(\",\")));\n }\n ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);\n } catch (ConfigException ex) {\n ConfigLogger.error(ex);\n throw ex;\n } catch (Throwable th) {\n ConfigLogger.error(th);\n throw th;\n }\n }", "public void retrieveCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, false);\r\n }", "public static String getPrefix(String column) {\n\t\treturn column.contains( \".\" ) ? DOT_SEPARATOR_PATTERN.split( column )[0] : null;\n\t}", "String getQueryString(Map<String, String> params) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\ttry {\n\t\t\tboolean first = true;\n\t\t\tfor (Map.Entry<String,String> entry : params.entrySet()) {\n\t\t\t\tif (first) {\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tbuilder.append(\"&\");\n\t\t\t\t}\n\t\t\t\tbuilder.append(URLEncoder.encode(entry.getKey(), \"UTF-8\"));\n\t\t\t\tbuilder.append(\"=\");\n\t\t\t\tbuilder.append(URLEncoder.encode(entry.getValue(), \"UTF-8\"));\n\t\t\t}\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\"Your Java version does not support UTF-8 encoding.\");\n\t\t}\n\n\t\treturn builder.toString();\n\t}", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static double checkDouble(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInDoubleRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), DOUBLE_MIN, DOUBLE_MAX);\n\t\t}\n\n\t\treturn number.doubleValue();\n\t}", "public void setGroupsForPath(Integer[] groups, int pathId) {\n String newGroups = Arrays.toString(groups);\n newGroups = newGroups.substring(1, newGroups.length() - 1).replaceAll(\"\\\\s\", \"\");\n\n logger.info(\"adding groups={}, to pathId={}\", newGroups, pathId);\n EditService.updatePathTable(Constants.PATH_PROFILE_GROUP_IDS, newGroups, pathId);\n }" ]
We have an OLE compound document... but is it an MPP file? @param stream file input stream @return ProjectFile instance
[ "private ProjectFile handleOleCompoundDocument(InputStream stream) throws Exception\n {\n POIFSFileSystem fs = new POIFSFileSystem(POIFSFileSystem.createNonClosingInputStream(stream));\n String fileFormat = MPPReader.getFileFormat(fs);\n if (fileFormat != null && fileFormat.startsWith(\"MSProject\"))\n {\n MPPReader reader = new MPPReader();\n addListeners(reader);\n return reader.read(fs);\n }\n return null;\n }" ]
[ "public void warn(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.WARNING, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "private void deleteDir(File dir)\r\n {\r\n if (dir.exists() && dir.isDirectory())\r\n {\r\n File[] files = dir.listFiles();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (!files[idx].exists())\r\n {\r\n continue;\r\n }\r\n if (files[idx].isDirectory())\r\n {\r\n deleteDir(files[idx]);\r\n }\r\n else\r\n {\r\n files[idx].delete();\r\n }\r\n }\r\n dir.delete();\r\n }\r\n }", "public void stopListenting() {\n if (channel != null) {\n log.info(\"closing server channel\");\n channel.close().syncUninterruptibly();\n channel = null;\n }\n }", "void lockSharedInterruptibly(final Integer permit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n sync.acquireSharedInterruptibly(permit);\n }", "private static String makeAsciiTableCell(Object obj, int padLeft, int padRight, boolean tsv) {\r\n String result = obj.toString();\r\n if (padLeft > 0) {\r\n result = padLeft(result, padLeft);\r\n }\r\n if (padRight > 0) {\r\n result = pad(result, padRight);\r\n }\r\n if (tsv) {\r\n result = result + '\\t';\r\n }\r\n return result;\r\n }", "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 ItemRequest<Story> update(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"PUT\");\n }", "public static long addressToLong(InetAddress address) {\n long result = 0;\n for (byte element : address.getAddress()) {\n result = (result << 8) + unsign(element);\n }\n return result;\n }", "public void writeNameValuePair(String name, long value) throws IOException\n {\n internalWriteNameValuePair(name, Long.toString(value));\n }" ]
Parses server section of Zookeeper connection string
[ "public static String parseServers(String zookeepers) {\n int slashIndex = zookeepers.indexOf(\"/\");\n if (slashIndex != -1) {\n return zookeepers.substring(0, slashIndex);\n }\n return zookeepers;\n }" ]
[ "public Iterable<BoxItem.Info> getChildren(String sort, SortDirection direction, final String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"sort\", sort)\n .appendParam(\"direction\", direction.toString());\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n final String query = builder.toString();\n return new Iterable<BoxItem.Info>() {\n @Override\n public Iterator<BoxItem.Info> iterator() {\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), query, getID());\n return new BoxItemIterator(getAPI(), url);\n }\n };\n }", "List<CmsFavoriteEntry> getEntries() {\n\n List<CmsFavoriteEntry> result = new ArrayList<>();\n for (I_CmsEditableGroupRow row : m_group.getRows()) {\n CmsFavoriteEntry entry = ((CmsFavInfo)row).getEntry();\n result.add(entry);\n }\n return result;\n }", "public String getBaselineDurationText()\n {\n Object result = getCachedValue(TaskField.BASELINE_DURATION);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION);\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }", "public static FormValidation validateEmails(String emails) {\n if (!Strings.isNullOrEmpty(emails)) {\n String[] recipients = StringUtils.split(emails, \" \");\n for (String email : recipients) {\n FormValidation validation = validateInternetAddress(email);\n if (validation != FormValidation.ok()) {\n return validation;\n }\n }\n }\n return FormValidation.ok();\n }", "public static String fancyStringF(double value, DecimalFormat format, int length, int significant) {\n\n String formatted = fancyString(value, format, length, significant);\n\n int n = length-formatted.length();\n if( n > 0 ) {\n StringBuilder builder = new StringBuilder(n);\n for (int i = 0; i < n; i++) {\n builder.append(' ');\n }\n return formatted + builder.toString();\n } else {\n return formatted;\n }\n }", "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 void setIdleMaxAge(long idleMaxAge, TimeUnit timeUnit) {\n\t\tthis.idleMaxAgeInSeconds = TimeUnit.SECONDS.convert(idleMaxAge, checkNotNull(timeUnit)); \n\t}", "@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }", "protected synchronized void stealExistingAllocations(){\r\n\t\t\r\n\t\tfor (ConnectionHandle handle: this.threadFinalizableRefs.keySet()){\r\n\t\t\t// if they're not in use, pretend they are in use now and close them off.\r\n\t\t\t// this method assumes that the strategy has been flipped back to non-caching mode\r\n\t\t\t// prior to this method invocation.\r\n\t\t\tif (handle.logicallyClosed.compareAndSet(true, false)){ \r\n\t\t\t\ttry {\r\n\t\t\t\t\tthis.pool.releaseConnection(handle);\r\n\t\t\t\t} catch (SQLException e) {\r\n\t\t\t\t\tlogger.error(\"Error releasing connection\", e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (this.warnApp.compareAndSet(false, true)){ // only issue warning once.\r\n\t\t\tlogger.warn(\"Cached strategy chosen, but more threads are requesting a connection than are configured. Switching permanently to default strategy.\");\r\n\t\t}\r\n\t\tthis.threadFinalizableRefs.clear();\r\n\t\t\r\n\t}" ]
commit all envelopes against the current broker
[ "private void writeAllEnvelopes(boolean reuse)\r\n {\r\n // perform remove of m:n indirection table entries first\r\n performM2NUnlinkEntries();\r\n\r\n Iterator iter;\r\n // using clone to avoid ConcurentModificationException\r\n iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n boolean insert = false;\r\n if(needsCommit)\r\n {\r\n insert = mod.needsInsert();\r\n mod.getModificationState().commit(mod);\r\n if(reuse && insert)\r\n {\r\n getTransaction().doSingleLock(mod.getClassDescriptor(), mod.getObject(), mod.getIdentity(), Transaction.WRITE);\r\n }\r\n }\r\n /*\r\n arminw: important to call this cleanup method for each registered\r\n ObjectEnvelope, because this method will e.g. remove proxy listener\r\n objects for registered objects.\r\n */\r\n mod.cleanup(reuse, insert);\r\n }\r\n // add m:n indirection table entries\r\n performM2NLinkEntries();\r\n }" ]
[ "int read(InputStream is, int contentLength) {\n if (is != null) {\n try {\n int capacity = (contentLength > 0) ? (contentLength + 4096) : 16384;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream(capacity);\n int nRead;\n byte[] data = new byte[16384];\n while ((nRead = is.read(data, 0, data.length)) != -1) {\n buffer.write(data, 0, nRead);\n }\n buffer.flush();\n\n read(buffer.toByteArray());\n } catch (IOException e) {\n Logger.d(TAG, \"Error reading data from stream\", e);\n }\n } else {\n status = STATUS_OPEN_ERROR;\n }\n\n try {\n if (is != null) {\n is.close();\n }\n } catch (IOException e) {\n Logger.d(TAG, \"Error closing stream\", e);\n }\n\n return status;\n }", "public static clusterinstance get(nitro_service service, Long clid) throws Exception{\n\t\tclusterinstance obj = new clusterinstance();\n\t\tobj.set_clid(clid);\n\t\tclusterinstance response = (clusterinstance) obj.get_resource(service);\n\t\treturn response;\n\t}", "public CollectionDescriptor getCollectionDescriptorByName(String name)\r\n {\r\n if (name == null)\r\n {\r\n return null;\r\n }\r\n\r\n CollectionDescriptor cod = (CollectionDescriptor) getCollectionDescriptorNameMap().get(name);\r\n\r\n //\r\n // BRJ: if the CollectionDescriptor is not found\r\n // look in the ClassDescriptor referenced by 'super' for it\r\n //\r\n if (cod == null)\r\n {\r\n ClassDescriptor superCld = getSuperClassDescriptor();\r\n if (superCld != null)\r\n {\r\n cod = superCld.getCollectionDescriptorByName(name);\r\n }\r\n }\r\n\r\n return cod;\r\n }", "private 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 int getInt(Integer type)\n {\n int result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getInt(item, 0);\n }\n\n return (result);\n }", "private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) {\n if (args.length!=1) return;\n if (!receiver.isArray()) return;\n if (!isIntCategory(getUnwrapper(args[0]))) return;\n if (\"getAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n } else if (\"setAt\".equals(name)) {\n MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],\"arg\")}, null, null);\n node.setDeclaringClass(receiver.redirect());\n methods.add(node);\n }\n }", "private static void registerImage(String imageId, String imageTag, String targetRepo,\n ArrayListMultimap<String, String> artifactsProps, int buildInfoId) throws IOException {\n DockerImage image = new DockerImage(imageId, imageTag, targetRepo, buildInfoId, artifactsProps);\n images.add(image);\n }", "public static double TopsoeDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double den = p[i] + q[i];\n r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den);\n }\n }\n return r;\n }", "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 }" ]
Read the domain controller data from an S3 file. @param directoryName the name of the directory in the bucket that contains the S3 file @return the domain controller data
[ "private List<DomainControllerData> readFromFile(String directoryName) {\n List<DomainControllerData> data = new ArrayList<DomainControllerData>();\n if (directoryName == null) {\n return data;\n }\n\n if (conn == null) {\n init();\n }\n\n try {\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n directoryName = parsedPut.getPrefix();\n }\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n GetResponse val = conn.get(location, key, null);\n if (val.object != null) {\n byte[] buf = val.object.data;\n if (buf != null && buf.length > 0) {\n try {\n data = S3Util.domainControllerDataFromByteBuffer(buf);\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.failedMarshallingDomainControllerData();\n }\n }\n }\n return data;\n } catch (IOException e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3File(e.getLocalizedMessage());\n }\n }" ]
[ "public static double StdDev( int[] values, double mean ){\n double stddev = 0;\n double diff;\n int hits;\n int total = 0;\n\n // for all values\n for ( int i = 0, n = values.length; i < n; i++ )\n {\n hits = values[i];\n diff = (double) i - mean;\n // accumulate std.dev.\n stddev += diff * diff * hits;\n // accumalate total\n total += hits;\n }\n\n return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) );\n }", "public AddonChange addAddon(String appName, String addonName) {\n return connection.execute(new AddonInstall(appName, addonName), apiKey);\n }", "public int[] sampleBatchWithReplacement() {\n // Sample the indices with replacement.\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n batch[i] = Prng.nextInt(numExamples);\n }\n return batch;\n }", "private byte[] readStreamCompressed(InputStream stream) throws IOException\r\n {\r\n ByteArrayOutputStream bao = new ByteArrayOutputStream();\r\n GZIPOutputStream gos = new GZIPOutputStream(bao);\r\n OutputStreamWriter output = new OutputStreamWriter(gos);\r\n BufferedReader input = new BufferedReader(new InputStreamReader(stream));\r\n String line;\r\n\r\n while ((line = input.readLine()) != null)\r\n {\r\n output.write(line);\r\n output.write('\\n');\r\n }\r\n input.close();\r\n stream.close();\r\n output.close();\r\n gos.close();\r\n bao.close();\r\n return bao.toByteArray();\r\n }", "private ProjectCalendar getTaskCalendar(Project.Tasks.Task task)\n {\n ProjectCalendar calendar = null;\n\n BigInteger calendarID = task.getCalendarUID();\n if (calendarID != null)\n {\n calendar = m_projectFile.getCalendarByUniqueID(Integer.valueOf(calendarID.intValue()));\n }\n\n return (calendar);\n }", "public static String[] sortStringArray(String[] array) {\n if (isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }", "private void createPropertyVfsBundleFiles() throws CmsIllegalArgumentException, CmsLoaderException, CmsException {\n\n String bundleFileBasePath = m_sitepath + m_basename + \"_\";\n for (Locale l : m_localizations.keySet()) {\n CmsResource res = m_cms.createResource(\n bundleFileBasePath + l.toString(),\n OpenCms.getResourceManager().getResourceType(\n CmsMessageBundleEditorTypes.BundleType.PROPERTY.toString()));\n m_bundleFiles.put(l, res);\n LockedFile file = LockedFile.lockResource(m_cms, res);\n file.setCreated(true);\n m_lockedBundleFiles.put(l, file);\n m_changedTranslations.add(l);\n }\n\n }", "public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster,\n final int greedyAttempts,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<Integer> greedySwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(greedySwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(greedySwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n for(int i = 0; i < greedyAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster,\n nodeIds,\n greedySwapMaxPartitionsPerNode,\n greedySwapMaxPartitionsPerZone,\n storeDefs);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (swap attempt \" + i + \" in zone \"\n + zoneIds.get(zoneIdOffset) + \")\");\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n return returnCluster;\n }", "public ConnectionInfo getConnection(String name) {\n final URI uri = uriWithPath(\"./connections/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ConnectionInfo.class);\n }" ]
Use this API to fetch all the nsconfig resources that are configured on netscaler.
[ "public static nsconfig get(nitro_service service) throws Exception{\n\t\tnsconfig obj = new nsconfig();\n\t\tnsconfig[] response = (nsconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
[ "public FieldLocation getFieldLocation(FieldType type)\n {\n FieldLocation result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFieldLocation();\n }\n return result;\n }", "public static void setDefaultConfiguration(SimpleConfiguration config) {\n config.setProperty(CONNECTION_ZOOKEEPERS_PROP, CONNECTION_ZOOKEEPERS_DEFAULT);\n config.setProperty(CONNECTION_ZOOKEEPER_TIMEOUT_PROP, CONNECTION_ZOOKEEPER_TIMEOUT_DEFAULT);\n config.setProperty(DFS_ROOT_PROP, DFS_ROOT_DEFAULT);\n config.setProperty(ACCUMULO_ZOOKEEPERS_PROP, ACCUMULO_ZOOKEEPERS_DEFAULT);\n config.setProperty(WORKER_NUM_THREADS_PROP, WORKER_NUM_THREADS_DEFAULT);\n config.setProperty(TRANSACTION_ROLLBACK_TIME_PROP, TRANSACTION_ROLLBACK_TIME_DEFAULT);\n config.setProperty(LOADER_NUM_THREADS_PROP, LOADER_NUM_THREADS_DEFAULT);\n config.setProperty(LOADER_QUEUE_SIZE_PROP, LOADER_QUEUE_SIZE_DEFAULT);\n config.setProperty(MINI_START_ACCUMULO_PROP, MINI_START_ACCUMULO_DEFAULT);\n config.setProperty(MINI_DATA_DIR_PROP, MINI_DATA_DIR_DEFAULT);\n }", "public static String createOdataFilterForTags(String tagName, String tagValue) {\n if (tagName == null) {\n return null;\n } else if (tagValue == null) {\n return String.format(\"tagname eq '%s'\", tagName);\n } else {\n return String.format(\"tagname eq '%s' and tagvalue eq '%s'\", tagName, tagValue);\n }\n }", "public static PersistenceBroker createPersistenceBroker(String jcdAlias,\r\n String user,\r\n String password) throws PBFactoryException\r\n {\r\n return PersistenceBrokerFactoryFactory.instance().\r\n createPersistenceBroker(jcdAlias, user, password);\r\n }", "public static filterpolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tfilterpolicy_csvserver_binding obj = new filterpolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\tfilterpolicy_csvserver_binding response[] = (filterpolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void animate(float timeInSec)\n {\n GVRSkeleton skel = getSkeleton();\n GVRPose pose = skel.getPose();\n computePose(timeInSec,pose);\n skel.poseToBones();\n skel.updateBonePose();\n skel.updateSkinPose();\n }", "public Object remove(String name) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\t\treturn context.remove(name);\n\t}", "protected <T> T fromJsonString(String json, Class<T> clazz) {\n\t\treturn _gsonParser.fromJson(json, clazz);\n\t}", "public ReplicationResult trigger() {\n assertNotEmpty(source, \"Source\");\n assertNotEmpty(target, \"Target\");\n InputStream response = null;\n try {\n JsonObject json = createJson();\n if (log.isLoggable(Level.FINE)) {\n log.fine(json.toString());\n }\n\n final URI uri = new DatabaseURIHelper(client.getBaseUri()).path(\"_replicate\").build();\n response = client.post(uri, json.toString());\n final InputStreamReader reader = new InputStreamReader(response, \"UTF-8\");\n return client.getGson().fromJson(reader, ReplicationResult.class);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n } finally {\n close(response);\n }\n }" ]
Print duration in thousandths of minutes. @param duration Duration instance @return duration in thousandths of minutes
[ "public static final BigDecimal printDurationInDecimalThousandthsOfMinutes(Duration duration)\n {\n BigDecimal result = null;\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigDecimal.valueOf(printDurationFractionsOfMinutes(duration, 1000));\n }\n return result;\n }" ]
[ "protected void addImage(PdfContext context, ImageResult imageResult) throws BadElementException, IOException {\n\t\tBbox imageBounds = imageResult.getRasterImage().getBounds();\n\t\tfloat scaleFactor = (float) (72 / getMap().getRasterResolution());\n\t\tfloat width = (float) imageBounds.getWidth() * scaleFactor;\n\t\tfloat height = (float) imageBounds.getHeight() * scaleFactor;\n\t\t// subtract screen position of lower-left corner\n\t\tfloat x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;\n\t\t// shift y to lowerleft corner, flip y to user space and subtract\n\t\t// screen position of lower-left\n\t\t// corner\n\t\tfloat y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;\n\t\tif (log.isDebugEnabled()) {\n\t\t\tlog.debug(\"adding image, width=\" + width + \",height=\" + height + \",x=\" + x + \",y=\" + y);\n\t\t}\n\t\t// opacity\n\t\tlog.debug(\"before drawImage\");\n\t\tcontext.drawImage(Image.getInstance(imageResult.getImage()), new Rectangle(x, y, x + width, y + height),\n\t\t\t\tgetSize(), getOpacity());\n\t\tlog.debug(\"after drawImage\");\n\t}", "public ByteArray readBytes(int size) throws IOException\n {\n byte[] data = new byte[size];\n m_stream.read(data);\n return new ByteArray(data);\n }", "public static appfwlearningdata[] get(nitro_service service, appfwlearningdata_args args) throws Exception{\n\t\tappfwlearningdata obj = new appfwlearningdata();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tappfwlearningdata[] response = (appfwlearningdata[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public static void copy(String in, Writer out) throws IOException {\n\t\tAssert.notNull(in, \"No input String specified\");\n\t\tAssert.notNull(out, \"No Writer specified\");\n\t\ttry {\n\t\t\tout.write(in);\n\t\t}\n\t\tfinally {\n\t\t\ttry {\n\t\t\t\tout.close();\n\t\t\t}\n\t\t\tcatch (IOException ex) {\n\t\t\t}\n\t\t}\n\t}", "protected String calculateNextVersion(String fromVersion) {\n // first turn it to release version\n fromVersion = calculateReleaseVersion(fromVersion);\n String nextVersion;\n int lastDotIndex = fromVersion.lastIndexOf('.');\n try {\n if (lastDotIndex != -1) {\n // probably a major minor version e.g., 2.1.1\n String minorVersionToken = fromVersion.substring(lastDotIndex + 1);\n String nextMinorVersion;\n int lastDashIndex = minorVersionToken.lastIndexOf('-');\n if (lastDashIndex != -1) {\n // probably a minor-buildNum e.g., 2.1.1-4 (should change to 2.1.1-5)\n String buildNumber = minorVersionToken.substring(lastDashIndex + 1);\n int nextBuildNumber = Integer.parseInt(buildNumber) + 1;\n nextMinorVersion = minorVersionToken.substring(0, lastDashIndex + 1) + nextBuildNumber;\n } else {\n nextMinorVersion = Integer.parseInt(minorVersionToken) + 1 + \"\";\n }\n nextVersion = fromVersion.substring(0, lastDotIndex + 1) + nextMinorVersion;\n } else {\n // maybe it's just a major version; try to parse as an int\n int nextMajorVersion = Integer.parseInt(fromVersion) + 1;\n nextVersion = nextMajorVersion + \"\";\n }\n } catch (NumberFormatException e) {\n return fromVersion;\n }\n return nextVersion + \"-SNAPSHOT\";\n }", "public String propertyValue(Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n\r\n if (value == null)\r\n {\r\n value = attributes.getProperty(ATTRIBUTE_DEFAULT);\r\n }\r\n return value;\r\n }", "public static <T> List<T> flatten(Collection<List<T>> nestedList) {\r\n List<T> result = new ArrayList<T>();\r\n for (List<T> list : nestedList) {\r\n result.addAll(list);\r\n }\r\n return result;\r\n }", "@SafeVarargs\n public static <T> Set<T> of(T... elements) {\n Preconditions.checkNotNull(elements);\n return ImmutableSet.<T> builder().addAll(elements).build();\n }", "public V get(final K1 firstKey, final K2 secondKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, V> innerMap = map.get(firstKey);\n\t\tif( innerMap == null ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn innerMap.get(secondKey);\n\t}" ]
Makes sure that the operation name and the address have been set and returns a ModelNode representing the operation request.
[ "public ModelNode buildRequest() throws OperationFormatException {\n\n ModelNode address = request.get(Util.ADDRESS);\n if(prefix.isEmpty()) {\n address.setEmptyList();\n } else {\n Iterator<Node> iterator = prefix.iterator();\n while (iterator.hasNext()) {\n OperationRequestAddress.Node node = iterator.next();\n if (node.getName() != null) {\n address.add(node.getType(), node.getName());\n } else if (iterator.hasNext()) {\n throw new OperationFormatException(\n \"The node name is not specified for type '\"\n + node.getType() + \"'\");\n }\n }\n }\n\n if(!request.hasDefined(Util.OPERATION)) {\n throw new OperationFormatException(\"The operation name is missing or the format of the operation request is wrong.\");\n }\n\n return request;\n }" ]
[ "public void removeMetadataProvider(MetadataProvider provider) {\n for (Set<MetadataProvider> providers : metadataProviders.values()) {\n providers.remove(provider);\n }\n }", "private static String findOutputPath(String[][] options) {\n\tfor (int i = 0; i < options.length; i++) {\n\t if (options[i][0].equals(\"-d\"))\n\t\treturn options[i][1];\n\t}\n\treturn \".\";\n }", "@Override\n public TagsInterface getTagsInterface() {\n if (tagsInterface == null) {\n tagsInterface = new TagsInterface(apiKey, sharedSecret, transport);\n }\n return tagsInterface;\n }", "public static long randomLongBetween(long min, long max) {\n Random rand = new Random();\n return min + (long) (rand.nextDouble() * (max - min));\n }", "public String toDecodedString(final java.net.URI uri) {\n final String scheme = uri.getScheme();\n final String part = uri.getSchemeSpecificPart();\n if ((scheme == null)) {\n return part;\n }\n return ((scheme + \":\") + part);\n }", "public static List<Node> getSiblings(Node parent, Node element) {\n\t\tList<Node> result = new ArrayList<>();\n\t\tNodeList list = parent.getChildNodes();\n\n\t\tfor (int i = 0; i < list.getLength(); i++) {\n\t\t\tNode el = list.item(i);\n\n\t\t\tif (el.getNodeName().equals(element.getNodeName())) {\n\t\t\t\tresult.add(el);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}", "public String getStatement() throws SQLException {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendSql(null, sb, new ArrayList<ArgumentHolder>());\n\t\treturn sb.toString();\n\t}", "public ImmutableList<CandidateElement> extract(StateVertex currentState)\n\t\t\tthrows CrawljaxException {\n\t\tLinkedList<CandidateElement> results = new LinkedList<>();\n\n\t\tif (!checkedElements.checkCrawlCondition(browser)) {\n\t\t\tLOG.info(\"State {} did not satisfy the CrawlConditions.\", currentState.getName());\n\t\t\treturn ImmutableList.of();\n\t\t}\n\t\tLOG.debug(\"Looking in state: {} for candidate elements\", currentState.getName());\n\n\t\ttry {\n\t\t\tDocument dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());\n\t\t\textractElements(dom, results, \"\");\n\t\t} catch (IOException e) {\n\t\t\tLOG.error(e.getMessage(), e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t\tif (randomizeElementsOrder) {\n\t\t\tCollections.shuffle(results);\n\t\t}\n\t\tcurrentState.setElementsFound(results);\n\t\tLOG.debug(\"Found {} new candidate elements to analyze!\", results.size());\n\t\treturn ImmutableList.copyOf(results);\n\t}", "public ParallelTaskBuilder setReplaceVarMapToSingleTarget(\n List<StrStrMap> replacementVarMapList, String uniformTargetHost) {\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skil setting.\");\n return this;\n }\n this.replacementVarMapNodeSpecific.clear();\n this.targetHosts.clear();\n int i = 0;\n for (StrStrMap ssm : replacementVarMapList) {\n if (ssm == null)\n continue;\n String hostName = PcConstants.API_PREFIX + i;\n ssm.addPair(PcConstants.UNIFORM_TARGET_HOST_VAR, uniformTargetHost);\n replacementVarMapNodeSpecific.put(hostName, ssm);\n targetHosts.add(hostName);\n ++i;\n }\n this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;\n logger.info(\n \"Set requestReplacementType as {} for single target. Will disable the set target hosts.\"\n + \"Also Simulated \"\n + \"Now Already set targetHost list with size {}. \\nPLEASE NOT TO SET TARGET HOSTS AGAIN WITH THIS API.\",\n requestReplacementType.toString(), targetHosts.size());\n\n return this;\n }" ]
Calculates directory size as total size of all its files, recursively. @param self a file object @return directory size (length) @since 2.1 @throws IOException if File object specified does not exist @throws IllegalArgumentException if the provided File object does not represent a directory
[ "public static long directorySize(File self) throws IOException, IllegalArgumentException\n {\n final long[] size = {0L};\n\n eachFileRecurse(self, FileType.FILES, new Closure<Void>(null) {\n public void doCall(Object[] args) {\n size[0] += ((File) args[0]).length();\n }\n });\n\n return size[0];\n }" ]
[ "public void forAllMemberTagTokens(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n forAllMemberTagTokens(template, attributes, FOR_FIELD);\r\n }\r\n else if (getCurrentMethod() != null) {\r\n forAllMemberTagTokens(template, attributes, FOR_METHOD);\r\n }\r\n }", "@Deprecated\r\n private InputStream getImageAsStream(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImageAsStream(buffer.toString());\r\n }", "protected static String jacksonObjectToString(Object object) {\n\t\ttry {\n\t\t\treturn mapper.writeValueAsString(object);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tlogger.error(\"Failed to serialize JSON data: \" + e.toString());\n\t\t\treturn null;\n\t\t}\n\t}", "@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }", "public Map<InetSocketAddress, ServerPort> activePorts() {\n final Server server = this.server;\n if (server != null) {\n return server.activePorts();\n } else {\n return Collections.emptyMap();\n }\n }", "public Diff compare(String left, String right) {\n\t\treturn compare(getCtType(left), getCtType(right));\n\t}", "public static csvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cachepolicy_binding obj = new csvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cachepolicy_binding response[] = (csvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void setLinearUpperLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setLinearUpperLimits(getNative(), limitX, limitY, limitZ);\n }", "public BoxComment.Info reply(String message) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"comment\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n if (BoxComment.messageContainsMention(message)) {\n requestJSON.add(\"tagged_message\", message);\n } else {\n requestJSON.add(\"message\", message);\n }\n\n URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedComment.new Info(responseJSON);\n }" ]
Checks if class package match provided list of package locators @param classPackageName name of class package @return true if class package is on the {@link #packageLocators} list
[ "protected boolean checkPackageLocators(String classPackageName) {\n\t\tif (packageLocators != null && !disablePackageLocatorsScanning && classPackageName.length() > 0\n\t\t\t\t&& (packageLocatorsBasePackage == null || classPackageName.startsWith(packageLocatorsBasePackage))) {\n\t\t\tfor (String packageLocator : packageLocators) {\n\t\t\t\tString[] splitted = classPackageName.split(\"\\\\.\");\n\n\t\t\t\tif (es.cenobit.struts2.json.util.StringUtils.contains(splitted, packageLocator, false))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}" ]
[ "private ArrayList handleDependentCollections(Identity oid, Object obj,\r\n Object[] origCollections, Object[] newCollections,\r\n Object[] newCollectionsOfObjects)\r\n throws LockingException\r\n {\r\n ClassDescriptor mif = _pb.getClassDescriptor(obj.getClass());\r\n Collection colDescs = mif.getCollectionDescriptors();\r\n ArrayList newObjects = new ArrayList();\r\n int count = 0;\r\n\r\n for (Iterator it = colDescs.iterator(); it.hasNext(); count++)\r\n {\r\n CollectionDescriptor cds = (CollectionDescriptor) it.next();\r\n\r\n if (cds.getOtmDependent())\r\n {\r\n ArrayList origList = (origCollections == null ? null\r\n : (ArrayList) origCollections[count]);\r\n ArrayList newList = (ArrayList) newCollections[count];\r\n\r\n if (origList != null)\r\n {\r\n for (Iterator it2 = origList.iterator(); it2.hasNext(); )\r\n {\r\n Identity origOid = (Identity) it2.next();\r\n\r\n if ((newList == null) || !newList.contains(origOid))\r\n {\r\n markDelete(origOid, oid, true);\r\n }\r\n }\r\n }\r\n\r\n if (newList != null)\r\n {\r\n int countElem = 0;\r\n for (Iterator it2 = newList.iterator(); it2.hasNext(); countElem++)\r\n {\r\n Identity newOid = (Identity) it2.next();\r\n\r\n if ((origList == null) || !origList.contains(newOid))\r\n {\r\n ContextEntry entry = (ContextEntry) _objects.get(newOid);\r\n\r\n if (entry == null)\r\n {\r\n ArrayList relCol = (ArrayList)\r\n newCollectionsOfObjects[count];\r\n Object relObj = relCol.get(countElem);\r\n insertInternal(newOid, relObj, LockType.WRITE_LOCK,\r\n true, null, new Stack());\r\n newObjects.add(newOid);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return newObjects;\r\n }", "public 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}", "public Equation process( String equation , boolean debug ) {\n compile(equation,true,debug).perform();\n return this;\n }", "public List<List<String>> getAllScopes() {\n this.checkInitialized();\n final ImmutableList.Builder<List<String>> builder = ImmutableList.<List<String>>builder();\n final Consumer<Integer> _function = (Integer it) -> {\n List<String> _get = this.scopes.get(it);\n StringConcatenation _builder = new StringConcatenation();\n _builder.append(\"No scopes are available for index: \");\n _builder.append(it);\n builder.add(Preconditions.<List<String>>checkNotNull(_get, _builder));\n };\n this.scopes.keySet().forEach(_function);\n return builder.build();\n }", "public static int randomIntBetween(int min, int max) {\n Random rand = new Random();\n return rand.nextInt((max - min) + 1) + min;\n }", "public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\r\n\t\tRandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model);\r\n\t\treturn conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions);\r\n\t}", "private static String getUnexpectedTypeMessage(final Class<?> expectedType, final Object actualValue) {\n\t\tif( expectedType == null ) {\n\t\t\tthrow new NullPointerException(\"expectedType should not be null\");\n\t\t}\n\t\tString expectedClassName = expectedType.getName();\n\t\tString actualClassName = (actualValue != null) ? actualValue.getClass().getName() : \"null\";\n\t\treturn String.format(\"the input value should be of type %s but is %s\", expectedClassName, actualClassName);\n\t}", "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 void addProcedureArgument(ProcedureArgumentDef argDef)\r\n {\r\n argDef.setOwner(this);\r\n _procedureArguments.put(argDef.getName(), argDef);\r\n }" ]
Increases the maximum number of columns in the matrix. @param desiredColumns Desired number of columns. @param preserveValue If the array needs to be expanded should it copy the previous values?
[ "public void growMaxColumns( int desiredColumns , boolean preserveValue ) {\n if( col_idx.length < desiredColumns+1 ) {\n int[] c = new int[ desiredColumns+1 ];\n if( preserveValue )\n System.arraycopy(col_idx,0,c,0,col_idx.length);\n col_idx = c;\n }\n }" ]
[ "public synchronized void addRange(final float range, final GVRSceneObject sceneObject)\n {\n if (null == sceneObject) {\n throw new IllegalArgumentException(\"sceneObject must be specified!\");\n }\n if (range < 0) {\n throw new IllegalArgumentException(\"range cannot be negative\");\n }\n\n final int size = mRanges.size();\n final float rangePow2 = range*range;\n final Object[] newElement = new Object[] {rangePow2, sceneObject};\n\n for (int i = 0; i < size; ++i) {\n final Object[] el = mRanges.get(i);\n final Float r = (Float)el[0];\n if (r > rangePow2) {\n mRanges.add(i, newElement);\n break;\n }\n }\n\n if (mRanges.size() == size) {\n mRanges.add(newElement);\n }\n\n final GVRSceneObject owner = getOwnerObject();\n if (null != owner) {\n owner.addChildObject(sceneObject);\n }\n }", "private void writeAssignments(Project project)\n {\n Project.Assignments assignments = m_factory.createProjectAssignments();\n project.setAssignments(assignments);\n List<Project.Assignments.Assignment> list = assignments.getAssignment();\n\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n list.add(writeAssignment(assignment));\n }\n\n //\n // Check to see if we have any tasks that have a percent complete value\n // but do not have resource assignments. If any exist, then we must\n // write a dummy resource assignment record to ensure that the MSPDI\n // file shows the correct percent complete amount for the task.\n //\n ProjectConfig config = m_projectFile.getProjectConfig();\n boolean autoUniqueID = config.getAutoAssignmentUniqueID();\n if (!autoUniqueID)\n {\n config.setAutoAssignmentUniqueID(true);\n }\n\n for (Task task : m_projectFile.getTasks())\n {\n double percentComplete = NumberHelper.getDouble(task.getPercentageComplete());\n if (percentComplete != 0 && task.getResourceAssignments().isEmpty() == true)\n {\n ResourceAssignment dummy = new ResourceAssignment(m_projectFile, task);\n Duration duration = task.getDuration();\n if (duration == null)\n {\n duration = Duration.getInstance(0, TimeUnit.HOURS);\n }\n double durationValue = duration.getDuration();\n TimeUnit durationUnits = duration.getUnits();\n double actualWork = (durationValue * percentComplete) / 100;\n double remainingWork = durationValue - actualWork;\n\n dummy.setResourceUniqueID(NULL_RESOURCE_ID);\n dummy.setWork(duration);\n dummy.setActualWork(Duration.getInstance(actualWork, durationUnits));\n dummy.setRemainingWork(Duration.getInstance(remainingWork, durationUnits));\n \n // Without this, MS Project will mark a 100% complete milestone as 99% complete\n if (percentComplete == 100 && duration.getDuration() == 0)\n { \n dummy.setActualFinish(task.getActualStart());\n }\n \n list.add(writeAssignment(dummy));\n }\n }\n\n config.setAutoAssignmentUniqueID(autoUniqueID);\n }", "public static String parseString(String value)\n {\n if (value != null)\n {\n // Strip angle brackets if present\n if (!value.isEmpty() && value.charAt(0) == '<')\n {\n value = value.substring(1, value.length() - 1);\n }\n\n // Strip quotes if present\n if (!value.isEmpty() && value.charAt(0) == '\"')\n {\n value = value.substring(1, value.length() - 1);\n }\n }\n return value;\n }", "private boolean hidden(ProgramElementDoc c) {\n\tif (c.tags(\"hidden\").length > 0 || c.tags(\"view\").length > 0)\n\t return true;\n\tOptions opt = optionProvider.getOptionsFor(c instanceof ClassDoc ? (ClassDoc) c : c.containingClass());\n\treturn opt.matchesHideExpression(c.toString()) //\n\t\t|| (opt.hidePrivateInner && c instanceof ClassDoc && c.isPrivate() && ((ClassDoc) c).containingClass() != null);\n }", "public static void hideChannels(Object... channels){\r\n // TODO this could share more code with the other show/hide(Only)Channels methods\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n for (Object channel : channels) {\r\n visHandler.alsoHide(channel);\r\n }\r\n }\r\n }\r\n }", "private void handleMultiInstanceEncapResponse(\r\n\t\t\tSerialMessage serialMessage, int offset) {\r\n\t\tlogger.trace(\"Process Multi-instance Encapsulation\");\r\n\t\tint instance = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset + 1);\r\n\t\tCommandClass commandClass = CommandClass.getCommandClass(commandClassCode);\r\n\r\n\t\tif (commandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\tZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d, Instance = %d, calling handleApplicationCommandRequest.\", this.getNode().getNodeId(), instance));\r\n\t\tzwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset+ 3, instance);\r\n\t}", "List<CmsFavoriteEntry> getEntries() {\n\n List<CmsFavoriteEntry> result = new ArrayList<>();\n for (I_CmsEditableGroupRow row : m_group.getRows()) {\n CmsFavoriteEntry entry = ((CmsFavInfo)row).getEntry();\n result.add(entry);\n }\n return result;\n }", "public void retrieveReferences(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n Iterator i = cld.getObjectReferenceDescriptors().iterator();\r\n\r\n // turn off auto prefetching for related proxies\r\n final Class saveClassToPrefetch = classToPrefetch;\r\n classToPrefetch = null;\r\n\r\n pb.getInternalCache().enableMaterializationCache();\r\n try\r\n {\r\n while (i.hasNext())\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) i.next();\r\n retrieveReference(newObj, cld, rds, forced);\r\n }\r\n\r\n pb.getInternalCache().disableMaterializationCache();\r\n }\r\n catch(RuntimeException e)\r\n {\r\n pb.getInternalCache().doLocalClear();\r\n throw e;\r\n }\r\n finally\r\n {\r\n classToPrefetch = saveClassToPrefetch;\r\n }\r\n }", "public void downloadRange(OutputStream output, long rangeStart, long rangeEnd, ProgressListener listener) {\n URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n if (rangeEnd > 0) {\n request.addHeader(\"Range\", String.format(\"bytes=%s-%s\", Long.toString(rangeStart),\n Long.toString(rangeEnd)));\n } else {\n request.addHeader(\"Range\", String.format(\"bytes=%s-\", Long.toString(rangeStart)));\n }\n\n BoxAPIResponse response = request.send();\n InputStream input = response.getBody(listener);\n\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = input.read(buffer);\n while (n != -1) {\n output.write(buffer, 0, n);\n n = input.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n } finally {\n response.disconnect();\n }\n }" ]
Use this API to login into Netscaler. @param username Username @param password Password for the Netscaler. @param timeout timeout for netscaler session.Default is 1800secs @return status of the operation performed. @throws Exception nitro exception is thrown.
[ "public base_response login(String username, String password, Long timeout) throws Exception\n\t{\n\t\tthis.set_credential(username, password);\n\t\tthis.set_timeout(timeout);\n\t\treturn this.login();\n\t}" ]
[ "public BufferedImage getNewImageInstance() {\n BufferedImage buf = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());\n buf.setData(image.getData());\n return buf;\n }", "private Layout getActiveLayout(Project phoenixProject)\n {\n //\n // Start with the first layout we find\n //\n Layout activeLayout = phoenixProject.getLayouts().getLayout().get(0);\n\n //\n // If this isn't active, find one which is... and if none are,\n // we'll just use the first.\n //\n if (!activeLayout.isActive().booleanValue())\n {\n for (Layout layout : phoenixProject.getLayouts().getLayout())\n {\n if (layout.isActive().booleanValue())\n {\n activeLayout = layout;\n break;\n }\n }\n }\n\n return activeLayout;\n }", "public static base_response flush(nitro_service client, cacheobject resource) throws Exception {\n\t\tcacheobject flushresource = new cacheobject();\n\t\tflushresource.locator = resource.locator;\n\t\tflushresource.url = resource.url;\n\t\tflushresource.host = resource.host;\n\t\tflushresource.port = resource.port;\n\t\tflushresource.groupname = resource.groupname;\n\t\tflushresource.httpmethod = resource.httpmethod;\n\t\tflushresource.force = resource.force;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}", "private void addTypes(Injector injector, List<Class<?>> types) {\n for (Binding<?> binding : injector.getBindings().values()) {\n Key<?> key = binding.getKey();\n Type type = key.getTypeLiteral().getType();\n if (hasAnnotatedMethods(type)) {\n types.add(((Class<?>)type));\n }\n }\n if (injector.getParent() != null) {\n addTypes(injector.getParent(), types);\n }\n }", "public static boolean intersectsPointWithRectF(RectF _Rect, float _X, float _Y) {\n return _X > _Rect.left && _X < _Rect.right && _Y > _Rect.top && _Y < _Rect.bottom;\n }", "public void register() {\n synchronized (loaders) {\n loaders.add(this);\n\n maximumHeaderLength = 0;\n for (GVRCompressedTextureLoader loader : loaders) {\n int headerLength = loader.headerLength();\n if (headerLength > maximumHeaderLength) {\n maximumHeaderLength = headerLength;\n }\n }\n }\n }", "@SuppressWarnings(\"WeakerAccess\")\n public int findBeatAtTime(long milliseconds) {\n int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);\n if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number\n return found + 1;\n } else if (found == -1) { // We are before the first beat\n return found;\n } else { // We are after some beat, report its beat number\n return -(found + 1);\n }\n }", "public static SimpleFeatureType createGridFeatureType(\n @Nonnull final MapfishMapContext mapContext,\n @Nonnull final Class<? extends Geometry> geomClass) {\n final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();\n CoordinateReferenceSystem projection = mapContext.getBounds().getProjection();\n typeBuilder.add(Constants.Style.Grid.ATT_GEOM, geomClass, projection);\n typeBuilder.setName(Constants.Style.Grid.NAME_LINES);\n\n return typeBuilder.buildFeatureType();\n }", "public void setCanvasWidthHeight(int width, int height) {\n hudWidth = width;\n hudHeight = height;\n HUD = Bitmap.createBitmap(width, height, Config.ARGB_8888);\n canvas = new Canvas(HUD);\n texture = null;\n }" ]
Converts an object into a tab delimited string with given fields Requires the object has public access for the specified fields @param object Object to convert @param delimiter delimiter @param fieldNames fieldnames @return String representing object
[ "public static String objectToColumnString(Object object, String delimiter, String[] fieldNames)\r\n throws IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException\r\n {\r\n StringBuilder sb = new StringBuilder();\r\n for (int i = 0; i < fieldNames.length; i++) {\r\n if (sb.length() > 0) {\r\n sb.append(delimiter);\r\n }\r\n try {\r\n Field field = object.getClass().getDeclaredField(fieldNames[i]);\r\n sb.append(field.get(object)) ;\r\n } catch (IllegalAccessException ex) {\r\n Method method = object.getClass().getDeclaredMethod(\"get\" + StringUtils.capitalize(fieldNames[i]));\r\n sb.append(method.invoke(object));\r\n }\r\n }\r\n return sb.toString();\r\n }" ]
[ "public static 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 String escapeAndJoin(String[] commandline) {\n // TODO: we should try to escape special characters here, depending on the OS.\n StringBuilder b = new StringBuilder();\n Pattern specials = Pattern.compile(\"[\\\\ ]\");\n for (String arg : commandline) {\n if (b.length() > 0) {\n b.append(\" \");\n }\n\n if (specials.matcher(arg).find()) {\n b.append('\"').append(arg).append('\"');\n } else {\n b.append(arg);\n }\n }\n return b.toString();\n }", "public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) {\n login(userIdentifier);\n RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl);\n }", "private void addStatement(RecordImpl record,\n String subject,\n String property,\n String object) {\n Collection<Column> cols = columns.get(property);\n if (cols == null) {\n if (property.equals(RDF_TYPE) && !types.isEmpty())\n addValue(record, subject, property, object);\n return;\n }\n \n for (Column col : cols) {\n String cleaned = object;\n if (col.getCleaner() != null)\n cleaned = col.getCleaner().clean(object);\n if (cleaned != null && !cleaned.equals(\"\"))\n addValue(record, subject, col.getProperty(), cleaned);\n }\n }", "public boolean process( int sideLength,\n double diag[] ,\n double off[] ,\n double eigenvalues[] ) {\n if( diag != null )\n helper.init(diag,off,sideLength);\n if( Q == null )\n Q = CommonOps_DDRM.identity(helper.N);\n helper.setQ(Q);\n\n this.followingScript = true;\n this.eigenvalues = eigenvalues;\n this.fastEigenvalues = false;\n\n return _process();\n }", "private String getRequestBody(ServletRequest request) throws IOException {\n\n final StringBuilder sb = new StringBuilder();\n\n String line = request.getReader().readLine();\n while (null != line) {\n sb.append(line);\n line = request.getReader().readLine();\n }\n\n return sb.toString();\n }", "private boolean isSpecial(final char chr) {\n\t\treturn ((chr == '.') || (chr == '?') || (chr == '*') || (chr == '^') || (chr == '$') || (chr == '+')\n\t\t\t\t|| (chr == '[') || (chr == ']') || (chr == '(') || (chr == ')') || (chr == '|') || (chr == '\\\\')\n\t\t\t\t|| (chr == '&'));\n\t}", "private static float angleDeg(final float ax, final float ay,\n final float bx, final float by) {\n final double angleRad = Math.atan2(ay - by, ax - bx);\n double angle = Math.toDegrees(angleRad);\n if (angleRad < 0) {\n angle += 360;\n }\n return (float) angle;\n }", "@Override\n public JulianDate date(int prolepticYear, int month, int dayOfMonth) {\n return JulianDate.of(prolepticYear, month, dayOfMonth);\n }" ]
Clones the cluster by constructing a new one with same name, partition layout, and nodes. @param cluster @return clone of Cluster cluster.
[ "public static Cluster cloneCluster(Cluster cluster) {\n // Could add a better .clone() implementation that clones the derived\n // data structures. The constructor invoked by this clone implementation\n // can be slow for large numbers of partitions. Probably faster to copy\n // all the maps and stuff.\n return new Cluster(cluster.getName(),\n new ArrayList<Node>(cluster.getNodes()),\n new ArrayList<Zone>(cluster.getZones()));\n /*-\n * Historic \"clone\" code being kept in case this, for some reason, was the \"right\" way to be doing this.\n ClusterMapper mapper = new ClusterMapper();\n return mapper.readCluster(new StringReader(mapper.writeCluster(cluster)));\n */\n }" ]
[ "public Iterator getAllExtentClasses()\r\n {\r\n ArrayList subTypes = new ArrayList();\r\n\r\n subTypes.addAll(_extents);\r\n\r\n for (int idx = 0; idx < subTypes.size(); idx++)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)subTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curSubTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!subTypes.contains(curSubTypeDef))\r\n {\r\n subTypes.add(curSubTypeDef);\r\n }\r\n }\r\n }\r\n return subTypes.iterator();\r\n }", "public static RgbaColor fromRgb(String rgb) {\n if (rgb.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbParts(rgb).split(\",\");\n if (parts.length == 3) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]));\n }\n else {\n return getDefaultColor();\n }\n }", "private TrackMetadata requestMetadataInternal(final DataReference track, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n // First check if we are using cached data for this request.\n MetadataCache cache = getMetadataCache(SlotReference.getSlotReference(track));\n if (cache != null && trackType == CdjStatus.TrackType.REKORDBOX) {\n return cache.getTrackMetadata(null, track);\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = getMediaDetailsFor(track.getSlotReference());\n if (sourceDetails != null) {\n final TrackMetadata provided = allMetadataProviders.getTrackMetadata(sourceDetails, track);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (passive.get() && failIfPassive && track.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // Use the dbserver protocol implementation to request the metadata.\n ConnectionManager.ClientTask<TrackMetadata> task = new ConnectionManager.ClientTask<TrackMetadata>() {\n @Override\n public TrackMetadata useClient(Client client) throws Exception {\n return queryMetadata(track, trackType, client);\n }\n };\n\n try {\n return ConnectionManager.getInstance().invokeWithClientSession(track.player, task, \"requesting metadata\");\n } catch (Exception e) {\n logger.error(\"Problem requesting metadata, returning null\", e);\n }\n return null;\n }", "@Override\n public void setCursorDepth(float depth)\n {\n super.setCursorDepth(depth);\n if (mRayModel != null)\n {\n mRayModel.getTransform().setScaleZ(mCursorDepth);\n }\n }", "protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }", "public 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 GridLabelFormat fromConfig(final GridParam param) {\n if (param.labelFormat != null) {\n return new GridLabelFormat.Simple(param.labelFormat);\n } else if (param.valueFormat != null) {\n return new GridLabelFormat.Detailed(\n param.valueFormat, param.unitFormat,\n param.formatDecimalSeparator, param.formatGroupingSeparator);\n }\n return null;\n }", "public void fire(TestCaseEvent event) {\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n notifier.fire(event);\n }", "private boolean isToIgnore(CtElement element) {\n\t\tif (element instanceof CtStatementList && !(element instanceof CtCase)) {\n\t\t\tif (element.getRoleInParent() == CtRole.ELSE || element.getRoleInParent() == CtRole.THEN) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn element.isImplicit() || element instanceof CtReference;\n\t}" ]
Use this API to Import sslfipskey.
[ "public static base_response Import(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey Importresource = new sslfipskey();\n\t\tImportresource.fipskeyname = resource.fipskeyname;\n\t\tImportresource.key = resource.key;\n\t\tImportresource.inform = resource.inform;\n\t\tImportresource.wrapkeyname = resource.wrapkeyname;\n\t\tImportresource.iv = resource.iv;\n\t\tImportresource.exponent = resource.exponent;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}" ]
[ "public Collection<Contact> getListRecentlyUploaded(Date lastUpload, String filter) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIST_RECENTLY_UPLOADED);\r\n\r\n if (lastUpload != null) {\r\n parameters.put(\"date_lastupload\", String.valueOf(lastUpload.getTime() / 1000L));\r\n }\r\n if (filter != null) {\r\n parameters.put(\"filter\", filter);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setRealName(contactElement.getAttribute(\"realname\"));\r\n contact.setFriend(\"1\".equals(contactElement.getAttribute(\"friend\")));\r\n contact.setFamily(\"1\".equals(contactElement.getAttribute(\"family\")));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }", "public static void dumpPlanToFile(String outputDirName, RebalancePlan plan) {\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n try {\n FileUtils.writeStringToFile(new File(outputDirName, \"plan.out\"), plan.toString());\n } catch(IOException e) {\n logger.error(\"IOException during dumpPlanToFile: \" + e);\n }\n }\n }", "public void updateShownOptions(boolean showModeSwitch, boolean showAddKeyOption) {\n\n if (showModeSwitch != m_showModeSwitch) {\n m_upperLeftComponent.removeAllComponents();\n m_upperLeftComponent.addComponent(m_languageSwitch);\n if (showModeSwitch) {\n m_upperLeftComponent.addComponent(m_modeSwitch);\n }\n m_upperLeftComponent.addComponent(m_filePathLabel);\n m_showModeSwitch = showModeSwitch;\n }\n if (showAddKeyOption != m_showAddKeyOption) {\n if (showAddKeyOption) {\n m_optionsComponent.addComponent(m_lowerLeftComponent, 0, 1);\n m_optionsComponent.addComponent(m_lowerRightComponent, 1, 1);\n } else {\n m_optionsComponent.removeComponent(0, 1);\n m_optionsComponent.removeComponent(1, 1);\n }\n m_showAddKeyOption = showAddKeyOption;\n }\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public synchronized void pushInstallReferrer(String source, String medium, String campaign) {\n if (source == null && medium == null && campaign == null) return;\n try {\n // If already pushed, don't send it again\n int status = StorageHelper.getInt(context, \"app_install_status\", 0);\n if (status != 0) {\n Logger.d(\"Install referrer has already been set. Will not override it\");\n return;\n }\n StorageHelper.putInt(context, \"app_install_status\", 1);\n\n if (source != null) source = Uri.encode(source);\n if (medium != null) medium = Uri.encode(medium);\n if (campaign != null) campaign = Uri.encode(campaign);\n\n String uriStr = \"wzrk://track?install=true\";\n if (source != null) uriStr += \"&utm_source=\" + source;\n if (medium != null) uriStr += \"&utm_medium=\" + medium;\n if (campaign != null) uriStr += \"&utm_campaign=\" + campaign;\n\n Uri uri = Uri.parse(uriStr);\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n Logger.v(\"Failed to push install referrer\", t);\n }\n }", "protected void solveL(double[] vv) {\n\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sumReal = vv[ip*2];\n double sumImg = vv[ip*2+1];\n\n vv[ip*2] = vv[i*2];\n vv[ip*2+1] = vv[i*2+1];\n\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*stride + (ii-1)*2;\n for( int j = ii-1; j < i; j++ ){\n double luReal = dataLU[index++];\n double luImg = dataLU[index++];\n\n double vvReal = vv[j*2];\n double vvImg = vv[j*2+1];\n\n sumReal -= luReal*vvReal - luImg*vvImg;\n sumImg -= luReal*vvImg + luImg*vvReal;\n }\n } else if( sumReal*sumReal + sumImg*sumImg != 0.0 ) {\n ii=i+1;\n }\n vv[i*2] = sumReal;\n vv[i*2+1] = sumImg;\n }\n }", "public 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 void clearDeck(TrackMetadataUpdate update) {\n if (hotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverBeatGridUpdate(update.player, null);\n }\n }", "private void printStatistics(UsageStatistics usageStatistics,\n\t\t\tString entityLabel) {\n\t\tSystem.out.println(\"Processed \" + usageStatistics.count + \" \"\n\t\t\t\t+ entityLabel + \":\");\n\t\tSystem.out.println(\" * Labels: \" + usageStatistics.countLabels\n\t\t\t\t+ \", descriptions: \" + usageStatistics.countDescriptions\n\t\t\t\t+ \", aliases: \" + usageStatistics.countAliases);\n\t\tSystem.out.println(\" * Statements: \" + usageStatistics.countStatements\n\t\t\t\t+ \", with references: \"\n\t\t\t\t+ usageStatistics.countReferencedStatements);\n\t}", "public void removeOverride(int overrideId, int pathId, Integer ordinal, String clientUUID) {\n // TODO: reorder priorities after removal\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n int enabledId = getEnabledEndpoint(pathId, overrideId, ordinal, clientUUID).getId();\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, enabledId);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }" ]
Create a counter if one is not defined already, otherwise return the existing one. @param counterName unique name for the counter @param initialValue initial value for the counter @return a {@link StrongCounter}
[ "protected StrongCounter getCounterOrCreateIt(String counterName, int initialValue) {\n\t\tCounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager( cacheManager );\n\t\tif ( !counterManager.isDefined( counterName ) ) {\n\t\t\tLOG.tracef( \"Counter %s is not defined, creating it\", counterName );\n\n\t\t\t// global configuration is mandatory in order to define\n\t\t\t// a new clustered counter with persistent storage\n\t\t\tvalidateGlobalConfiguration();\n\n\t\t\tcounterManager.defineCounter( counterName,\n\t\t\t\tCounterConfiguration.builder(\n\t\t\t\t\tCounterType.UNBOUNDED_STRONG )\n\t\t\t\t\t\t.initialValue( initialValue )\n\t\t\t\t\t\t.storage( Storage.PERSISTENT )\n\t\t\t\t\t\t.build() );\n\t\t}\n\n\t\tStrongCounter strongCounter = counterManager.getStrongCounter( counterName );\n\t\treturn strongCounter;\n\t}" ]
[ "public synchronized boolean tryDelegateSlop(Node node) {\n if(asyncCallbackShouldSendhint) {\n return false;\n } else {\n slopDestinations.put(node, true);\n return true;\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 }", "public static Set<String> listAllLinks(OperationContext context, String overlay) {\n Set<String> serverGoupNames = listServerGroupsReferencingOverlay(context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS), overlay);\n Set<String> links = new HashSet<>();\n for (String serverGoupName : serverGoupNames) {\n links.addAll(listLinks(context, PathAddress.pathAddress(\n PathElement.pathElement(SERVER_GROUP, serverGoupName),\n PathElement.pathElement(DEPLOYMENT_OVERLAY, overlay))));\n }\n return links;\n }", "public App named(String name) {\n App newApp = copy();\n newApp.name = name;\n return newApp;\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 BoxGroupMembership.Info addMembership(BoxUser user, Role role) {\n BoxAPIConnection api = this.getAPI();\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"user\", new JsonObject().add(\"id\", user.getID()));\n requestJSON.add(\"group\", new JsonObject().add(\"id\", this.getID()));\n if (role != null) {\n requestJSON.add(\"role\", role.toJSONString());\n }\n\n URL url = ADD_MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxGroupMembership membership = new BoxGroupMembership(api, responseJSON.get(\"id\").asString());\n return membership.new Info(responseJSON);\n }", "public void addImportedPackages(String... importedPackages) {\n\t\tString oldBundles = mainAttributes.get(IMPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : importedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(IMPORT_PACKAGE, result);\n\t}", "private int countCharsStart(final char ch, final boolean allowSpaces)\n {\n int count = 0;\n for (int i = 0; i < this.value.length(); i++)\n {\n final char c = this.value.charAt(i);\n if (c == ' ' && allowSpaces)\n {\n continue;\n }\n if (c == ch)\n {\n count++;\n }\n else\n {\n break;\n }\n }\n return count;\n }", "public void addHiDpiImage(String factor, CmsJspImageBean image) {\n\n if (m_hiDpiImages == null) {\n m_hiDpiImages = CmsCollectionsGenericWrapper.createLazyMap(new CmsScaleHiDpiTransformer());\n }\n m_hiDpiImages.put(factor, image);\n }" ]
Internal used method which start the real store work.
[ "protected void store(Object obj, Identity oid, ClassDescriptor cld, boolean insert)\n {\n store(obj, oid, cld, insert, false);\n }" ]
[ "public static Command newStartProcess(String processId,\n Map<String, Object> parameters) {\n return getCommandFactoryProvider().newStartProcess( processId,\n parameters );\n }", "public static double[] computeSeasonalAdjustments(double[] realizedCPIValues, int lastMonth, int numberOfYearsToAverage) {\n\n\t\t/*\n\t\t * Cacluate average log returns\n\t\t */\n\t\tdouble[] averageLogReturn = new double[12];\n\t\tArrays.fill(averageLogReturn, 0.0);\n\t\tfor(int arrayIndex = 0; arrayIndex < 12*numberOfYearsToAverage; arrayIndex++){\n\n\t\t\tint month = (((((lastMonth-1 - arrayIndex) % 12) + 12) % 12));\n\n\t\t\tdouble logReturn = Math.log(realizedCPIValues[realizedCPIValues.length - 1 - arrayIndex] / realizedCPIValues[realizedCPIValues.length - 2 - arrayIndex]);\n\t\t\taverageLogReturn[month] += logReturn/numberOfYearsToAverage;\n\t\t}\n\n\t\t/*\n\t\t * Normalize\n\t\t */\n\t\tdouble sum = 0.0;\n\t\tfor(int index = 0; index < averageLogReturn.length; index++){\n\t\t\tsum += averageLogReturn[index];\n\t\t}\n\t\tdouble averageSeasonal = sum / averageLogReturn.length;\n\n\t\tdouble[] seasonalAdjustments = new double[averageLogReturn.length];\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = averageLogReturn[index] - averageSeasonal;\n\t\t}\n\n\t\t// Annualize seasonal adjustments\n\t\tfor(int index = 0; index < seasonalAdjustments.length; index++){\n\t\t\tseasonalAdjustments[index] = seasonalAdjustments[index] * 12;\n\t\t}\n\n\t\treturn seasonalAdjustments;\n\t}", "public WebSocketContext messageReceived(String receivedMessage) {\n this.stringMessage = S.string(receivedMessage).trim();\n isJson = stringMessage.startsWith(\"{\") || stringMessage.startsWith(\"]\");\n tryParseQueryParams();\n return this;\n }", "public Script[] getScripts(Integer type) {\n ArrayList<Script> returnData = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" ORDER BY \" + Constants.GENERIC_ID);\n if (type != null) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.SCRIPT_TYPE + \"= ?\" +\n \" ORDER BY \" + Constants.GENERIC_ID);\n statement.setInt(1, type);\n }\n\n logger.info(\"Query: {}\", statement);\n\n results = statement.executeQuery();\n while (results.next()) {\n returnData.add(scriptFromSQLResult(results));\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnData.toArray(new Script[0]);\n }", "public void removeChildTask(Task child)\n {\n if (m_children.remove(child))\n {\n child.m_parent = null;\n }\n setSummary(!m_children.isEmpty());\n }", "public static <V> V doWorkInPoolNicely(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) {\n final V result;\n try {\n result = doWorkInPool(pool, work);\n } catch (RuntimeException re) {\n throw re;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n return result;\n }", "public static authenticationtacacspolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_authenticationvserver_binding obj = new authenticationtacacspolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_authenticationvserver_binding response[] = (authenticationtacacspolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) {\n return createEnterpriseUser(api, login, name, null);\n }", "private void readRelationships(net.sf.mpxj.ganttproject.schema.Task gpTask)\n {\n for (Depend depend : gpTask.getDepend())\n {\n Task task1 = m_projectFile.getTaskByUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1));\n Task task2 = m_projectFile.getTaskByUniqueID(Integer.valueOf(NumberHelper.getInt(depend.getId()) + 1));\n if (task1 != null && task2 != null)\n {\n Duration lag = Duration.getInstance(NumberHelper.getInt(depend.getDifference()), TimeUnit.DAYS);\n Relation relation = task2.addPredecessor(task1, getRelationType(depend.getType()), lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }" ]
Checks if the required option exists. @param options OptionSet to checked @param opt Required option to check @throws VoldemortException
[ "public static void checkRequired(OptionSet options, String opt) throws VoldemortException {\n List<String> opts = Lists.newArrayList();\n opts.add(opt);\n checkRequired(options, opts);\n }" ]
[ "public Set<RGBColor> colours() {\n return stream().map(Pixel::toColor).collect(Collectors.toSet());\n }", "protected FieldDescriptor resolvePayloadField(Message message) {\n for (FieldDescriptor field : message.getDescriptorForType().getFields()) {\n if (message.hasField(field)) {\n return field;\n }\n }\n\n throw new RuntimeException(\"No payload found in message \" + message);\n }", "public static String getDateTimeStr(Date d) {\n if (d == null)\n return \"\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSSZ\");\n // 20140315 test will problem +0000\n return sdf.format(d);\n }", "public void addRequest(long timeNS,\n long numEmptyResponses,\n long valueBytes,\n long keyBytes,\n long getAllAggregatedCount) {\n // timing instrumentation (trace only)\n long startTimeNs = 0;\n if(logger.isTraceEnabled()) {\n startTimeNs = System.nanoTime();\n }\n\n long currentTime = time.milliseconds();\n\n timeSensor.record((double) timeNS / voldemort.utils.Time.NS_PER_MS, currentTime);\n emptyResponseKeysSensor.record(numEmptyResponses, currentTime);\n valueBytesSensor.record(valueBytes, currentTime);\n keyBytesSensor.record(keyBytes, currentTime);\n getAllKeysCountSensor.record(getAllAggregatedCount, currentTime);\n\n // timing instrumentation (trace only)\n if(logger.isTraceEnabled()) {\n logger.trace(\"addRequest took \" + (System.nanoTime() - startTimeNs) + \" ns.\");\n }\n }", "public static double Cosh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return 1 + (x * x) / 2D;\r\n } else {\r\n\r\n double mult = x * x;\r\n double fact = 2;\r\n int factS = 4;\r\n double result = 1 + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }", "public void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n final SortedSet<WeekDay> newWeekDays = null == weekDays ? new TreeSet<WeekDay>() : weekDays;\n SortedSet<WeekDay> currentWeekDays = m_model.getWeekDays();\n if (!currentWeekDays.equals(newWeekDays)) {\n conditionallyRemoveExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDays(newWeekDays);\n onValueChange();\n }\n }, !newWeekDays.containsAll(m_model.getWeekDays()));\n }\n }", "private void reInitLayoutElements() {\n\n m_panel.clear();\n for (CmsCheckBox cb : m_checkBoxes) {\n m_panel.add(setStyle(m_onlyLabels ? new Label(cb.getText()) : cb));\n }\n }", "public Slice newSlice(long address, int size, Object reference)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (reference == null) {\n throw new NullPointerException(\"Object reference is null\");\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, size, reference);\n }", "private void releaseConnection()\n {\n if (m_rs != null)\n {\n try\n {\n m_rs.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_rs = null;\n }\n\n if (m_ps != null)\n {\n try\n {\n m_ps.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore errors on close\n }\n\n m_ps = null;\n }\n }" ]
Sets a new image @param BufferedImage imagem
[ "public void setBufferedImage(BufferedImage img) {\n image = img;\n width = img.getWidth();\n height = img.getHeight();\n updateColorArray();\n }" ]
[ "private File makeDestFile(URL src) {\n if (dest == null) {\n throw new IllegalArgumentException(\"Please provide a download destination\");\n }\n\n File destFile = dest;\n if (destFile.isDirectory()) {\n //guess name from URL\n String name = src.toString();\n if (name.endsWith(\"/\")) {\n name = name.substring(0, name.length() - 1);\n }\n name = name.substring(name.lastIndexOf('/') + 1);\n destFile = new File(dest, name);\n } else {\n //create destination directory\n File parent = destFile.getParentFile();\n if (parent != null) {\n parent.mkdirs();\n }\n }\n return destFile;\n }", "public static pqbinding[] get(nitro_service service, pqbinding_args args) throws Exception{\n\t\tpqbinding obj = new pqbinding();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tpqbinding[] response = (pqbinding[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "boolean isUserPasswordReset(CmsUser user) {\n\n if (USER_PASSWORD_STATUS.containsKey(user.getId())) { //Check if user was checked before\n if (!USER_PASSWORD_STATUS.get(user.getId()).booleanValue()) { // was false before, false->true is never done without changing map\n return false;\n }\n if (m_checkedUserPasswordReset.contains(user.getId())) { //was true before, true->false happens when user resets password. Only check one time per table load.\n return true; //Set gets flushed on reloading table\n }\n }\n CmsUser currentUser = user;\n if (user.getAdditionalInfo().size() < 3) {\n\n try {\n currentUser = m_cms.readUser(user.getId());\n } catch (CmsException e) {\n LOG.error(\"Can not read user\", e);\n }\n }\n if (currentUser.getAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET) != null) {\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(true));\n m_checkedUserPasswordReset.add(currentUser.getId());\n return true;\n }\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(false));\n return false;\n }", "public static void closeMASCaseManager(File caseManager) {\n\n FileWriter caseManagerWriter;\n try {\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\"}\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger\n .getLogger(\"CreateMASCaseManager.closeMASCaseManager\");\n logger.info(\"ERROR: There is a mistake closing caseManager file.\\n\");\n }\n\n }", "public void incrementVersion(int node, long time) {\n if(node < 0 || node > Short.MAX_VALUE)\n throw new IllegalArgumentException(node\n + \" is outside the acceptable range of node ids.\");\n\n this.timestamp = time;\n\n Long version = versionMap.get((short) node);\n if(version == null) {\n version = 1L;\n } else {\n version = version + 1L;\n }\n\n versionMap.put((short) node, version);\n if(versionMap.size() >= MAX_NUMBER_OF_VERSIONS) {\n throw new IllegalStateException(\"Vector clock is full!\");\n }\n\n }", "@Override\n\tpublic void format(final StringBuffer sbuf, final LoggingEvent event) {\n\t\tfor (int i = 0; i < patternConverters.length; i++) {\n\t\t\tfinal int startField = sbuf.length();\n\t\t\tpatternConverters[i].format(event, sbuf);\n\t\t\tpatternFields[i].format(startField, sbuf);\n\t\t}\n\t}", "public Capsule newCapsule(String mode, Path wrappedJar) {\n final String oldMode = properties.getProperty(PROP_MODE);\n final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();\n Thread.currentThread().setContextClassLoader(capsuleClass.getClassLoader());\n try {\n setProperty(PROP_MODE, mode);\n\n final Constructor<?> ctor = accessible(capsuleClass.getDeclaredConstructor(Path.class));\n final Object capsule = ctor.newInstance(jarFile);\n\n if (wrappedJar != null) {\n final Method setTarget = accessible(capsuleClass.getDeclaredMethod(\"setTarget\", Path.class));\n setTarget.invoke(capsule, wrappedJar);\n }\n\n return wrap(capsule);\n } catch (ReflectiveOperationException e) {\n throw new RuntimeException(\"Could not create capsule instance.\", e);\n } finally {\n setProperty(PROP_MODE, oldMode);\n Thread.currentThread().setContextClassLoader(oldCl);\n }\n }", "public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster,\n final int greedyAttempts,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<Integer> greedySwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(greedySwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(greedySwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n for(int i = 0; i < greedyAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster,\n nodeIds,\n greedySwapMaxPartitionsPerNode,\n greedySwapMaxPartitionsPerZone,\n storeDefs);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (swap attempt \" + i + \" in zone \"\n + zoneIds.get(zoneIdOffset) + \")\");\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n return returnCluster;\n }", "public static appqoepolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tappqoepolicy[] response = (appqoepolicy[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}" ]
Visit all child nodes but not this one. @param visitor The visitor to use.
[ "public final void visitChildren(final Visitor visitor)\n\t{\n\t\tfor (final DiffNode child : children.values())\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tchild.visit(visitor);\n\t\t\t}\n\t\t\tcatch (final StopVisitationException e)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}" ]
[ "@RequestMapping(value = \"/api/backup\", method = RequestMethod.POST)\n public\n @ResponseBody\n Backup processBackup(@RequestParam(\"fileData\") MultipartFile fileData) throws Exception {\n // Method taken from: http://spring.io/guides/gs/uploading-files/\n if (!fileData.isEmpty()) {\n try {\n byte[] bytes = fileData.getBytes();\n BufferedOutputStream stream =\n new BufferedOutputStream(new FileOutputStream(new File(\"backup-uploaded.json\")));\n stream.write(bytes);\n stream.close();\n\n } catch (Exception e) {\n }\n }\n File f = new File(\"backup-uploaded.json\");\n BackupService.getInstance().restoreBackupData(new FileInputStream(f));\n return BackupService.getInstance().getBackupData();\n }", "@Override\n public void run() {\n ExecutorService executorService = Executors.newFixedThreadPool(maxClients);\n try {\n serverSocket = new ServerSocket(port, maxClients);\n while (!shuttingDown) {\n try {\n Socket socket = serverSocket.accept();\n debugConnection = new DebugConnection(socket);\n executorService.submit(debugConnection);\n } catch (SocketException e) {\n // closed\n debugConnection = null;\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n debugConnection = null;\n serverSocket.close();\n } catch (Exception e) {\n }\n executorService.shutdownNow();\n }\n }", "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 }", "public Map<String, String> getSitePath() {\n\n if (m_sitePaths == null) {\n m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object rootPath) {\n\n if (rootPath instanceof String) {\n return getRequestContext().removeSiteRoot((String)rootPath);\n }\n return null;\n }\n });\n }\n return m_sitePaths;\n }", "public static String getModuleVersion(final String moduleId) {\n final int splitter = moduleId.lastIndexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(splitter+1);\n }", "private void readTaskBaselines(Project.Tasks.Task xmlTask, Task mpxjTask, TimeUnit durationFormat)\n {\n for (Project.Tasks.Task.Baseline baseline : xmlTask.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n Double cost = DatatypeConverter.parseCurrency(baseline.getCost());\n Duration duration = DatatypeConverter.parseDuration(m_projectFile, durationFormat, baseline.getDuration());\n Date finish = baseline.getFinish();\n Date start = baseline.getStart();\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpxjTask.setBaselineCost(cost);\n mpxjTask.setBaselineDuration(duration);\n mpxjTask.setBaselineFinish(finish);\n mpxjTask.setBaselineStart(start);\n mpxjTask.setBaselineWork(work);\n }\n else\n {\n mpxjTask.setBaselineCost(number, cost);\n mpxjTask.setBaselineDuration(number, duration);\n mpxjTask.setBaselineFinish(number, finish);\n mpxjTask.setBaselineStart(number, start);\n mpxjTask.setBaselineWork(number, work);\n }\n }\n }", "protected PrintResult withOpenOutputStream(final PrintAction function) throws Exception {\n final File reportFile = getReportFile();\n final Processor.ExecutionContext executionContext;\n try (FileOutputStream out = new FileOutputStream(reportFile);\n BufferedOutputStream bout = new BufferedOutputStream(out)) {\n executionContext = function.run(bout);\n }\n return new PrintResult(reportFile.length(), executionContext);\n }", "protected void setupPivotInfo() {\n for( int col = 0; col < numCols; col++ ) {\n pivots[col] = col;\n double c[] = dataQR[col];\n double norm = 0;\n for( int row = 0; row < numRows; row++ ) {\n double element = c[row];\n norm += element*element;\n }\n normsCol[col] = norm;\n }\n }", "private static Predicate join(final String joinWord, final List<Predicate> preds) {\n return new Predicate() {\n public void init(AbstractSqlCreator creator) {\n for (Predicate p : preds) {\n p.init(creator);\n }\n }\n public String toSql() {\n StringBuilder sb = new StringBuilder()\n .append(\"(\");\n boolean first = true;\n for (Predicate p : preds) {\n if (!first) {\n sb.append(\" \").append(joinWord).append(\" \");\n }\n sb.append(p.toSql());\n first = false;\n }\n return sb.append(\")\").toString();\n }\n };\n }" ]
Create a new Date. To the last day.
[ "public static java.sql.Date newDate() {\n return new java.sql.Date((System.currentTimeMillis() / DAY_MILLIS) * DAY_MILLIS);\n }" ]
[ "private void printPropertyRecord(PrintStream out,\n\t\t\tPropertyRecord propertyRecord, PropertyIdValue propertyIdValue) {\n\n\t\tprintTerms(out, propertyRecord.propertyDocument, propertyIdValue, null);\n\n\t\tString datatype = \"Unknown\";\n\t\tif (propertyRecord.propertyDocument != null) {\n\t\t\tdatatype = getDatatypeLabel(propertyRecord.propertyDocument\n\t\t\t\t\t.getDatatype());\n\t\t}\n\n\t\tout.print(\",\"\n\t\t\t\t+ datatype\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.statementCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.itemCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.statementWithQualifierCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.qualifierCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.referenceCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ (propertyRecord.statementCount\n\t\t\t\t\t\t+ propertyRecord.qualifierCount + propertyRecord.referenceCount));\n\n\t\tprintRelatedProperties(out, propertyRecord);\n\n\t\tout.println(\"\");\n\t}", "public B set(String key, int value) {\n this.data.put(key, value);\n return (B) this;\n }", "public BoxFile.Info uploadFile(FileUploadParams uploadParams) {\n URL uploadURL = UPLOAD_FILE_URL.build(this.getAPI().getBaseUploadURL());\n BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL);\n\n JsonObject fieldJSON = new JsonObject();\n JsonObject parentIdJSON = new JsonObject();\n parentIdJSON.add(\"id\", getID());\n fieldJSON.add(\"name\", uploadParams.getName());\n fieldJSON.add(\"parent\", parentIdJSON);\n\n if (uploadParams.getCreated() != null) {\n fieldJSON.add(\"content_created_at\", BoxDateFormat.format(uploadParams.getCreated()));\n }\n\n if (uploadParams.getModified() != null) {\n fieldJSON.add(\"content_modified_at\", BoxDateFormat.format(uploadParams.getModified()));\n }\n\n if (uploadParams.getSHA1() != null && !uploadParams.getSHA1().isEmpty()) {\n request.setContentSHA1(uploadParams.getSHA1());\n }\n\n if (uploadParams.getDescription() != null) {\n fieldJSON.add(\"description\", uploadParams.getDescription());\n }\n\n request.putField(\"attributes\", fieldJSON.toString());\n\n if (uploadParams.getSize() > 0) {\n request.setFile(uploadParams.getContent(), uploadParams.getName(), uploadParams.getSize());\n } else if (uploadParams.getContent() != null) {\n request.setFile(uploadParams.getContent(), uploadParams.getName());\n } else {\n request.setUploadFileCallback(uploadParams.getUploadFileCallback(), uploadParams.getName());\n }\n\n BoxJSONResponse response;\n if (uploadParams.getProgressListener() == null) {\n response = (BoxJSONResponse) request.send();\n } else {\n response = (BoxJSONResponse) request.send(uploadParams.getProgressListener());\n }\n JsonObject collection = JsonObject.readFrom(response.getJSON());\n JsonArray entries = collection.get(\"entries\").asArray();\n JsonObject fileInfoJSON = entries.get(0).asObject();\n String uploadedFileID = fileInfoJSON.get(\"id\").asString();\n\n BoxFile uploadedFile = new BoxFile(getAPI(), uploadedFileID);\n return uploadedFile.new Info(fileInfoJSON);\n }", "public ContentAssistEntry createSnippet(final String proposal, final String label, final ContentAssistContext context) {\n final Procedure1<ContentAssistEntry> _function = (ContentAssistEntry it) -> {\n it.setLabel(label);\n };\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_SNIPPET, _function);\n }", "private boolean runQueuedTask(boolean hasPermit) {\n if (!hasPermit && beginRequest(paused) == RunResult.REJECTED) {\n return false;\n }\n QueuedTask task = null;\n if (!paused) {\n task = taskQueue.poll();\n } else {\n //the container is suspended, but we still need to run any force queued tasks\n task = findForcedTask();\n }\n if (task != null) {\n if(!task.runRequest()) {\n decrementRequestCount();\n }\n return true;\n } else {\n decrementRequestCount();\n return false;\n }\n }", "public static base_response unset(nitro_service client, ntpserver resource, String[] args) throws Exception{\n\t\tntpserver unsetresource = new ntpserver();\n\t\tunsetresource.serverip = resource.serverip;\n\t\tunsetresource.servername = resource.servername;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "boolean hasNoAlternativeWildcardRegistration() {\n return parent == null || PathElement.WILDCARD_VALUE.equals(valueString) || !parent.getChildNames().contains(PathElement.WILDCARD_VALUE);\n }", "public byte[] encrypt(byte[] plainData) {\n checkArgument(plainData.length >= OVERHEAD_SIZE,\n \"Invalid plainData, %s bytes\", plainData.length);\n\n // workBytes := initVector || payload || zeros:4\n byte[] workBytes = plainData.clone();\n ByteBuffer workBuffer = ByteBuffer.wrap(workBytes);\n boolean success = false;\n\n try {\n // workBytes := initVector || payload || I(signature)\n int signature = hmacSignature(workBytes);\n workBuffer.putInt(workBytes.length - SIGNATURE_SIZE, signature);\n // workBytes := initVector || E(payload) || I(signature)\n xorPayloadToHmacPad(workBytes);\n\n if (logger.isDebugEnabled()) {\n logger.debug(dump(\"Encrypted\", plainData, workBytes));\n }\n\n success = true;\n return workBytes;\n } finally {\n if (!success && logger.isDebugEnabled()) {\n logger.debug(dump(\"Encrypted (failed)\", plainData, workBytes));\n }\n }\n }", "@Override\n public Object invoke(Object self, Method method, Method proceed, Object[] args) throws Throwable {\n if (\"destroy\".equals(method.getName()) && Marker.isMarker(0, method, args)) {\n if (bean.getEjbDescriptor().isStateful()) {\n if (!reference.isRemoved()) {\n reference.remove();\n }\n }\n return null;\n }\n\n if (!bean.isClientCanCallRemoveMethods() && isRemoveMethod(method)) {\n throw BeanLogger.LOG.invalidRemoveMethodInvocation(method);\n }\n Class<?> businessInterface = getBusinessInterface(method);\n if (reference.isRemoved() && isToStringMethod(method)) {\n return businessInterface.getName() + \" [REMOVED]\";\n }\n Object proxiedInstance = reference.getBusinessObject(businessInterface);\n\n if (!Modifier.isPublic(method.getModifiers())) {\n throw new EJBException(\"Not a business method \" + method.toString() +\". Do not call non-public methods on EJB's.\");\n }\n Object returnValue = Reflections.invokeAndUnwrap(proxiedInstance, method, args);\n BeanLogger.LOG.callProxiedMethod(method, proxiedInstance, args, returnValue);\n return returnValue;\n }" ]
Changes the given filenames suffix from the current suffix to the provided suffix. <b>Directly exposed for JSP EL</b>, not through {@link org.opencms.jsp.util.CmsJspElFunctions}.<p> @param filename the filename to be changed @param suffix the new suffix of the file @return the filename with the replaced suffix
[ "public static String changeFileNameSuffixTo(String filename, String suffix) {\n\n int dotPos = filename.lastIndexOf('.');\n if (dotPos != -1) {\n return filename.substring(0, dotPos + 1) + suffix;\n } else {\n // the string has no suffix\n return filename;\n }\n }" ]
[ "public static java.util.Date getDateTime(Object value) {\n try {\n return toDateTime(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "public static boolean containsOnlyNotNull(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}", "public static boolean pushImage(Launcher launcher, final JenkinsBuildInfoLog log, final String imageTag, final String username, final String password, final String host)\n throws IOException, InterruptedException {\n\n return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n String message = \"Pushing image: \" + imageTag;\n if (StringUtils.isNotEmpty(host)) {\n message += \" using docker daemon host: \" + host;\n }\n\n log.info(message);\n DockerUtils.pushImage(imageTag, username, password, host);\n return true;\n }\n });\n }", "private ArrayList<RunListener> instantiateRunListeners() throws Exception {\n ArrayList<RunListener> instances = new ArrayList<>();\n\n if (runListeners != null) {\n for (String className : Arrays.asList(runListeners.split(\",\"))) {\n instances.add((RunListener) this.instantiate(className).newInstance());\n }\n }\n\n return instances;\n }", "int getDelay(int n) {\n int delay = -1;\n if ((n >= 0) && (n < header.frameCount)) {\n delay = header.frames.get(n).delay;\n }\n return delay;\n }", "private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException {\n\t\tif (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultSvgDocument document = new DefaultSvgDocument(writer, false);\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer()));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new SvgTileWriter());\n\t\t\treturn document;\n\t\t} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultVmlDocument document = new DefaultVmlDocument(writer);\n\t\t\tint coordWidth = tile.getScreenWidth();\n\t\t\tint coordHeight = tile.getScreenHeight();\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,\n\t\t\t\t\tcoordHeight));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight));\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\treturn document;\n\t\t} else {\n\t\t\tthrow new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);\n\t\t}\n\t}", "private ClassDescriptor[] getMultiJoinedClassDescriptors(ClassDescriptor cld)\r\n {\r\n DescriptorRepository repository = cld.getRepository();\r\n Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, true);\r\n ClassDescriptor[] result = new ClassDescriptor[multiJoinedClasses.length];\r\n\r\n for (int i = 0 ; i < multiJoinedClasses.length; i++)\r\n {\r\n result[i] = repository.getDescriptorFor(multiJoinedClasses[i]);\r\n }\r\n\r\n return result;\r\n }", "public static Node addPartitionsToNode(final Node node, final Set<Integer> donatedPartitions) {\n List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());\n deepCopy.addAll(donatedPartitions);\n Collections.sort(deepCopy);\n return updateNode(node, deepCopy);\n }", "public List<CRFCliqueTree> getCliqueTrees(String filename, DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n List<CRFCliqueTree> cts = new ArrayList<CRFCliqueTree>();\r\n ObjectBank<List<IN>> docs = makeObjectBankFromFile(filename, readerAndWriter);\r\n for (List<IN> doc : docs) {\r\n cts.add(getCliqueTree(doc));\r\n }\r\n\r\n return cts;\r\n }" ]
Add a cause to the backtrace. @param cause the cause @param bTrace the backtrace list
[ "private static void addCauseToBacktrace(final Throwable cause, final List<String> bTrace) {\n if (cause.getMessage() == null) {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName());\n } else {\n bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName() + \": \" + cause.getMessage());\n }\n for (final StackTraceElement ste : cause.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (cause.getCause() != null) {\n addCauseToBacktrace(cause.getCause(), bTrace);\n }\n }" ]
[ "public static void start(final GVRContext context, final String appId, final ResultListener listener) {\n if (null == listener) {\n throw new IllegalArgumentException(\"listener cannot be null\");\n }\n\n final Activity activity = context.getActivity();\n final long result = create(activity, appId);\n if (0 != result) {\n throw new IllegalStateException(\"Could not initialize the platform sdk; error code: \" + result);\n }\n\n context.registerDrawFrameListener(new GVRDrawFrameListener() {\n @Override\n public void onDrawFrame(float frameTime) {\n final int result = processEntitlementCheckResponse();\n if (0 != result) {\n context.unregisterDrawFrameListener(this);\n\n final Runnable runnable;\n if (-1 == result) {\n runnable = new Runnable() {\n @Override\n public void run() {\n listener.onFailure();\n }\n };\n } else {\n runnable = new Runnable() {\n @Override\n public void run() {\n listener.onSuccess();\n }\n };\n }\n activity.runOnUiThread(runnable);\n }\n }\n });\n }", "public static PersistenceBroker createPersistenceBroker(String jcdAlias,\r\n String user,\r\n String password) throws PBFactoryException\r\n {\r\n return PersistenceBrokerFactoryFactory.instance().\r\n createPersistenceBroker(jcdAlias, user, password);\r\n }", "public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment){\n\t\t\tdouble minDistance = Double.MAX_VALUE;\n\t\t\tPoint2D.Double minDistancePoint = null;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/nPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < nPointsPerSegment; j++){\n\t\t \t\tPoint2D.Double candidate = new Point2D.Double(x, spline.value(x));\n\t\t \t\tdouble d = p.distance(candidate);\n\t\t \t\tif(d<minDistance){\n\t\t \t\t\tminDistance = d;\n\t\t \t\t\tminDistancePoint = candidate;\n\t\t \t\t}\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t return minDistancePoint;\n\t}", "public String getString(Integer type)\n {\n String result = null;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = m_data.getString(getOffset(item));\n }\n\n return (result);\n }", "public void signOff(WebSocketConnection connection) {\n for (ConcurrentMap<WebSocketConnection, WebSocketConnection> connections : registry.values()) {\n connections.remove(connection);\n }\n }", "private String getProjectName() {\n String pName = Strings.emptyToNull(projectName);\n if (pName == null) { \n pName = Strings.emptyToNull(junit4.getProject().getName());\n }\n if (pName == null) {\n pName = \"(unnamed project)\"; \n }\n return pName;\n }", "private Date getTime(String value) throws MPXJException\n {\n try\n {\n Number hours = m_twoDigitFormat.parse(value.substring(0, 2));\n Number minutes = m_twoDigitFormat.parse(value.substring(2, 4));\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, hours.intValue());\n cal.set(Calendar.MINUTE, minutes.intValue());\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 time \" + value, ex);\n }\n }", "public static int[] arrayFromStringOfIntegers(String str) throws IllegalArgumentException {\n StringTokenizer tokenizer = new StringTokenizer(str, \",\");\n int n = tokenizer.countTokens();\n int[] list = new int[n];\n for (int i = 0; i < n; i++) {\n String token = tokenizer.nextToken();\n list[i] = Integer.parseInt(token);\n }\n return list;\n }", "@Override\n protected void initBuilderSpecific() throws Exception {\n reset();\n FilePath workspace = getModuleRoot(EnvVars.masterEnvVars);\n FilePath gradlePropertiesPath = new FilePath(workspace, \"gradle.properties\");\n if (releaseProps == null) {\n releaseProps = PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getReleaseProperties());\n }\n if (nextIntegProps == null) {\n nextIntegProps =\n PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getNextIntegProperties());\n }\n }" ]
Use this API to fetch all the sslfipskey resources that are configured on netscaler.
[ "public static sslfipskey[] get(nitro_service service) throws Exception{\n\t\tsslfipskey obj = new sslfipskey();\n\t\tsslfipskey[] response = (sslfipskey[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public ItemRequest<Task> addSubtask(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public boolean link(D declaration, ServiceReference<S> declarationBinderRef) {\n S declarationBinder = bindersManager.getDeclarationBinder(declarationBinderRef);\n LOG.debug(declaration + \" match the filter of \" + declarationBinder + \" : bind them together\");\n declaration.bind(declarationBinderRef);\n try {\n declarationBinder.addDeclaration(declaration);\n } catch (Exception e) {\n declaration.unbind(declarationBinderRef);\n LOG.debug(declarationBinder + \" throw an exception when giving to it the Declaration \"\n + declaration, e);\n return false;\n }\n return true;\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 FormValidation validateEmails(String emails) {\n if (!Strings.isNullOrEmpty(emails)) {\n String[] recipients = StringUtils.split(emails, \" \");\n for (String email : recipients) {\n FormValidation validation = validateInternetAddress(email);\n if (validation != FormValidation.ok()) {\n return validation;\n }\n }\n }\n return FormValidation.ok();\n }", "@Modified(id = \"importerServices\")\n void modifiedImporterService(ServiceReference<ImporterService> serviceReference) {\n try {\n importersManager.modified(serviceReference);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.error(\"The ServiceProperty \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" of the ImporterService \"\n + bundleContext.getService(serviceReference) + \" doesn't provides a valid Filter.\"\n + \" To be used, it must provides a correct \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" ServiceProperty.\",\n invalidFilterException\n );\n importersManager.removeLinks(serviceReference);\n return;\n }\n if (importersManager.matched(serviceReference)) {\n importersManager.updateLinks(serviceReference);\n } else {\n importersManager.removeLinks(serviceReference);\n }\n }", "public static long count(nitro_service service, String id) throws Exception{\n\t\tlinkset_interface_binding obj = new linkset_interface_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tlinkset_interface_binding response[] = (linkset_interface_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 process(SearchDistributor distributor) {\r\n List<PossibleState> bootStrap;\r\n try {\r\n bootStrap = bfs(bootStrapMin);\r\n } catch (ModelException e) {\r\n bootStrap = new LinkedList<>();\r\n }\n\r\n List<Frontier> frontiers = new LinkedList<>();\r\n for (PossibleState p : bootStrap) {\r\n SCXMLFrontier dge = new SCXMLFrontier(p, model, tagExtensionList);\r\n frontiers.add(dge);\r\n }\n\r\n distributor.distribute(frontiers);\r\n }", "public List<Action> getRootActions() {\n\t\tfinal List<Action> rootActions = srcUpdTrees.stream().map(t -> originalActionsSrc.get(t))\n\t\t\t\t.collect(Collectors.toList());\n\n\t\trootActions.addAll(srcDelTrees.stream() //\n\t\t\t\t.filter(t -> !srcDelTrees.contains(t.getParent()) && !srcUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsSrc.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstAddTrees.stream() //\n\t\t\t\t.filter(t -> !dstAddTrees.contains(t.getParent()) && !dstUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstMvTrees.stream() //\n\t\t\t\t.filter(t -> !dstMvTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.removeAll(Collections.singleton(null));\n\t\treturn rootActions;\n\t}", "private static void loadFile(String filePath) {\n final Path path = FileSystems.getDefault().getPath(filePath);\n\n try {\n data.clear();\n data.load(Files.newBufferedReader(path));\n } catch(IOException e) {\n LOG.warn(\"Exception while loading \" + path.toString(), e);\n }\n }" ]
Process a text-based PP file. @param inputStream file input stream @return ProjectFile instance
[ "private ProjectFile readTextFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaTextFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }" ]
[ "@Override public void setUniqueID(Integer uniqueID)\n {\n ProjectFile parent = getParentFile();\n\n if (m_uniqueID != null)\n {\n parent.getCalendars().unmapUniqueID(m_uniqueID);\n }\n\n parent.getCalendars().mapUniqueID(uniqueID, this);\n\n m_uniqueID = uniqueID;\n }", "public void syncInternalStateFromFileSystem(boolean alsoSyncRemoteState) {\n // Make sure versions missing from the file-system are cleaned up from the internal state\n for (Long version: versionToEnabledMap.keySet()) {\n File[] existingVersionDirs = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (existingVersionDirs.length == 0) {\n removeVersion(version, alsoSyncRemoteState);\n }\n }\n\n // Make sure we have all versions on the file-system in the internal state\n File[] versionDirs = ReadOnlyUtils.getVersionDirs(rootDir);\n if (versionDirs != null) {\n for (File versionDir: versionDirs) {\n long versionNumber = ReadOnlyUtils.getVersionId(versionDir);\n boolean versionEnabled = isVersionEnabled(versionDir);\n versionToEnabledMap.put(versionNumber, versionEnabled);\n }\n }\n\n // Identify the current version (based on a symlink in the file-system)\n File currentVersionDir = ReadOnlyUtils.getCurrentVersion(rootDir);\n if (currentVersionDir != null) {\n currentVersion = ReadOnlyUtils.getVersionId(currentVersionDir);\n } else {\n currentVersion = -1; // Should we throw instead?\n }\n\n logger.info(\"Successfully synced internal state from local file-system: \" + this.toString());\n }", "protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) {\r\n Map<String, AbstractServer> srvc = new HashMap<>();\r\n for (ServerSetup setup : config) {\r\n if (srvc.containsKey(setup.getProtocol())) {\r\n throw new IllegalArgumentException(\"Server '\" + setup.getProtocol() + \"' was found at least twice in the array\");\r\n }\r\n final String protocol = setup.getProtocol();\r\n if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) {\r\n srvc.put(protocol, new SmtpServer(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) {\r\n srvc.put(protocol, new Pop3Server(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) {\r\n srvc.put(protocol, new ImapServer(setup, mgr));\r\n }\r\n }\r\n return srvc;\r\n }", "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 static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) {\n\t\tSet<Class<?>> entities = new HashSet<Class<?>>();\n\t\t//first build the \"entities\" set containing all indexed subtypes of \"selection\".\n\t\tfor ( Class<?> entityType : selection ) {\n\t\t\tIndexedTypeSet targetedClasses = extendedIntegrator.getIndexedTypesPolymorphic( IndexedTypeSets.fromClass( entityType ) );\n\t\t\tif ( targetedClasses.isEmpty() ) {\n\t\t\t\tString msg = entityType.getName() + \" is not an indexed entity or a subclass of an indexed entity\";\n\t\t\t\tthrow new IllegalArgumentException( msg );\n\t\t\t}\n\t\t\tentities.addAll( targetedClasses.toPojosSet() );\n\t\t}\n\t\tSet<Class<?>> cleaned = new HashSet<Class<?>>();\n\t\tSet<Class<?>> toRemove = new HashSet<Class<?>>();\n\t\t//now remove all repeated types to avoid duplicate loading by polymorphic query loading\n\t\tfor ( Class<?> type : entities ) {\n\t\t\tboolean typeIsOk = true;\n\t\t\tfor ( Class<?> existing : cleaned ) {\n\t\t\t\tif ( existing.isAssignableFrom( type ) ) {\n\t\t\t\t\ttypeIsOk = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( type.isAssignableFrom( existing ) ) {\n\t\t\t\t\ttoRemove.add( existing );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( typeIsOk ) {\n\t\t\t\tcleaned.add( type );\n\t\t\t}\n\t\t}\n\t\tcleaned.removeAll( toRemove );\n\t\tlog.debugf( \"Targets for indexing job: %s\", cleaned );\n\t\treturn IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) );\n\t}", "public void begin(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n data = new TimingData(key);\n executionInfo.put(key, data);\n }\n data.begin();\n }", "private Object runWithPossibleProxySwap(Method method, Object target, Object[] args)\n\t\t\tthrows IllegalAccessException, InvocationTargetException {\n\t\tObject result;\n\t\t// swap with proxies to these too.\n\t\tif (method.getName().equals(\"createStatement\")){\n\t\t\tresult = memorize((Statement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse if (method.getName().equals(\"prepareStatement\")){\n\t\t\tresult = memorize((PreparedStatement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse if (method.getName().equals(\"prepareCall\")){\n\t\t\tresult = memorize((CallableStatement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse result = method.invoke(target, args);\n\t\treturn result;\n\t}", "public void alias( double value , String name ) {\n if( isReserved(name))\n throw new RuntimeException(\"Reserved word or contains a reserved character. '\"+name+\"'\");\n\n VariableDouble old = (VariableDouble)variables.get(name);\n if( old == null ) {\n variables.put(name, new VariableDouble(value));\n }else {\n old.value = value;\n }\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 }" ]
Find the the qualified container port of the target service Uses java annotations first or returns the container port. @param service The target service. @param qualifiers The set of qualifiers. @return Returns the resolved containerPort of '0' as a fallback.
[ "private static int getPort(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Port) {\n Port port = (Port) q;\n if (port.value() > 0) {\n return port.value();\n }\n }\n }\n\n ServicePort servicePort = findQualifiedServicePort(service, qualifiers);\n if (servicePort != null) {\n return servicePort.getPort();\n }\n return 0;\n }" ]
[ "private boolean initCheckTypeModifiers() {\n\n Class<?> classInfoclass = Reflections.loadClass(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader()));\n if (classInfoclass != null) {\n try {\n Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(classInfoclass, \"setFlags\", short.class));\n return setFlags != null;\n } catch (Exception exceptionIgnored) {\n BootstrapLogger.LOG.usingOldJandexVersion();\n return false;\n }\n } else {\n return true;\n }\n }", "private static void multBlockAdd( double []blockA, double []blockB, double []blockC,\n final int m, final int n, final int o,\n final int blockLength ) {\n// for( int i = 0; i < m; i++ ) {\n// for( int j = 0; j < o; j++ ) {\n// double val = 0;\n// for( int k = 0; k < n; k++ ) {\n// val += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];\n// }\n//\n// blockC[ i*blockLength + j] += val;\n// }\n// }\n\n// int rowA = 0;\n// for( int i = 0; i < m; i++ , rowA += blockLength) {\n// for( int j = 0; j < o; j++ ) {\n// double val = 0;\n// int indexB = j;\n// int indexA = rowA;\n// int end = indexA + n;\n// for( ; indexA != end; indexA++ , indexB += blockLength ) {\n// val += blockA[ indexA ]*blockB[ indexB ];\n// }\n//\n// blockC[ rowA + j] += val;\n// }\n// }\n\n// for( int k = 0; k < n; k++ ) {\n// for( int i = 0; i < m; i++ ) {\n// for( int j = 0; j < o; j++ ) {\n// blockC[ i*blockLength + j] += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];\n// }\n// }\n// }\n\n for( int k = 0; k < n; k++ ) {\n int rowB = k*blockLength;\n int endB = rowB+o;\n for( int i = 0; i < m; i++ ) {\n int indexC = i*blockLength;\n double valA = blockA[ indexC + k];\n int indexB = rowB;\n \n while( indexB != endB ) {\n blockC[ indexC++ ] += valA*blockB[ indexB++];\n }\n }\n }\n }", "public static int cudnnConvolutionForward(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n cudnnFilterDescriptor wDesc, \n Pointer w, \n cudnnConvolutionDescriptor convDesc, \n int algo, \n Pointer workSpace, \n long workSpaceSizeInBytes, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnConvolutionForwardNative(handle, alpha, xDesc, x, wDesc, w, convDesc, algo, workSpace, workSpaceSizeInBytes, beta, yDesc, y));\n }", "public void diffUpdate(List<T> newList) {\n if (getCollection().size() == 0) {\n addAll(newList);\n notifyDataSetChanged();\n } else {\n DiffCallback diffCallback = new DiffCallback(collection, newList);\n DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);\n clear();\n addAll(newList);\n diffResult.dispatchUpdatesTo(this);\n }\n }", "public IntBuffer getIntVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n IntBuffer data = buffer.asIntBuffer();\n if (!NativeVertexBuffer.getIntVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }", "@SuppressWarnings(\"deprecation\")\n private void cancelRequestAndWorkerOnHost(List<String> targetHosts) {\n\n List<String> validTargetHosts = new ArrayList<String>(workers.keySet());\n validTargetHosts.retainAll(targetHosts);\n logger.info(\"targetHosts for cancel: Total: {}\"\n + \" Valid in current manager with worker threads: {}\",\n targetHosts.size(), validTargetHosts.size());\n\n for (String targetHost : validTargetHosts) {\n\n ActorRef worker = workers.get(targetHost);\n\n if (worker != null && !worker.isTerminated()) {\n worker.tell(OperationWorkerMsgType.CANCEL, getSelf());\n logger.info(\"Submitted CANCEL request on Host {}\", targetHost);\n } else {\n logger.info(\n \"Did NOT Submitted \"\n + \"CANCEL request on Host {} as worker on this host is null or already killed\",\n targetHost);\n }\n\n }\n\n }", "private void setVerticalScrollbar(final CmsScrollBar scrollbar, int width) {\r\n\r\n // Validate.\r\n if ((scrollbar == m_scrollbar) || (scrollbar == null)) {\r\n return;\r\n }\r\n // Detach new child.\r\n\r\n scrollbar.asWidget().removeFromParent();\r\n // Remove old child.\r\n if (m_scrollbar != null) {\r\n if (m_verticalScrollbarHandlerRegistration != null) {\r\n m_verticalScrollbarHandlerRegistration.removeHandler();\r\n m_verticalScrollbarHandlerRegistration = null;\r\n }\r\n remove(m_scrollbar);\r\n }\r\n m_scrollLayer.appendChild(scrollbar.asWidget().getElement());\r\n adopt(scrollbar.asWidget());\r\n\r\n // Logical attach.\r\n m_scrollbar = scrollbar;\r\n m_verticalScrollbarWidth = width;\r\n\r\n // Initialize the new scrollbar.\r\n m_verticalScrollbarHandlerRegistration = scrollbar.addValueChangeHandler(new ValueChangeHandler<Integer>() {\r\n\r\n public void onValueChange(ValueChangeEvent<Integer> event) {\r\n\r\n int vPos = scrollbar.getVerticalScrollPosition();\r\n int v = getVerticalScrollPosition();\r\n if (v != vPos) {\r\n setVerticalScrollPosition(vPos);\r\n }\r\n\r\n }\r\n });\r\n maybeUpdateScrollbars();\r\n }", "@Override\n synchronized public V put(K key, V value) {\n V oldValue = this.get(key);\n try {\n super.put(key, value);\n writeBack(key, value);\n return oldValue;\n } catch(Exception e) {\n super.put(key, oldValue);\n writeBack(key, oldValue);\n throw new VoldemortException(\"Failed to put(\" + key + \", \" + value\n + \") in write through cache\", e);\n }\n }", "private void processCustomValueLists() throws IOException\n {\n CustomFieldValueReader9 reader = new CustomFieldValueReader9(m_projectDir, m_file.getProjectProperties(), m_projectProps, m_file.getCustomFields());\n reader.process();\n }" ]
Kicks off an animation that will result in the pointer being centered in the pie slice of the currently selected item.
[ "private void centerOnCurrentItem() {\n if(!mPieData.isEmpty()) {\n PieModel current = mPieData.get(getCurrentItem());\n int targetAngle;\n\n if(mOpenClockwise) {\n targetAngle = (mIndicatorAngle - current.getStartAngle()) - ((current.getEndAngle() - current.getStartAngle()) / 2);\n if (targetAngle < 0 && mPieRotation > 0) targetAngle += 360;\n }\n else {\n targetAngle = current.getStartAngle() + (current.getEndAngle() - current.getStartAngle()) / 2;\n targetAngle += mIndicatorAngle;\n if (targetAngle > 270 && mPieRotation < 90) targetAngle -= 360;\n }\n\n mAutoCenterAnimator.setIntValues(targetAngle);\n mAutoCenterAnimator.setDuration(AUTOCENTER_ANIM_DURATION).start();\n\n }\n }" ]
[ "public T addFile(final String name, final List<String> path, final byte[] newHash, final boolean isDirectory) {\n return addFile(name, path, newHash, isDirectory, null);\n }", "protected void setInputElementValue(Node element, FormInput input) {\n\n\t\tLOGGER.debug(\"INPUTFIELD: {} ({})\", input.getIdentification(), input.getType());\n\t\tif (element == null || input.getInputValues().isEmpty()) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\n\t\t\tswitch (input.getType()) {\n\t\t\t\tcase TEXT:\n\t\t\t\tcase TEXTAREA:\n\t\t\t\tcase PASSWORD:\n\t\t\t\t\thandleText(input);\n\t\t\t\t\tbreak;\n\t\t\t\tcase HIDDEN:\n\t\t\t\t\thandleHidden(input);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHECKBOX:\n\t\t\t\t\thandleCheckBoxes(input);\n\t\t\t\t\tbreak;\n\t\t\t\tcase RADIO:\n\t\t\t\t\thandleRadioSwitches(input);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SELECT:\n\t\t\t\t\thandleSelectBoxes(input);\n\t\t\t}\n\n\t\t} catch (ElementNotVisibleException e) {\n\t\t\tLOGGER.warn(\"Element not visible, input not completed.\");\n\t\t} catch (BrowserConnectionException e) {\n\t\t\tthrow e;\n\t\t} catch (RuntimeException e) {\n\t\t\tLOGGER.error(\"Could not input element values\", e);\n\t\t}\n\t}", "public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\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 }", "private void updateMaxMin(IntervalRBTreeNode<T> n, IntervalRBTreeNode<T> c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n if (n.min > c.min) {\n n.min = c.min;\n }\n }\n }", "public void process(String name) throws Exception\n {\n ProjectFile file = new UniversalProjectReader().read(name);\n for (Task task : file.getTasks())\n {\n if (!task.getSummary())\n {\n System.out.print(task.getWBS());\n System.out.print(\"\\t\");\n System.out.print(task.getName());\n System.out.print(\"\\t\");\n System.out.print(format(task.getStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getFinish()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualFinish()));\n System.out.println();\n }\n }\n }", "private static List<Integer> stripNodeIds(List<Node> nodeList) {\n List<Integer> nodeidList = new ArrayList<Integer>();\n if(nodeList != null) {\n for(Node node: nodeList) {\n nodeidList.add(node.getId());\n }\n }\n return nodeidList;\n }", "private static JsonArray toJsonArray(Collection<String> values) {\n JsonArray array = new JsonArray();\n for (String value : values) {\n array.add(value);\n }\n return array;\n\n }", "void createDirectory(Path path) throws IOException {\n\t\tif (Files.exists(path) && Files.isDirectory(path)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.readOnly) {\n\t\t\tthrow new FileNotFoundException(\n\t\t\t\t\t\"The requested directory \\\"\"\n\t\t\t\t\t\t\t+ path.toString()\n\t\t\t\t\t\t\t+ \"\\\" does not exist and we are in read-only mode, so it cannot be created.\");\n\t\t}\n\n\t\tFiles.createDirectory(path);\n\t}" ]
Sets the last operation response. @param response the last operation response.
[ "PollingState<T> withResponse(Response<ResponseBody> response) {\n this.response = response;\n withPollingUrlFromResponse(response);\n withPollingRetryTimeoutFromResponse(response);\n return this;\n }" ]
[ "protected StrongCounter getCounterOrCreateIt(String counterName, int initialValue) {\n\t\tCounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager( cacheManager );\n\t\tif ( !counterManager.isDefined( counterName ) ) {\n\t\t\tLOG.tracef( \"Counter %s is not defined, creating it\", counterName );\n\n\t\t\t// global configuration is mandatory in order to define\n\t\t\t// a new clustered counter with persistent storage\n\t\t\tvalidateGlobalConfiguration();\n\n\t\t\tcounterManager.defineCounter( counterName,\n\t\t\t\tCounterConfiguration.builder(\n\t\t\t\t\tCounterType.UNBOUNDED_STRONG )\n\t\t\t\t\t\t.initialValue( initialValue )\n\t\t\t\t\t\t.storage( Storage.PERSISTENT )\n\t\t\t\t\t\t.build() );\n\t\t}\n\n\t\tStrongCounter strongCounter = counterManager.getStrongCounter( counterName );\n\t\treturn strongCounter;\n\t}", "private XopBean createXopBean() throws Exception {\n XopBean xop = new XopBean();\n xop.setName(\"xopName\");\n \n InputStream is = getClass().getResourceAsStream(\"/java.jpg\");\n byte[] data = IOUtils.readBytesFromStream(is);\n \n // Pass java.jpg as an array of bytes\n xop.setBytes(data);\n \n // Wrap java.jpg as a DataHandler\n xop.setDatahandler(new DataHandler(\n new ByteArrayDataSource(data, \"application/octet-stream\")));\n \n if (Boolean.getBoolean(\"java.awt.headless\")) {\n System.out.println(\"Running headless. Ignoring an Image property.\");\n } else {\n xop.setImage(getImage(\"/java.jpg\"));\n }\n \n return xop;\n }", "public static inatparam get(nitro_service service) throws Exception{\n\t\tinatparam obj = new inatparam();\n\t\tinatparam[] response = (inatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static appfwhtmlerrorpage get(nitro_service service, options option) throws Exception{\n\t\tappfwhtmlerrorpage obj = new appfwhtmlerrorpage();\n\t\tappfwhtmlerrorpage[] response = (appfwhtmlerrorpage[])obj.get_resources(service,option);\n\t\treturn response[0];\n\t}", "@NotNull\n static MetaTreeImpl.Proto saveMetaTree(@NotNull final ITreeMutable metaTree,\n @NotNull final EnvironmentImpl env,\n @NotNull final ExpiredLoggableCollection expired) {\n final long newMetaTreeAddress = metaTree.save();\n final Log log = env.getLog();\n final int lastStructureId = env.getLastStructureId();\n final long dbRootAddress = log.write(DatabaseRoot.DATABASE_ROOT_TYPE, Loggable.NO_STRUCTURE_ID,\n DatabaseRoot.asByteIterable(newMetaTreeAddress, lastStructureId));\n expired.add(dbRootAddress, (int) (log.getWrittenHighAddress() - dbRootAddress));\n return new MetaTreeImpl.Proto(newMetaTreeAddress, dbRootAddress);\n }", "public static auditsyslogpolicy_aaauser_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_aaauser_binding obj = new auditsyslogpolicy_aaauser_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_aaauser_binding response[] = (auditsyslogpolicy_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public DynamicReportBuilder setTemplateFile(String path, boolean importFields, boolean importVariables, boolean importParameters, boolean importDatasets) {\n report.setTemplateFileName(path);\n report.setTemplateImportFields(importFields);\n report.setTemplateImportParameters(importParameters);\n report.setTemplateImportVariables(importVariables);\n report.setTemplateImportDatasets(importDatasets);\n return this;\n }", "public void flipBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n data[word] ^= (1 << offset);\n }", "protected void writePropertiesToLog(Logger logger, Level level) {\n writeToLog(logger, level, getMapAsString(this.properties, separator), null);\n\n if (this.exception != null) {\n writeToLog(this.logger, Level.ERROR, \"Error:\", this.exception);\n }\n }" ]
Computes the product of the diagonal elements. For a diagonal or triangular matrix this is the determinant. @param T A matrix. @return product of the diagonal elements.
[ "public static double diagProd( DMatrix1Row T )\n {\n double prod = 1.0;\n int N = Math.min(T.numRows,T.numCols);\n for( int i = 0; i < N; i++ ) {\n prod *= T.unsafe_get(i,i);\n }\n\n return prod;\n }" ]
[ "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerFilters(List<AlgoliaFilter> filters) {\n for (final AlgoliaFilter filter : filters) {\n searcher.addFacet(filter.getAttribute());\n }\n }", "public static String[] copyArrayAddFirst(String[] arr, String add) {\n String[] arrCopy = new String[arr.length + 1];\n arrCopy[0] = add;\n System.arraycopy(arr, 0, arrCopy, 1, arr.length);\n return arrCopy;\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 }", "public static systementitydata[] get(nitro_service service, systementitydata_args args) throws Exception{\n\t\tsystementitydata obj = new systementitydata();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsystementitydata[] response = (systementitydata[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public static boolean isRegularQueue(final Jedis jedis, final String key) {\n return LIST.equalsIgnoreCase(jedis.type(key));\n }", "public long removeRangeByScore(final ScoreRange scoreRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zremrangeByScore(getKey(), scoreRange.from(), scoreRange.to());\n }\n });\n }", "public static String roundCorner(int radiusInner, int radiusOuter, int color) {\n if (radiusInner < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radiusOuter < 0) {\n throw new IllegalArgumentException(\"Outer radius must be greater than or equal to zero.\");\n }\n StringBuilder builder = new StringBuilder(FILTER_ROUND_CORNER).append(\"(\").append(radiusInner);\n if (radiusOuter > 0) {\n builder.append(\"|\").append(radiusOuter);\n }\n final int r = (color & 0xFF0000) >>> 16;\n final int g = (color & 0xFF00) >>> 8;\n final int b = color & 0xFF;\n return builder.append(\",\") //\n .append(r).append(\",\") //\n .append(g).append(\",\") //\n .append(b).append(\")\") //\n .toString();\n }", "private TrackMetadata requestMetadataInternal(final DataReference track, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n // First check if we are using cached data for this request.\n MetadataCache cache = getMetadataCache(SlotReference.getSlotReference(track));\n if (cache != null && trackType == CdjStatus.TrackType.REKORDBOX) {\n return cache.getTrackMetadata(null, track);\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = getMediaDetailsFor(track.getSlotReference());\n if (sourceDetails != null) {\n final TrackMetadata provided = allMetadataProviders.getTrackMetadata(sourceDetails, track);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (passive.get() && failIfPassive && track.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // Use the dbserver protocol implementation to request the metadata.\n ConnectionManager.ClientTask<TrackMetadata> task = new ConnectionManager.ClientTask<TrackMetadata>() {\n @Override\n public TrackMetadata useClient(Client client) throws Exception {\n return queryMetadata(track, trackType, client);\n }\n };\n\n try {\n return ConnectionManager.getInstance().invokeWithClientSession(track.player, task, \"requesting metadata\");\n } catch (Exception e) {\n logger.error(\"Problem requesting metadata, returning null\", e);\n }\n return null;\n }", "public User getLimits() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIMITS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n NodeList photoNodes = userElement.getElementsByTagName(\"photos\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element plElement = (Element) photoNodes.item(i);\r\n PhotoLimits pl = new PhotoLimits();\r\n user.setPhotoLimits(pl);\r\n pl.setMaxDisplay(plElement.getAttribute(\"maxdisplaypx\"));\r\n pl.setMaxUpload(plElement.getAttribute(\"maxupload\"));\r\n }\r\n NodeList videoNodes = userElement.getElementsByTagName(\"videos\");\r\n for (int i = 0; i < videoNodes.getLength(); i++) {\r\n Element vlElement = (Element) videoNodes.item(i);\r\n VideoLimits vl = new VideoLimits();\r\n user.setPhotoLimits(vl);\r\n vl.setMaxDuration(vlElement.getAttribute(\"maxduration\"));\r\n vl.setMaxUpload(vlElement.getAttribute(\"maxupload\"));\r\n }\r\n return user;\r\n }" ]
Tokenize the the string as a package hierarchy @param str @return
[ "static String[] tokenize(String str) {\n char sep = '.';\n int start = 0;\n int len = str.length();\n int count = 0;\n for (int pos = 0; pos < len; pos++) {\n if (str.charAt(pos) == sep) {\n if (pos != start) {\n count++;\n }\n start = pos + 1;\n }\n }\n if (len != start) {\n count++;\n }\n String[] l = new String[count];\n\n count = 0;\n start = 0;\n for (int pos = 0; pos < len; pos++) {\n if (str.charAt(pos) == sep) {\n if (pos != start) {\n String tok = str.substring(start, pos);\n l[count++] = tok;\n }\n start = pos + 1;\n }\n }\n if (len != start) {\n String tok = str.substring(start);\n l[count/* ++ */] = tok;\n }\n return l;\n }" ]
[ "private int beatOffset(int beatNumber) {\n if (beatCount == 0) {\n throw new IllegalStateException(\"There are no beats in this beat grid.\");\n }\n if (beatNumber < 1 || beatNumber > beatCount) {\n throw new IndexOutOfBoundsException(\"beatNumber (\" + beatNumber + \") must be between 1 and \" + beatCount);\n }\n return beatNumber - 1;\n }", "public void addTags(String photoId, String[] tags) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_TAGS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \", true));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "private void processFile(InputStream is) throws MPXJException\n {\n int line = 1;\n\n try\n {\n //\n // Test the header and extract the separator. If this is successful,\n // we reset the stream back as far as we can. The design of the\n // BufferedInputStream class means that we can't get back to character\n // zero, so the first record we will read will get \"RMHDR\" rather than\n // \"ERMHDR\" in the first field position.\n //\n BufferedInputStream bis = new BufferedInputStream(is);\n byte[] data = new byte[6];\n data[0] = (byte) bis.read();\n bis.mark(1024);\n bis.read(data, 1, 5);\n\n if (!new String(data).equals(\"ERMHDR\"))\n {\n throw new MPXJException(MPXJException.INVALID_FILE);\n }\n\n bis.reset();\n\n InputStreamReader reader = new InputStreamReader(bis, getCharset());\n Tokenizer tk = new ReaderTokenizer(reader);\n tk.setDelimiter('\\t');\n List<String> record = new ArrayList<String>();\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n readRecord(tk, record);\n if (!record.isEmpty())\n {\n if (processRecord(record))\n {\n break;\n }\n }\n ++line;\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR + \" (failed at line \" + line + \")\", ex);\n }\n }", "private float colorToAngle(int color) {\n\t\tfloat[] colors = new float[3];\n\t\tColor.colorToHSV(color, colors);\n\t\t\n\t\treturn (float) Math.toRadians(-colors[0]);\n\t}", "public 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 }", "private Map<String, Integer> runSampling(\n final ProctorContext proctorContext,\n final Set<String> targetTestNames,\n final TestType testType,\n final int determinationsToRun\n ) {\n final Set<String> targetTestGroups = getTargetTestGroups(targetTestNames);\n final Map<String, Integer> testGroupToOccurrences = Maps.newTreeMap();\n for (final String testGroup : targetTestGroups) {\n testGroupToOccurrences.put(testGroup, 0);\n }\n\n for (int i = 0; i < determinationsToRun; ++i) {\n final Identifiers identifiers = TestType.RANDOM.equals(testType)\n ? new Identifiers(Collections.<TestType, String>emptyMap(), /* randomEnabled */ true)\n : Identifiers.of(testType, Long.toString(random.nextLong()));\n final AbstractGroups groups = supplier.getRandomGroups(proctorContext, identifiers);\n for (final Entry<String, TestBucket> e : groups.getProctorResult().getBuckets().entrySet()) {\n final String testName = e.getKey();\n if (targetTestNames.contains(testName)) {\n final int group = e.getValue().getValue();\n final String testGroup = testName + group;\n testGroupToOccurrences.put(testGroup, testGroupToOccurrences.get(testGroup) + 1);\n }\n }\n }\n\n return testGroupToOccurrences;\n }", "public ProjectCalendar addDefaultBaseCalendar()\n {\n ProjectCalendar calendar = add();\n\n calendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n calendar.setWorkingDay(Day.SUNDAY, false);\n calendar.setWorkingDay(Day.MONDAY, true);\n calendar.setWorkingDay(Day.TUESDAY, true);\n calendar.setWorkingDay(Day.WEDNESDAY, true);\n calendar.setWorkingDay(Day.THURSDAY, true);\n calendar.setWorkingDay(Day.FRIDAY, true);\n calendar.setWorkingDay(Day.SATURDAY, false);\n\n calendar.addDefaultCalendarHours();\n\n return (calendar);\n }", "public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }", "private void processGeneratedProperties(\n\t\t\tSerializable id,\n\t\t\tObject entity,\n\t\t\tObject[] state,\n\t\t\tSharedSessionContractImplementor session,\n\t\t\tGenerationTiming matchTiming) {\n\n\t\tTuple tuple = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\t\tsaveSharedTuple( entity, tuple, session );\n\n\t\tif ( tuple == null || tuple.getSnapshot().isEmpty() ) {\n\t\t\tthrow log.couldNotRetrieveEntityForRetrievalOfGeneratedProperties( getEntityName(), id );\n\t\t}\n\n\t\tint propertyIndex = -1;\n\t\tfor ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) {\n\t\t\tpropertyIndex++;\n\t\t\tfinal ValueGeneration valueGeneration = attribute.getValueGenerationStrategy();\n\t\t\tif ( isReadRequired( valueGeneration, matchTiming ) ) {\n\t\t\t\tObject hydratedState = gridPropertyTypes[propertyIndex].hydrate( tuple, getPropertyAliases( \"\", propertyIndex ), session, entity );\n\t\t\t\tstate[propertyIndex] = gridPropertyTypes[propertyIndex].resolve( hydratedState, session, entity );\n\t\t\t\tsetPropertyValue( entity, propertyIndex, state[propertyIndex] );\n\t\t\t}\n\t\t}\n\t}" ]
Compare two integers, accounting for null values. @param n1 integer value @param n2 integer value @return comparison result
[ "public static int compare(Integer n1, Integer n2)\n {\n int result;\n if (n1 == null || n2 == null)\n {\n result = (n1 == null && n2 == null ? 0 : (n1 == null ? 1 : -1));\n }\n else\n {\n result = n1.compareTo(n2);\n }\n return (result);\n }" ]
[ "public double Function2D(double x, double y) {\n return Math.exp(-(x * x + y * y) / (2 * sqrSigma)) / (2 * Math.PI * sqrSigma);\n }", "public static Class<?> getRawType(Type type) {\n\t\tif (type instanceof Class) {\n\t\t\treturn (Class<?>) type;\n\t\t} else if (type instanceof ParameterizedType) {\n\t\t\tParameterizedType actualType = (ParameterizedType) type;\n\t\t\treturn getRawType(actualType.getRawType());\n\t\t} else if (type instanceof GenericArrayType) {\n\t\t\tGenericArrayType genericArrayType = (GenericArrayType) type;\n\t\t\tObject rawArrayType = Array.newInstance(getRawType(genericArrayType\n\t\t\t\t\t.getGenericComponentType()), 0);\n\t\t\treturn rawArrayType.getClass();\n\t\t} else if (type instanceof WildcardType) {\n\t\t\tWildcardType castedType = (WildcardType) type;\n\t\t\treturn getRawType(castedType.getUpperBounds()[0]);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Type \\'\"\n\t\t\t\t\t\t\t+ type\n\t\t\t\t\t\t\t+ \"\\' is not a Class, \"\n\t\t\t\t\t\t\t+ \"ParameterizedType, or GenericArrayType. Can't extract class.\");\n\t\t}\n\t}", "public void hideKeyboard() {\n InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0);\n }", "@Nonnull\n\tprivate static Properties findDefaultProperties() {\n\t\tfinal InputStream in = SourceCodeFormatter.class.getClassLoader().getResourceAsStream(DEFAULT_PROPERTIES_PATH);\n\t\tfinal Properties p = new Properties();\n\t\ttry {\n\t\t\tp.load(in);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(String.format(\"Can not load resource %s\", DEFAULT_PROPERTIES_PATH));\n\t\t}\n\t\treturn p;\n\t}", "protected String buildErrorSetMsg(Object obj, Object value, Field aField)\r\n {\r\n String eol = SystemUtils.LINE_SEPARATOR;\r\n StringBuffer buf = new StringBuffer();\r\n buf\r\n .append(eol + \"[try to set 'object value' in 'target object'\")\r\n .append(eol + \"target obj class: \" + (obj != null ? obj.getClass().getName() : null))\r\n .append(eol + \"target field name: \" + (aField != null ? aField.getName() : null))\r\n .append(eol + \"target field type: \" + (aField != null ? aField.getType() : null))\r\n .append(eol + \"target field declared in: \" + (aField != null ? aField.getDeclaringClass().getName() : null))\r\n .append(eol + \"object value class: \" + (value != null ? value.getClass().getName() : null))\r\n .append(eol + \"object value: \" + (value != null ? value : null))\r\n .append(eol + \"]\");\r\n return buf.toString();\r\n }", "protected I_CmsSearchDocument appendFieldMappingsFromElementsOnThePage(\n I_CmsSearchDocument document,\n CmsObject cms,\n CmsResource resource,\n List<String> systemFields) {\n\n try {\n CmsFile file = cms.readFile(resource);\n CmsXmlContainerPage containerPage = CmsXmlContainerPageFactory.unmarshal(cms, file);\n CmsContainerPageBean containerBean = containerPage.getContainerPage(cms);\n if (containerBean != null) {\n for (CmsContainerElementBean element : containerBean.getElements()) {\n element.initResource(cms);\n CmsResource elemResource = element.getResource();\n Set<CmsSearchField> mappedFields = getXSDMappingsForPage(cms, elemResource);\n if (mappedFields != null) {\n\n for (CmsSearchField field : mappedFields) {\n if (!systemFields.contains(field.getName())) {\n document = appendFieldMapping(\n document,\n field,\n cms,\n elemResource,\n CmsSolrDocumentXmlContent.extractXmlContent(cms, elemResource, getIndex()),\n cms.readPropertyObjects(resource, false),\n cms.readPropertyObjects(resource, true));\n } else {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.LOG_SOLR_ERR_MAPPING_TO_INTERNALLY_USED_FIELD_3,\n elemResource.getRootPath(),\n field.getName(),\n resource.getRootPath()));\n }\n }\n }\n }\n }\n } catch (CmsException e) {\n // Should be thrown if element on the page does not exist anymore - this is possible, but not necessarily an error.\n // Hence, just notice it in the debug log.\n if (LOG.isDebugEnabled()) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n }\n return document;\n }", "public Number getFloat(int field) throws MPXJException\n {\n try\n {\n Number result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = m_formats.getDecimalFormat().parse(m_fields[field]);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse float\", ex);\n }\n }", "public MACAddressSection toEUI(boolean extended) {\n\t\tMACAddressSegment[] segs = toEUISegments(extended);\n\t\tif(segs == null) {\n\t\t\treturn null;\n\t\t}\n\t\tMACAddressCreator creator = getMACNetwork().getAddressCreator();\n\t\treturn createSectionInternal(creator, segs, Math.max(0, addressSegmentIndex - 4) << 1, extended);\n\t}", "public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) {\n\n int lastDot = path.lastIndexOf('.');\n\n if (lastDot > -1) {\n String parentPath = path.substring(0, lastDot);\n String fieldName = path.substring(lastDot + 1);\n Field parentField = getDeclaredFieldWithPath(clazz, parentPath);\n return getDeclaredFieldInHierarchy(parentField.getType(), fieldName);\n } else {\n return getDeclaredFieldInHierarchy(clazz, path);\n }\n }" ]
Simple context menu handler for multi-select tables. @param table the table @param menu the table's context menu @param event the click event @param entries the context menu entries
[ "@SuppressWarnings(\"unchecked\")\n public static <T> void defaultHandleContextMenuForMultiselect(\n Table table,\n CmsContextMenu menu,\n ItemClickEvent event,\n List<I_CmsSimpleContextMenuEntry<Collection<T>>> entries) {\n\n if (!event.isCtrlKey() && !event.isShiftKey()) {\n if (event.getButton().equals(MouseButton.RIGHT)) {\n Collection<T> oldValue = ((Collection<T>)table.getValue());\n if (oldValue.isEmpty() || !oldValue.contains(event.getItemId())) {\n table.setValue(new HashSet<Object>(Arrays.asList(event.getItemId())));\n }\n Collection<T> selection = (Collection<T>)table.getValue();\n menu.setEntries(entries, selection);\n menu.openForTable(event, table);\n }\n }\n\n }" ]
[ "public final static String process(final String input, final Configuration configuration)\n {\n try\n {\n return process(new StringReader(input), configuration);\n }\n catch (final IOException e)\n {\n // This _can never_ happen\n return null;\n }\n }", "public static FileStatus[] getDataChunkFiles(FileSystem fs,\n Path path,\n final int partitionId,\n final int replicaType) throws IOException {\n return fs.listStatus(path, new PathFilter() {\n\n public boolean accept(Path input) {\n if(input.getName().matches(\"^\" + Integer.toString(partitionId) + \"_\"\n + Integer.toString(replicaType) + \"_[\\\\d]+\\\\.data\")) {\n return true;\n } else {\n return false;\n }\n }\n });\n }", "private void lockDescriptor() throws CmsException {\n\n if ((null == m_descFile) && (null != m_desc)) {\n m_descFile = LockedFile.lockResource(m_cms, m_desc);\n }\n }", "private void generateWrappingPart(WrappingHint.Builder builder) {\n builder.setWrappingMethodOwnerName(configuration.UNMODIFIABLE_METHOD_OWNER)\n .setWrappingMethodName(configuration.FIELD_TYPE_TO_UNMODIFIABLE_METHOD.get(typeAssignedToField));\n }", "private void writeAssignmentExtendedAttributes(Project.Assignments.Assignment xml, ResourceAssignment mpx)\n {\n Project.Assignments.Assignment.ExtendedAttribute attrib;\n List<Project.Assignments.Assignment.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (AssignmentField mpxFieldID : getAllAssignmentExtendedAttributes())\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(MPPAssignmentField.getID(mpxFieldID) | MPPAssignmentField.ASSIGNMENT_FIELD_BASE);\n\n attrib = m_factory.createProjectAssignmentsAssignmentExtendedAttribute();\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 void setJdbcLevel(String jdbcLevel)\r\n {\r\n if (jdbcLevel != null)\r\n {\r\n try\r\n {\r\n double intLevel = Double.parseDouble(jdbcLevel);\r\n setJdbcLevel(intLevel);\r\n }\r\n catch(NumberFormatException nfe)\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was not numeric (Value=\" + jdbcLevel + \"), used default jdbc level of 2.0 \");\r\n }\r\n }\r\n else\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was null, used default jdbc level of 2.0 \");\r\n }\r\n }", "public static auditmessages[] get(nitro_service service, auditmessages_args args) throws Exception{\n\t\tauditmessages obj = new auditmessages();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tauditmessages[] response = (auditmessages[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public void setSiteRoot(String siteRoot) {\n\n if (siteRoot != null) {\n siteRoot = siteRoot.replaceFirst(\"/$\", \"\");\n }\n m_siteRoot = siteRoot;\n }", "public double[] getBasisVector( int which ) {\n if( which < 0 || which >= numComponents )\n throw new IllegalArgumentException(\"Invalid component\");\n\n DMatrixRMaj v = new DMatrixRMaj(1,A.numCols);\n CommonOps_DDRM.extract(V_t,which,which+1,0,A.numCols,v,0,0);\n\n return v.data;\n }" ]
Perform construction with custom thread pool size.
[ "private void initialize(Handler callbackHandler, int threadPoolSize) {\n\t\tmDownloadDispatchers = new DownloadDispatcher[threadPoolSize];\n\t\tmDelivery = new CallBackDelivery(callbackHandler);\n\t}" ]
[ "protected void recycleChildren() {\n for (ListItemHostWidget host: getAllHosts()) {\n recycle(host);\n }\n mContent.onTransformChanged();\n mContent.requestLayout();\n }", "private Query getReportQueryByCriteriaCount(ReportQueryByCriteria aQuery)\r\n {\r\n ReportQueryByCriteria countQuery = (ReportQueryByCriteria) getQueryByCriteriaCount(aQuery);\r\n\r\n // BRJ: keep the original columns to build the Join\r\n countQuery.setJoinAttributes(aQuery.getAttributes());\r\n\r\n // BRJ: we have to preserve groupby information\r\n Iterator iter = aQuery.getGroupBy().iterator();\r\n while(iter.hasNext())\r\n {\r\n countQuery.addGroupBy((FieldHelper) iter.next());\r\n }\r\n\r\n return countQuery;\r\n }", "public float[] getFloatArray(String attributeName)\n {\n float[] array = NativeVertexBuffer.getFloatArray(getNative(), attributeName);\n if (array == null)\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return array;\n }", "public void setStatusBarMessage(final String message)\r\n {\r\n // Guaranteed to return a non-null array\r\n Object[] listeners = listenerList.getListenerList();\r\n // Process the listeners last to first, notifying\r\n // those that are interested in this event\r\n for (int i = listeners.length-2; i>=0; i-=2) {\r\n if (listeners[i]==StatusMessageListener.class) \r\n {\r\n ((StatusMessageListener)listeners[i+1]).statusMessageReceived(message);\r\n } \r\n } \r\n }", "public SingleAssetEuropeanOptionProductDescriptor getDescriptor(LocalDate referenceDate, int index) throws ArrayIndexOutOfBoundsException{\n\t\tLocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);\n\t\tif(index >= strikes.length) {\n\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Strike index out of bounds\");\n\t\t}else {\n\t\t\treturn new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[index]);\n\t\t}\n\t}", "public void loadModel(GVRAndroidResource avatarResource, String attachBone)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n GVRSceneObject boneObject;\n int boneIndex;\n\n if (mSkeleton == null)\n {\n throw new IllegalArgumentException(\"Cannot attach model to avatar - there is no skeleton\");\n }\n boneIndex = mSkeleton.getBoneIndex(attachBone);\n if (boneIndex < 0)\n {\n throw new IllegalArgumentException(attachBone + \" is not a bone in the avatar skeleton\");\n }\n boneObject = mSkeleton.getBone(boneIndex);\n if (boneObject == null)\n {\n throw new IllegalArgumentException(attachBone +\n \" does not have a bone object in the avatar skeleton\");\n }\n boneObject.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }", "public ClientBootstrap bootStrapTcpClient()\n throws HttpRequestCreateException {\n\n ClientBootstrap tcpClient = null;\n try {\n\n // Configure the client.\n tcpClient = new ClientBootstrap(tcpMeta.getChannelFactory());\n\n // Configure the pipeline factory.\n tcpClient.setPipelineFactory(new MyPipelineFactory(TcpUdpSshPingResourceStore.getInstance().getTimer(),\n this, tcpMeta.getTcpIdleTimeoutSec())\n );\n\n tcpClient.setOption(\"connectTimeoutMillis\",\n tcpMeta.getTcpConnectTimeoutMillis());\n tcpClient.setOption(\"tcpNoDelay\", true);\n // tcpClient.setOption(\"keepAlive\", true);\n\n } catch (Exception t) {\n throw new TcpUdpRequestCreateException(\n \"Error in creating request in Tcpworker. \"\n + \" If tcpClient is null. Then fail to create.\", t);\n }\n\n return tcpClient;\n\n }", "@SuppressWarnings(\"WeakerAccess\")\n protected boolean isJettyWithJMX(ClassLoaderLeakPreventor preventor) {\n final ClassLoader classLoader = preventor.getClassLoader();\n try {\n // If package org.eclipse.jetty is found, we may be running under jetty\n if (classLoader.getResource(\"org/eclipse/jetty\") == null) {\n return false;\n }\n\n Class.forName(\"org.eclipse.jetty.jmx.MBeanContainer\", false, classLoader.getParent()); // JMX enabled?\n Class.forName(\"org.eclipse.jetty.webapp.WebAppContext\", false, classLoader.getParent());\n }\n catch(Exception ex) { // For example ClassNotFoundException\n return false;\n }\n \n // Seems we are running in Jetty with JMX enabled\n return true;\n }", "@SuppressWarnings(\"unchecked\")\n public T[] nextPermutationAsArray()\n {\n T[] permutation = (T[]) Array.newInstance(elements.getClass().getComponentType(),\n permutationIndices.length);\n return nextPermutationAsArray(permutation);\n }" ]
Get the auth URL, this is step two of authorization. @param oAuthRequestToken the token from a {@link AuthInterface#getRequestToken} call.
[ "public String getAuthorizationUrl(OAuth1RequestToken oAuthRequestToken, Permission permission) {\r\n\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n String authorizationUrl = service.getAuthorizationUrl(oAuthRequestToken);\r\n return String.format(\"%s&perms=%s\", authorizationUrl, permission.toString());\r\n }" ]
[ "private void validate(Object object) {\n\t\tSet<ConstraintViolation<Object>> viols = validator.validate(object);\n\t\tfor (ConstraintViolation<Object> constraintViolation : viols) {\n\t\t\tif (Null.class.isAssignableFrom(constraintViolation.getConstraintDescriptor().getAnnotation().getClass())) {\n\t\t\t\tObject o = constraintViolation.getLeafBean();\n\t\t\t\tIterator<Node> iterator = constraintViolation.getPropertyPath().iterator();\n\t\t\t\tString propertyName = null;\n\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\tpropertyName = iterator.next().getName();\n\t\t\t\t}\n\t\t\t\tif (propertyName != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tPropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(o.getClass(), propertyName);\n\t\t\t\t\t\tdescriptor.getWriteMethod().invoke(o, new Object[] { null });\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public Replication queryParams(Map<String, Object> queryParams) {\r\n this.replication = replication.queryParams(queryParams);\r\n return this;\r\n }", "public DynamicReportBuilder setTemplateFile(String path, boolean importFields, boolean importVariables, boolean importParameters, boolean importDatasets) {\n report.setTemplateFileName(path);\n report.setTemplateImportFields(importFields);\n report.setTemplateImportParameters(importParameters);\n report.setTemplateImportVariables(importVariables);\n report.setTemplateImportDatasets(importDatasets);\n return this;\n }", "public BoundRequestBuilder createRequest()\n throws HttpRequestCreateException {\n BoundRequestBuilder builder = null;\n\n getLogger().debug(\"AHC completeUrl \" + requestUrl);\n\n try {\n\n switch (httpMethod) {\n case GET:\n builder = client.prepareGet(requestUrl);\n break;\n case POST:\n builder = client.preparePost(requestUrl);\n break;\n case PUT:\n builder = client.preparePut(requestUrl);\n break;\n case HEAD:\n builder = client.prepareHead(requestUrl);\n break;\n case OPTIONS:\n builder = client.prepareOptions(requestUrl);\n break;\n case DELETE:\n builder = client.prepareDelete(requestUrl);\n break;\n default:\n break;\n }\n\n PcHttpUtils.addHeaders(builder, this.httpHeaderMap);\n if (!Strings.isNullOrEmpty(postData)) {\n builder.setBody(postData);\n String charset = \"\";\n if (null!=this.httpHeaderMap) {\n charset = this.httpHeaderMap.get(\"charset\");\n }\n if(!Strings.isNullOrEmpty(charset)) {\n builder.setBodyEncoding(charset);\n }\n }\n\n } catch (Exception t) {\n throw new HttpRequestCreateException(\n \"Error in creating request in Httpworker. \"\n + \" If BoundRequestBuilder is null. Then fail to create.\",\n t);\n }\n\n return builder;\n\n }", "private void initExceptionsPanel() {\n\n m_exceptionsPanel.setLegend(Messages.get().key(Messages.GUI_SERIALDATE_PANEL_EXCEPTIONS_0));\n m_exceptionsPanel.addCloseHandler(this);\n m_exceptionsPanel.setVisible(false);\n }", "public static void main(String[] args) throws Exception {\n if(args.length < 1)\n Utils.croak(\"USAGE: java \" + HdfsFetcher.class.getName()\n + \" url [keytab-location kerberos-username hadoop-config-path [destDir]]\");\n String url = args[0];\n\n VoldemortConfig config = new VoldemortConfig(-1, \"\");\n\n HdfsFetcher fetcher = new HdfsFetcher(config);\n\n String destDir = null;\n Long diskQuotaSizeInKB;\n if(args.length >= 4) {\n fetcher.voldemortConfig.setReadOnlyKeytabPath(args[1]);\n fetcher.voldemortConfig.setReadOnlyKerberosUser(args[2]);\n fetcher.voldemortConfig.setHadoopConfigPath(args[3]);\n }\n if(args.length >= 5)\n destDir = args[4];\n\n if(args.length >= 6)\n diskQuotaSizeInKB = Long.parseLong(args[5]);\n else\n diskQuotaSizeInKB = null;\n\n // for testing we want to be able to download a single file\n allowFetchingOfSingleFile = true;\n\n FileSystem fs = HadoopUtils.getHadoopFileSystem(fetcher.voldemortConfig, url);\n Path p = new Path(url);\n\n FileStatus status = fs.listStatus(p)[0];\n long size = status.getLen();\n long start = System.currentTimeMillis();\n if(destDir == null)\n destDir = System.getProperty(\"java.io.tmpdir\") + File.separator + start;\n\n File location = fetcher.fetch(url, destDir, null, null, -1, null, diskQuotaSizeInKB);\n\n double rate = size * Time.MS_PER_SECOND / (double) (System.currentTimeMillis() - start);\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMaximumFractionDigits(2);\n System.out.println(\"Fetch to \" + location + \" completed: \"\n + nf.format(rate / (1024.0 * 1024.0)) + \" MB/sec.\");\n fs.close();\n }", "@Override\n public final String getString(final String key) {\n String result = optString(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "private void deliverSyncCommand(byte command) {\n for (final SyncListener listener : getSyncListeners()) {\n try {\n switch (command) {\n\n case 0x01:\n listener.becomeMaster();\n\n case 0x10:\n listener.setSyncMode(true);\n break;\n\n case 0x20:\n listener.setSyncMode(false);\n break;\n\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering sync command to listener\", t);\n }\n }\n }", "private int getDaysInRange(Date startDate, Date endDate)\n {\n int result;\n Calendar cal = DateHelper.popCalendar(endDate);\n int endDateYear = cal.get(Calendar.YEAR);\n int endDateDayOfYear = cal.get(Calendar.DAY_OF_YEAR);\n\n cal.setTime(startDate);\n\n if (endDateYear == cal.get(Calendar.YEAR))\n {\n result = (endDateDayOfYear - cal.get(Calendar.DAY_OF_YEAR)) + 1;\n }\n else\n {\n result = 0;\n do\n {\n result += (cal.getActualMaximum(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR)) + 1;\n cal.roll(Calendar.YEAR, 1);\n cal.set(Calendar.DAY_OF_YEAR, 1);\n }\n while (cal.get(Calendar.YEAR) < endDateYear);\n result += endDateDayOfYear;\n }\n DateHelper.pushCalendar(cal);\n \n return result;\n }" ]
Sends the JSON-formatted spellchecking results to the client. @param res The HttpServletResponse object. @param request The spellchecking request object. @throws IOException in case writing the response fails
[ "private void sendResponse(final HttpServletResponse res, final CmsSpellcheckingRequest request) throws IOException {\n\n final PrintWriter pw = res.getWriter();\n final JSONObject response = getJsonFormattedSpellcheckResult(request);\n pw.println(response.toString());\n pw.close();\n }" ]
[ "public Task<RemoteInsertOneResult> insertOne(final DocumentT document) {\n return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() {\n @Override\n public RemoteInsertOneResult call() {\n return proxy.insertOne(document);\n }\n });\n }", "public static void setEnabled(Element element, boolean enabled) {\n element.setPropertyBoolean(\"disabled\", !enabled);\n\tsetStyleName(element, \"disabled\", !enabled);\n }", "private void updateSession(Session newSession) {\n if (this.currentSession == null) {\n this.currentSession = newSession;\n } else {\n synchronized (this.currentSession) {\n this.currentSession = newSession;\n }\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 }", "@Deprecated\n public synchronized FailureDetectorConfig setNodes(Collection<Node> nodes) {\n Utils.notNull(nodes);\n this.nodes = new HashSet<Node>(nodes);\n return this;\n }", "public static final Rate parseRate(BigDecimal value)\n {\n Rate result = null;\n\n if (value != null)\n {\n result = new Rate(value, TimeUnit.HOURS);\n }\n\n return (result);\n }", "public boolean isValidStore(String name) {\n readLock.lock();\n try {\n if(this.storeNames.contains(name)) {\n return true;\n }\n return false;\n } finally {\n readLock.unlock();\n }\n }", "private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public void racRent() {\n\t\tpos = pos - 1;\n\t\tString userName = CarSearch.getLastSearchParams()[0];\n\t\tString pickupDate = CarSearch.getLastSearchParams()[1];\n\t\tString returnDate = CarSearch.getLastSearchParams()[2];\n\t\tthis.searcher.search(userName, pickupDate, returnDate);\n\t\tif (searcher!=null && searcher.getCars()!= null && pos < searcher.getCars().size() && searcher.getCars().get(pos) != null) {\n\t\t\tRESStatusType resStatus = reserver.reserveCar(searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\t\t\tConfirmationType confirm = reserver.getConfirmation(resStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\n\t\t\tRESCarType car = confirm.getCar();\n\t\t\tCustomerDetailsType customer = confirm.getCustomer();\n\t\t\t\n\t\t\tSystem.out.println(MessageFormat.format(CONFIRMATION\n\t\t\t\t\t, confirm.getDescription()\n\t\t\t\t\t, confirm.getReservationId()\n\t\t\t\t\t, customer.getName()\n\t\t\t\t\t, customer.getEmail()\n\t\t\t\t\t, customer.getCity()\n\t\t\t\t\t, customer.getStatus()\n\t\t\t\t\t, car.getBrand()\n\t\t\t\t\t, car.getDesignModel()\n\t\t\t\t\t, confirm.getFromDate()\n\t\t\t\t\t, confirm.getToDate()\n\t\t\t\t\t, padl(car.getRateDay(), 10)\n\t\t\t\t\t, padl(car.getRateWeekend(), 10)\n\t\t\t\t\t, padl(confirm.getCreditPoints().toString(), 7)));\n\t\t} else {\n\t\t\tSystem.out.println(\"Invalid selection: \" + (pos+1)); //$NON-NLS-1$\n\t\t}\n\t}" ]
Remove write.lock file in the data directory to ensure the index is unlocked. @param dataDir the data directory of the Solr index that should be unlocked.
[ "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 }" ]
[ "private void readNetscapeExt() {\n do {\n readBlock();\n if (block[0] == 1) {\n // Loop count sub-block.\n int b1 = ((int) block[1]) & 0xff;\n int b2 = ((int) block[2]) & 0xff;\n header.loopCount = (b2 << 8) | b1;\n if(header.loopCount == 0) {\n header.loopCount = GifDecoder.LOOP_FOREVER;\n }\n }\n } while ((blockSize > 0) && !err());\n }", "public static void moveBandsElemnts(int yOffset, JRDesignBand band) {\n\t\tif (band == null)\n\t\t\treturn;\n\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\telem.setY(elem.getY() + yOffset);\n\t\t}\n\t}", "public static void saveContentMap(Map<String, String> map, File file) throws IOException {\n\n FileWriter out = new FileWriter(file);\n for (String key : map.keySet()) {\n if (map.get(key) != null) {\n out.write(key.replace(\":\", \"#escapedtwodots#\") + \":\"\n + map.get(key).replace(\":\", \"#escapedtwodots#\") + \"\\r\\n\");\n }\n }\n out.close();\n }", "public int getIndexMax() {\n int indexMax = 0;\n double max = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m > max ) {\n max = m;\n indexMax = i;\n }\n }\n\n return indexMax;\n }", "private Set<String> checkModel(final ModelNode model, TransformationContext context) throws OperationFailedException {\n final Set<String> attributes = new HashSet<String>();\n AttributeTransformationRequirementChecker checker;\n for (final String attribute : attributeNames) {\n if (model.hasDefined(attribute)) {\n if (attributeCheckers != null && (checker = attributeCheckers.get(attribute)) != null) {\n if (checker.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {\n attributes.add(attribute);\n }\n } else if (SIMPLE_EXPRESSIONS.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {\n attributes.add(attribute);\n }\n }\n }\n return attributes;\n }", "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 }", "public static boolean lower( double[]T , int indexT , int n ) {\n double el_ii;\n double div_el_ii=0;\n\n for( int i = 0; i < n; i++ ) {\n for( int j = i; j < n; j++ ) {\n double sum = T[ indexT + j*n+i];\n\n // todo optimize\n for( int k = 0; k < i; k++ ) {\n sum -= T[ indexT + i*n+k] * T[ indexT + j*n+k];\n }\n\n if( i == j ) {\n // is it positive-definite?\n if( sum <= 0.0 )\n return false;\n\n el_ii = Math.sqrt(sum);\n T[ indexT + i*n+i] = el_ii;\n div_el_ii = 1.0/el_ii;\n } else {\n T[ indexT + j*n+i] = sum*div_el_ii;\n }\n }\n }\n\n return true;\n }", "public static void addLoadInstruction(CodeAttribute code, String type, int variable) {\n char tp = type.charAt(0);\n if (tp != 'L' && tp != '[') {\n // we have a primitive type\n switch (tp) {\n case 'J':\n code.lload(variable);\n break;\n case 'D':\n code.dload(variable);\n break;\n case 'F':\n code.fload(variable);\n break;\n default:\n code.iload(variable);\n }\n } else {\n code.aload(variable);\n }\n }", "public static base_response add(nitro_service client, authenticationradiusaction resource) throws Exception {\n\t\tauthenticationradiusaction addresource = new authenticationradiusaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.serverip = resource.serverip;\n\t\taddresource.serverport = resource.serverport;\n\t\taddresource.authtimeout = resource.authtimeout;\n\t\taddresource.radkey = resource.radkey;\n\t\taddresource.radnasip = resource.radnasip;\n\t\taddresource.radnasid = resource.radnasid;\n\t\taddresource.radvendorid = resource.radvendorid;\n\t\taddresource.radattributetype = resource.radattributetype;\n\t\taddresource.radgroupsprefix = resource.radgroupsprefix;\n\t\taddresource.radgroupseparator = resource.radgroupseparator;\n\t\taddresource.passencoding = resource.passencoding;\n\t\taddresource.ipvendorid = resource.ipvendorid;\n\t\taddresource.ipattributetype = resource.ipattributetype;\n\t\taddresource.accounting = resource.accounting;\n\t\taddresource.pwdvendorid = resource.pwdvendorid;\n\t\taddresource.pwdattributetype = resource.pwdattributetype;\n\t\taddresource.defaultauthenticationgroup = resource.defaultauthenticationgroup;\n\t\taddresource.callingstationid = resource.callingstationid;\n\t\treturn addresource.add_resource(client);\n\t}" ]
The mediator registration config. If it contains default config and definitions, then the dynamic config will be initialized with those values. @see org.openhim.mediator.engine.RegistrationConfig @see #getDynamicConfig()
[ "public void setRegistrationConfig(RegistrationConfig registrationConfig) {\n this.registrationConfig = registrationConfig;\n\n if (registrationConfig.getDefaultConfig()!=null) {\n for (String key : registrationConfig.getDefaultConfig().keySet()) {\n dynamicConfig.put(key, registrationConfig.getDefaultConfig().get(key));\n }\n }\n }" ]
[ "public HttpRequestFactory makeClient(DatastoreOptions options) {\n Credential credential = options.getCredential();\n HttpTransport transport = options.getTransport();\n if (transport == null) {\n transport = credential == null ? new NetHttpTransport() : credential.getTransport();\n transport = transport == null ? new NetHttpTransport() : transport;\n }\n return transport.createRequestFactory(credential);\n }", "public static vpnglobal_authenticationsamlpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_authenticationsamlpolicy_binding obj = new vpnglobal_authenticationsamlpolicy_binding();\n\t\tvpnglobal_authenticationsamlpolicy_binding response[] = (vpnglobal_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public DbOrganization getOrganization(final String organizationId) {\n final DbOrganization dbOrganization = repositoryHandler.getOrganization(organizationId);\n\n if(dbOrganization == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Organization \" + organizationId + \" does not exist.\").build());\n }\n\n return dbOrganization;\n }", "private static ModelNode createOperation(final ModelNode operationToValidate) {\n PathAddress pa = PathAddress.pathAddress(operationToValidate.require(OP_ADDR));\n PathAddress validationAddress = pa.subAddress(0, pa.size() - 1);\n\n return Util.getEmptyOperation(\"validate-cache\", validationAddress.toModelNode());\n }", "private List<Versioned<byte[]>> disassembleValues(byte[] values) throws IOException {\n\n if(values == null)\n return new ArrayList<Versioned<byte[]>>(0);\n\n List<Versioned<byte[]>> returnList = new ArrayList<Versioned<byte[]>>();\n ByteArrayInputStream stream = new ByteArrayInputStream(values);\n DataInputStream dataStream = new DataInputStream(stream);\n\n while(dataStream.available() > 0) {\n byte[] object = new byte[dataStream.readInt()];\n dataStream.read(object);\n\n byte[] clockBytes = new byte[dataStream.readInt()];\n dataStream.read(clockBytes);\n VectorClock clock = new VectorClock(clockBytes);\n\n returnList.add(new Versioned<byte[]>(object, clock));\n }\n\n return returnList;\n }", "private static boolean getSystemConnectivity(Context context) {\n try {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if (cm == null) {\n return false;\n }\n\n NetworkInfo activeNetwork = cm.getActiveNetworkInfo();\n return activeNetwork.isConnectedOrConnecting();\n } catch (Exception exception) {\n return false;\n }\n }", "public static void checkFolderForFile(String fileName) throws IOException {\n\n\t\tif (fileName.lastIndexOf(File.separator) > 0) {\n\t\t\tString folder = fileName.substring(0, fileName.lastIndexOf(File.separator));\n\t\t\tdirectoryCheck(folder);\n\t\t}\n\t}", "public synchronized void persistProperties() throws IOException {\n beginPersistence();\n\n // Read the properties file into memory\n // Shouldn't be so bad - it's a small file\n List<String> content = readFile(propertiesFile);\n\n BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(propertiesFile), StandardCharsets.UTF_8));\n\n try {\n for (String line : content) {\n String trimmed = line.trim();\n if (trimmed.length() == 0) {\n bw.newLine();\n } else {\n Matcher matcher = PROPERTY_PATTERN.matcher(trimmed);\n if (matcher.matches()) {\n final String key = cleanKey(matcher.group(1));\n if (toSave.containsKey(key) || toSave.containsKey(key + DISABLE_SUFFIX_KEY)) {\n writeProperty(bw, key, matcher.group(2));\n toSave.remove(key);\n toSave.remove(key + DISABLE_SUFFIX_KEY);\n } else if (trimmed.startsWith(COMMENT_PREFIX)) {\n // disabled user\n write(bw, line, true);\n }\n } else {\n write(bw, line, true);\n }\n }\n }\n\n endPersistence(bw);\n } finally {\n safeClose(bw);\n }\n }", "private void readCostRateTables(Resource resource, Rates rates)\n {\n if (rates == null)\n {\n CostRateTable table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(0, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(1, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(2, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(3, table);\n\n table = new CostRateTable();\n table.add(CostRateTableEntry.DEFAULT_ENTRY);\n resource.setCostRateTable(4, table);\n }\n else\n {\n Set<CostRateTable> tables = new HashSet<CostRateTable>();\n\n for (net.sf.mpxj.mspdi.schema.Project.Resources.Resource.Rates.Rate rate : rates.getRate())\n {\n Rate standardRate = DatatypeConverter.parseRate(rate.getStandardRate());\n TimeUnit standardRateFormat = DatatypeConverter.parseTimeUnit(rate.getStandardRateFormat());\n Rate overtimeRate = DatatypeConverter.parseRate(rate.getOvertimeRate());\n TimeUnit overtimeRateFormat = DatatypeConverter.parseTimeUnit(rate.getOvertimeRateFormat());\n Double costPerUse = DatatypeConverter.parseCurrency(rate.getCostPerUse());\n Date endDate = rate.getRatesTo();\n\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n\n int tableIndex = rate.getRateTable().intValue();\n CostRateTable table = resource.getCostRateTable(tableIndex);\n if (table == null)\n {\n table = new CostRateTable();\n resource.setCostRateTable(tableIndex, table);\n }\n table.add(entry);\n tables.add(table);\n }\n\n for (CostRateTable table : tables)\n {\n Collections.sort(table);\n }\n }\n }" ]
helper extracts the cursor data from the db object
[ "private QueueCursor updateCursorForDBObject(JSONObject dbObject, QueueCursor cursor) {\n\n if (dbObject == null) return cursor;\n\n Iterator<String> keys = dbObject.keys();\n if (keys.hasNext()) {\n String key = keys.next();\n cursor.setLastId(key);\n try {\n cursor.setData(dbObject.getJSONArray(key));\n } catch (JSONException e) {\n cursor.setLastId(null);\n cursor.setData(null);\n }\n }\n\n return cursor;\n }" ]
[ "private void deliverWaveformDetailUpdate(final int player, final WaveformDetail detail) {\n if (!getWaveformListeners().isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformDetailUpdate update = new WaveformDetailUpdate(player, detail);\n for (final WaveformListener listener : getWaveformListeners()) {\n try {\n listener.detailChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform detail update to listener\", t);\n }\n }\n }\n });\n }\n }", "public static <T> SessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager, EnhancedAnnotatedType<T> type) {\n return new SessionBeanImpl<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifier(type, ejbDescriptor)), beanManager);\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}", "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}", "synchronized int read(byte[] data) {\n this.header = getHeaderParser().setData(data).parseHeader();\n if (data != null) {\n setData(header, data);\n }\n\n return status;\n }", "private OJBIterator getRsIteratorFromQuery(Query query, ClassDescriptor cld, RsIteratorFactory factory)\n throws PersistenceBrokerException\n {\n query.setFetchSize(1);\n if (query instanceof QueryBySQL)\n {\n if(logger.isDebugEnabled()) logger.debug(\"Creating SQL-RsIterator for class [\"+cld.getClassNameOfObject()+\"]\");\n return factory.createRsIterator((QueryBySQL) query, cld, this);\n }\n\n if (!cld.isExtent() || !query.getWithExtents())\n {\n // no extents just use the plain vanilla RsIterator\n if(logger.isDebugEnabled()) logger.debug(\"Creating RsIterator for class [\"+cld.getClassNameOfObject()+\"]\");\n\n return factory.createRsIterator(query, cld, this);\n }\n\n if(logger.isDebugEnabled()) logger.debug(\"Creating ChainingIterator for class [\"+cld.getClassNameOfObject()+\"]\");\n\n ChainingIterator chainingIter = new ChainingIterator();\n\n // BRJ: add base class iterator\n if (!cld.isInterface())\n {\n if(logger.isDebugEnabled()) logger.debug(\"Adding RsIterator for class [\"+cld.getClassNameOfObject()+\"] to ChainingIterator\");\n\n chainingIter.addIterator(factory.createRsIterator(query, cld, this));\n }\n\n Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();\n while (extents.hasNext())\n {\n ClassDescriptor extCld = (ClassDescriptor) extents.next();\n\n // read same table only once\n if (chainingIter.containsIteratorForTable(extCld.getFullTableName()))\n {\n if(logger.isDebugEnabled()) logger.debug(\"Skipping class [\"+extCld.getClassNameOfObject()+\"]\");\n }\n else\n {\n if(logger.isDebugEnabled()) logger.debug(\"Adding RsIterator of class [\"+extCld.getClassNameOfObject()+\"] to ChainingIterator\");\n\n // add the iterator to the chaining iterator.\n chainingIter.addIterator(factory.createRsIterator(query, extCld, this));\n }\n }\n\n return chainingIter;\n }", "private static byte calculateChecksum(byte[] buffer) {\n\t\tbyte checkSum = (byte)0xFF;\n\t\tfor (int i=1; i<buffer.length-1; i++) {\n\t\t\tcheckSum = (byte) (checkSum ^ buffer[i]);\n\t\t}\n\t\tlogger.trace(String.format(\"Calculated checksum = 0x%02X\", checkSum));\n\t\treturn checkSum;\n\t}", "public 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 }", "public static Dimension getDimension(File videoFile) throws IOException {\n try (FileInputStream fis = new FileInputStream(videoFile)) {\n return getDimension(fis, new AtomicReference<ByteBuffer>());\n }\n }" ]
Random string from string array @param s Array @return String
[ "private String randomString(String[] s) {\n if (s == null || s.length <= 0) return \"\";\n return s[this.random.nextInt(s.length)];\n }" ]
[ "public EventBus emit(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }", "public OTMConnection acquireConnection(PBKey pbKey)\r\n {\r\n TransactionFactory txFactory = getTransactionFactory();\r\n return txFactory.acquireConnection(pbKey);\r\n }", "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }", "public Date getFinishDate()\n {\n Date finishDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date\n //\n Date taskFinishDate;\n taskFinishDate = task.getActualFinish();\n if (taskFinishDate == null)\n {\n taskFinishDate = task.getFinish();\n }\n\n if (taskFinishDate != null)\n {\n if (finishDate == null)\n {\n finishDate = taskFinishDate;\n }\n else\n {\n if (taskFinishDate.getTime() > finishDate.getTime())\n {\n finishDate = taskFinishDate;\n }\n }\n }\n }\n\n return (finishDate);\n }", "public static base_response update(nitro_service client, appfwlearningsettings resource) throws Exception {\n\t\tappfwlearningsettings updateresource = new appfwlearningsettings();\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.starturlminthreshold = resource.starturlminthreshold;\n\t\tupdateresource.starturlpercentthreshold = resource.starturlpercentthreshold;\n\t\tupdateresource.cookieconsistencyminthreshold = resource.cookieconsistencyminthreshold;\n\t\tupdateresource.cookieconsistencypercentthreshold = resource.cookieconsistencypercentthreshold;\n\t\tupdateresource.csrftagminthreshold = resource.csrftagminthreshold;\n\t\tupdateresource.csrftagpercentthreshold = resource.csrftagpercentthreshold;\n\t\tupdateresource.fieldconsistencyminthreshold = resource.fieldconsistencyminthreshold;\n\t\tupdateresource.fieldconsistencypercentthreshold = resource.fieldconsistencypercentthreshold;\n\t\tupdateresource.crosssitescriptingminthreshold = resource.crosssitescriptingminthreshold;\n\t\tupdateresource.crosssitescriptingpercentthreshold = resource.crosssitescriptingpercentthreshold;\n\t\tupdateresource.sqlinjectionminthreshold = resource.sqlinjectionminthreshold;\n\t\tupdateresource.sqlinjectionpercentthreshold = resource.sqlinjectionpercentthreshold;\n\t\tupdateresource.fieldformatminthreshold = resource.fieldformatminthreshold;\n\t\tupdateresource.fieldformatpercentthreshold = resource.fieldformatpercentthreshold;\n\t\tupdateresource.xmlwsiminthreshold = resource.xmlwsiminthreshold;\n\t\tupdateresource.xmlwsipercentthreshold = resource.xmlwsipercentthreshold;\n\t\tupdateresource.xmlattachmentminthreshold = resource.xmlattachmentminthreshold;\n\t\tupdateresource.xmlattachmentpercentthreshold = resource.xmlattachmentpercentthreshold;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static boolean isClosureDeclaration(ASTNode expression) {\r\n if (expression instanceof DeclarationExpression) {\r\n if (((DeclarationExpression) expression).getRightExpression() instanceof ClosureExpression) {\r\n return true;\r\n }\r\n }\r\n if (expression instanceof FieldNode) {\r\n ClassNode type = ((FieldNode) expression).getType();\r\n if (AstUtil.classNodeImplementsType(type, Closure.class)) {\r\n return true;\r\n } else if (((FieldNode) expression).getInitialValueExpression() instanceof ClosureExpression) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public boolean removePredecessor(Task targetTask, RelationType type, Duration lag)\n {\n boolean matchFound = false;\n\n //\n // Retrieve the list of predecessors\n //\n List<Relation> predecessorList = getPredecessors();\n if (!predecessorList.isEmpty())\n {\n //\n // Ensure that we have a valid lag duration\n //\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n //\n // Ensure that there is a predecessor relationship between\n // these two tasks, and remove it.\n //\n matchFound = removeRelation(predecessorList, targetTask, type, lag);\n\n //\n // If we have removed a predecessor, then we must remove the\n // corresponding successor entry from the target task list\n //\n if (matchFound)\n {\n //\n // Retrieve the list of successors\n //\n List<Relation> successorList = targetTask.getSuccessors();\n if (!successorList.isEmpty())\n {\n //\n // Ensure that there is a successor relationship between\n // these two tasks, and remove it.\n //\n removeRelation(successorList, this, type, lag);\n }\n }\n }\n\n return matchFound;\n }", "@Override\n public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "@JmxGetter(name = \"getChunkIdToNumChunks\", description = \"Returns a string representation of the map of chunk id to number of chunks\")\n public String getChunkIdToNumChunks() {\n StringBuilder builder = new StringBuilder();\n for(Entry<Object, Integer> entry: fileSet.getChunkIdToNumChunks().entrySet()) {\n builder.append(entry.getKey().toString() + \" - \" + entry.getValue().toString() + \", \");\n }\n return builder.toString();\n }" ]
Creates a random diagonal matrix where the diagonal elements are selected from a uniform distribution that goes from min to max. @param N Dimension of the matrix. @param min Minimum value of a diagonal element. @param max Maximum value of a diagonal element. @param rand Random number generator. @return A random diagonal matrix.
[ "public static DMatrixRMaj diagonal(int N , double min , double max , Random rand ) {\n return diagonal(N,N,min,max,rand);\n }" ]
[ "public Backup getBackupData() throws Exception {\n Backup backupData = new Backup();\n\n backupData.setGroups(getGroups());\n backupData.setProfiles(getProfiles());\n ArrayList<Script> scripts = new ArrayList<Script>();\n Collections.addAll(scripts, ScriptService.getInstance().getScripts());\n backupData.setScripts(scripts);\n\n return backupData;\n }", "protected String getContextPath(){\n\n if(context != null) return context;\n\n if(get(\"context_path\") == null){\n throw new ViewException(\"context_path missing - red alarm!\");\n }\n return get(\"context_path\").toString();\n }", "public static Object toObject(Class<?> clazz, Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (clazz == null) {\n return value;\n }\n\n if (java.sql.Date.class.isAssignableFrom(clazz)) {\n return toDate(value);\n }\n if (java.sql.Time.class.isAssignableFrom(clazz)) {\n return toTime(value);\n }\n if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {\n return toTimestamp(value);\n }\n if (java.util.Date.class.isAssignableFrom(clazz)) {\n return toDateTime(value);\n }\n\n return value;\n }", "protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }", "public PhotoContext getContext(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\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 PhotoContext photoContext = new PhotoContext();\r\n Collection<Element> payload = response.getPayloadCollection();\r\n for (Element payloadElement : payload) {\r\n String tagName = payloadElement.getTagName();\r\n if (tagName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (tagName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setNextPhoto(photo);\r\n }\r\n }\r\n return photoContext;\r\n }", "public static DMatrixRMaj elements(DMatrixRMaj A , BMatrixRMaj marked , DMatrixRMaj output ) {\n if( A.numRows != marked.numRows || A.numCols != marked.numCols )\n throw new MatrixDimensionException(\"Input matrices must have the same shape\");\n if( output == null )\n output = new DMatrixRMaj(1,1);\n\n output.reshape(countTrue(marked),1);\n\n int N = A.getNumElements();\n\n int index = 0;\n for (int i = 0; i < N; i++) {\n if( marked.data[i] ) {\n output.data[index++] = A.data[i];\n }\n }\n\n return output;\n }", "@Modified(id = \"exporterServices\")\n void modifiedExporterService(ServiceReference<ExporterService> serviceReference) {\n try {\n exportersManager.modified(serviceReference);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.error(\"The ServiceProperty \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" of the ExporterService \"\n + bundleContext.getService(serviceReference) + \" doesn't provides a valid Filter.\"\n + \" To be used, it must provides a correct \\\"\" + TARGET_FILTER_PROPERTY + \"\\\" ServiceProperty.\",\n invalidFilterException\n );\n exportersManager.removeLinks(serviceReference);\n return;\n }\n if (exportersManager.matched(serviceReference)) {\n exportersManager.updateLinks(serviceReference);\n } else {\n exportersManager.removeLinks(serviceReference);\n }\n }", "public Metadata add(String path, String value) {\n this.values.add(this.pathToProperty(path), value);\n this.addOp(\"add\", path, value);\n return this;\n }", "protected String consumeQuoted(ImapRequestLineReader request)\n throws ProtocolException {\n // The 1st character must be '\"'\n consumeChar(request, '\"');\n\n StringBuilder quoted = new StringBuilder();\n char next = request.nextChar();\n while (next != '\"') {\n if (next == '\\\\') {\n request.consume();\n next = request.nextChar();\n if (!isQuotedSpecial(next)) {\n throw new ProtocolException(\"Invalid escaped character in quote: '\" +\n next + '\\'');\n }\n }\n quoted.append(next);\n request.consume();\n next = request.nextChar();\n }\n\n consumeChar(request, '\"');\n\n return quoted.toString();\n }" ]
Creates a producer field @param field The underlying method abstraction @param declaringBean The declaring bean abstraction @param beanManager the current manager @return A producer field
[ "public static <X, T> ProducerField<X, T> of(BeanAttributes<T> attributes, EnhancedAnnotatedField<T, ? super X> field, AbstractClassBean<X> declaringBean, DisposalMethod<X, ?> disposalMethod, BeanManagerImpl beanManager, ServiceRegistry services) {\n return new ProducerField<X, T>(attributes, field, declaringBean, disposalMethod, beanManager, services);\n }" ]
[ "public static void addToListIfNotExists(List<String> list, String value) {\n boolean found = false;\n for (String item : list) {\n if (item.equalsIgnoreCase(value)) {\n found = true;\n break;\n }\n }\n if (!found) {\n list.add(value);\n }\n }", "@Override\n\tpublic void visit(FeatureTypeStyle fts) {\n\n\t\tFeatureTypeStyle copy = new FeatureTypeStyleImpl(\n\t\t\t\t(FeatureTypeStyleImpl) fts);\n\t\tRule[] rules = fts.getRules();\n\t\tint length = rules.length;\n\t\tRule[] rulesCopy = new Rule[length];\n\t\tfor (int i = 0; i < length; i++) {\n\t\t\tif (rules[i] != null) {\n\t\t\t\trules[i].accept(this);\n\t\t\t\trulesCopy[i] = (Rule) pages.pop();\n\t\t\t}\n\t\t}\n\t\tcopy.setRules(rulesCopy);\n\t\tif (fts.getTransformation() != null) {\n\t\t\tcopy.setTransformation(copy(fts.getTransformation()));\n\t\t}\n\t\tif (STRICT && !copy.equals(fts)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided FeatureTypeStyle:\" + fts);\n\t\t}\n\t\tpages.push(copy);\n\t}", "public void removePathnameFromProfile(int path_id, int profileId) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public AT_Context setFrameTopBottomMargin(int frameTop, int frameBottom){\r\n\t\tif(frameTop>-1 && frameBottom>-1){\r\n\t\t\tthis.frameTopMargin = frameTop;\r\n\t\t\tthis.frameBottomMargin = frameBottom;\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalArgumentException {\n\t\tAssert.notNull(pathSegments, \"'segments' must not be null\");\n\t\tthis.pathBuilder.addPathSegments(pathSegments);\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}", "public static List<String> asListLines(String content) {\n List<String> retorno = new ArrayList<String>();\n content = content.replace(CARRIAGE_RETURN, RETURN);\n content = content.replace(RETURN, CARRIAGE_RETURN);\n for (String str : content.split(CARRIAGE_RETURN)) {\n retorno.add(str);\n }\n return retorno;\n }", "private boolean isWorkingDay(ProjectCalendar mpxjCalendar, Day day)\n {\n boolean result = false;\n net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);\n if (type == null)\n {\n type = net.sf.mpxj.DayType.DEFAULT;\n }\n\n switch (type)\n {\n case WORKING:\n {\n result = true;\n break;\n }\n\n case NON_WORKING:\n {\n result = false;\n break;\n }\n\n case DEFAULT:\n {\n if (mpxjCalendar.getParent() == null)\n {\n result = false;\n }\n else\n {\n result = isWorkingDay(mpxjCalendar.getParent(), day);\n }\n break;\n }\n }\n\n return (result);\n }", "public static base_response update(nitro_service client, aaaparameter resource) throws Exception {\n\t\taaaparameter updateresource = new aaaparameter();\n\t\tupdateresource.enablestaticpagecaching = resource.enablestaticpagecaching;\n\t\tupdateresource.enableenhancedauthfeedback = resource.enableenhancedauthfeedback;\n\t\tupdateresource.defaultauthtype = resource.defaultauthtype;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.maxloginattempts = resource.maxloginattempts;\n\t\tupdateresource.failedlogintimeout = resource.failedlogintimeout;\n\t\tupdateresource.aaadnatip = resource.aaadnatip;\n\t\treturn updateresource.update_resource(client);\n\t}", "@PostConstruct\n public final void init() {\n this.cleanUpTimer = Executors.newScheduledThreadPool(1, timerTask -> {\n final Thread thread = new Thread(timerTask, \"Clean up old job records\");\n thread.setDaemon(true);\n return thread;\n });\n this.cleanUpTimer.scheduleAtFixedRate(this::cleanup, this.cleanupInterval, this.cleanupInterval,\n TimeUnit.SECONDS);\n }" ]
Tells you if the expression is true, which can be true or Boolean.TRUE. @param expression expression @return as described
[ "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 }" ]
[ "@SuppressWarnings(\"SameParameterValue\")\n public static long bytesToNumberLittleEndian(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start + length - 1; index >= start; index--) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }", "public void setSegmentReject(String reject) {\n\t\tif (!StringUtils.hasText(reject)) {\n\t\t\treturn;\n\t\t}\n\t\tInteger parsedLimit = null;\n\t\ttry {\n\t\t\tparsedLimit = Integer.parseInt(reject);\n\t\t\tsegmentRejectType = SegmentRejectType.ROWS;\n\t\t} catch (NumberFormatException e) {\n\t\t}\n\t\tif (parsedLimit == null && reject.contains(\"%\")) {\n\t\t\ttry {\n\t\t\t\tparsedLimit = Integer.parseInt(reject.replace(\"%\", \"\").trim());\n\t\t\t\tsegmentRejectType = SegmentRejectType.PERCENT;\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t}\n\t\t}\n\t\tsegmentRejectLimit = parsedLimit;\n\t}", "public static base_responses update(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 updateresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nspbr6();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].msr = resources[i].msr;\n\t\t\t\tupdateresources[i].monitor = resources[i].monitor;\n\t\t\t\tupdateresources[i].nexthop = resources[i].nexthop;\n\t\t\t\tupdateresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\tupdateresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static double extractColumnAndMax( ZMatrixRMaj A ,\n int row0 , int row1 ,\n int col , double u[], int offsetU) {\n int indexU = (offsetU+row0)*2;\n\n // find the largest value in this column\n // this is used to normalize the column and mitigate overflow/underflow\n double max = 0;\n\n int indexA = A.getIndex(row0,col);\n double h[] = A.data;\n\n for( int i = row0; i < row1; i++, indexA += A.numCols*2 ) {\n // copy the householder vector to an array to reduce cache misses\n // big improvement on larger matrices and a relatively small performance hit on small matrices.\n double realVal = u[indexU++] = h[indexA];\n double imagVal = u[indexU++] = h[indexA+1];\n\n double magVal = realVal*realVal + imagVal*imagVal;\n if( max < magVal ) {\n max = magVal;\n }\n }\n return Math.sqrt(max);\n }", "public static final String printAccrueType(AccrueType value)\n {\n return (Integer.toString(value == null ? AccrueType.PRORATED.getValue() : value.getValue()));\n }", "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 }", "public static Map<String, String> parseProperties(String s) {\n\t\tMap<String, String> properties = new HashMap<String, String>();\n\t\tif (!StringUtils.isEmpty(s)) {\n\t\t\tMatcher matcher = PROPERTIES_PATTERN.matcher(s);\n\t\t\tint start = 0;\n\t\t\twhile (matcher.find()) {\n\t\t\t\taddKeyValuePairAsProperty(s.substring(start, matcher.start()), properties);\n\t\t\t\tstart = matcher.start() + 1;\n\t\t\t}\n\t\t\taddKeyValuePairAsProperty(s.substring(start), properties);\n\t\t}\n\t\treturn properties;\n\t}", "public float getMetallic()\n {\n Property p = getProperty(PropertyKey.METALLIC.m_key);\n\n if (null == p || null == p.getData())\n {\n throw new IllegalArgumentException(\"Metallic property not found\");\n }\n Object rawValue = p.getData();\n if (rawValue instanceof java.nio.ByteBuffer)\n {\n java.nio.FloatBuffer fbuf = ((java.nio.ByteBuffer) rawValue).asFloatBuffer();\n return fbuf.get();\n }\n else\n {\n return (Float) rawValue;\n }\n }", "public ProjectCalendarException getException(Date date)\n {\n ProjectCalendarException exception = null;\n\n // We're working with expanded exceptions, which includes any recurring exceptions\n // expanded into individual entries.\n populateExpandedExceptions();\n if (!m_expandedExceptions.isEmpty())\n {\n sortExceptions();\n\n int low = 0;\n int high = m_expandedExceptions.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarException midVal = m_expandedExceptions.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getFromDate(), midVal.getToDate(), 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 exception = midVal;\n break;\n }\n }\n }\n }\n\n if (exception == null && getParent() != null)\n {\n // Check base calendar as well for an exception.\n exception = getParent().getException(date);\n }\n return (exception);\n }" ]
Gets the end. @return the end
[ "public Integer getEnd() {\n if (mtasPositionType.equals(POSITION_RANGE)\n || mtasPositionType.equals(POSITION_SET)) {\n return mtasPositionEnd;\n } else if (mtasPositionType.equals(POSITION_SINGLE)) {\n return mtasPositionStart;\n } else {\n return null;\n }\n }" ]
[ "public Bytes subSequence(int start, int end) {\n if (start > end || start < 0 || end > length) {\n throw new IndexOutOfBoundsException(\"Bad start and/end start = \" + start + \" end=\" + end\n + \" offset=\" + offset + \" length=\" + length);\n }\n return new Bytes(data, offset + start, end - start);\n }", "public static final Color getColor(byte[] data, int offset)\n {\n Color result = null;\n\n if (getByte(data, offset + 3) == 0)\n {\n int r = getByte(data, offset);\n int g = getByte(data, offset + 1);\n int b = getByte(data, offset + 2);\n result = new Color(r, g, b);\n }\n\n return result;\n }", "public static HashMap<String, String> getParameters(String query) {\n HashMap<String, String> params = new HashMap<String, String>();\n if (query == null || query.length() == 0) {\n return params;\n }\n\n String[] splitQuery = query.split(\"&\");\n for (String splitItem : splitQuery) {\n String[] items = splitItem.split(\"=\");\n\n if (items.length == 1) {\n params.put(items[0], \"\");\n } else {\n params.put(items[0], items[1]);\n }\n }\n\n return params;\n }", "private void buildMultiJoinTree(TableAlias left, ClassDescriptor cld, String name, boolean useOuterJoin)\r\n {\r\n DescriptorRepository repository = cld.getRepository();\r\n Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, false);\r\n\r\n for (int i = 0; i < multiJoinedClasses.length; i++)\r\n {\r\n ClassDescriptor subCld = repository.getDescriptorFor(multiJoinedClasses[i]);\r\n SuperReferenceDescriptor srd = subCld.getSuperReference();\r\n if (srd != null)\r\n {\r\n FieldDescriptor[] leftFields = subCld.getPkFields();\r\n FieldDescriptor[] rightFields = srd.getForeignKeyFieldDescriptors(subCld);\r\n TableAlias base_alias = getTableAliasForPath(name, null, null);\r\n\r\n String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++;\r\n TableAlias right = new TableAlias(subCld, aliasName, false, null);\r\n\r\n Join join1to1 = new Join(left, leftFields, right, rightFields, useOuterJoin, \"subClass\");\r\n base_alias.addJoin(join1to1);\r\n\r\n buildMultiJoinTree(right, subCld, name, useOuterJoin);\r\n }\r\n }\r\n }", "public static void checkVectorAddition() {\n DoubleMatrix x = new DoubleMatrix(3, 1, 1.0, 2.0, 3.0);\n DoubleMatrix y = new DoubleMatrix(3, 1, 4.0, 5.0, 6.0);\n DoubleMatrix z = new DoubleMatrix(3, 1, 5.0, 7.0, 9.0);\n\n check(\"checking vector addition\", x.add(y).equals(z));\n }", "protected void solveL(double[] vv) {\n\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sumReal = vv[ip*2];\n double sumImg = vv[ip*2+1];\n\n vv[ip*2] = vv[i*2];\n vv[ip*2+1] = vv[i*2+1];\n\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*stride + (ii-1)*2;\n for( int j = ii-1; j < i; j++ ){\n double luReal = dataLU[index++];\n double luImg = dataLU[index++];\n\n double vvReal = vv[j*2];\n double vvImg = vv[j*2+1];\n\n sumReal -= luReal*vvReal - luImg*vvImg;\n sumImg -= luReal*vvImg + luImg*vvReal;\n }\n } else if( sumReal*sumReal + sumImg*sumImg != 0.0 ) {\n ii=i+1;\n }\n vv[i*2] = sumReal;\n vv[i*2+1] = sumImg;\n }\n }", "public static int cudnnLRNCrossChannelBackward(\n cudnnHandle handle, \n cudnnLRNDescriptor normDesc, \n int lrnMode, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnLRNCrossChannelBackwardNative(handle, normDesc, lrnMode, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }", "public static String common() {\n String common = SysProps.get(KEY_COMMON_CONF_TAG);\n if (S.blank(common)) {\n common = \"common\";\n }\n return common;\n }", "public GVRAnimation setDuration(float start, float end)\n {\n if(start>end || start<0 || end>mDuration){\n throw new IllegalArgumentException(\"start and end values are wrong\");\n }\n animationOffset = start;\n mDuration = end-start;\n return this;\n }" ]
Check if this request is part of the specified request. This is the case if both requests have equal properties and the specified request is asking for the same or more paint operations than this one. @param request another request @return true if the current request is contained in the specified request @since 1.10.0
[ "public boolean isPartOf(GetVectorTileRequest request) {\n\t\tif (Math.abs(request.scale - scale) > EQUALS_DELTA) { return false; }\n\t\tif (code != null ? !code.equals(request.code) : request.code != null) { return false; }\n\t\tif (crs != null ? !crs.equals(request.crs) : request.crs != null) { return false; }\n\t\tif (filter != null ? !filter.equals(request.filter) : request.filter != null) { return false; }\n\t\tif (panOrigin != null ? !panOrigin.equals(request.panOrigin) : request.panOrigin != null) { return false; }\n\t\tif (renderer != null ? !renderer.equals(request.renderer) : request.renderer != null) { return false; }\n\t\tif (styleInfo != null ? !styleInfo.equals(request.styleInfo) : request.styleInfo != null) { return false; }\n\t\tif (paintGeometries && !request.paintGeometries) { return false; }\n\t\tif (paintLabels && !request.paintLabels) { return false; }\n\t\treturn true;\n\t}" ]
[ "public static vpnsessionaction get(nitro_service service, String name) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tobj.set_name(name);\n\t\tvpnsessionaction response = (vpnsessionaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void addBasicSentence(MtasCQLParserBasicSentenceCondition s)\n throws ParseException {\n if (!simplified) {\n List<MtasCQLParserBasicSentencePartCondition> newWordList = s\n .getPartList();\n partList.addAll(newWordList);\n } else {\n throw new ParseException(\"already simplified\");\n }\n }", "public static String getVcsRevision(Map<String, String> env) {\n String revision = env.get(\"SVN_REVISION\");\n if (StringUtils.isBlank(revision)) {\n revision = env.get(GIT_COMMIT);\n }\n if (StringUtils.isBlank(revision)) {\n revision = env.get(\"P4_CHANGELIST\");\n }\n return revision;\n }", "static String md5(String input) {\n if (input == null || input.length() == 0) {\n throw new IllegalArgumentException(\"Input string must not be blank.\");\n }\n try {\n MessageDigest algorithm = MessageDigest.getInstance(\"MD5\");\n algorithm.reset();\n algorithm.update(input.getBytes());\n byte[] messageDigest = algorithm.digest();\n\n StringBuilder hexString = new StringBuilder();\n for (byte messageByte : messageDigest) {\n hexString.append(Integer.toHexString((messageByte & 0xFF) | 0x100).substring(1, 3));\n }\n return hexString.toString();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public static final BigInteger printEarnedValueMethod(EarnedValueMethod value)\n {\n return (value == null ? BigInteger.valueOf(EarnedValueMethod.PERCENT_COMPLETE.getValue()) : BigInteger.valueOf(value.getValue()));\n }", "protected String statusMsg(final String queue, final Job job) throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setQueue(queue);\n status.setPayload(job);\n return ObjectMapperFactory.get().writeValueAsString(status);\n }", "public ConnectionRepository readConnectionRepository(String fileName)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readConnectionRepository(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 }", "@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}", "private void stripCommas(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getSymbol() == Symbol.COMMA ) {\n tokens.remove(t);\n }\n t = next;\n }\n }" ]
Lookup an object via its name. @param name The name of an object. @return The object with that name. @exception ObjectNameNotFoundException There is no object with the specified name. ObjectNameNotFoundException
[ "public Object lookup(String name) throws ObjectNameNotFoundException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call bind.\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 lookup\");\r\n }\r\n /**\r\n * Is Tx open? ODMG 3.0 says it has to be to call bind.\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 return tx.getNamedRootsMap().lookup(name);\r\n }" ]
[ "public static <T> List<T> flatten(Collection<List<T>> nestedList) {\r\n List<T> result = new ArrayList<T>();\r\n for (List<T> list : nestedList) {\r\n result.addAll(list);\r\n }\r\n return result;\r\n }", "protected static Statement memorize(final Statement target, final ConnectionHandle connectionHandle) {\n\t\treturn (Statement) Proxy.newProxyInstance(\n\t\t\t\tStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {StatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "private String stripLineBreaks(String text, String replacement)\n {\n if (text.indexOf('\\r') != -1 || text.indexOf('\\n') != -1)\n {\n StringBuilder sb = new StringBuilder(text);\n\n int index;\n\n while ((index = sb.indexOf(\"\\r\\n\")) != -1)\n {\n sb.replace(index, index + 2, replacement);\n }\n\n while ((index = sb.indexOf(\"\\n\\r\")) != -1)\n {\n sb.replace(index, index + 2, replacement);\n }\n\n while ((index = sb.indexOf(\"\\r\")) != -1)\n {\n sb.replace(index, index + 1, replacement);\n }\n\n while ((index = sb.indexOf(\"\\n\")) != -1)\n {\n sb.replace(index, index + 1, replacement);\n }\n\n text = sb.toString();\n }\n\n return (text);\n }", "private void populateRelationList(Task task, TaskField field, String data)\n {\n DeferredRelationship dr = new DeferredRelationship();\n dr.setTask(task);\n dr.setField(field);\n dr.setData(data);\n m_deferredRelationships.add(dr);\n }", "public static String constructUrl(final HttpServerExchange exchange, final String path) {\n final HeaderMap headers = exchange.getRequestHeaders();\n String host = headers.getFirst(HOST);\n String protocol = exchange.getConnection().getSslSessionInfo() != null ? \"https\" : \"http\";\n\n return protocol + \"://\" + host + path;\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}", "public static String getLocalizedKey(Map<String, ?> propertiesMap, String key, Locale locale) {\n\n List<String> localizedKeys = CmsLocaleManager.getLocaleVariants(key, locale, true, false);\n for (String localizedKey : localizedKeys) {\n if (propertiesMap.containsKey(localizedKey)) {\n return localizedKey;\n }\n }\n return key;\n }", "public static double normP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return normF(A);\n } else {\n return inducedP2(A);\n }\n }", "public static String base64Encode(byte[] bytes) {\n if (bytes == null) {\n throw new IllegalArgumentException(\"Input bytes must not be null.\");\n }\n if (bytes.length >= BASE64_UPPER_BOUND) {\n throw new IllegalArgumentException(\n \"Input bytes length must not exceed \" + BASE64_UPPER_BOUND);\n }\n\n // Every three bytes is encoded into four characters.\n //\n // Example:\n // input |0 1 0 1 0 0 1 0|0 1 1 0 1 1 1 1|0 1 1 0 0 0 1 0|\n // encode grouping |0 1 0 1 0 0|1 0 0 1 1 0|1 1 1 1 0 1|1 0 0 0 1 0|\n // encoded ascii | U | m | 9 | i |\n\n int triples = bytes.length / 3;\n\n // If the number of input bytes is not a multiple of three, padding characters will be added.\n if (bytes.length % 3 != 0) {\n triples += 1;\n }\n\n // The encoded string will have four characters for every three bytes.\n char[] encoding = new char[triples << 2];\n\n for (int in = 0, out = 0; in < bytes.length; in += 3, out += 4) {\n int triple = (bytes[in] & 0xff) << 16;\n if (in + 1 < bytes.length) {\n triple |= ((bytes[in + 1] & 0xff) << 8);\n }\n if (in + 2 < bytes.length) {\n triple |= (bytes[in + 2] & 0xff);\n }\n encoding[out] = BASE64_CHARS.charAt((triple >> 18) & 0x3f);\n encoding[out + 1] = BASE64_CHARS.charAt((triple >> 12) & 0x3f);\n encoding[out + 2] = BASE64_CHARS.charAt((triple >> 6) & 0x3f);\n encoding[out + 3] = BASE64_CHARS.charAt(triple & 0x3f);\n }\n\n // Add padding characters if needed.\n for (int i = encoding.length - (triples * 3 - bytes.length); i < encoding.length; i++) {\n encoding[i] = '=';\n }\n\n return String.valueOf(encoding);\n }" ]
We have identified that we have a SQLite file. This could be a Primavera Project database or an Asta database. Open the database and use the table names present to determine which type this is. @param stream schedule data @return ProjectFile instance
[ "private ProjectFile handleSQLiteFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".sqlite\");\n\n try\n {\n Class.forName(\"org.sqlite.JDBC\");\n String url = \"jdbc:sqlite:\" + file.getCanonicalPath();\n Set<String> tableNames = populateTableNames(url);\n\n if (tableNames.contains(\"EXCEPTIONN\"))\n {\n return readProjectFile(new AstaDatabaseFileReader(), file);\n }\n\n if (tableNames.contains(\"PROJWBS\"))\n {\n Connection connection = null;\n try\n {\n Properties props = new Properties();\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n connection = DriverManager.getConnection(url, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(connection);\n addListeners(reader);\n return reader.read();\n }\n finally\n {\n if (connection != null)\n {\n connection.close();\n }\n }\n }\n\n if (tableNames.contains(\"ZSCHEDULEITEM\"))\n {\n return readProjectFile(new MerlinReader(), file);\n }\n\n return null;\n }\n\n finally\n {\n FileHelper.deleteQuietly(file);\n }\n }" ]
[ "public <T> List<T> query(String query, Class<T> classOfT) {\r\n InputStream instream = null;\r\n List<T> result = new ArrayList<T>();\r\n try {\r\n Reader reader = new InputStreamReader(instream = queryForStream(query), \"UTF-8\");\r\n JsonObject json = new JsonParser().parse(reader).getAsJsonObject();\r\n if (json.has(\"rows\")) {\r\n if (!includeDocs) {\r\n log.warning(\"includeDocs set to false and attempting to retrieve doc. \" +\r\n \"null object will be returned\");\r\n }\r\n for (JsonElement e : json.getAsJsonArray(\"rows\")) {\r\n result.add(jsonToObject(client.getGson(), e, \"doc\", classOfT));\r\n }\r\n } else {\r\n log.warning(\"No ungrouped result available. Use queryGroups() if grouping set\");\r\n }\r\n return result;\r\n } catch (UnsupportedEncodingException e1) {\r\n // This should never happen as every implementation of the java platform is required\r\n // to support UTF-8.\r\n throw new RuntimeException(e1);\r\n } finally {\r\n close(instream);\r\n }\r\n }", "public static base_response add(nitro_service client, autoscaleaction resource) throws Exception {\n\t\tautoscaleaction addresource = new autoscaleaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.parameters = resource.parameters;\n\t\taddresource.vmdestroygraceperiod = resource.vmdestroygraceperiod;\n\t\taddresource.quiettime = resource.quiettime;\n\t\taddresource.vserver = resource.vserver;\n\t\treturn addresource.add_resource(client);\n\t}", "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Creatable<? extends Indexable> creatable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatable;\n return this.addPostRunDependent(dependency);\n }", "public synchronized void stop() {\r\n\r\n if (m_thread != null) {\r\n long timeBeforeShutdownWasCalled = System.currentTimeMillis();\r\n JLANServer.shutdownServer(new String[] {});\r\n while (m_thread.isAlive()\r\n && ((System.currentTimeMillis() - timeBeforeShutdownWasCalled) < MAX_SHUTDOWN_WAIT_MILLIS)) {\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException e) {\r\n // ignore\r\n }\r\n }\r\n }\r\n\r\n }", "private List<String> parseParams(String param) {\n\t\tAssert.hasText(param, \"param must not be empty nor null\");\n\t\tList<String> paramsToUse = new ArrayList<>();\n\t\tMatcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN.matcher(param);\n\t\tint start = 0;\n\t\twhile (regexMatcher.find()) {\n\t\t\tString p = removeQuoting(param.substring(start, regexMatcher.start()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t\tstart = regexMatcher.start();\n\t\t}\n\t\tif (param != null && param.length() > 0) {\n\t\t\tString p = removeQuoting(param.substring(start, param.length()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t}\n\t\treturn paramsToUse;\n\t}", "protected void merge(Set<Annotation> stereotypeAnnotations) {\n final MetaAnnotationStore store = manager.getServices().get(MetaAnnotationStore.class);\n for (Annotation stereotypeAnnotation : stereotypeAnnotations) {\n // Retrieve and merge all metadata from stereotypes\n StereotypeModel<?> stereotype = store.getStereotype(stereotypeAnnotation.annotationType());\n if (stereotype == null) {\n throw MetadataLogger.LOG.stereotypeNotRegistered(stereotypeAnnotation);\n }\n if (stereotype.isAlternative()) {\n alternative = true;\n }\n if (stereotype.getDefaultScopeType() != null) {\n possibleScopeTypes.add(stereotype.getDefaultScopeType());\n }\n if (stereotype.isBeanNameDefaulted()) {\n beanNameDefaulted = true;\n }\n this.stereotypes.add(stereotypeAnnotation.annotationType());\n // Merge in inherited stereotypes\n merge(stereotype.getInheritedStereotypes());\n }\n }", "public Photoset create(String title, String description, String primaryPhotoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CREATE);\r\n\r\n parameters.put(\"title\", title);\r\n parameters.put(\"description\", description);\r\n parameters.put(\"primary_photo_id\", primaryPhotoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n photoset.setUrl(photosetElement.getAttribute(\"url\"));\r\n return photoset;\r\n }", "public void setObjectForStatement(PreparedStatement ps, int index,\r\n Object value, int sqlType) throws SQLException\r\n {\r\n if (sqlType == Types.TINYINT)\r\n {\r\n ps.setByte(index, ((Byte) value).byteValue());\r\n }\r\n else\r\n {\r\n super.setObjectForStatement(ps, index, value, sqlType);\r\n }\r\n }", "private FieldType addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n FieldType field = null;\n \n try\n {\n switch (fieldType)\n {\n case TASK:\n {\n do\n {\n field = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (RESERVED_TASK_FIELDS.contains(field));\n\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n\n break;\n }\n \n case RESOURCE:\n {\n field = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n case ASSIGNMENT:\n {\n field = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n m_projectFile.getCustomFields().getCustomField(field).setAlias(name);\n break;\n }\n \n default:\n {\n break;\n }\n } \n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\n \n return field;\n }" ]
Retrieve the default mapping between MPXJ task fields and Primavera wbs field names. @return mapping
[ "public static Map<FieldType, String> getDefaultWbsFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(TaskField.UNIQUE_ID, \"wbs_id\");\n map.put(TaskField.GUID, \"guid\");\n map.put(TaskField.NAME, \"wbs_name\");\n map.put(TaskField.BASELINE_COST, \"orig_cost\");\n map.put(TaskField.REMAINING_COST, \"indep_remain_total_cost\");\n map.put(TaskField.REMAINING_WORK, \"indep_remain_work_qty\");\n map.put(TaskField.DEADLINE, \"anticip_end_date\");\n map.put(TaskField.DATE1, \"suspend_date\");\n map.put(TaskField.DATE2, \"resume_date\");\n map.put(TaskField.TEXT1, \"task_code\");\n map.put(TaskField.WBS, \"wbs_short_name\");\n\n return map;\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 }", "private void addPropertyCounters(UsageStatistics usageStatistics,\n\t\t\tPropertyIdValue property) {\n\t\tif (!usageStatistics.propertyCountsMain.containsKey(property)) {\n\t\t\tusageStatistics.propertyCountsMain.put(property, 0);\n\t\t\tusageStatistics.propertyCountsQualifier.put(property, 0);\n\t\t\tusageStatistics.propertyCountsReferences.put(property, 0);\n\t\t}\n\t}", "public static final void setSize(UIObject o, Rect size) {\n o.setPixelSize(size.w, size.h);\n\n }", "public void processReference(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n XClass type = OjbMemberTagsHandler.getMemberType();\r\n int dim = OjbMemberTagsHandler.getMemberDimension();\r\n ReferenceDescriptorDef refDef = _curClassDef.getReference(name);\r\n String attrName;\r\n\r\n if (refDef == null)\r\n {\r\n refDef = new ReferenceDescriptorDef(name);\r\n _curClassDef.addReference(refDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processReference\", \" Processing reference \"+refDef.getName());\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n refDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n // storing default info for later use\r\n if (type == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (dim > 0)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.MEMBER_CANNOT_BE_A_REFERENCE,\r\n new String[]{name, _curClassDef.getName()}));\r\n }\r\n\r\n refDef.setProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE, type.getQualifiedName());\r\n\r\n // searching for default type\r\n String typeName = searchForPersistentSubType(type);\r\n\r\n if (typeName != null)\r\n {\r\n refDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CLASS_REF, typeName);\r\n }\r\n\r\n _curReferenceDef = refDef;\r\n generate(template);\r\n _curReferenceDef = null;\r\n }", "public void process(Connection connection, String directory) throws Exception\n {\n connection.setAutoCommit(true);\n\n //\n // Retrieve meta data about the connection\n //\n DatabaseMetaData dmd = connection.getMetaData();\n\n String[] types =\n {\n \"TABLE\"\n };\n\n FileWriter fw = new FileWriter(directory);\n PrintWriter pw = new PrintWriter(fw);\n\n pw.println(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n pw.println();\n pw.println(\"<database>\");\n\n ResultSet tables = dmd.getTables(null, null, null, types);\n while (tables.next() == true)\n {\n processTable(pw, connection, tables.getString(\"TABLE_NAME\"));\n }\n\n pw.println(\"</database>\");\n\n pw.close();\n\n tables.close();\n }", "public Double getProgress() {\n\n if (state.equals(ParallelTaskState.IN_PROGRESS)) {\n if (requestNum != 0) {\n return 100.0 * ((double) responsedNum / (double) requestNumActual);\n } else {\n return 0.0;\n }\n }\n\n if (state.equals(ParallelTaskState.WAITING)) {\n return 0.0;\n }\n\n // fix task if fail validation, still try to poll progress 0901\n if (state.equals(ParallelTaskState.COMPLETED_WITH_ERROR)\n || state.equals(ParallelTaskState.COMPLETED_WITHOUT_ERROR)) {\n return 100.0;\n }\n\n return 0.0;\n\n }", "public boolean hasSameConfiguration(BoneCPConfig that){\n\t\tif ( that != null && Objects.equal(this.acquireIncrement, that.getAcquireIncrement())\n\t\t\t\t&& Objects.equal(this.acquireRetryDelayInMs, that.getAcquireRetryDelayInMs())\n\t\t\t\t&& Objects.equal(this.closeConnectionWatch, that.isCloseConnectionWatch())\n\t\t\t\t&& Objects.equal(this.logStatementsEnabled, that.isLogStatementsEnabled())\n\t\t\t\t&& Objects.equal(this.connectionHook, that.getConnectionHook())\n\t\t\t\t&& Objects.equal(this.connectionTestStatement, that.getConnectionTestStatement())\n\t\t\t\t&& Objects.equal(this.idleConnectionTestPeriodInSeconds, that.getIdleConnectionTestPeriod(TimeUnit.SECONDS))\n\t\t\t\t&& Objects.equal(this.idleMaxAgeInSeconds, that.getIdleMaxAge(TimeUnit.SECONDS))\n\t\t\t\t&& Objects.equal(this.initSQL, that.getInitSQL())\n\t\t\t\t&& Objects.equal(this.jdbcUrl, that.getJdbcUrl())\n\t\t\t\t&& Objects.equal(this.maxConnectionsPerPartition, that.getMaxConnectionsPerPartition())\n\t\t\t\t&& Objects.equal(this.minConnectionsPerPartition, that.getMinConnectionsPerPartition())\n\t\t\t\t&& Objects.equal(this.partitionCount, that.getPartitionCount())\n\t\t\t\t&& Objects.equal(this.releaseHelperThreads, that.getReleaseHelperThreads())\n\t\t\t\t&& Objects.equal(this.statementsCacheSize, that.getStatementsCacheSize())\n\t\t\t\t&& Objects.equal(this.username, that.getUsername())\n\t\t\t\t&& Objects.equal(this.password, that.getPassword())\n\t\t\t\t&& Objects.equal(this.lazyInit, that.isLazyInit())\n\t\t\t\t&& Objects.equal(this.transactionRecoveryEnabled, that.isTransactionRecoveryEnabled())\n\t\t\t\t&& Objects.equal(this.acquireRetryAttempts, that.getAcquireRetryAttempts())\n\t\t\t\t&& Objects.equal(this.statementReleaseHelperThreads, that.getStatementReleaseHelperThreads())\n\t\t\t\t&& Objects.equal(this.closeConnectionWatchTimeoutInMs, that.getCloseConnectionWatchTimeout())\n\t\t\t\t&& Objects.equal(this.connectionTimeoutInMs, that.getConnectionTimeoutInMs())\n\t\t\t\t&& Objects.equal(this.datasourceBean, that.getDatasourceBean())\n\t\t\t\t&& Objects.equal(this.getQueryExecuteTimeLimitInMs(), that.getQueryExecuteTimeLimitInMs())\n\t\t\t\t&& Objects.equal(this.poolAvailabilityThreshold, that.getPoolAvailabilityThreshold())\n\t\t\t\t&& Objects.equal(this.poolName, that.getPoolName())\n\t\t\t\t&& Objects.equal(this.disableConnectionTracking, that.isDisableConnectionTracking())\n\n\t\t\t\t){\n\t\t\treturn true;\n\t\t} \n\n\t\treturn false;\n\t}", "public double getCouponPayment(int periodIndex, AnalyticModel model) {\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve with name '\" + forwardCurveName + \"' was found in the model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\t\tdouble couponPayment=fixedCoupon ;\n\t\tif(forwardCurve != null ) {\n\t\t\tcouponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex));\n\t\t}\n\t\treturn couponPayment*periodLength;\n\t}", "public Map<String, Object> getValues(double evaluationTime, MonteCarloSimulationInterface model) throws CalculationException\n\t{\n\t\tRandomVariableInterface values = getValue(evaluationTime, model);\n\n\t\tif(values == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Sum up values on path\n\t\tdouble value = values.getAverage();\n\t\tdouble error = values.getStandardError();\n\n\t\tMap<String, Object> results = new HashMap<String, Object>();\n\t\tresults.put(\"value\", value);\n\t\tresults.put(\"error\", error);\n\n\t\treturn results;\n\t}" ]
Possibly coalesces the newest change event to match the user's original intent. For example, an unsynchronized insert and update is still an insert. @param lastUncommittedChangeEvent the last change event known about for a document. @param newestChangeEvent the newest change event known about for a document. @return the possibly coalesced change event.
[ "private static ChangeEvent<BsonDocument> coalesceChangeEvents(\n final ChangeEvent<BsonDocument> lastUncommittedChangeEvent,\n final ChangeEvent<BsonDocument> newestChangeEvent\n ) {\n if (lastUncommittedChangeEvent == null) {\n return newestChangeEvent;\n }\n switch (lastUncommittedChangeEvent.getOperationType()) {\n case INSERT:\n switch (newestChangeEvent.getOperationType()) {\n // Coalesce replaces/updates to inserts since we believe at some point a document did not\n // exist remotely and that this replace or update should really be an insert if we are\n // still in an uncommitted state.\n case REPLACE:\n case UPDATE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.INSERT,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n case DELETE:\n switch (newestChangeEvent.getOperationType()) {\n // Coalesce inserts to replaces since we believe at some point a document existed\n // remotely and that this insert should really be an replace if we are still in an\n // uncommitted state.\n case INSERT:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.REPLACE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n case UPDATE:\n switch (newestChangeEvent.getOperationType()) {\n case UPDATE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.UPDATE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n lastUncommittedChangeEvent.getUpdateDescription() != null\n ? lastUncommittedChangeEvent\n .getUpdateDescription()\n .merge(newestChangeEvent.getUpdateDescription())\n : newestChangeEvent.getUpdateDescription(),\n newestChangeEvent.hasUncommittedWrites()\n );\n case REPLACE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.REPLACE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n case REPLACE:\n switch (newestChangeEvent.getOperationType()) {\n case UPDATE:\n return new ChangeEvent<>(\n newestChangeEvent.getId(),\n OperationType.REPLACE,\n newestChangeEvent.getFullDocument(),\n newestChangeEvent.getNamespace(),\n newestChangeEvent.getDocumentKey(),\n null,\n newestChangeEvent.hasUncommittedWrites()\n );\n default:\n break;\n }\n break;\n default:\n break;\n }\n return newestChangeEvent;\n }" ]
[ "protected void layoutChild(final int dataIndex) {\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n float offset = mOffset.get(Axis.X);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.X, offset);\n }\n\n offset = mOffset.get(Axis.Y);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Y, offset);\n }\n\n offset = mOffset.get(Axis.Z);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Z, offset);\n }\n }\n }", "private List<ParameterConverter> methodReturningConverters(final Class<?> type) {\n final List<ParameterConverter> converters = new ArrayList<>();\n for (final Method method : type.getMethods()) {\n if (method.isAnnotationPresent(AsParameterConverter.class)) {\n converters.add(new MethodReturningConverter(method, type, this));\n }\n }\n return converters;\n }", "public String getAuthorizationUrl(OAuth1RequestToken oAuthRequestToken, Permission permission) {\r\n\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n String authorizationUrl = service.getAuthorizationUrl(oAuthRequestToken);\r\n return String.format(\"%s&perms=%s\", authorizationUrl, permission.toString());\r\n }", "public static String digestToFileName(String digest) {\n if (StringUtils.startsWith(digest, \"sha1\")) {\n return \"manifest.json\";\n }\n return getShaVersion(digest) + \"__\" + getShaValue(digest);\n }", "private 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.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoWBS(false);\n config.setAutoOutlineNumber(false);\n\n m_project.getProjectProperties().setFileApplication(\"FastTrack\");\n m_project.getProjectProperties().setFileType(\"FTS\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n // processProject();\n // processCalendars();\n processResources();\n processTasks();\n processDependencies();\n processAssignments();\n\n return m_project;\n }", "protected String getUserDefinedFieldName(String field) {\n int index = field.indexOf('-');\n char letter = getUserDefinedFieldLetter();\n\n for (int i = 0; i < index; ++i) {\n if (field.charAt(i) == letter) {\n return field.substring(index + 1);\n }\n }\n\n return null;\n }", "public static boolean respondsTo(Object object, String methodName) {\r\n MetaClass metaClass = DefaultGroovyMethods.getMetaClass(object);\r\n if (!metaClass.respondsTo(object, methodName).isEmpty()) {\r\n return true;\r\n }\r\n Map properties = DefaultGroovyMethods.getProperties(object);\r\n return properties.containsKey(methodName);\r\n }", "public double areaSquared(HalfEdge hedge0, HalfEdge hedge1) {\n Point3d p0 = hedge0.tail().pnt;\n Point3d p1 = hedge0.head().pnt;\n Point3d p2 = hedge1.head().pnt;\n\n double dx1 = p1.x - p0.x;\n double dy1 = p1.y - p0.y;\n double dz1 = p1.z - p0.z;\n\n double dx2 = p2.x - p0.x;\n double dy2 = p2.y - p0.y;\n double dz2 = p2.z - p0.z;\n\n double x = dy1 * dz2 - dz1 * dy2;\n double y = dz1 * dx2 - dx1 * dz2;\n double z = dx1 * dy2 - dy1 * dx2;\n\n return x * x + y * y + z * z;\n }", "public static void addStory(File caseManager, String storyName,\n String testPath, String user, String feature, String benefit) throws BeastException {\n FileWriter caseManagerWriter;\n\n String storyClass = SystemReader.createClassName(storyName);\n try {\n BufferedReader reader = new BufferedReader(new FileReader(\n caseManager));\n String targetLine1 = \" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\";\n String targetLine2 = \" Result result = JUnitCore.runClasses(\" + testPath + \".\"\n + storyClass + \".class);\";\n String in;\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine1)) {\n while ((in = reader.readLine()) != null) {\n if (in.equals(targetLine2)) {\n reader.close();\n // This test is already written in the case manager.\n return;\n }\n }\n reader.close();\n throw new BeastException(\"Two different stories with the same name (same method name) are being created in the same CaseManager file. That is not possible. Please, change the name of the story: \" + testPath + \".\"\n + storyClass + \".java\");\n }\n }\n reader.close();\n caseManagerWriter = new FileWriter(caseManager, true);\n caseManagerWriter.write(\" /**\\n\");\n caseManagerWriter.write(\" * This is the story: \" + storyName\n + \"\\n\");\n caseManagerWriter.write(\" * requested by: \" + user + \"\\n\");\n caseManagerWriter.write(\" * providing the feature: \" + feature\n + \"\\n\");\n caseManagerWriter.write(\" * so the user gets the benefit: \"\n + benefit + \"\\n\");\n caseManagerWriter.write(\" */\\n\");\n caseManagerWriter.write(\" @Test\\n\");\n caseManagerWriter.write(\" public void \"\n + MASReader.createFirstLowCaseName(storyName) + \"() {\\n\");\n caseManagerWriter.write(\" Result result = JUnitCore.runClasses(\" + testPath\n + \".\" + storyClass + \".class);\\n\");\n caseManagerWriter.write(\" Assert.assertTrue(result.wasSuccessful());\\n\");\n caseManagerWriter.write(\" }\\n\");\n caseManagerWriter.write(\"\\n\");\n caseManagerWriter.flush();\n caseManagerWriter.close();\n } catch (IOException e) {\n Logger logger = Logger.getLogger(\"CreateMASCaseManager.createTest\");\n logger.info(\"ERROR writing the file\");\n }\n\n }" ]
Returns the count of total number of unread inbox messages for the user @return int - count of all unread messages
[ "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getInboxMessageUnreadCount(){\n synchronized (inboxControllerLock) {\n if (this.ctInboxController != null) {\n return ctInboxController.unreadCount();\n } else {\n getConfigLogger().debug(getAccountId(), \"Notification Inbox not initialized\");\n return -1;\n }\n }\n }" ]
[ "public static Identifiers convertProfileAndPathIdentifier(String profileIdentifier, String pathIdentifier) throws Exception {\n Identifiers id = new Identifiers();\n\n Integer profileId = null;\n try {\n profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n } catch (Exception e) {\n // this is OK for this since it isn't always needed\n }\n Integer pathId = convertPathIdentifier(pathIdentifier, profileId);\n\n id.setProfileId(profileId);\n id.setPathId(pathId);\n\n return id;\n }", "public static Artifact withVersion(Version v)\n {\n Artifact artifact = new Artifact();\n artifact.version = v;\n return artifact;\n }", "public double getValue(ForwardCurveInterface forwardCurve, double swaprateVolatility) {\n\t\tdouble swaprate = swaprates[0];\n\t\tfor (double swaprate1 : swaprates) {\n\t\t\tif (swaprate1 != swaprate) {\n\t\t\t\tthrow new RuntimeException(\"Uneven swaprates not allows for analytical pricing.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble[] swapTenor = new double[fixingDates.length+1];\n\t\tSystem.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);\n\t\tswapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];\n\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(new TimeDiscretization(swapTenor), new TimeDiscretization(swapTenor), forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(new TimeDiscretization(swapTenor), forwardCurve);\n\n\t\treturn AnalyticFormulas.blackModelSwaptionValue(forwardSwapRate, swaprateVolatility, exerciseDate, swaprate, swapAnnuity);\n\t}", "public final void notifyFooterItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n// if (position < 0 || position >= newFooterItemCount) {\n// throw new IndexOutOfBoundsException(\"The given position \" + position\n// + \" is not within the position bounds for footer items [0 - \"\n// + (newFooterItemCount - 1) + \"].\");\n// }\n notifyItemInserted(position + newHeaderItemCount + newContentItemCount);\n }", "public ItemRequest<Task> addSubtask(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "protected boolean checkExcludePackages(String classPackageName) {\n\t\tif (excludePackages != null && excludePackages.length > 0) {\n\t\t\tWildcardHelper wildcardHelper = new WildcardHelper();\n\n\t\t\t// we really don't care about the results, just the boolean\n\t\t\tMap<String, String> matchMap = new HashMap<String, String>();\n\n\t\t\tfor (String packageExclude : excludePackages) {\n\t\t\t\tint[] packagePattern = wildcardHelper.compilePattern(packageExclude);\n\t\t\t\tif (wildcardHelper.match(matchMap, classPackageName, packagePattern)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {\n // updates the coordinator metadata with recent stores and cluster xml\n updateCoordinatorMetadataWithLatestState();\n\n logger.info(\"Creating a Fat client for store: \" + storeName);\n SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),\n storeClientProps);\n\n if(this.fatClientMap == null) {\n this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>();\n }\n DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,\n fatClientFactory,\n 1,\n this.coordinatorMetadata.getStoreDefs(),\n this.coordinatorMetadata.getClusterXmlStr());\n this.fatClientMap.put(storeName, fatClient);\n\n }", "public 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 }", "private String appendXmlEndingTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"</\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }" ]
Creates a new undeploy description. @param deploymentDescription the deployment description to copy @return the description
[ "public static UndeployDescription of(final DeploymentDescription deploymentDescription) {\n Assert.checkNotNullParam(\"deploymentDescription\", deploymentDescription);\n return of(deploymentDescription.getName()).addServerGroups(deploymentDescription.getServerGroups());\n }" ]
[ "public void prettyPrint(StringBuffer sb, int indent) {\n sb.append(Log.getSpaces(indent));\n sb.append(getClass().getSimpleName());\n sb.append(\" [name=\");\n sb.append(this.getName());\n sb.append(\"]\");\n sb.append(System.lineSeparator());\n GVRRenderData rdata = getRenderData();\n GVRTransform trans = getTransform();\n\n if (rdata == null) {\n sb.append(Log.getSpaces(indent + 2));\n sb.append(\"RenderData: null\");\n sb.append(System.lineSeparator());\n } else {\n rdata.prettyPrint(sb, indent + 2);\n }\n sb.append(Log.getSpaces(indent + 2));\n sb.append(\"Transform: \"); sb.append(trans);\n sb.append(System.lineSeparator());\n\n // dump its children\n for (GVRSceneObject child : getChildren()) {\n child.prettyPrint(sb, indent + 2);\n }\n }", "public String getUncPath() {\n getUncPath0();\n if( share == null ) {\n return \"\\\\\\\\\" + url.getHost();\n }\n return \"\\\\\\\\\" + url.getHost() + canon.replace( '/', '\\\\' );\n }", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean timeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }", "public ConnectionRepository readConnectionRepository(String fileName)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readConnectionRepository(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 Date getTimestampFromLong(long timestamp)\n {\n TimeZone tz = TimeZone.getDefault();\n Date result = new Date(timestamp - tz.getRawOffset());\n\n if (tz.inDaylightTime(result) == true)\n {\n int savings;\n\n if (HAS_DST_SAVINGS == true)\n {\n savings = tz.getDSTSavings();\n }\n else\n {\n savings = DEFAULT_DST_SAVINGS;\n }\n\n result = new Date(result.getTime() - savings);\n }\n return (result);\n }", "public static audit_stats get(nitro_service service, options option) throws Exception{\n\t\taudit_stats obj = new audit_stats();\n\t\taudit_stats[] response = (audit_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}", "protected Violation createViolationForImport(SourceCode sourceCode, String className, String alias, String violationMessage) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, className, alias);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(violationMessage);\n return violation;\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getInboxMessageUnreadCount(){\n synchronized (inboxControllerLock) {\n if (this.ctInboxController != null) {\n return ctInboxController.unreadCount();\n } else {\n getConfigLogger().debug(getAccountId(), \"Notification Inbox not initialized\");\n return -1;\n }\n }\n }", "private static long getVersionId(String versionDir) {\n try {\n return Long.parseLong(versionDir.replace(\"version-\", \"\"));\n } catch(NumberFormatException e) {\n logger.trace(\"Cannot parse version directory to obtain id \" + versionDir);\n return -1;\n }\n }" ]
This method dumps the entire contents of a file to an output print writer as hex and ASCII data. @param is Input Stream @param pw Output PrintWriter @return number of bytes read @throws Exception Thrown on file read errors
[ "private static long hexdump(InputStream is, PrintWriter pw) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n long byteCount = 0;\n\n char c;\n int loop;\n int count;\n StringBuilder sb = new StringBuilder();\n\n while (true)\n {\n count = is.read(buffer);\n if (count == -1)\n {\n break;\n }\n\n byteCount += count;\n\n sb.setLength(0);\n\n for (loop = 0; loop < count; loop++)\n {\n sb.append(\" \");\n sb.append(HEX_DIGITS[(buffer[loop] & 0xF0) >> 4]);\n sb.append(HEX_DIGITS[buffer[loop] & 0x0F]);\n }\n\n while (loop < BUFFER_SIZE)\n {\n sb.append(\" \");\n ++loop;\n }\n\n sb.append(\" \");\n\n for (loop = 0; loop < count; loop++)\n {\n c = (char) buffer[loop];\n if (c > 200 || c < 27)\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n\n pw.println(sb.toString());\n }\n\n return (byteCount);\n }" ]
[ "public static sslcertkey_sslvserver_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslvserver_binding obj = new sslcertkey_sslvserver_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslvserver_binding response[] = (sslcertkey_sslvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void initializePersistenceStrategy(CacheMappingType cacheMappingType, Set<EntityKeyMetadata> entityTypes, Set<AssociationKeyMetadata> associationTypes, Set<IdSourceKeyMetadata> idSourceTypes, Iterable<Namespace> namespaces) {\n\t\tpersistenceStrategy = PersistenceStrategy.getInstance(\n\t\t\t\tcacheMappingType,\n\t\t\t\texternalCacheManager,\n\t\t\t\tconfig.getConfigurationUrl(),\n\t\t\t\tjtaPlatform,\n\t\t\t\tentityTypes,\n\t\t\t\tassociationTypes,\n\t\t\t\tidSourceTypes\n\t\t);\n\n\t\t// creates handler for TableGenerator Id sources\n\t\tboolean requiresCounter = hasIdGeneration( idSourceTypes );\n\t\tif ( requiresCounter ) {\n\t\t\tthis.tableClusterHandler = new TableClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager() );\n\t\t}\n\n\t\t// creates handlers for SequenceGenerator Id sources\n\t\tfor ( Namespace namespace : namespaces ) {\n\t\t\tfor ( Sequence seq : namespace.getSequences() ) {\n\t\t\t\tthis.sequenceCounterHandlers.put( seq.getExportIdentifier(),\n\t\t\t\t\t\tnew SequenceClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager(), seq ) );\n\t\t\t}\n\t\t}\n\n\t\t// clear resources\n\t\tthis.externalCacheManager = null;\n\t\tthis.jtaPlatform = null;\n\t}", "private static void deleteOldAndEmptyFiles() {\n File dir = LOG_FILE_DIR;\n if (dir.exists()) {\n File[] files = dir.listFiles();\n\n for (File f : files) {\n if (f.length() == 0 ||\n f.lastModified() + MAXFILEAGE < System.currentTimeMillis()) {\n f.delete();\n }\n }\n }\n }", "public static boolean isSuccess(JsonRtn jsonRtn) {\n if (jsonRtn == null) {\n return false;\n }\n\n String errCode = jsonRtn.getErrCode();\n if (StringUtils.isEmpty(errCode) || StringUtils.equals(WECHAT_JSON_RTN_SUCCESS_CODE, errCode)) {\n return true;\n }\n\n return false;\n }", "public static double Taneja(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double pq = p[i] + q[i];\n r += (pq / 2) * Math.log(pq / (2 * Math.sqrt(p[i] * q[i])));\n }\n }\n return r;\n }", "public static sslservice get(nitro_service service, String servicename) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\tobj.set_servicename(servicename);\n\t\tsslservice response = (sslservice) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected boolean hasPermissions(CmsObject cms, CmsSolrDocument doc, CmsResourceFilter filter) {\r\n\r\n return null != (filter == null ? getResource(cms, doc) : getResource(cms, doc, filter));\r\n }", "public static boolean canUseAsDelayedQueue(final Jedis jedis, final String key) {\n final String type = jedis.type(key);\n return (ZSET.equalsIgnoreCase(type) || NONE.equalsIgnoreCase(type));\n }", "@Override\n protected Deque<Step> childValue(Deque<Step> parentValue) {\n Deque<Step> queue = new LinkedList<>();\n queue.add(parentValue.getFirst());\n return queue;\n }" ]
This method extracts calendar data from a Planner file. @param project Root node of the Planner file
[ "private void readCalendars(Project project) throws MPXJException\n {\n Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n for (net.sf.mpxj.planner.schema.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, null);\n }\n\n Integer defaultCalendarID = getInteger(project.getCalendar());\n m_defaultCalendar = m_projectFile.getCalendarByUniqueID(defaultCalendarID);\n if (m_defaultCalendar != null)\n {\n m_projectFile.getProjectProperties().setDefaultCalendarName(m_defaultCalendar.getName());\n }\n }\n }" ]
[ "public List<String> findAssociationPath(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tList<String> subPath = new ArrayList<String>( pathWithoutAlias.size() );\n\t\tfor ( String name : pathWithoutAlias ) {\n\t\t\tsubPath.add( name );\n\t\t\tif ( isAssociation( targetTypeName, subPath ) ) {\n\t\t\t\treturn subPath;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "private String formatPriority(Priority value)\n {\n String result = null;\n\n if (value != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(m_locale, LocaleData.PRIORITY_TYPES);\n int priority = value.getValue();\n if (priority < Priority.LOWEST)\n {\n priority = Priority.LOWEST;\n }\n else\n {\n if (priority > Priority.DO_NOT_LEVEL)\n {\n priority = Priority.DO_NOT_LEVEL;\n }\n }\n\n priority /= 100;\n\n result = priorityTypes[priority - 1];\n }\n\n return (result);\n }", "protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) {\r\n Map<String, AbstractServer> srvc = new HashMap<>();\r\n for (ServerSetup setup : config) {\r\n if (srvc.containsKey(setup.getProtocol())) {\r\n throw new IllegalArgumentException(\"Server '\" + setup.getProtocol() + \"' was found at least twice in the array\");\r\n }\r\n final String protocol = setup.getProtocol();\r\n if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) {\r\n srvc.put(protocol, new SmtpServer(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) {\r\n srvc.put(protocol, new Pop3Server(setup, mgr));\r\n } else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) {\r\n srvc.put(protocol, new ImapServer(setup, mgr));\r\n }\r\n }\r\n return srvc;\r\n }", "public Collection getReaders(Object obj)\r\n {\r\n \tcheckTimedOutLocks();\r\n Identity oid = new Identity(obj,getBroker());\r\n return getReaders(oid);\r\n }", "public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, null);\n }", "public static base_responses update(nitro_service client, nsrpcnode resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsrpcnode updateresources[] = new nsrpcnode[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsrpcnode();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].srcip = resources[i].srcip;\n\t\t\t\tupdateresources[i].secure = resources[i].secure;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "@Override\n protected void checkType() {\n if (!isDependent() && getEnhancedAnnotated().isParameterizedType()) {\n throw BeanLogger.LOG.managedBeanWithParameterizedBeanClassMustBeDependent(type);\n }\n boolean passivating = beanManager.isPassivatingScope(getScope());\n if (passivating && !isPassivationCapableBean()) {\n if (!getEnhancedAnnotated().isSerializable()) {\n throw BeanLogger.LOG.passivatingBeanNeedsSerializableImpl(this);\n } else if (hasDecorators() && !allDecoratorsArePassivationCapable()) {\n throw BeanLogger.LOG.passivatingBeanHasNonPassivationCapableDecorator(this, getFirstNonPassivationCapableDecorator());\n } else if (hasInterceptors() && !allInterceptorsArePassivationCapable()) {\n throw BeanLogger.LOG.passivatingBeanHasNonPassivationCapableInterceptor(this, getFirstNonPassivationCapableInterceptor());\n }\n }\n }", "private void processCalendarData(ProjectCalendar calendar, List<ResultSetRow> calendarData)\n {\n for (ResultSetRow row : calendarData)\n {\n processCalendarData(calendar, row);\n }\n }", "String getUriStringForRank(StatementRank rank) {\n\t\tswitch (rank) {\n\t\tcase NORMAL:\n\t\t\treturn Vocabulary.WB_NORMAL_RANK;\n\t\tcase PREFERRED:\n\t\t\treturn Vocabulary.WB_PREFERRED_RANK;\n\t\tcase DEPRECATED:\n\t\t\treturn Vocabulary.WB_DEPRECATED_RANK;\n\t\tdefault:\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t}" ]
Refresh this context with the specified configuration locations. @param configLocations list of configuration resources (see implementation for specifics) @throws GeomajasException indicates a problem with the new location files (see cause)
[ "public void refresh(String[] configLocations) throws GeomajasException {\n\t\ttry {\n\t\t\tsetConfigLocations(configLocations);\n\t\t\trefresh();\n\t\t} catch (Exception e) {\n\t\t\tthrow new GeomajasException(e, ExceptionCode.REFRESH_CONFIGURATION_FAILED);\n\t\t}\n\t}" ]
[ "private void checkAllEnvelopes(PersistenceBroker broker)\r\n {\r\n Iterator iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n // only non transient objects should be performed\r\n if(!mod.getModificationState().isTransient())\r\n {\r\n mod.markReferenceElements(broker);\r\n }\r\n }\r\n }", "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax) {\n\t\treturn getMSDLineChart(t, lagMin, lagMax, new MeanSquaredDisplacmentFeature(t,\n\t\t\t\tlagMin));\n\t}", "public static final BigDecimal printDurationInDecimalThousandthsOfMinutes(Duration duration)\n {\n BigDecimal result = null;\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigDecimal.valueOf(printDurationFractionsOfMinutes(duration, 1000));\n }\n return result;\n }", "final public void addOffset(Integer start, Integer end) {\n if (tokenOffset == null) {\n setOffset(start, end);\n } else if ((start == null) || (end == null)) {\n // do nothing\n } else if (start > end) {\n throw new IllegalArgumentException(\"Start offset after end offset\");\n } else {\n tokenOffset.add(start, end);\n }\n }", "private Map<UUID, FieldType> populateCustomFieldMap()\n {\n byte[] data = m_taskProps.getByteArray(Props.CUSTOM_FIELDS);\n int length = MPPUtility.getInt(data, 0);\n int index = length + 36;\n\n // 4 byte record count\n int recordCount = MPPUtility.getInt(data, index);\n index += 4;\n\n // 8 bytes per record\n index += (8 * recordCount);\n \n Map<UUID, FieldType> map = new HashMap<UUID, FieldType>();\n while (index < data.length)\n {\n int blockLength = MPPUtility.getInt(data, index); \n if (blockLength <= 0 || index + blockLength > data.length)\n {\n break;\n }\n \n int fieldID = MPPUtility.getInt(data, index + 4);\n FieldType field = FieldTypeHelper.getInstance(fieldID);\n UUID guid = MPPUtility.getGUID(data, index + 160);\n map.put(guid, field);\n index += blockLength;\n }\n return map;\n }", "public void setSomePendingWritesAndSave(\n final long atTime,\n final ChangeEvent<BsonDocument> changeEvent\n ) {\n docLock.writeLock().lock();\n try {\n // if we were frozen\n if (isPaused) {\n // unfreeze the document due to the local write\n setPaused(false);\n // and now the unfrozen document is now stale\n setStale(true);\n }\n\n this.lastUncommittedChangeEvent =\n coalesceChangeEvents(this.lastUncommittedChangeEvent, changeEvent);\n this.lastResolution = atTime;\n docsColl.replaceOne(\n getDocFilter(namespace, documentId),\n this);\n } finally {\n docLock.writeLock().unlock();\n }\n }", "public static base_response update(nitro_service client, sslocspresponder resource) throws Exception {\n\t\tsslocspresponder updateresource = new sslocspresponder();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.cache = resource.cache;\n\t\tupdateresource.cachetimeout = resource.cachetimeout;\n\t\tupdateresource.batchingdepth = resource.batchingdepth;\n\t\tupdateresource.batchingdelay = resource.batchingdelay;\n\t\tupdateresource.resptimeout = resource.resptimeout;\n\t\tupdateresource.respondercert = resource.respondercert;\n\t\tupdateresource.trustresponder = resource.trustresponder;\n\t\tupdateresource.producedattimeskew = resource.producedattimeskew;\n\t\tupdateresource.signingcert = resource.signingcert;\n\t\tupdateresource.usenonce = resource.usenonce;\n\t\tupdateresource.insertclientcert = resource.insertclientcert;\n\t\treturn updateresource.update_resource(client);\n\t}", "@Pure\n\t@Inline(value = \"$3.union($1, $2)\", imported = MapExtensions.class)\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, Map<? extends K, ? extends V> right) {\n\t\treturn union(left, right);\n\t}", "protected void addPoint(double time, RandomVariable value, boolean isParameter) {\n\t\tsynchronized (rationalFunctionInterpolationLazyInitLock) {\n\t\t\tif(interpolationEntity == InterpolationEntity.LOG_OF_VALUE_PER_TIME && time == 0) {\n\t\t\t\tboolean containsOne = false; int index=0;\n\t\t\t\tfor(int i = 0; i< value.size(); i++){if(value.get(i)==1.0) {containsOne = true; index=i; break;}}\n\t\t\t\tif(containsOne && isParameter == false) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new IllegalArgumentException(\"The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index\" + index + \").\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tRandomVariable interpolationEntityValue = interpolationEntityFromValue(value, time);\n\n\t\t\tint index = getTimeIndex(time);\n\t\t\tif(index >= 0) {\n\t\t\t\tif(points.get(index).value == interpolationEntityValue) {\n\t\t\t\t\treturn;\t\t\t// Already in list\n\t\t\t\t} else if(isParameter) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new RuntimeException(\"Trying to add a value for a time for which another value already exists.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Insert the new point, retain ordering.\n\t\t\t\tPoint point = new Point(time, interpolationEntityValue, isParameter);\n\t\t\t\tpoints.add(-index-1, point);\n\n\t\t\t\tif(isParameter) {\n\t\t\t\t\t// Add this point also to the list of parameters\n\t\t\t\t\tint parameterIndex = getParameterIndex(time);\n\t\t\t\t\tif(parameterIndex >= 0) {\n\t\t\t\t\t\tnew RuntimeException(\"CurveFromInterpolationPoints inconsistent.\");\n\t\t\t\t\t}\n\t\t\t\t\tpointsBeingParameters.add(-parameterIndex-1, point);\n\t\t\t\t}\n\t\t\t}\n\t\t\trationalFunctionInterpolation = null;\n\t\t\tcurveCacheReference = null;\n\t\t}\n\t}" ]
Creates, writes and loads a new keystore and CA root certificate.
[ "protected void createKeystore() {\n\n\t\tjava.security.cert.Certificate signingCert = null;\n\t\tPrivateKey caPrivKey = null;\n\n\t\tif(_caCert == null || _caPrivKey == null)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tlog.debug(\"Keystore or signing cert & keypair not found. Generating...\");\n\n\t\t\t\tKeyPair caKeypair = getRSAKeyPair();\n\t\t\t\tcaPrivKey = caKeypair.getPrivate();\n\t\t\t\tsigningCert = CertificateCreator.createTypicalMasterCert(caKeypair);\n\n\t\t\t\tlog.debug(\"Done generating signing cert\");\n\t\t\t\tlog.debug(signingCert);\n\n\t\t\t\t_ks.load(null, _keystorepass);\n\n\t\t\t\t_ks.setCertificateEntry(_caCertAlias, signingCert);\n\t\t\t\t_ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new java.security.cert.Certificate[] {signingCert});\n\n\t\t\t\tFile caKsFile = new File(root, _caPrivateKeystore);\n\n\t\t\t\tOutputStream os = new FileOutputStream(caKsFile);\n\t\t\t\t_ks.store(os, _keystorepass);\n\n\t\t\t\tlog.debug(\"Wrote JKS keystore to: \" +\n\t\t\t\t\t\tcaKsFile.getAbsolutePath());\n\n\t\t\t\t// also export a .cer that can be imported as a trusted root\n\t\t\t\t// to disable all warning dialogs for interception\n\n\t\t\t\tFile signingCertFile = new File(root, EXPORTED_CERT_NAME);\n\n\t\t\t\tFileOutputStream cerOut = new FileOutputStream(signingCertFile);\n\n\t\t\t\tbyte[] buf = signingCert.getEncoded();\n\n\t\t\t\tlog.debug(\"Wrote signing cert to: \" + signingCertFile.getAbsolutePath());\n\n\t\t\t\tcerOut.write(buf);\n\t\t\t\tcerOut.flush();\n\t\t\t\tcerOut.close();\n\n\t\t\t\t_caCert = (X509Certificate)signingCert;\n\t\t\t\t_caPrivKey = caPrivKey;\n\t\t\t}\n\t\t\tcatch(Exception e)\n\t\t\t{\n\t\t\t\tlog.error(\"Fatal error creating/storing keystore or signing cert.\", e);\n\t\t\t\tthrow new Error(e);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlog.debug(\"Successfully loaded keystore.\");\n\t\t\tlog.debug(_caCert);\n\n\t\t}\n\n\t}" ]
[ "public static void validateZip(File file) throws IOException {\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n zipEntry = zipInput.getNextEntry();\n }\n\n try {\n if (zipInput != null) {\n zipInput.close();\n }\n } catch (IOException e) {\n }\n }", "@Override\n\tpublic ProxyAuthenticationMethod getMethod() {\n\t\tswitch (authenticationMethod) {\n\t\tcase BASIC:\n\t\t\treturn ProxyAuthenticationMethod.BASIC;\n\t\tcase DIGEST:\n\t\t\treturn ProxyAuthenticationMethod.DIGEST;\n\t\tcase URL:\n\t\t\treturn ProxyAuthenticationMethod.URL;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "public void flushAllLogs(final boolean force) {\n Iterator<Log> iter = getLogIterator();\n while (iter.hasNext()) {\n Log log = iter.next();\n try {\n boolean needFlush = force;\n if (!needFlush) {\n long timeSinceLastFlush = System.currentTimeMillis() - log.getLastFlushedTime();\n Integer logFlushInterval = logFlushIntervalMap.get(log.getTopicName());\n if (logFlushInterval == null) {\n logFlushInterval = config.getDefaultFlushIntervalMs();\n }\n final String flushLogFormat = \"[%s] flush interval %d, last flushed %d, need flush? %s\";\n needFlush = timeSinceLastFlush >= logFlushInterval.intValue();\n logger.trace(String.format(flushLogFormat, log.getTopicName(), logFlushInterval,\n log.getLastFlushedTime(), needFlush));\n }\n if (needFlush) {\n log.flush();\n }\n } catch (IOException ioe) {\n logger.error(\"Error flushing topic \" + log.getTopicName(), ioe);\n logger.error(\"Halting due to unrecoverable I/O error while flushing logs: \" + ioe.getMessage(), ioe);\n Runtime.getRuntime().halt(1);\n } catch (Exception e) {\n logger.error(\"Error flushing topic \" + log.getTopicName(), e);\n }\n }\n }", "public static void mainInternal(String[] args) throws Exception {\n\n Options options = new Options();\n CmdLineParser parser = new CmdLineParser(options);\n try {\n parser.parseArgument(args);\n } catch (CmdLineException e) {\n helpScreen(parser);\n return;\n }\n\n try {\n List<String> configs = new ArrayList<>();\n if (options.configs != null) {\n configs.addAll(Arrays.asList(options.configs.split(\",\")));\n }\n ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);\n } catch (ConfigException ex) {\n ConfigLogger.error(ex);\n throw ex;\n } catch (Throwable th) {\n ConfigLogger.error(th);\n throw th;\n }\n }", "private void validateAttributesToCreateANewRendererViewHolder() {\n if (viewType == null) {\n throw new NullContentException(\n \"RendererBuilder needs a view type to create a RendererViewHolder\");\n }\n if (layoutInflater == null) {\n throw new NullLayoutInflaterException(\n \"RendererBuilder needs a LayoutInflater to create a RendererViewHolder\");\n }\n if (parent == null) {\n throw new NullParentException(\n \"RendererBuilder needs a parent to create a RendererViewHolder\");\n }\n }", "@Override\n\tpublic ProxyAuthenticationMethod getMethod() {\n\t\tswitch (authenticationMethod) {\n\t\tcase BASIC:\n\t\t\treturn ProxyAuthenticationMethod.BASIC;\n\t\tcase DIGEST:\n\t\t\treturn ProxyAuthenticationMethod.DIGEST;\n\t\tcase URL:\n\t\t\treturn ProxyAuthenticationMethod.URL;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "public void doLocalClear()\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clear materialization cache\");\r\n invokeCounter = 0;\r\n enabledReadCache = false;\r\n objectBuffer.clear();\r\n }", "public UriComponentsBuilder queryParams(MultiValueMap<String, String> params) {\n\t\tAssert.notNull(params, \"'params' must not be null\");\n\t\tthis.queryParams.putAll(params);\n\t\treturn this;\n\t}", "public static ResourceKey key(Class<?> clazz, Enum<?> value) {\n return new ResourceKey(clazz.getName(), value.name());\n }" ]
Checks the given model. @param modelDef The model @param checkLevel The amount of checks to perform @exception ConstraintException If a constraint has been violated
[ "public void check(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureReferencedKeys(modelDef, checkLevel);\r\n checkReferenceForeignkeys(modelDef, checkLevel);\r\n checkCollectionForeignkeys(modelDef, checkLevel);\r\n checkKeyModifications(modelDef, checkLevel);\r\n }" ]
[ "public Collection<V> put(K key, Collection<V> collection) {\r\n return map.put(key, collection);\r\n }", "public static dnstxtrec get(nitro_service service, String domain) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\tobj.set_domain(domain);\n\t\tdnstxtrec response = (dnstxtrec) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setOnCloseListener(@NonNull final android.support.v7.widget.SearchView.OnCloseListener listener) {\n if (searchView != null) {\n searchView.setOnCloseListener(new SearchView.OnCloseListener() {\n @Override public boolean onClose() {\n return listener.onClose();\n }\n });\n } else if (supportView != null) {\n supportView.setOnCloseListener(listener);\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }", "public void check(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureColumn(fieldDef, checkLevel);\r\n ensureJdbcType(fieldDef, checkLevel);\r\n ensureConversion(fieldDef, checkLevel);\r\n ensureLength(fieldDef, checkLevel);\r\n ensurePrecisionAndScale(fieldDef, checkLevel);\r\n checkLocking(fieldDef, checkLevel);\r\n checkSequenceName(fieldDef, checkLevel);\r\n checkId(fieldDef, checkLevel);\r\n if (fieldDef.isAnonymous())\r\n {\r\n checkAnonymous(fieldDef, checkLevel);\r\n }\r\n else\r\n {\r\n checkReadonlyAccessForNativePKs(fieldDef, checkLevel);\r\n }\r\n }", "public static double[][] invert(double[][] matrix) {\n\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tLUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = lu.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}", "private static boolean isCollectionMatching(Joinable mainSideJoinable, OgmCollectionPersister inverseSidePersister) {\n\t\tboolean isSameTable = mainSideJoinable.getTableName().equals( inverseSidePersister.getTableName() );\n\n\t\tif ( !isSameTable ) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn Arrays.equals( mainSideJoinable.getKeyColumnNames(), inverseSidePersister.getElementColumnNames() );\n\t}", "private void writeTask(Task mpxjTask, List<net.sf.mpxj.planner.schema.Task> taskList) throws JAXBException\n {\n net.sf.mpxj.planner.schema.Task plannerTask = m_factory.createTask();\n taskList.add(plannerTask);\n plannerTask.setEnd(getDateTimeString(mpxjTask.getFinish()));\n plannerTask.setId(getIntegerString(mpxjTask.getUniqueID()));\n plannerTask.setName(getString(mpxjTask.getName()));\n plannerTask.setNote(mpxjTask.getNotes());\n plannerTask.setPercentComplete(getIntegerString(mpxjTask.getPercentageWorkComplete()));\n plannerTask.setPriority(mpxjTask.getPriority() == null ? null : getIntegerString(mpxjTask.getPriority().getValue() * 10));\n plannerTask.setScheduling(getScheduling(mpxjTask.getType()));\n plannerTask.setStart(getDateTimeString(DateHelper.getDayStartDate(mpxjTask.getStart())));\n if (mpxjTask.getMilestone())\n {\n plannerTask.setType(\"milestone\");\n }\n else\n {\n plannerTask.setType(\"normal\");\n }\n plannerTask.setWork(getDurationString(mpxjTask.getWork()));\n plannerTask.setWorkStart(getDateTimeString(mpxjTask.getStart()));\n\n ConstraintType mpxjConstraintType = mpxjTask.getConstraintType();\n if (mpxjConstraintType != ConstraintType.AS_SOON_AS_POSSIBLE)\n {\n Constraint plannerConstraint = m_factory.createConstraint();\n plannerTask.setConstraint(plannerConstraint);\n if (mpxjConstraintType == ConstraintType.START_NO_EARLIER_THAN)\n {\n plannerConstraint.setType(\"start-no-earlier-than\");\n }\n else\n {\n if (mpxjConstraintType == ConstraintType.MUST_START_ON)\n {\n plannerConstraint.setType(\"must-start-on\");\n }\n }\n\n plannerConstraint.setTime(getDateTimeString(mpxjTask.getConstraintDate()));\n }\n\n //\n // Write predecessors\n //\n writePredecessors(mpxjTask, plannerTask);\n\n m_eventManager.fireTaskWrittenEvent(mpxjTask);\n\n //\n // Write child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTaskList = plannerTask.getTask();\n for (Task task : mpxjTask.getChildTasks())\n {\n writeTask(task, childTaskList);\n }\n }", "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.DELETE)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID) throws Exception {\n logger.info(\"Attempting to remove the following client: {}\", clientUUID);\n if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n clientService.remove(profileId, clientUUID);\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }", "private Properties mapToProperties(Map<String, String> map) {\r\n\t\t Properties p = new Properties();\r\n\t\t for (Map.Entry<String,String> entry : map.entrySet()) {\r\n\t\t p.put(entry.getKey(), entry.getValue());\r\n\t\t }\r\n\t\t return p;\r\n\t\t }" ]
Convert an Object of type Class to an Object.
[ "public static Object toObject(Class<?> clazz, Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (clazz == null) {\n return value;\n }\n\n if (java.sql.Date.class.isAssignableFrom(clazz)) {\n return toDate(value);\n }\n if (java.sql.Time.class.isAssignableFrom(clazz)) {\n return toTime(value);\n }\n if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {\n return toTimestamp(value);\n }\n if (java.util.Date.class.isAssignableFrom(clazz)) {\n return toDateTime(value);\n }\n\n return value;\n }" ]
[ "public PhotoList<Photo> getPublicPhotos(String userId, Set<String> extras, 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_GET_PUBLIC_PHOTOS);\r\n\r\n parameters.put(\"user_id\", userId);\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 if (extras != null) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n 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 }", "public static DMatrixRMaj copyTriangle(DMatrixRMaj src , DMatrixRMaj dst , boolean upper ) {\n if( dst == null ) {\n dst = new DMatrixRMaj(src.numRows,src.numCols);\n } else if( src.numRows != dst.numRows || src.numCols != dst.numCols ) {\n throw new IllegalArgumentException(\"src and dst must have the same dimensions.\");\n }\n\n if( upper ) {\n int N = Math.min(src.numRows,src.numCols);\n for( int i = 0; i < N; i++ ) {\n int index = i*src.numCols+i;\n System.arraycopy(src.data,index,dst.data,index,src.numCols-i);\n }\n } else {\n for( int i = 0; i < src.numRows; i++ ) {\n int length = Math.min(i+1,src.numCols);\n int index = i*src.numCols;\n System.arraycopy(src.data,index,dst.data,index,length);\n }\n }\n\n return dst;\n }", "public static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\n }", "public static Connection connectSync(final ProtocolConnectionConfiguration configuration) throws IOException {\n long timeoutMillis = configuration.getConnectionTimeout();\n CallbackHandler handler = configuration.getCallbackHandler();\n final CallbackHandler actualHandler;\n ProtocolTimeoutHandler timeoutHandler = configuration.getTimeoutHandler();\n // Note: If a client supplies a ProtocolTimeoutHandler it is taking on full responsibility for timeout management.\n if (timeoutHandler == null) {\n GeneralTimeoutHandler defaultTimeoutHandler = new GeneralTimeoutHandler();\n // No point wrapping our AnonymousCallbackHandler.\n actualHandler = handler != null ? new WrapperCallbackHandler(defaultTimeoutHandler, handler) : null;\n timeoutHandler = defaultTimeoutHandler;\n } else {\n actualHandler = handler;\n }\n\n final IoFuture<Connection> future = connect(actualHandler, configuration);\n\n IoFuture.Status status = timeoutHandler.await(future, timeoutMillis);\n\n if (status == IoFuture.Status.DONE) {\n return future.get();\n }\n if (status == IoFuture.Status.FAILED) {\n throw ProtocolLogger.ROOT_LOGGER.failedToConnect(configuration.getUri(), future.getException());\n }\n throw ProtocolLogger.ROOT_LOGGER.couldNotConnect(configuration.getUri());\n }", "@Override\n\tpublic IPAddress toAddress() throws UnknownHostException, HostNameException {\n\t\tIPAddress addr = resolvedAddress;\n\t\tif(addr == null && !resolvedIsNull) {\n\t\t\t//note that validation handles empty address resolution\n\t\t\tvalidate();\n\t\t\tsynchronized(this) {\n\t\t\t\taddr = resolvedAddress;\n\t\t\t\tif(addr == null && !resolvedIsNull) {\n\t\t\t\t\tif(parsedHost.isAddressString()) {\n\t\t\t\t\t\taddr = parsedHost.asAddress();\n\t\t\t\t\t\tresolvedIsNull = (addr == null);\n\t\t\t\t\t\t//note there is no need to apply prefix or mask here, it would have been applied to the address already\n\t\t\t\t\t} else {\n\t\t\t\t\t\tString strHost = parsedHost.getHost();\n\t\t\t\t\t\tif(strHost.length() == 0 && !validationOptions.emptyIsLoopback) {\n\t\t\t\t\t\t\taddr = null;\n\t\t\t\t\t\t\tresolvedIsNull = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//Note we do not set resolvedIsNull, so we will attempt to resolve again if the previous attempt threw an exception\n\t\t\t\t\t\t\tInetAddress inetAddress = InetAddress.getByName(strHost);\n\t\t\t\t\t\t\tbyte bytes[] = inetAddress.getAddress();\n\t\t\t\t\t\t\tInteger networkPrefixLength = parsedHost.getNetworkPrefixLength();\n\t\t\t\t\t\t\tif(networkPrefixLength == null) {\n\t\t\t\t\t\t\t\tIPAddress mask = parsedHost.getMask();\n\t\t\t\t\t\t\t\tif(mask != null) {\n\t\t\t\t\t\t\t\t\tbyte maskBytes[] = mask.getBytes();\n\t\t\t\t\t\t\t\t\tif(maskBytes.length != bytes.length) {\n\t\t\t\t\t\t\t\t\t\tthrow new HostNameException(host, \"ipaddress.error.ipMismatch\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tfor(int i = 0; i < bytes.length; i++) {\n\t\t\t\t\t\t\t\t\t\tbytes[i] &= maskBytes[i];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tnetworkPrefixLength = mask.getBlockMaskPrefixLength(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tIPAddressStringParameters addressParams = validationOptions.addressOptions;\n\t\t\t\t\t\t\tif(bytes.length == IPv6Address.BYTE_COUNT) {\n\t\t\t\t\t\t\t\tIPv6AddressCreator creator = addressParams.getIPv6Parameters().getNetwork().getAddressCreator();\n\t\t\t\t\t\t\t\taddr = creator.createAddressInternal(bytes, networkPrefixLength, null, this); /* address creation */\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tIPv4AddressCreator creator = addressParams.getIPv4Parameters().getNetwork().getAddressCreator();\n\t\t\t\t\t\t\t\taddr = creator.createAddressInternal(bytes, networkPrefixLength, this); /* address creation */\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\tresolvedAddress = addr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn addr;\n\t}", "protected List<I_CmsFacetQueryItem> parseFacetQueryItems(JSONObject queryFacetObject) throws JSONException {\n\n JSONArray items = queryFacetObject.getJSONArray(JSON_KEY_QUERY_FACET_QUERY);\n List<I_CmsFacetQueryItem> result = new ArrayList<I_CmsFacetQueryItem>(items.length());\n for (int i = 0; i < items.length(); i++) {\n I_CmsFacetQueryItem item = parseFacetQueryItem(items.getJSONObject(i));\n if (item != null) {\n result.add(item);\n }\n }\n return result;\n }", "public OperationBuilder addInputStream(final InputStream in) {\n Assert.checkNotNullParam(\"in\", in);\n if (inputStreams == null) {\n inputStreams = new ArrayList<InputStream>();\n }\n inputStreams.add(in);\n return this;\n }", "protected final void error(final HttpServletResponse httpServletResponse, final Throwable e) {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n LOGGER.error(\"Error while processing request\", e);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }", "private List<Map<Class<? extends Annotation>, ParameterInfo<?>>> createParametersInfos(Method method) {\n if (method.getParameterTypes().length <= 2) {\n return Collections.emptyList();\n }\n\n List<Map<Class<? extends Annotation>, ParameterInfo<?>>> result = new ArrayList<>();\n Type[] parameterTypes = method.getGenericParameterTypes();\n Annotation[][] parameterAnnotations = method.getParameterAnnotations();\n\n for (int i = 2; i < parameterAnnotations.length; i++) {\n Annotation[] annotations = parameterAnnotations[i];\n Map<Class<? extends Annotation>, ParameterInfo<?>> paramAnnotations = new IdentityHashMap<>();\n\n for (Annotation annotation : annotations) {\n Class<? extends Annotation> annotationType = annotation.annotationType();\n ParameterInfo<?> parameterInfo;\n\n if (PathParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createPathParamConverter(parameterTypes[i]));\n } else if (QueryParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createQueryParamConverter(parameterTypes[i]));\n } else if (HeaderParam.class.isAssignableFrom(annotationType)) {\n parameterInfo = ParameterInfo.create(annotation,\n ParamConvertUtils.createHeaderParamConverter(parameterTypes[i]));\n } else {\n parameterInfo = ParameterInfo.create(annotation, null);\n }\n\n paramAnnotations.put(annotationType, parameterInfo);\n }\n\n // Must have either @PathParam, @QueryParam or @HeaderParam, but not two or more.\n int presence = 0;\n for (Class<? extends Annotation> annotationClass : paramAnnotations.keySet()) {\n if (SUPPORTED_PARAM_ANNOTATIONS.contains(annotationClass)) {\n presence++;\n }\n }\n if (presence != 1) {\n throw new IllegalArgumentException(\n String.format(\"Must have exactly one annotation from %s for parameter %d in method %s\",\n SUPPORTED_PARAM_ANNOTATIONS, i, method));\n }\n\n result.add(Collections.unmodifiableMap(paramAnnotations));\n }\n\n return Collections.unmodifiableList(result);\n }" ]
Returns the item at the specified position. @param position index of the item to return @return the item at the specified position or {@code null} when not found
[ "@Nullable\n public T getItem(final int position) {\n if (position < 0 || position >= mObjects.size()) {\n return null;\n }\n return mObjects.get(position);\n }" ]
[ "public static void extractHouseholderRow( ZMatrixRMaj A ,\n int row ,\n int col0, int col1 , double u[], int offsetU )\n {\n int indexU = (offsetU+col0)*2;\n u[indexU] = 1;\n u[indexU+1] = 0;\n\n int indexA = (row*A.numCols + (col0+1))*2;\n System.arraycopy(A.data,indexA,u,indexU+2,(col1-col0-1)*2);\n }", "private String escapeString(String value)\n {\n m_buffer.setLength(0);\n m_buffer.append('\"');\n for (int index = 0; index < value.length(); index++)\n {\n char c = value.charAt(index);\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\\\\\"\");\n break;\n }\n\n case '\\\\':\n {\n m_buffer.append(\"\\\\\\\\\");\n break;\n }\n\n case '/':\n {\n m_buffer.append(\"\\\\/\");\n break;\n }\n\n case '\\b':\n {\n m_buffer.append(\"\\\\b\");\n break;\n }\n\n case '\\f':\n {\n m_buffer.append(\"\\\\f\");\n break;\n }\n\n case '\\n':\n {\n m_buffer.append(\"\\\\n\");\n break;\n }\n\n case '\\r':\n {\n m_buffer.append(\"\\\\r\");\n break;\n }\n\n case '\\t':\n {\n m_buffer.append(\"\\\\t\");\n break;\n }\n\n default:\n {\n // Append if it's not a control character (0x00 to 0x1f)\n if (c > 0x1f)\n {\n m_buffer.append(c);\n }\n break;\n }\n }\n }\n m_buffer.append('\"');\n return m_buffer.toString();\n }", "@SuppressWarnings(\"unchecked\")\n public static <E> E getObject(String className) {\n if (className == null) {\n return (E) null;\n }\n try {\n return (E) Class.forName(className).newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\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 ParallelTaskBuilder prepareTcp(String command) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.TCP);\n cb.getTcpMeta().setCommand(command);\n return cb;\n }", "private void rotatorPushRight2( int m , int offset)\n {\n double b11 = bulge;\n double b12 = diag[m+offset];\n\n computeRotator(b12,-b11);\n\n diag[m+offset] = b12*c-b11*s;\n\n if( m+offset<N-1) {\n double b22 = off[m+offset];\n off[m+offset] = b22*c;\n bulge = b22*s;\n }\n\n// SimpleMatrix Q = createQ(m,m+offset, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+offset,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }", "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 <E> Filter<E> switchedFilter(Filter<E> filter, boolean negated) {\r\n return (new NegatedFilter<E>(filter, negated));\r\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 }" ]
As part of checking whether a metadata cache can be auto-mounted for a particular media slot, this method looks up the track at the specified offset within the player's track list, and returns its rekordbox ID. @param slot the slot being considered for auto-attaching a metadata cache @param client the connection to the database server on the player holding that slot @param offset an index into the list of all tracks present in the slot @throws IOException if there is a problem communicating with the player
[ "private static int findTrackIdAtOffset(SlotReference slot, Client client, int offset) throws IOException {\n Message entry = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot.slot, CdjStatus.TrackType.REKORDBOX, offset, 1).get(0);\n if (entry.getMenuItemType() == Message.MenuItemType.UNKNOWN) {\n logger.warn(\"Encountered unrecognized track list entry item type: {}\", entry);\n }\n return (int)((NumberField)entry.arguments.get(1)).getValue();\n }" ]
[ "private List<String> getCommandLines(File file) {\n List<String> lines = new ArrayList<>();\n try (BufferedReader reader = new BufferedReader(new FileReader(file))) {\n String line = reader.readLine();\n while (line != null) {\n lines.add(line);\n line = reader.readLine();\n }\n } catch (Throwable e) {\n throw new IllegalStateException(\"Failed to process file \" + file.getAbsolutePath(), e);\n }\n return lines;\n }", "public CustomField getCustomField(FieldType field)\n {\n CustomField result = m_configMap.get(field);\n if (result == null)\n {\n result = new CustomField(field, this);\n m_configMap.put(field, result);\n }\n return result;\n }", "public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_WHITELIST_ENTRY_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE);\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "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 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 Map<String, String> mapStringToMap(String map) {\r\n String[] m = map.split(\"[,;]\");\r\n Map<String, String> res = new HashMap<String, String>();\r\n for (String str : m) {\r\n int index = str.lastIndexOf('=');\r\n String key = str.substring(0, index);\r\n String val = str.substring(index + 1);\r\n res.put(key.trim(), val.trim());\r\n }\r\n return res;\r\n }", "public void install(@Observes(precedence = 90) CubeDockerConfiguration configuration,\n ArquillianDescriptor arquillianDescriptor) {\n\n DockerCompositions cubes = configuration.getDockerContainersContent();\n\n final SeleniumContainers seleniumContainers =\n SeleniumContainers.create(getBrowser(arquillianDescriptor), cubeDroneConfigurationInstance.get());\n cubes.add(seleniumContainers.getSeleniumContainerName(), seleniumContainers.getSeleniumContainer());\n\n final boolean recording = cubeDroneConfigurationInstance.get().isRecording();\n if (recording) {\n cubes.add(seleniumContainers.getVncContainerName(), seleniumContainers.getVncContainer());\n cubes.add(seleniumContainers.getVideoConverterContainerName(),\n seleniumContainers.getVideoConverterContainer());\n }\n\n seleniumContainersInstanceProducer.set(seleniumContainers);\n\n System.out.println(\"SELENIUM INSTALLED\");\n System.out.println(ConfigUtil.dump(cubes));\n }", "static byte[] hmacSha1(StringBuilder message, String key) {\n try {\n Mac mac = Mac.getInstance(\"HmacSHA1\");\n mac.init(new SecretKeySpec(key.getBytes(), \"HmacSHA1\"));\n return mac.doFinal(message.toString().getBytes());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "@Pure\n\tpublic static <P1, P2, P3, RESULT> Function2<P2, P3, RESULT> curry(final Function3<? super P1, ? super P2, ? super P3, ? extends RESULT> function,\n\t\t\tfinal P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function2<P2, P3, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p2, P3 p3) {\n\t\t\t\treturn function.apply(argument, p2, p3);\n\t\t\t}\n\t\t};\n\t}" ]
Create content assist proposals and pass them to the given acceptor.
[ "public void createProposals(final Collection<ContentAssistContext> contexts, final IIdeContentProposalAcceptor acceptor) {\n Iterable<ContentAssistContext> _filteredContexts = this.getFilteredContexts(contexts);\n for (final ContentAssistContext context : _filteredContexts) {\n ImmutableList<AbstractElement> _firstSetGrammarElements = context.getFirstSetGrammarElements();\n for (final AbstractElement element : _firstSetGrammarElements) {\n {\n boolean _canAcceptMoreProposals = acceptor.canAcceptMoreProposals();\n boolean _not = (!_canAcceptMoreProposals);\n if (_not) {\n return;\n }\n this.createProposals(element, context, acceptor);\n }\n }\n }\n }" ]
[ "public static void initialize(BeanManagerImpl deploymentManager, ServiceRegistry deploymentServices) {\n Container instance = new Container(RegistrySingletonProvider.STATIC_INSTANCE, deploymentManager, deploymentServices);\n Container.instance.set(RegistrySingletonProvider.STATIC_INSTANCE, instance);\n }", "public static base_response add(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey addresource = new sslcertkey();\n\t\taddresource.certkey = resource.certkey;\n\t\taddresource.cert = resource.cert;\n\t\taddresource.key = resource.key;\n\t\taddresource.password = resource.password;\n\t\taddresource.fipskey = resource.fipskey;\n\t\taddresource.inform = resource.inform;\n\t\taddresource.passplain = resource.passplain;\n\t\taddresource.expirymonitor = resource.expirymonitor;\n\t\taddresource.notificationperiod = resource.notificationperiod;\n\t\taddresource.bundle = resource.bundle;\n\t\treturn addresource.add_resource(client);\n\t}", "static void addDeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) {\n final String name = deployment.getName();\n\n final Set<String> serverGroups = deployment.getServerGroups();\n // If the server groups are empty this is a standalone deployment\n if (serverGroups.isEmpty()) {\n final ModelNode address = createAddress(DEPLOYMENT, name);\n builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address));\n } else {\n for (String serverGroup : serverGroups) {\n final ModelNode address = createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, name);\n builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address));\n }\n }\n }", "private void sendAnnouncement(InetAddress broadcastAddress) {\n try {\n DatagramPacket announcement = new DatagramPacket(announcementBytes, announcementBytes.length,\n broadcastAddress, DeviceFinder.ANNOUNCEMENT_PORT);\n socket.get().send(announcement);\n Thread.sleep(getAnnounceInterval());\n } catch (Throwable t) {\n logger.warn(\"Unable to send announcement packet, shutting down\", t);\n stop();\n }\n }", "@SuppressWarnings(\"unchecked\")\n public <T> DistributedFuture<GROUP, T> createFuture(HazeltaskTask<GROUP> task) {\n DistributedFuture<GROUP, T> future = new DistributedFuture<GROUP, T>(topologyService, task.getGroup(), task.getId());\n this.futures.put(task.getId(), (DistributedFuture<GROUP, Serializable>) future);\n return future;\n }", "public static <T> ConflictHandler<T> localWins() {\n return new ConflictHandler<T>() {\n @Override\n public T resolveConflict(\n final BsonValue documentId,\n final ChangeEvent<T> localEvent,\n final ChangeEvent<T> remoteEvent\n ) {\n return localEvent.getFullDocument();\n }\n };\n }", "public void setWorkingDay(Day day, boolean working)\n {\n setWorkingDay(day, (working ? DayType.WORKING : DayType.NON_WORKING));\n }", "public static BufferedImage resizeToHeight(BufferedImage originalImage, int heightOut) {\n\n int width = originalImage.getWidth();\n\n int height = originalImage.getHeight();\n\n int heightPercent = (heightOut * 100) / height;\n\n int newWidth = (width * heightPercent) / 100;\n\n BufferedImage resizedImage =\n new BufferedImage(newWidth, heightOut, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(originalImage, 0, 0, newWidth, heightOut, null);\n g.dispose();\n\n return resizedImage;\n }", "protected void addConstructors(ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) {\n try {\n if (getBeanType().isInterface()) {\n ConstructorUtils.addDefaultConstructor(proxyClassType, initialValueBytecode, !useConstructedFlag());\n } else {\n boolean constructorFound = false;\n for (Constructor<?> constructor : AccessController.doPrivileged(new GetDeclaredConstructorsAction(getBeanType()))) {\n if ((constructor.getModifiers() & Modifier.PRIVATE) == 0) {\n constructorFound = true;\n String[] exceptions = new String[constructor.getExceptionTypes().length];\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = constructor.getExceptionTypes()[i].getName();\n }\n ConstructorUtils.addConstructor(BytecodeUtils.VOID_CLASS_DESCRIPTOR, DescriptorUtils.parameterDescriptors(constructor.getParameterTypes()), exceptions, proxyClassType, initialValueBytecode, !useConstructedFlag());\n }\n }\n if (!constructorFound) {\n // the bean only has private constructors, we need to generate\n // two fake constructors that call each other\n addConstructorsForBeanWithPrivateConstructors(proxyClassType);\n }\n }\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }" ]
Figure out, based on how much time has elapsed since we received an update, and the playback position, speed, and direction at the time of that update, where the player will be now. @param update the most recent update received from a player @param currentTimestamp the nanosecond timestamp representing when we want to interpolate the track's position @return the playback position we believe that player has reached now
[ "private long interpolateTimeSinceUpdate(TrackPositionUpdate update, long currentTimestamp) {\n if (!update.playing) {\n return update.milliseconds;\n }\n long elapsedMillis = (currentTimestamp - update.timestamp) / 1000000;\n long moved = Math.round(update.pitch * elapsedMillis);\n if (update.reverse) {\n return update.milliseconds - moved;\n }\n return update.milliseconds + moved;\n }" ]
[ "public void add(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> newC = cf.newCollection();\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n newC.addAll(c);\r\n }\r\n newC.add(value);\r\n map.put(key, newC); // replacing the old collection\r\n } else {\r\n Collection<V> c = map.get(key);\r\n if (c == null) {\r\n c = cf.newCollection();\r\n map.put(key, c);\r\n }\r\n c.add(value); // modifying the old collection\r\n }\r\n }", "public static <T, ID> int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig,\n\t\t\tboolean ignoreErrors) throws SQLException {\n\t\tDatabaseType databaseType = connectionSource.getDatabaseType();\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\tif (dao instanceof BaseDaoImpl<?, ?>) {\n\t\t\treturn doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\tTableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t\treturn doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors);\n\t\t}\n\t}", "public static inat get(nitro_service service, String name) throws Exception{\n\t\tinat obj = new inat();\n\t\tobj.set_name(name);\n\t\tinat response = (inat) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void init(AttributeSet attrs) {\n inflate(getContext(), R.layout.intl_phone_input, this);\n\n /**+\n * Country spinner\n */\n mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country);\n mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext());\n mCountrySpinner.setAdapter(mCountrySpinnerAdapter);\n\n mCountries = CountriesFetcher.getCountries(getContext());\n mCountrySpinnerAdapter.addAll(mCountries);\n mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener);\n\n setFlagDefaults(attrs);\n\n /**\n * Phone text field\n */\n mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone);\n mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher);\n\n setDefault();\n setEditTextDefaults(attrs);\n }", "public void update(int width, int height, int sampleCount) {\n if (capturing) {\n throw new IllegalStateException(\"Cannot update backing texture while capturing\");\n }\n\n this.width = width;\n this.height = height;\n\n if (sampleCount == 0)\n captureTexture = new GVRRenderTexture(getGVRContext(), width, height);\n else\n captureTexture = new GVRRenderTexture(getGVRContext(), width, height, sampleCount);\n\n setRenderTexture(captureTexture);\n readBackBuffer = new int[width * height];\n }", "public static base_responses add(nitro_service client, dnstxtrec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnstxtrec addresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnstxtrec();\n\t\t\t\taddresources[i].domain = resources[i].domain;\n\t\t\t\taddresources[i].String = resources[i].String;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static void applyToOrTransparent(ColorHolder colorHolder, Context ctx, GradientDrawable gradientDrawable) {\n if (colorHolder != null && gradientDrawable != null) {\n colorHolder.applyTo(ctx, gradientDrawable);\n } else if (gradientDrawable != null) {\n gradientDrawable.setColor(Color.TRANSPARENT);\n }\n }", "@GET\n @Produces(MediaType.APPLICATION_JSON)\n @Path(\"/graph/{name}/{version}\")\n public Response getModuleGraph(@PathParam(\"name\") final String moduleName,\n @PathParam(\"version\") final String moduleVersion,\n @Context final UriInfo uriInfo){\n\n LOG.info(\"Dependency Checker got a get module graph export request.\");\n\n if(moduleName == null || moduleVersion == null){\n return Response.serverError().status(HttpStatus.NOT_ACCEPTABLE_406).build();\n }\n\n final FiltersHolder filters = new FiltersHolder();\n filters.init(uriInfo.getQueryParameters());\n\n final String moduleId = DbModule.generateID(moduleName, moduleVersion);\n final AbstractGraph moduleGraph = getGraphsHandler(filters).getModuleGraph(moduleId);\n\n return Response.ok(moduleGraph).build();\n }", "public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }" ]
Pick arbitrary copying method from available configuration and don't forget to set generic method type if required. @param builder
[ "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 String validationErrors() {\n\n List<String> errors = new ArrayList<>();\n for (File config : getConfigFiles()) {\n String filename = config.getName();\n try (FileInputStream stream = new FileInputStream(config)) {\n CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(stream, false), new CmsXmlEntityResolver(null), true);\n } catch (CmsXmlException e) {\n errors.add(filename + \":\" + e.getCause().getMessage());\n } catch (Exception e) {\n errors.add(filename + \":\" + e.getMessage());\n }\n }\n if (errors.size() == 0) {\n return null;\n }\n String errString = CmsStringUtil.listAsString(errors, \"\\n\");\n JSONObject obj = new JSONObject();\n try {\n obj.put(\"err\", errString);\n } catch (JSONException e) {\n\n }\n return obj.toString();\n }", "public static Record getRecord(String text)\n {\n Record root;\n\n try\n {\n root = new Record(text);\n }\n\n //\n // I've come across invalid calendar data in an otherwise fine Primavera\n // database belonging to a customer. We deal with this gracefully here\n // rather than propagating an exception.\n //\n catch (Exception ex)\n {\n root = null;\n }\n\n return root;\n }", "public synchronized static SQLiteDatabase getConnection(Context context) {\n\t\tif (database == null) {\n\t\t\t// Construct the single helper and open the unique(!) db connection for the app\n\t\t\tdatabase = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase();\n\t\t}\n\t\treturn database;\n\t}", "public 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 }", "public int getIndexMin() {\n int indexMin = 0;\n double min = getEigenvalue(0).getMagnitude2();\n\n final int N = getNumberOfEigenvalues();\n for( int i = 1; i < N; i++ ) {\n double m = getEigenvalue(i).getMagnitude2();\n if( m < min ) {\n min = m;\n indexMin = i;\n }\n }\n\n return indexMin;\n }", "public static HttpResponse getResponse(String urls, HttpRequest request,\n HttpMethod method, int connectTimeoutMillis, int readTimeoutMillis) throws IOException {\n OutputStream out = null;\n InputStream content = null;\n HttpResponse response = null;\n HttpURLConnection httpConn = request\n .getHttpConnection(urls, method.name());\n httpConn.setConnectTimeout(connectTimeoutMillis);\n httpConn.setReadTimeout(readTimeoutMillis);\n\n try {\n httpConn.connect();\n if (null != request.getPayload() && request.getPayload().length > 0) {\n out = httpConn.getOutputStream();\n out.write(request.getPayload());\n }\n content = httpConn.getInputStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } catch (SocketTimeoutException e) {\n throw e;\n } catch (IOException e) {\n content = httpConn.getErrorStream();\n response = new HttpResponse();\n parseHttpConn(response, httpConn, content);\n return response;\n } finally {\n if (content != null) {\n content.close();\n }\n httpConn.disconnect();\n }\n }", "public String getURN() throws InvalidRegistrationContentException {\n if (parsedConfig==null || parsedConfig.urn==null || parsedConfig.urn.trim().isEmpty()) {\n throw new InvalidRegistrationContentException(\"Invalid registration config - failed to read mediator URN\");\n }\n return parsedConfig.urn;\n }", "private void handleContentLength(Event event) {\n if (event.getContent() == null) {\n return;\n }\n\n if (maxContentLength == -1 || event.getContent().length() <= maxContentLength) {\n return;\n }\n\n if (maxContentLength < CUT_START_TAG.length() + CUT_END_TAG.length()) {\n event.setContent(\"\");\n event.setContentCut(true);\n return;\n }\n\n int contentLength = maxContentLength - CUT_START_TAG.length() - CUT_END_TAG.length();\n event.setContent(CUT_START_TAG + event.getContent().substring(0, contentLength) + CUT_END_TAG);\n event.setContentCut(true);\n }", "public static void Forward(double[] data) {\n double[] result = new double[data.length];\n\n for (int k = 0; k < result.length; k++) {\n double sum = 0;\n for (int n = 0; n < data.length; n++) {\n double theta = ((2.0 * Math.PI) / data.length) * k * n;\n sum += data[n] * cas(theta);\n }\n result[k] = (1.0 / Math.sqrt(data.length)) * sum;\n }\n\n for (int i = 0; i < result.length; i++) {\n data[i] = result[i];\n }\n\n }" ]
Use this API to unset the properties of csparameter resource. Properties that need to be unset are specified in args array.
[ "public static base_response unset(nitro_service client, csparameter resource, String[] args) throws Exception{\n\t\tcsparameter unsetresource = new csparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
[ "public static base_responses add(nitro_service client, cacheselector resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheselector addresources[] = new cacheselector[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cacheselector();\n\t\t\t\taddresources[i].selectorname = resources[i].selectorname;\n\t\t\t\taddresources[i].rule = resources[i].rule;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public boolean process( DMatrixSparseCSC A ) {\n init(A);\n\n TriangularSolver_DSCC.eliminationTree(A,true,parent,gwork);\n\n countNonZeroInR(parent);\n countNonZeroInV(parent);\n\n // if more columns than rows it's possible that Q*R != A. That's because a householder\n // would need to be created that's outside the m by m Q matrix. In reality it has\n // a partial solution. Column pivot are needed.\n if( m < n ) {\n for (int row = 0; row <m; row++) {\n if( gwork.data[head+row] < 0 ) {\n return false;\n }\n }\n }\n return true;\n }", "protected void runQuery() {\n\n String pool = m_pool.getValue();\n String stmt = m_script.getValue();\n if (stmt.trim().isEmpty()) {\n return;\n }\n CmsStringBufferReport report = new CmsStringBufferReport(Locale.ENGLISH);\n List<Throwable> errors = new ArrayList<>();\n CmsSqlConsoleResults result = m_console.execute(stmt, pool, report, errors);\n if (errors.size() > 0) {\n CmsErrorDialog.showErrorDialog(report.toString() + errors.get(0).getMessage(), errors.get(0));\n } else {\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_SQLCONSOLE_QUERY_RESULTS_0));\n window.setContent(new CmsSqlConsoleResultsForm(result, report.toString()));\n A_CmsUI.get().addWindow(window);\n window.center();\n }\n\n }", "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 }", "public static csvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_spilloverpolicy_binding obj = new csvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_spilloverpolicy_binding response[] = (csvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String strip(String text)\n {\n String result = text;\n if (text != null && !text.isEmpty())\n {\n try\n {\n boolean formalRTF = isFormalRTF(text);\n StringTextConverter stc = new StringTextConverter();\n stc.convert(new RtfStringSource(text));\n result = stripExtraLineEnd(stc.getText(), formalRTF);\n }\n catch (IOException ex)\n {\n result = \"\";\n }\n }\n\n return result;\n }", "public Bytes subSequence(int start, int end) {\n if (start > end || start < 0 || end > length) {\n throw new IndexOutOfBoundsException(\"Bad start and/end start = \" + start + \" end=\" + end\n + \" offset=\" + offset + \" length=\" + length);\n }\n return new Bytes(data, offset + start, end - start);\n }", "public static void generateJRXML(DynamicReport dr, LayoutManager layoutManager, Map _parameters, String xmlEncoding, OutputStream outputStream) throws JRException {\n JasperReport jr = generateJasperReport(dr, layoutManager, _parameters);\n if (xmlEncoding == null)\n xmlEncoding = DEFAULT_XML_ENCODING;\n JRXmlWriter.writeReport(jr, outputStream, xmlEncoding);\n }", "public ProjectCalendar getByName(String calendarName)\n {\n ProjectCalendar calendar = null;\n\n if (calendarName != null && calendarName.length() != 0)\n {\n Iterator<ProjectCalendar> iter = iterator();\n while (iter.hasNext() == true)\n {\n calendar = iter.next();\n String name = calendar.getName();\n\n if ((name != null) && (name.equalsIgnoreCase(calendarName) == true))\n {\n break;\n }\n\n calendar = null;\n }\n }\n\n return (calendar);\n }" ]
Use this API to fetch autoscaleaction resource of given name .
[ "public static autoscaleaction get(nitro_service service, String name) throws Exception{\n\t\tautoscaleaction obj = new autoscaleaction();\n\t\tobj.set_name(name);\n\t\tautoscaleaction response = (autoscaleaction) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public static int getSystemPort(String portIdentifier) {\n int defaultPort = 0;\n\n if (portIdentifier.compareTo(Constants.SYS_API_PORT) == 0) {\n defaultPort = Constants.DEFAULT_API_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_DB_PORT) == 0) {\n defaultPort = Constants.DEFAULT_DB_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_FWD_PORT) == 0) {\n defaultPort = Constants.DEFAULT_FWD_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_HTTP_PORT) == 0) {\n defaultPort = Constants.DEFAULT_HTTP_PORT;\n } else if (portIdentifier.compareTo(Constants.SYS_HTTPS_PORT) == 0) {\n defaultPort = Constants.DEFAULT_HTTPS_PORT;\n } else {\n return defaultPort;\n }\n\n String portStr = System.getenv(portIdentifier);\n return (portStr == null || portStr.isEmpty()) ? defaultPort : Integer.valueOf(portStr);\n }", "public void disconnect() {\n\t\tif (sendThread != null) {\n\t\t\tsendThread.interrupt();\n\t\t\ttry {\n\t\t\t\tsendThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\tsendThread = null;\n\t\t}\n\t\tif (receiveThread != null) {\n\t\t\treceiveThread.interrupt();\n\t\t\ttry {\n\t\t\t\treceiveThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\treceiveThread = null;\n\t\t}\n\t\tif(transactionCompleted.availablePermits() < 0)\n\t\t\ttransactionCompleted.release(transactionCompleted.availablePermits());\n\t\t\n\t\ttransactionCompleted.drainPermits();\n\t\tlogger.trace(\"Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\tif (this.serialPort != null) {\n\t\t\tthis.serialPort.close();\n\t\t\tthis.serialPort = null;\n\t\t}\n\t\tlogger.info(\"Disconnected from serial port\");\n\t}", "public static double HighAccuracyFunction(double x) {\n if (x < -8 || x > 8)\n return 0;\n\n double sum = x;\n double term = 0;\n\n double nextTerm = x;\n double pwr = x * x;\n double i = 1;\n\n // Iterate until adding next terms doesn't produce\n // any change within the current numerical accuracy.\n\n while (sum != term) {\n term = sum;\n\n // Next term\n nextTerm *= pwr / (i += 2);\n\n sum += nextTerm;\n }\n\n return 0.5 + sum * Math.exp(-0.5 * pwr - 0.5 * Constants.Log2PI);\n }", "void handleAddKey() {\n\n String key = m_addKeyInput.getValue();\n if (m_listener.handleAddKey(key)) {\n Notification.show(\n key.isEmpty()\n ? m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_EMPTY_KEY_SUCCESSFULLY_ADDED_0)\n : m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_SUCCESSFULLY_ADDED_1, key));\n } else {\n CmsMessageBundleEditorTypes.showWarning(\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_CAPTION_0),\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_DESCRIPTION_1, key));\n\n }\n m_addKeyInput.focus();\n m_addKeyInput.selectAll();\n }", "public static final char getChar(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return (bundle.getString(key).charAt(0));\n }", "private void readTask(ChildTaskContainer mpxjParent, net.sf.mpxj.ganttproject.schema.Task gpTask)\n {\n Task mpxjTask = mpxjParent.addTask();\n mpxjTask.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1));\n mpxjTask.setName(gpTask.getName());\n mpxjTask.setPercentageComplete(gpTask.getComplete());\n mpxjTask.setPriority(getPriority(gpTask.getPriority()));\n mpxjTask.setHyperlink(gpTask.getWebLink());\n\n Duration duration = Duration.getInstance(NumberHelper.getDouble(gpTask.getDuration()), TimeUnit.DAYS);\n mpxjTask.setDuration(duration);\n\n if (duration.getDuration() == 0)\n {\n mpxjTask.setMilestone(true);\n }\n else\n {\n mpxjTask.setStart(gpTask.getStart());\n mpxjTask.setFinish(m_mpxjCalendar.getDate(gpTask.getStart(), mpxjTask.getDuration(), false));\n }\n\n mpxjTask.setConstraintDate(gpTask.getThirdDate());\n if (mpxjTask.getConstraintDate() != null)\n {\n // TODO: you don't appear to be able to change this setting in GanttProject\n // task.getThirdDateConstraint()\n mpxjTask.setConstraintType(ConstraintType.START_NO_EARLIER_THAN);\n }\n\n readTaskCustomFields(gpTask, mpxjTask);\n\n m_eventManager.fireTaskReadEvent(mpxjTask);\n\n // TODO: read custom values\n\n //\n // Process child tasks\n //\n for (net.sf.mpxj.ganttproject.schema.Task childTask : gpTask.getTask())\n {\n readTask(mpxjTask, childTask);\n }\n }", "private static boolean extractSimpleExtents(Variable var, Extents e, boolean row, int length) {\n int lower;\n int upper;\n if( var.getType() == VariableType.INTEGER_SEQUENCE ) {\n IntegerSequence sequence = ((VariableIntegerSequence)var).sequence;\n if( sequence.getType() == IntegerSequence.Type.FOR ) {\n IntegerSequence.For seqFor = (IntegerSequence.For)sequence;\n seqFor.initialize(length);\n if( seqFor.getStep() == 1 ) {\n lower = seqFor.getStart();\n upper = seqFor.getEnd();\n } else {\n return false;\n }\n } else {\n return false;\n }\n } else if( var.getType() == VariableType.SCALAR ) {\n lower = upper = ((VariableInteger)var).value;\n } else {\n throw new RuntimeException(\"How did a bad variable get put here?!?!\");\n }\n if( row ) {\n e.row0 = lower;\n e.row1 = upper;\n } else {\n e.col0 = lower;\n e.col1 = upper;\n }\n return true;\n }", "public static ComponentsMultiThread getComponentsMultiThread() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.componentsMultiThread;\n }", "private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }" ]
You should use the server's time here. Otherwise you might get unexpected results. The typical use case is: <pre> HTTPResponse response = .... HTTPRequest request = createRequest(); request = request.conditionals(new Conditionals().ifModifiedSince(response.getLastModified()); </pre> @param time the time to check. @return the conditionals with the If-Modified-Since date set.
[ "public Conditionals ifModifiedSince(LocalDateTime time) {\n Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH));\n Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_UNMODIFIED_SINCE));\n time = time.withNano(0);\n return new Conditionals(empty(), noneMatch, Optional.of(time), Optional.empty());\n }" ]
[ "protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\n }", "private String getCacheFormatEntry() throws IOException {\n ZipEntry zipEntry = zipFile.getEntry(CACHE_FORMAT_ENTRY);\n InputStream is = zipFile.getInputStream(zipEntry);\n try {\n Scanner s = new Scanner(is, \"UTF-8\").useDelimiter(\"\\\\A\");\n String tag = null;\n if (s.hasNext()) tag = s.next();\n return tag;\n } finally {\n is.close();\n }\n }", "public void ojbAdd(Object anObject)\r\n {\r\n DSetEntry entry = prepareEntry(anObject);\r\n entry.setPosition(elements.size());\r\n elements.add(entry);\r\n }", "@Override\n public int add(DownloadRequest request) throws IllegalArgumentException {\n checkReleased(\"add(...) called on a released ThinDownloadManager.\");\n if (request == null) {\n throw new IllegalArgumentException(\"DownloadRequest cannot be null\");\n }\n return mRequestQueue.add(request);\n }", "public static Method findDeclaredMethodByName(Class<?> clazz, String methodName) {\n for (Method method : AccessController.doPrivileged(new GetDeclaredMethodsAction(clazz))) {\n if (methodName.equals(method.getName())) {\n return method;\n }\n }\n return null;\n }", "private void openBrowser(URI url) throws IOException {\n if (Desktop.isDesktopSupported()) {\n Desktop.getDesktop().browse(url);\n } else {\n LOGGER.error(\"Can not open browser because this capability is not supported on \" +\n \"your platform. You can use the link below to open the report manually.\");\n }\n }", "public DesignDocument get(String id) {\r\n assertNotEmpty(id, \"id\");\r\n return db.find(DesignDocument.class, ensureDesignPrefix(id));\r\n }", "public void setAttribute(final String name, final Attribute attribute) {\n if (name.equals(MAP_KEY)) {\n this.mapAttribute = (MapAttribute) attribute;\n }\n }", "@Override\n public final Boolean optBool(final String key) {\n if (this.obj.optString(key, null) == null) {\n return null;\n } else {\n return this.obj.optBoolean(key);\n }\n }" ]
Gets a collection of photo counts for the given date ranges for the calling user. This method requires authentication with 'read' permission. @param dates An array of dates, denoting the periods to return counts for. They should be specified smallest first. @param takenDates An array of dates, denoting the periods to return counts for. They should be specified smallest first. @return A Collection of Photocount objects
[ "public Collection<Photocount> getCounts(Date[] dates, Date[] takenDates) throws FlickrException {\r\n List<Photocount> photocounts = new ArrayList<Photocount>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_COUNTS);\r\n\r\n if (dates == null && takenDates == null) {\r\n throw new IllegalArgumentException(\"You must provide a value for either dates or takenDates\");\r\n }\r\n\r\n if (dates != null) {\r\n List<String> dateList = new ArrayList<String>();\r\n for (int i = 0; i < dates.length; i++) {\r\n dateList.add(String.valueOf(dates[i].getTime() / 1000L));\r\n }\r\n parameters.put(\"dates\", StringUtilities.join(dateList, \",\"));\r\n }\r\n\r\n if (takenDates != null) {\r\n List<String> takenDateList = new ArrayList<String>();\r\n for (int i = 0; i < takenDates.length; i++) {\r\n takenDateList.add(String.valueOf(takenDates[i].getTime() / 1000L));\r\n }\r\n parameters.put(\"taken_dates\", StringUtilities.join(takenDateList, \",\"));\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 photocountsElement = response.getPayload();\r\n NodeList photocountNodes = photocountsElement.getElementsByTagName(\"photocount\");\r\n for (int i = 0; i < photocountNodes.getLength(); i++) {\r\n Element photocountElement = (Element) photocountNodes.item(i);\r\n Photocount photocount = new Photocount();\r\n photocount.setCount(photocountElement.getAttribute(\"count\"));\r\n photocount.setFromDate(photocountElement.getAttribute(\"fromdate\"));\r\n photocount.setToDate(photocountElement.getAttribute(\"todate\"));\r\n photocounts.add(photocount);\r\n }\r\n return photocounts;\r\n }" ]
[ "public ApiClient setHttpClient(OkHttpClient newHttpClient) {\n if (!httpClient.equals(newHttpClient)) {\n newHttpClient.networkInterceptors().addAll(httpClient.networkInterceptors());\n httpClient.networkInterceptors().clear();\n newHttpClient.interceptors().addAll(httpClient.interceptors());\n httpClient.interceptors().clear();\n this.httpClient = newHttpClient;\n }\n return this;\n }", "public GroovyConstructorDoc[] constructors() {\n Collections.sort(constructors);\n return constructors.toArray(new GroovyConstructorDoc[constructors.size()]);\n }", "public static BufferedImage resizeToHeight(BufferedImage originalImage, int heightOut) {\n\n int width = originalImage.getWidth();\n\n int height = originalImage.getHeight();\n\n int heightPercent = (heightOut * 100) / height;\n\n int newWidth = (width * heightPercent) / 100;\n\n BufferedImage resizedImage =\n new BufferedImage(newWidth, heightOut, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(originalImage, 0, 0, newWidth, heightOut, null);\n g.dispose();\n\n return resizedImage;\n }", "private int getDaysToNextMatch(WeekDay weekDay) {\n\n for (WeekDay wd : m_weekDays) {\n if (wd.compareTo(weekDay) > 0) {\n return wd.toInt() - weekDay.toInt();\n }\n }\n return (m_weekDays.iterator().next().toInt() + (m_interval * I_CmsSerialDateValue.NUM_OF_WEEKDAYS))\n - weekDay.toInt();\n }", "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 int create(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedInsert == null) {\n\t\t\tmappedInsert = MappedCreate.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedInsert.insert(databaseType, databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}", "public static String readCorrelationId(Message message) {\n String correlationId = null;\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n List<String> correlationIds = headers.get(CORRELATION_ID_KEY);\n if (correlationIds != null && correlationIds.size() > 0) {\n correlationId = correlationIds.get(0);\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + CORRELATION_ID_KEY + \"' found: \" + correlationId);\n }\n } else {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"No HTTP header '\" + CORRELATION_ID_KEY + \"' found\");\n }\n }\n\n return correlationId;\n }", "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }", "public T findById(Object id) throws RowNotFoundException, TooManyRowsException {\n return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult();\n }" ]
Writes the results of the processing to a file.
[ "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"life-expectancies.csv\"))) {\n\n\t\t\tfor (int i = 0; i < lifeSpans.length; i++) {\n\t\t\t\tif (peopleCount[i] != 0) {\n\t\t\t\t\tout.println(i + \",\" + (double) lifeSpans[i]\n\t\t\t\t\t\t\t/ peopleCount[i] + \",\" + peopleCount[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}" ]
[ "public PayloadBuilder resizeAlertBody(final int payloadLength, final String postfix) {\n int currLength = length();\n if (currLength <= payloadLength) {\n return this;\n }\n\n // now we are sure that truncation is required\n String body = (String)customAlert.get(\"body\");\n\n final int acceptableSize = Utilities.toUTF8Bytes(body).length\n - (currLength - payloadLength\n + Utilities.toUTF8Bytes(postfix).length);\n body = Utilities.truncateWhenUTF8(body, acceptableSize) + postfix;\n\n // set it back\n customAlert.put(\"body\", body);\n\n // calculate the length again\n currLength = length();\n\n if(currLength > payloadLength) {\n // string is still too long, just remove the body as the body is\n // anyway not the cause OR the postfix might be too long\n customAlert.remove(\"body\");\n }\n\n return this;\n }", "public static<Z> Function0<Z> lift(Callable<Z> f) {\n\treturn bridge.lift(f);\n }", "public static Date min(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) < 0) ? d1 : d2;\n }\n return result;\n }", "protected static String jacksonObjectToString(Object object) {\n\t\ttry {\n\t\t\treturn mapper.writeValueAsString(object);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tlogger.error(\"Failed to serialize JSON data: \" + e.toString());\n\t\t\treturn null;\n\t\t}\n\t}", "public static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) {\n return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(List<InnerT> inners) {\n return Observable.from(inners);\n }\n });\n }", "synchronized void bulkRegisterSingleton() {\n for (Map.Entry<Class<? extends AppService>, AppService> entry : registry.entrySet()) {\n if (isSingletonService(entry.getKey())) {\n app.registerSingleton(entry.getKey(), entry.getValue());\n }\n }\n }", "private void readResource(net.sf.mpxj.planner.schema.Resource plannerResource) throws MPXJException\n {\n Resource mpxjResource = m_projectFile.addResource();\n\n //mpxjResource.setResourceCalendar(m_projectFile.getBaseCalendarByUniqueID(getInteger(plannerResource.getCalendar())));\n mpxjResource.setEmailAddress(plannerResource.getEmail());\n mpxjResource.setUniqueID(getInteger(plannerResource.getId()));\n mpxjResource.setName(plannerResource.getName());\n mpxjResource.setNotes(plannerResource.getNote());\n mpxjResource.setInitials(plannerResource.getShortName());\n mpxjResource.setType(getInt(plannerResource.getType()) == 2 ? ResourceType.MATERIAL : ResourceType.WORK);\n //plannerResource.getStdRate();\n //plannerResource.getOvtRate();\n //plannerResource.getUnits();\n //plannerResource.getProperties();\n\n ProjectCalendar calendar = mpxjResource.addResourceCalendar();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n ProjectCalendar baseCalendar = m_projectFile.getCalendarByUniqueID(getInteger(plannerResource.getCalendar()));\n if (baseCalendar == null)\n {\n baseCalendar = m_defaultCalendar;\n }\n calendar.setParent(baseCalendar);\n\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }", "private static void validate(String name, Collection<Geometry> geometries, int extent) {\n if (name == null) {\n throw new IllegalArgumentException(\"layer name is null\");\n }\n if (geometries == null) {\n throw new IllegalArgumentException(\"geometry collection is null\");\n }\n if (extent <= 0) {\n throw new IllegalArgumentException(\"extent is less than or equal to 0\");\n }\n }", "public void removeCollaborator(String appName, String collaborator) {\n connection.execute(new SharingRemove(appName, collaborator), apiKey);\n }" ]
Runs intermediate check on the Assembly status until it is finished executing, then returns it as a response. @return {@link AssemblyResponse} @throws LocalOperationException if something goes wrong while running non-http operations. @throws RequestException if request to Transloadit server fails.
[ "protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }" ]
[ "private void populateBar(Row row, Task task)\n {\n Integer calendarID = row.getInteger(\"CALENDAU\");\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n\n //PROJID\n task.setUniqueID(row.getInteger(\"BARID\"));\n task.setStart(row.getDate(\"STARV\"));\n task.setFinish(row.getDate(\"ENF\"));\n //NATURAL_ORDER\n //SPARI_INTEGER\n task.setName(row.getString(\"NAMH\"));\n //EXPANDED_TASK\n //PRIORITY\n //UNSCHEDULABLE\n //MARK_FOR_HIDING\n //TASKS_MAY_OVERLAP\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n //Proc_Approve\n //Proc_Design_info\n //Proc_Proc_Dur\n //Proc_Procurement\n //Proc_SC_design\n //Proc_Select_SC\n //Proc_Tender\n //QA Checked\n //Related_Documents\n task.setCalendar(calendar);\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 void populateContainer(FieldType field, byte[] values, byte[] descriptions)\n {\n CustomField config = m_container.getCustomField(field);\n CustomFieldLookupTable table = config.getLookupTable();\n\n List<Object> descriptionList = convertType(DataType.STRING, descriptions);\n List<Object> valueList = convertType(field.getDataType(), values);\n for (int index = 0; index < descriptionList.size(); index++)\n {\n CustomFieldValueItem item = new CustomFieldValueItem(Integer.valueOf(0));\n item.setDescription((String) descriptionList.get(index));\n if (index < valueList.size())\n {\n item.setValue(valueList.get(index));\n }\n table.add(item);\n }\n }", "public static String getMemberName() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getName();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n return MethodTagsHandler.getPropertyNameFor(getCurrentMethod());\r\n }\r\n else {\r\n return null;\r\n }\r\n }", "public AsciiTable setPaddingTop(int paddingTop) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public void growMaxColumns( int desiredColumns , boolean preserveValue ) {\n if( col_idx.length < desiredColumns+1 ) {\n int[] c = new int[ desiredColumns+1 ];\n if( preserveValue )\n System.arraycopy(col_idx,0,c,0,col_idx.length);\n col_idx = c;\n }\n }", "public static Calendar popCalendar()\n {\n Calendar result;\n Deque<Calendar> calendars = CALENDARS.get();\n if (calendars.isEmpty())\n {\n result = Calendar.getInstance();\n }\n else\n {\n result = calendars.pop();\n }\n return result;\n }", "private ProjectFile readProjectFile(ProjectReader reader, InputStream stream) throws MPXJException\n {\n addListeners(reader);\n return reader.read(stream);\n }", "private GenericCriteriaPrompt getPromptValue(FieldType field, byte[] block)\n {\n int textOffset = getPromptOffset(block);\n String value = MPPUtility.getUnicodeString(m_criteriaData, m_criteriaTextStart + textOffset);\n GenericCriteriaPrompt prompt = new GenericCriteriaPrompt(field.getDataType(), value);\n if (m_prompts != null)\n {\n m_prompts.add(prompt);\n }\n return prompt;\n }" ]
Constructs credentials for the given account and key file. @param serviceAccountId service account ID (typically an e-mail address). @param privateKeyFile the file name from which to get the private key. @param serviceAccountScopes Collection of OAuth scopes to use with the the service account flow or {@code null} if not. @return valid credentials or {@code null}
[ "public static Credential getServiceAccountCredential(String serviceAccountId,\n String privateKeyFile, Collection<String> serviceAccountScopes)\n throws GeneralSecurityException, IOException {\n return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes)\n .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFile))\n .build();\n }" ]
[ "private void appendParameter(Object value, StringBuffer buf)\r\n {\r\n if (value instanceof Query)\r\n {\r\n appendSubQuery((Query) value, buf);\r\n }\r\n else\r\n {\r\n buf.append(\"?\");\r\n }\r\n }", "public synchronized List<String> propertyListOf(Class<?> c) {\n String cn = c.getName();\n List<String> ls = repo.get(cn);\n if (ls != null) {\n return ls;\n }\n Set<Class<?>> circularReferenceDetector = new HashSet<>();\n ls = propertyListOf(c, circularReferenceDetector, null);\n repo.put(c.getName(), ls);\n return ls;\n }", "public Channel sessionConnectGenerateChannel(Session session)\n throws JSchException {\n \t// set timeout\n session.connect(sshMeta.getSshConnectionTimeoutMillis());\n \n ChannelExec channel = (ChannelExec) session.openChannel(\"exec\");\n channel.setCommand(sshMeta.getCommandLine());\n\n // if run as super user, assuming the input stream expecting a password\n if (sshMeta.isRunAsSuperUser()) {\n \ttry {\n channel.setInputStream(null, true);\n\n OutputStream out = channel.getOutputStream();\n channel.setOutputStream(System.out, true);\n channel.setExtOutputStream(System.err, true);\n channel.setPty(true);\n channel.connect();\n \n\t out.write((sshMeta.getPassword()+\"\\n\").getBytes());\n\t out.flush();\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"error in sessionConnectGenerateChannel for super user\", e);\n\t\t\t}\n } else {\n \tchannel.setInputStream(null);\n \tchannel.connect();\n }\n\n return channel;\n\n }", "protected void writePropertiesToLog(Logger logger, Level level) {\n writeToLog(logger, level, getMapAsString(this.properties, separator), null);\n\n if (this.exception != null) {\n writeToLog(this.logger, Level.ERROR, \"Error:\", this.exception);\n }\n }", "public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) {\r\n List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise);\n\r\n List<Map<String, String>> testCases = new ArrayList<>();\r\n for (Set<String> tuple : tuples) {\r\n testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains));\r\n }\n\r\n return testCases;\r\n }", "public static void serialize(final File folder, final String content, final String fileName) throws IOException {\n if (!folder.exists()) {\n folder.mkdirs();\n }\n\n final File output = new File(folder, fileName);\n\n try (\n final FileWriter writer = new FileWriter(output);\n ) {\n writer.write(content);\n writer.flush();\n } catch (Exception e) {\n throw new IOException(\"Failed to serialize the notification in folder \" + folder.getPath(), e);\n }\n }", "public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception\n {\n System.out.println(\"Reading Primavera database started.\");\n\n Class.forName(driverClass);\n Properties props = new Properties();\n\n //\n // This is not a very robust way to detect that we're working with SQLlite...\n // If you are trying to grab data from\n // a standalone P6 using SQLite, the SQLite JDBC driver needs this property\n // in order to correctly parse timestamps.\n //\n if (driverClass.equals(\"org.sqlite.JDBC\"))\n {\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n }\n\n Connection c = DriverManager.getConnection(connectionString, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(c);\n\n processProject(reader, Integer.parseInt(projectID), outputFile);\n }", "public void setFilePath(String filePath) throws IOException, GVRScriptException\n {\n GVRResourceVolume.VolumeType volumeType = GVRResourceVolume.VolumeType.ANDROID_ASSETS;\n String fname = filePath.toLowerCase();\n \n mLanguage = FileNameUtils.getExtension(fname); \n if (fname.startsWith(\"sd:\"))\n {\n volumeType = GVRResourceVolume.VolumeType.ANDROID_SDCARD;\n }\n else if (fname.startsWith(\"http:\") || fname.startsWith(\"https:\"))\n {\n volumeType = GVRResourceVolume.VolumeType.NETWORK; \n }\n GVRResourceVolume volume = new GVRResourceVolume(getGVRContext(), volumeType,\n FileNameUtils.getParentDirectory(filePath));\n GVRAndroidResource resource = volume.openResource(filePath);\n \n setScriptFile((GVRScriptFile)getGVRContext().getScriptManager().loadScript(resource, mLanguage));\n }", "public Replication queryParams(Map<String, Object> queryParams) {\r\n this.replication = replication.queryParams(queryParams);\r\n return this;\r\n }" ]
Sets an element in at the specified index.
[ "public CSTNode set( int index, CSTNode element ) \n {\n \n if( elements == null ) \n {\n throw new GroovyBugError( \"attempt to set() on a EMPTY Reduction\" );\n }\n\n if( index == 0 && !(element instanceof Token) ) \n {\n\n //\n // It's not the greatest of design that the interface allows this, but it\n // is a tradeoff with convenience, and the convenience is more important.\n\n throw new GroovyBugError( \"attempt to set() a non-Token as root of a Reduction\" );\n }\n\n\n //\n // Fill slots with nulls, if necessary.\n\n int count = elements.size();\n if( index >= count ) \n {\n for( int i = count; i <= index; i++ ) \n {\n elements.add( null );\n }\n }\n\n //\n // Then set in the element.\n\n elements.set( index, element );\n\n return element;\n }" ]
[ "public void addRegexRoute(String urlPattern, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(urlPattern, true), actorClass);\n }", "private void readUDFTypes(FieldContainer mpxj, List<UDFAssignmentType> udfs)\n {\n for (UDFAssignmentType udf : udfs)\n {\n FieldType fieldType = m_fieldTypeMap.get(Integer.valueOf(udf.getTypeObjectId()));\n if (fieldType != null)\n {\n mpxj.set(fieldType, getUdfValue(udf));\n }\n }\n }", "@Nonnull\n public static Proctor construct(@Nonnull final TestMatrixArtifact matrix, ProctorLoadResult loadResult, FunctionMapper functionMapper) {\n final ExpressionFactory expressionFactory = RuleEvaluator.EXPRESSION_FACTORY;\n\n final Map<String, TestChooser<?>> testChoosers = Maps.newLinkedHashMap();\n final Map<String, String> versions = Maps.newLinkedHashMap();\n\n for (final Entry<String, ConsumableTestDefinition> entry : matrix.getTests().entrySet()) {\n final String testName = entry.getKey();\n final ConsumableTestDefinition testDefinition = entry.getValue();\n final TestType testType = testDefinition.getTestType();\n final TestChooser<?> testChooser;\n if (TestType.RANDOM.equals(testType)) {\n testChooser = new RandomTestChooser(expressionFactory, functionMapper, testName, testDefinition);\n } else {\n testChooser = new StandardTestChooser(expressionFactory, functionMapper, testName, testDefinition);\n }\n testChoosers.put(testName, testChooser);\n versions.put(testName, testDefinition.getVersion());\n }\n\n return new Proctor(matrix, loadResult, testChoosers);\n }", "int getItemViewType(T content) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n return getItemViewType(prototypeClass);\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<EthiopicDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<EthiopicDate>) super.localDateTime(temporal);\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}", "public String format(final LoggingEvent event) {\n\t\tfinal StringBuffer buf = new StringBuffer();\n\t\tfor (PatternConverter c = head; c != null; c = c.next) {\n\t\t\tc.format(buf, event);\n\t\t}\n\t\treturn buf.toString();\n\t}", "@Override\n public Configuration configuration() {\n return new MostUsefulConfiguration()\n // where to find the stories\n .useStoryLoader(new LoadFromClasspath(this.getClass())) \n // CONSOLE and TXT reporting\n .useStoryReporterBuilder(new StoryReporterBuilder().withDefaultFormats().withFormats(Format.CONSOLE, Format.TXT)); \n }", "public static dos_stats get(nitro_service service, options option) throws Exception{\n\t\tdos_stats obj = new dos_stats();\n\t\tdos_stats[] response = (dos_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}" ]
Checks the preconditions for creating a new ForbidSubStr processor with a List of forbidden substrings. @param forbiddenSubStrings the forbidden substrings @throws NullPointerException if forbiddenSubStrings is null @throws IllegalArgumentException if forbiddenSubStrings is empty
[ "private static void checkPreconditions(final List<String> forbiddenSubStrings) {\n\t\tif( forbiddenSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"forbiddenSubStrings list should not be null\");\n\t\t} else if( forbiddenSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"forbiddenSubStrings list should not be empty\");\n\t\t}\n\t}" ]
[ "public void removePathnameFromProfile(int path_id, int profileId) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public void clear() {\n valueBoxBase.setText(\"\");\n clearStatusText();\n\n if (getPlaceholder() == null || getPlaceholder().isEmpty()) {\n label.removeStyleName(CssName.ACTIVE);\n }\n }", "public static void endThreads(String check){\r\n //(error check)\r\n if(currentThread != -1L){\r\n throw new IllegalStateException(\"endThreads() called, but thread \" + currentThread + \" has not finished (exception in thread?)\");\r\n }\r\n //(end threaded environment)\r\n assert !control.isHeldByCurrentThread();\r\n isThreaded = false;\r\n //(write remaining threads)\r\n boolean cleanPass = false;\r\n while(!cleanPass){\r\n cleanPass = true;\r\n for(long thread : threadedLogQueue.keySet()){\r\n assert currentThread < 0L;\r\n if(threadedLogQueue.get(thread) != null && !threadedLogQueue.get(thread).isEmpty()){\r\n //(mark queue as unclean)\r\n cleanPass = false;\r\n //(variables)\r\n Queue<Runnable> backlog = threadedLogQueue.get(thread);\r\n currentThread = thread;\r\n //(clear buffer)\r\n while(currentThread >= 0){\r\n if(currentThread != thread){ throw new IllegalStateException(\"Redwood control shifted away from flushing thread\"); }\r\n if(backlog.isEmpty()){ throw new IllegalStateException(\"Forgot to call finishThread() on thread \" + currentThread); }\r\n assert !control.isHeldByCurrentThread();\r\n backlog.poll().run();\r\n }\r\n //(unregister thread)\r\n threadsWaiting.remove(thread);\r\n }\r\n }\r\n }\r\n while(threadsWaiting.size() > 0){\r\n assert currentThread < 0L;\r\n assert control.tryLock();\r\n assert !threadsWaiting.isEmpty();\r\n control.lock();\r\n attemptThreadControlThreadsafe(-1);\r\n control.unlock();\r\n }\r\n //(clean up)\r\n for(long threadId : threadedLogQueue.keySet()){\r\n assert threadedLogQueue.get(threadId).isEmpty();\r\n }\r\n assert threadsWaiting.isEmpty();\r\n assert currentThread == -1L;\r\n endTrack(\"Threads( \"+check+\" )\");\r\n }", "public String getString(Integer id, Integer type)\n {\n return (getString(m_meta.getOffset(id, type)));\n }", "public Double score(final String member) {\n return doWithJedis(new JedisCallable<Double>() {\n @Override\n public Double call(Jedis jedis) {\n return jedis.zscore(getKey(), member);\n }\n });\n }", "public static void configureProtocolHandler() {\n final String pkgs = System.getProperty(\"java.protocol.handler.pkgs\");\n String newValue = \"org.mapfish.print.url\";\n if (pkgs != null && !pkgs.contains(newValue)) {\n newValue = newValue + \"|\" + pkgs;\n } else if (pkgs != null) {\n newValue = pkgs;\n }\n System.setProperty(\"java.protocol.handler.pkgs\", newValue);\n }", "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 void ensureNotSingular( DMatrixSparseCSC A , Random rand ) {\n// if( A.numRows < A.numCols ) {\n// throw new IllegalArgumentException(\"Fewer equations than variables\");\n// }\n\n int []s = UtilEjml.shuffled(A.numRows,rand);\n Arrays.sort(s);\n\n int N = Math.min(A.numCols,A.numRows);\n for (int col = 0; col < N; col++) {\n A.set(s[col],col,rand.nextDouble()+0.5);\n }\n }", "public String getDbProperty(String key) {\n\n // extract the database key out of the entire key\n String databaseKey = key.substring(0, key.indexOf('.'));\n Properties databaseProperties = getDatabaseProperties().get(databaseKey);\n\n return databaseProperties.getProperty(key, \"\");\n }" ]
Locks a file. @param expiresAt expiration date of the lock. @param isDownloadPrevented is downloading of file prevented when locked. @return the lock returned from the server.
[ "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 double huntKennedyCMSFloorValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit,\n\t\t\tdouble optionStrike)\n\t{\n\t\tdouble huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);\n\n\t\t// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)\n\t\treturn huntKennedyCMSOptionValue + optionStrike * payoffUnit;\n\t}", "public Axis getOrientationAxis() {\n final Axis axis;\n switch(getOrientation()) {\n case HORIZONTAL:\n axis = Axis.X;\n break;\n case VERTICAL:\n axis = Axis.Y;\n break;\n case STACK:\n axis = Axis.Z;\n break;\n default:\n Log.w(TAG, \"Unsupported orientation %s\", mOrientation);\n axis = Axis.X;\n break;\n }\n return axis;\n }", "public void forAllMemberTagTokens(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n forAllMemberTagTokens(template, attributes, FOR_FIELD);\r\n }\r\n else if (getCurrentMethod() != null) {\r\n forAllMemberTagTokens(template, attributes, FOR_METHOD);\r\n }\r\n }", "public String registerHandler(GFXEventHandler handler) {\n String uuid = UUID.randomUUID().toString();\n handlers.put(uuid, handler);\n return uuid;\n }", "public static void showErrorDialog(String message, String details) {\n\n Window window = prepareWindow(DialogWidth.wide);\n window.setCaption(\"Error\");\n window.setContent(new CmsSetupErrorDialog(message, details, null, window));\n A_CmsUI.get().addWindow(window);\n\n }", "public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }", "public int getPropertyId(@NotNull final PersistentStoreTransaction txn, @NotNull final String propertyName, final boolean allowCreate) {\n return allowCreate ? propertyIds.getOrAllocateId(txn, propertyName) : propertyIds.getId(txn, propertyName);\n }", "public static String getContent(String stringUrl) throws IOException {\n InputStream stream = getContentStream(stringUrl);\n return MyStreamUtils.readContent(stream);\n }", "private int getLiteralId(String literal) throws PersistenceBrokerException\r\n {\r\n ////logger.debug(\"lookup: \" + literal);\r\n try\r\n {\r\n return tags.getIdByTag(literal);\r\n }\r\n catch (NullPointerException t)\r\n {\r\n throw new MetadataException(\"unknown literal: '\" + literal + \"'\",t);\r\n }\r\n\r\n }" ]
Switch to a new DataSource using the given configuration. @param newConfig BoneCP DataSource to use. @throws SQLException
[ "public void switchDataSource(BoneCPConfig newConfig) throws SQLException {\n\t\tlogger.info(\"Switch to new datasource requested. New Config: \"+newConfig);\n\t\tDataSource oldDS = getTargetDataSource();\n \n\t\tif (!(oldDS instanceof BoneCPDataSource)){\n\t\t\tthrow new SQLException(\"Unknown datasource type! Was expecting BoneCPDataSource but received \"+oldDS.getClass()+\". Not switching datasource!\");\n\t\t}\n\t\t\n\t\tBoneCPDataSource newDS = new BoneCPDataSource(newConfig);\n\t\tnewDS.getConnection().close(); // initialize a connection (+ throw it away) to force the datasource to initialize the pool\n\t\t\n\t\t// force application to start using the new one \n\t\tsetTargetDataSource(newDS);\n\t\t\n\t\tlogger.info(\"Shutting down old datasource slowly. Old Config: \"+oldDS);\n\t\t// tell the old datasource to terminate. This terminates the pool lazily so existing checked out connections can still be used.\n\t\t((BoneCPDataSource)oldDS).close();\n\t}" ]
[ "public synchronized boolean acquireRebalancingPermit(int nodeId) {\n boolean added = rebalancePermits.add(nodeId);\n logger.info(\"Acquiring rebalancing permit for node id \" + nodeId + \", returned: \" + added);\n\n return added;\n }", "public static String getDateTimeStr(Date d) {\n if (d == null)\n return \"\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSSZ\");\n // 20140315 test will problem +0000\n return sdf.format(d);\n }", "public static String groupFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).resourceGroupName() : null;\n }", "@Override\n\tpublic void write(final char[] cbuf, final int off, final int len) throws IOException {\n\t\tint offset = off;\n\t\tint length = len;\n\t\twhile (suppressLineCount > 0 && length > 0) {\n\t\t\tlength = -1;\n\t\t\tfor (int i = 0; i < len && suppressLineCount > 0; i++) {\n\t\t\t\tif (cbuf[off + i] == '\\n') {\n\t\t\t\t\toffset = off + i + 1;\n\t\t\t\t\tlength = len - i - 1;\n\t\t\t\t\tsuppressLineCount--;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (length <= 0)\n\t\t\t\treturn;\n\t\t}\n\t\tdelegate.write(cbuf, offset, length);\n\t}", "public static boolean reconnectContext(RedirectException re, CommandContext ctx) {\n boolean reconnected = false;\n try {\n ConnectionInfo info = ctx.getConnectionInfo();\n ControllerAddress address = null;\n if (info != null) {\n address = info.getControllerAddress();\n }\n if (address != null && isHttpsRedirect(re, address.getProtocol())) {\n LOG.debug(\"Trying to reconnect an http to http upgrade\");\n try {\n ctx.connectController();\n reconnected = true;\n } catch (Exception ex) {\n LOG.warn(\"Exception reconnecting\", ex);\n // Proper https redirect but error.\n // Ignoring it.\n }\n }\n } catch (URISyntaxException ex) {\n LOG.warn(\"Invalid URI: \", ex);\n // OK, invalid redirect.\n }\n return reconnected;\n }", "public VideoCollection generate(final int videoCount) {\n List<Video> videos = new LinkedList<Video>();\n for (int i = 0; i < videoCount; i++) {\n Video video = generateRandomVideo();\n videos.add(video);\n }\n return new VideoCollection(videos);\n }", "public void setTextureBufferSize(final int size) {\n mRootViewGroup.post(new Runnable() {\n @Override\n public void run() {\n mRootViewGroup.setTextureBufferSize(size);\n }\n });\n }", "protected boolean lacksSomeLanguage(ItemDocument itemDocument) {\n\t\tfor (int i = 0; i < arabicNumeralLanguages.length; i++) {\n\t\t\tif (!itemDocument.getLabels()\n\t\t\t\t\t.containsKey(arabicNumeralLanguages[i])) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public void setFieldByAlias(String alias, Object value)\n {\n set(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias), value);\n }" ]
Removes the given row. @param row the row to remove
[ "public void remove(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index >= 0) {\n m_container.removeComponent(row);\n }\n updatePlaceholder();\n updateButtonBars();\n updateGroupValidation();\n }" ]
[ "public static sslocspresponder get(nitro_service service, String name) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tobj.set_name(name);\n\t\tsslocspresponder response = (sslocspresponder) obj.get_resource(service);\n\t\treturn response;\n\t}", "public Try<R,Throwable> execute(T input){\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)));\n\t\t \n\t}", "public static 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 org.apache.log4j.Logger getLogger()\r\n\t{\r\n /*\r\n Logger interface extends Serializable, thus Log field is\r\n declared 'transient' and we have to null-check\r\n\t\t*/\r\n\t\tif (logger == null)\r\n\t\t{\r\n\t\t\tlogger = org.apache.log4j.Logger.getLogger(name);\r\n\t\t}\r\n\t\treturn logger;\r\n\t}", "protected synchronized void handleCompleted() {\n latch.countDown();\n for (final ShutdownListener listener : listeners) {\n listener.handleCompleted();\n }\n listeners.clear();\n }", "public List<Widget> getAllViews() {\n List<Widget> views = new ArrayList<>();\n for (Widget child: mContent.getChildren()) {\n Widget item = ((ListItemHostWidget) child).getGuest();\n if (item != null) {\n views.add(item);\n }\n }\n return views;\n }", "protected void createNewFile(final File file) {\n try {\n file.createNewFile();\n setFileNotWorldReadablePermissions(file);\n } catch (IOException e){\n throw new RuntimeException(e);\n }\n }", "public CustomField getCustomField(FieldType field)\n {\n CustomField result = m_configMap.get(field);\n if (result == null)\n {\n result = new CustomField(field, this);\n m_configMap.put(field, result);\n }\n return result;\n }", "public List<Widget> getAllViews() {\n List<Widget> views = new ArrayList<>();\n for (Widget child: mContent.getChildren()) {\n Widget item = ((ListItemHostWidget) child).getGuest();\n if (item != null) {\n views.add(item);\n }\n }\n return views;\n }" ]
Given a list of keys and a number of splits find the keys to split on. @param keys the list of keys. @param numSplits the number of splits.
[ "private Iterable<Key> getSplitKey(List<Key> keys, int numSplits) {\n // If the number of keys is less than the number of splits, we are limited in the number of\n // splits we can make.\n if (keys.size() < numSplits - 1) {\n return keys;\n }\n\n // Calculate the number of keys per split. This should be KEYS_PER_SPLIT, but may\n // be less if there are not KEYS_PER_SPLIT * (numSplits - 1) scatter entities.\n //\n // Consider the following dataset, where - represents an entity and * represents an entity\n // that is returned as a scatter entity:\n // ||---*-----*----*-----*-----*------*----*----||\n // If we want 4 splits in this data, the optimal split would look like:\n // ||---*-----*----*-----*-----*------*----*----||\n // | | |\n // The scatter keys in the last region are not useful to us, so we never request them:\n // ||---*-----*----*-----*-----*------*---------||\n // | | |\n // With 6 scatter keys we want to set scatter points at indexes: 1, 3, 5.\n //\n // We keep this as a double so that any \"fractional\" keys per split get distributed throughout\n // the splits and don't make the last split significantly larger than the rest.\n double numKeysPerSplit = Math.max(1.0, ((double) keys.size()) / (numSplits - 1));\n\n List<Key> keysList = new ArrayList<Key>(numSplits - 1);\n // Grab the last sample for each split, otherwise the first split will be too small.\n for (int i = 1; i < numSplits; i++) {\n int splitIndex = (int) Math.round(i * numKeysPerSplit) - 1;\n keysList.add(keys.get(splitIndex));\n }\n\n return keysList;\n }" ]
[ "public int getNumWeights() {\r\n if (weights == null) return 0;\r\n int numWeights = 0;\r\n for (double[] wts : weights) {\r\n numWeights += wts.length;\r\n }\r\n return numWeights;\r\n }", "public static base_response update(nitro_service client, vpnsessionaction resource) throws Exception {\n\t\tvpnsessionaction updateresource = new vpnsessionaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.httpport = resource.httpport;\n\t\tupdateresource.winsip = resource.winsip;\n\t\tupdateresource.dnsvservername = resource.dnsvservername;\n\t\tupdateresource.splitdns = resource.splitdns;\n\t\tupdateresource.sesstimeout = resource.sesstimeout;\n\t\tupdateresource.clientsecurity = resource.clientsecurity;\n\t\tupdateresource.clientsecuritygroup = resource.clientsecuritygroup;\n\t\tupdateresource.clientsecuritymessage = resource.clientsecuritymessage;\n\t\tupdateresource.clientsecuritylog = resource.clientsecuritylog;\n\t\tupdateresource.splittunnel = resource.splittunnel;\n\t\tupdateresource.locallanaccess = resource.locallanaccess;\n\t\tupdateresource.rfc1918 = resource.rfc1918;\n\t\tupdateresource.spoofiip = resource.spoofiip;\n\t\tupdateresource.killconnections = resource.killconnections;\n\t\tupdateresource.transparentinterception = resource.transparentinterception;\n\t\tupdateresource.windowsclienttype = resource.windowsclienttype;\n\t\tupdateresource.defaultauthorizationaction = resource.defaultauthorizationaction;\n\t\tupdateresource.authorizationgroup = resource.authorizationgroup;\n\t\tupdateresource.clientidletimeout = resource.clientidletimeout;\n\t\tupdateresource.proxy = resource.proxy;\n\t\tupdateresource.allprotocolproxy = resource.allprotocolproxy;\n\t\tupdateresource.httpproxy = resource.httpproxy;\n\t\tupdateresource.ftpproxy = resource.ftpproxy;\n\t\tupdateresource.socksproxy = resource.socksproxy;\n\t\tupdateresource.gopherproxy = resource.gopherproxy;\n\t\tupdateresource.sslproxy = resource.sslproxy;\n\t\tupdateresource.proxyexception = resource.proxyexception;\n\t\tupdateresource.proxylocalbypass = resource.proxylocalbypass;\n\t\tupdateresource.clientcleanupprompt = resource.clientcleanupprompt;\n\t\tupdateresource.forcecleanup = resource.forcecleanup;\n\t\tupdateresource.clientoptions = resource.clientoptions;\n\t\tupdateresource.clientconfiguration = resource.clientconfiguration;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.ssocredential = resource.ssocredential;\n\t\tupdateresource.windowsautologon = resource.windowsautologon;\n\t\tupdateresource.usemip = resource.usemip;\n\t\tupdateresource.useiip = resource.useiip;\n\t\tupdateresource.clientdebug = resource.clientdebug;\n\t\tupdateresource.loginscript = resource.loginscript;\n\t\tupdateresource.logoutscript = resource.logoutscript;\n\t\tupdateresource.homepage = resource.homepage;\n\t\tupdateresource.icaproxy = resource.icaproxy;\n\t\tupdateresource.wihome = resource.wihome;\n\t\tupdateresource.citrixreceiverhome = resource.citrixreceiverhome;\n\t\tupdateresource.wiportalmode = resource.wiportalmode;\n\t\tupdateresource.clientchoices = resource.clientchoices;\n\t\tupdateresource.epaclienttype = resource.epaclienttype;\n\t\tupdateresource.iipdnssuffix = resource.iipdnssuffix;\n\t\tupdateresource.forcedtimeout = resource.forcedtimeout;\n\t\tupdateresource.forcedtimeoutwarning = resource.forcedtimeoutwarning;\n\t\tupdateresource.ntdomain = resource.ntdomain;\n\t\tupdateresource.clientlessvpnmode = resource.clientlessvpnmode;\n\t\tupdateresource.emailhome = resource.emailhome;\n\t\tupdateresource.clientlessmodeurlencoding = resource.clientlessmodeurlencoding;\n\t\tupdateresource.clientlesspersistentcookie = resource.clientlesspersistentcookie;\n\t\tupdateresource.allowedlogingroups = resource.allowedlogingroups;\n\t\tupdateresource.securebrowse = resource.securebrowse;\n\t\tupdateresource.storefronturl = resource.storefronturl;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\treturn updateresource.update_resource(client);\n\t}", "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 static String simpleTypeName(Object obj) {\n if (obj == null) {\n return \"null\";\n }\n\n return simpleTypeName(obj.getClass(), false);\n }", "public void publish() {\n\n CmsDirectPublishDialogAction action = new CmsDirectPublishDialogAction();\n List<CmsResource> resources = getBundleResources();\n I_CmsDialogContext context = new A_CmsDialogContext(\"\", ContextType.appToolbar, resources) {\n\n public void focus(CmsUUID structureId) {\n\n //Nothing to do.\n }\n\n public List<CmsUUID> getAllStructureIdsInView() {\n\n return null;\n }\n\n public void updateUserInfo() {\n\n //Nothing to do.\n }\n };\n action.executeAction(context);\n updateLockInformation();\n\n }", "public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }", "@Override\n public ResourceStorageLoadable getOrCreateResourceStorageLoadable(final StorageAwareResource resource) {\n try {\n final ResourceStorageProviderAdapter stateProvider = IterableExtensions.<ResourceStorageProviderAdapter>head(Iterables.<ResourceStorageProviderAdapter>filter(resource.getResourceSet().eAdapters(), ResourceStorageProviderAdapter.class));\n if ((stateProvider != null)) {\n final ResourceStorageLoadable inputStream = stateProvider.getResourceStorageLoadable(resource);\n if ((inputStream != null)) {\n return inputStream;\n }\n }\n InputStream _xifexpression = null;\n boolean _exists = resource.getResourceSet().getURIConverter().exists(this.getBinaryStorageURI(resource.getURI()), CollectionLiterals.<Object, Object>emptyMap());\n if (_exists) {\n _xifexpression = resource.getResourceSet().getURIConverter().createInputStream(this.getBinaryStorageURI(resource.getURI()));\n } else {\n InputStream _xblockexpression = null;\n {\n final AbstractFileSystemAccess2 fsa = this.getFileSystemAccess(resource);\n final String outputRelativePath = this.computeOutputPath(resource);\n _xblockexpression = fsa.readBinaryFile(outputRelativePath);\n }\n _xifexpression = _xblockexpression;\n }\n final InputStream inputStream_1 = _xifexpression;\n return this.createResourceStorageLoadable(inputStream_1);\n } catch (Throwable _e) {\n throw Exceptions.sneakyThrow(_e);\n }\n }", "public static String getArtifactoryPluginVersion() {\n String pluginsSortName = \"artifactory\";\n //Validates Jenkins existence because in some jobs the Jenkins instance is unreachable\n if (Jenkins.getInstance() != null\n && Jenkins.getInstance().getPlugin(pluginsSortName) != null\n && Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper() != null) {\n return Jenkins.getInstance().getPlugin(pluginsSortName).getWrapper().getVersion();\n }\n return \"\";\n }", "public static authenticationradiusaction[] get(nitro_service service) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tauthenticationradiusaction[] response = (authenticationradiusaction[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Convert a GanttProject task relationship type into an MPXJ RelationType instance. @param gpType GanttProject task relation type @return RelationType instance
[ "private RelationType getRelationType(Integer gpType)\n {\n RelationType result = null;\n if (gpType != null)\n {\n int index = NumberHelper.getInt(gpType);\n if (index > 0 && index < RELATION.length)\n {\n result = RELATION[index];\n }\n }\n\n if (result == null)\n {\n result = RelationType.FINISH_START;\n }\n\n return result;\n }" ]
[ "public void checkpoint(ObjectEnvelope mod)\r\n throws org.apache.ojb.broker.PersistenceBrokerException\r\n {\r\n mod.doUpdate();\r\n }", "@SuppressForbidden(\"legitimate sysstreams.\")\n public static void warn(String message, Throwable t) {\n PrintStream w = (warnings == null ? System.err : warnings);\n try {\n w.print(\"WARN: \");\n w.print(message);\n if (t != null) {\n w.print(\" -> \");\n try {\n t.printStackTrace(w);\n } catch (OutOfMemoryError e) {\n // Ignore, OOM.\n w.print(t.getClass().getName());\n w.print(\": \");\n w.print(t.getMessage());\n w.println(\" (stack unavailable; OOM)\");\n }\n } else {\n w.println();\n }\n w.flush();\n } catch (OutOfMemoryError t2) {\n w.println(\"ERROR: Couldn't even serialize a warning (out of memory).\");\n } catch (Throwable t2) {\n // Can't do anything, really. Probably an OOM?\n w.println(\"ERROR: Couldn't even serialize a warning.\");\n }\n }", "public void seekToSeason(String seasonString, String direction, String seekAmount) {\n Season season = Season.valueOf(seasonString);\n assert(season!= null);\n \n seekToIcsEvent(SEASON_ICS_FILE, season.getSummary(), direction, seekAmount);\n }", "private static String[] readArgsFile(String argsFile) throws IOException {\n final ArrayList<String> lines = new ArrayList<String>();\n final BufferedReader reader = new BufferedReader(\n new InputStreamReader(\n new FileInputStream(argsFile), \"UTF-8\"));\n try {\n String line;\n while ((line = reader.readLine()) != null) {\n line = line.trim();\n if (!line.isEmpty() && !line.startsWith(\"#\")) {\n lines.add(line);\n }\n }\n } finally {\n reader.close();\n }\n return lines.toArray(new String [lines.size()]);\n }", "public static DMatrixRMaj nullspaceSVD( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpace<DMatrixRMaj> solver = new SolveNullSpaceSvd_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }", "@Override\n\tprotected void clearReference(EObject obj, EReference ref) {\n\t\tsuper.clearReference(obj, ref);\n\t\tif (obj.eIsSet(ref) && ref.getEType().equals(XtextPackage.Literals.TYPE_REF)) {\n\t\t\tINode node = NodeModelUtils.getNode((EObject) obj.eGet(ref));\n\t\t\tif (node == null)\n\t\t\t\tobj.eUnset(ref);\n\t\t}\n\t\tif (obj.eIsSet(ref) && ref == XtextPackage.Literals.CROSS_REFERENCE__TERMINAL) {\n\t\t\tINode node = NodeModelUtils.getNode((EObject) obj.eGet(ref));\n\t\t\tif (node == null)\n\t\t\t\tobj.eUnset(ref);\n\t\t}\n\t\tif (ref == XtextPackage.Literals.RULE_CALL__RULE) {\n\t\t\tobj.eUnset(XtextPackage.Literals.RULE_CALL__EXPLICITLY_CALLED);\n\t\t}\n\t}", "public Object newInstance(String resource) {\n try {\n String name = resource.startsWith(\"/\") ? resource : \"/\" + resource;\n File file = new File(this.getClass().getResource(name).toURI());\n return newInstance(classLoader.parseClass(new GroovyCodeSource(file), true));\n } catch (Exception e) {\n throw new GroovyClassInstantiationFailed(classLoader, resource, e);\n }\n }", "@Override\n public final Map<String, OperationEntry> getOperationDescriptions(final PathAddress address, boolean inherited) {\n\n if (parent != null) {\n RootInvocation ri = getRootInvocation();\n return ri.root.getOperationDescriptions(ri.pathAddress.append(address), inherited);\n }\n // else we are the root\n Map<String, OperationEntry> providers = new TreeMap<String, OperationEntry>();\n getOperationDescriptions(address.iterator(), providers, inherited);\n return providers;\n }", "private void adjustVisibleColumns() {\n\n if (m_table.isColumnCollapsingAllowed()) {\n if ((m_model.hasDefaultValues()) || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, true);\n }\n\n if (((m_model.getEditMode().equals(EditMode.MASTER) || m_model.hasDescriptionValues()))\n || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, true);\n }\n }\n }" ]
Recursively scan the provided path and return a list of all Java packages contained therein.
[ "private static Map<String, Integer> findClasses(Path path)\n {\n List<String> paths = findPaths(path, true);\n Map<String, Integer> results = new HashMap<>();\n for (String subPath : paths)\n {\n if (subPath.endsWith(\".java\") || subPath.endsWith(\".class\"))\n {\n String qualifiedName = PathUtil.classFilePathToClassname(subPath);\n addClassToMap(results, qualifiedName);\n }\n }\n return results;\n }" ]
[ "public static Object readObject(File file) throws IOException,\n ClassNotFoundException {\n FileInputStream fileIn = new FileInputStream(file);\n ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(fileIn));\n try {\n return in.readObject();\n } finally {\n IoUtils.safeClose(in);\n }\n }", "public void viewDocument(DocumentEntry entry)\n {\n InputStream is = null;\n\n try\n {\n is = new DocumentInputStream(entry);\n byte[] data = new byte[is.available()];\n is.read(data);\n m_model.setData(data);\n updateTables();\n }\n\n catch (IOException ex)\n {\n throw new RuntimeException(ex);\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n }\n\n }", "public static <T> T[] concat(T firstElement, T... array) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( firstElement.getClass(), 1 + array.length );\n\t\tresult[0] = firstElement;\n\t\tSystem.arraycopy( array, 0, result, 1, array.length );\n\n\t\treturn result;\n\t}", "private static void setupFlowId(SoapMessage message) {\n String flowId = FlowIdHelper.getFlowId(message);\n\n if (flowId == null) {\n flowId = FlowIdProtocolHeaderCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n flowId = FlowIdSoapCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n Exchange ex = message.getExchange();\n if (null!=ex){\n Message reqMsg = ex.getOutMessage();\n if ( null != reqMsg) {\n flowId = FlowIdHelper.getFlowId(reqMsg);\n }\n }\n }\n\n if (flowId != null && !flowId.isEmpty()) {\n FlowIdHelper.setFlowId(message, flowId);\n }\n }", "protected void init(EnhancedAnnotation<T> annotatedAnnotation) {\n initType(annotatedAnnotation);\n initValid(annotatedAnnotation);\n check(annotatedAnnotation);\n }", "public static float smoothPulse(float a1, float a2, float b1, float b2, float x) {\n\t\tif (x < a1 || x >= b2)\n\t\t\treturn 0;\n\t\tif (x >= a2) {\n\t\t\tif (x < b1)\n\t\t\t\treturn 1.0f;\n\t\t\tx = (x - b1) / (b2 - b1);\n\t\t\treturn 1.0f - (x*x * (3.0f - 2.0f*x));\n\t\t}\n\t\tx = (x - a1) / (a2 - a1);\n\t\treturn x*x * (3.0f - 2.0f*x);\n\t}", "public void symm2x2_fast( double a11 , double a12, double a22 )\n {\n// double p = (a11 - a22)*0.5;\n// double r = Math.sqrt(p*p + a12*a12);\n//\n// value0.real = a22 + a12*a12/(r-p);\n// value1.real = a22 - a12*a12/(r+p);\n// }\n//\n// public void symm2x2_std( double a11 , double a12, double a22 )\n// {\n double left = (a11+a22)*0.5;\n double b = (a11-a22)*0.5;\n double right = Math.sqrt(b*b+a12*a12);\n value0.real = left + right;\n value1.real = left - right;\n }", "public void setOfflineState(boolean setToOffline) {\n // acquire write lock\n writeLock.lock();\n try {\n String currentState = ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(),\n \"UTF-8\");\n if(setToOffline) {\n // from NORMAL_SERVER to OFFLINE_SERVER\n if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) {\n put(SERVER_STATE_KEY, VoldemortState.OFFLINE_SERVER);\n initCache(SERVER_STATE_KEY);\n put(SLOP_STREAMING_ENABLED_KEY, false);\n initCache(SLOP_STREAMING_ENABLED_KEY);\n put(PARTITION_STREAMING_ENABLED_KEY, false);\n initCache(PARTITION_STREAMING_ENABLED_KEY);\n put(READONLY_FETCH_ENABLED_KEY, false);\n initCache(READONLY_FETCH_ENABLED_KEY);\n } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) {\n logger.warn(\"Already in OFFLINE_SERVER state.\");\n return;\n } else {\n logger.error(\"Cannot enter OFFLINE_SERVER state from \" + currentState);\n throw new VoldemortException(\"Cannot enter OFFLINE_SERVER state from \"\n + currentState);\n }\n } else {\n // from OFFLINE_SERVER to NORMAL_SERVER\n if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) {\n logger.warn(\"Already in NORMAL_SERVER state.\");\n return;\n } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) {\n put(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER);\n initCache(SERVER_STATE_KEY);\n put(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(SLOP_STREAMING_ENABLED_KEY);\n put(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY);\n put(READONLY_FETCH_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY);\n init();\n initNodeId(getNodeIdNoLock());\n } else {\n logger.error(\"Cannot enter NORMAL_SERVER state from \" + currentState);\n throw new VoldemortException(\"Cannot enter NORMAL_SERVER state from \"\n + currentState);\n }\n }\n } finally {\n writeLock.unlock();\n }\n }", "public static <T, C extends Comparable<? super C>> List<T> sortBy(Iterable<T> iterable,\n\t\t\tfinal Functions.Function1<? super T, C> key) {\n\t\treturn ListExtensions.sortInplaceBy(Lists.newArrayList(iterable), key);\n\t}" ]
map a property id. Property id can only be an Integer or String
[ "private Object mapToId(Object tmp) {\n if (tmp instanceof Double) {\n return new Integer(((Double)tmp).intValue());\n } else {\n return Context.toString(tmp);\n }\n }" ]
[ "public void setCastShadow(boolean enableFlag)\n {\n GVRSceneObject owner = getOwnerObject();\n\n if (owner != null)\n {\n GVRShadowMap shadowMap = (GVRShadowMap) getComponent(GVRRenderTarget.getComponentType());\n if (enableFlag)\n {\n if (shadowMap != null)\n {\n shadowMap.setEnable(true);\n }\n else\n {\n GVRCamera shadowCam = GVRShadowMap.makeOrthoShadowCamera(\n getGVRContext().getMainScene().getMainCameraRig().getCenterCamera());\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\n }", "private void readAssignments(Project plannerProject)\n {\n Allocations allocations = plannerProject.getAllocations();\n List<Allocation> allocationList = allocations.getAllocation();\n Set<Task> tasksWithAssignments = new HashSet<Task>();\n\n for (Allocation allocation : allocationList)\n {\n Integer taskID = getInteger(allocation.getTaskId());\n Integer resourceID = getInteger(allocation.getResourceId());\n Integer units = getInteger(allocation.getUnits());\n\n Task task = m_projectFile.getTaskByUniqueID(taskID);\n Resource resource = m_projectFile.getResourceByUniqueID(resourceID);\n\n if (task != null && resource != null)\n {\n Duration work = task.getWork();\n int percentComplete = NumberHelper.getInt(task.getPercentageComplete());\n\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setUnits(units);\n assignment.setWork(work);\n\n if (percentComplete != 0)\n {\n Duration actualWork = Duration.getInstance((work.getDuration() * percentComplete) / 100, work.getUnits());\n assignment.setActualWork(actualWork);\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n else\n {\n assignment.setRemainingWork(work);\n }\n\n assignment.setStart(task.getStart());\n assignment.setFinish(task.getFinish());\n\n tasksWithAssignments.add(task);\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }\n }\n\n //\n // Adjust work per assignment for tasks with multiple assignments\n //\n for (Task task : tasksWithAssignments)\n {\n List<ResourceAssignment> assignments = task.getResourceAssignments();\n if (assignments.size() > 1)\n {\n double maxUnits = 0;\n for (ResourceAssignment assignment : assignments)\n {\n maxUnits += assignment.getUnits().doubleValue();\n }\n\n for (ResourceAssignment assignment : assignments)\n {\n Duration work = assignment.getWork();\n double factor = assignment.getUnits().doubleValue() / maxUnits;\n\n work = Duration.getInstance(work.getDuration() * factor, work.getUnits());\n assignment.setWork(work);\n Duration actualWork = assignment.getActualWork();\n if (actualWork != null)\n {\n actualWork = Duration.getInstance(actualWork.getDuration() * factor, actualWork.getUnits());\n assignment.setActualWork(actualWork);\n }\n\n Duration remainingWork = assignment.getRemainingWork();\n if (remainingWork != null)\n {\n remainingWork = Duration.getInstance(remainingWork.getDuration() * factor, remainingWork.getUnits());\n assignment.setRemainingWork(remainingWork);\n }\n }\n }\n }\n }", "public static void append(File file, Object text) throws IOException {\n Writer writer = null;\n try {\n writer = new FileWriter(file, true);\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }", "public CompositeGeneratorNode appendNewLineIfNotEmpty(final CompositeGeneratorNode parent) {\n List<IGeneratorNode> _children = parent.getChildren();\n String _lineDelimiter = this.wsConfig.getLineDelimiter();\n NewLineNode _newLineNode = new NewLineNode(_lineDelimiter, true);\n _children.add(_newLineNode);\n return parent;\n }", "public static long access2d(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n\n for( int i = 0; i < a.numRows; i++ ) {\n\n for( int j = 0; j < b.numCols; j++ ) {\n c.set(i,j,a.get(i,0)*b.get(0,j));\n }\n\n for( int k = 1; k < b.numRows; k++ ) {\n for( int j = 0; j < b.numCols; j++ ) {\n// c.set(i,j, c.get(i,j) + a.get(i,k)*b.get(k,j));\n c.data[i*b.numCols+j] +=a.get(i,k)*b.get(k,j);\n }\n }\n }\n\n return System.currentTimeMillis() - timeBefore;\n }", "protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Identity oid) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getKeyValues(cld, oid);\r\n }", "public static synchronized void addCachedDatabaseConfigs(Collection<DatabaseTableConfig<?>> configs) {\n\t\tMap<Class<?>, DatabaseTableConfig<?>> newMap;\n\t\tif (configMap == null) {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>();\n\t\t} else {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>(configMap);\n\t\t}\n\t\tfor (DatabaseTableConfig<?> config : configs) {\n\t\t\tnewMap.put(config.getDataClass(), config);\n\t\t\tlogger.info(\"Loaded configuration for {}\", config.getDataClass());\n\t\t}\n\t\tconfigMap = newMap;\n\t}", "public static int optionLength(String option) {\n if(matchOption(option, \"qualify\", true) ||\n matchOption(option, \"qualifyGenerics\", true) ||\n matchOption(option, \"hideGenerics\", true) ||\n matchOption(option, \"horizontal\", true) ||\n matchOption(option, \"all\") ||\n matchOption(option, \"attributes\", true) ||\n matchOption(option, \"enumconstants\", true) ||\n matchOption(option, \"operations\", true) ||\n matchOption(option, \"enumerations\", true) ||\n matchOption(option, \"constructors\", true) ||\n matchOption(option, \"visibility\", true) ||\n matchOption(option, \"types\", true) ||\n matchOption(option, \"autosize\", true) ||\n matchOption(option, \"commentname\", true) ||\n matchOption(option, \"nodefontabstractitalic\", true) ||\n matchOption(option, \"postfixpackage\", true) ||\n matchOption(option, \"noguillemot\", true) ||\n matchOption(option, \"views\", true) ||\n matchOption(option, \"inferrel\", true) ||\n matchOption(option, \"useimports\", true) ||\n matchOption(option, \"collapsible\", true) ||\n matchOption(option, \"inferdep\", true) ||\n matchOption(option, \"inferdepinpackage\", true) ||\n matchOption(option, \"hideprivateinner\", true) ||\n matchOption(option, \"compact\", true))\n\n return 1;\n else if(matchOption(option, \"nodefillcolor\") ||\n matchOption(option, \"nodefontcolor\") ||\n matchOption(option, \"nodefontsize\") ||\n matchOption(option, \"nodefontname\") ||\n matchOption(option, \"nodefontclasssize\") ||\n matchOption(option, \"nodefontclassname\") ||\n matchOption(option, \"nodefonttagsize\") ||\n matchOption(option, \"nodefonttagname\") ||\n matchOption(option, \"nodefontpackagesize\") ||\n matchOption(option, \"nodefontpackagename\") ||\n matchOption(option, \"edgefontcolor\") ||\n matchOption(option, \"edgecolor\") ||\n matchOption(option, \"edgefontsize\") ||\n matchOption(option, \"edgefontname\") ||\n matchOption(option, \"shape\") ||\n matchOption(option, \"output\") ||\n matchOption(option, \"outputencoding\") ||\n matchOption(option, \"bgcolor\") ||\n matchOption(option, \"hide\") ||\n matchOption(option, \"include\") ||\n matchOption(option, \"apidocroot\") ||\n matchOption(option, \"apidocmap\") ||\n matchOption(option, \"d\") ||\n matchOption(option, \"view\") ||\n matchOption(option, \"inferreltype\") ||\n matchOption(option, \"inferdepvis\") ||\n matchOption(option, \"collpackages\") ||\n matchOption(option, \"nodesep\") ||\n matchOption(option, \"ranksep\") ||\n matchOption(option, \"dotexecutable\") ||\n matchOption(option, \"link\"))\n return 2;\n else if(matchOption(option, \"contextPattern\") ||\n matchOption(option, \"linkoffline\"))\n return 3;\n else\n return 0;\n }", "public static void zero( DMatrixSparseCSC A , int row0, int row1, int col0, int col1 ) {\n for (int col = col1-1; col >= col0; col--) {\n int numRemoved = 0;\n\n int idx0 = A.col_idx[col], idx1 = A.col_idx[col+1];\n for (int i = idx0; i < idx1; i++) {\n int row = A.nz_rows[i];\n\n // if sorted a faster technique could be used\n if( row >= row0 && row < row1 ) {\n numRemoved++;\n } else if( numRemoved > 0 ){\n A.nz_rows[i-numRemoved]=row;\n A.nz_values[i-numRemoved]=A.nz_values[i];\n }\n }\n\n if( numRemoved > 0 ) {\n // this could be done more intelligently. Each time a column is adjusted all the columns are adjusted\n // after it. Maybe accumulate the changes in each column and do it in one pass? Need an array to store\n // those results though\n\n for (int i = idx1; i < A.nz_length; i++) {\n A.nz_rows[i - numRemoved] = A.nz_rows[i];\n A.nz_values[i - numRemoved] = A.nz_values[i];\n }\n A.nz_length -= numRemoved;\n\n for (int i = col+1; i <= A.numCols; i++) {\n A.col_idx[i] -= numRemoved;\n }\n }\n }\n }" ]
Get the art available for all tracks currently loaded in any player, either on the play deck, or in a hot cue. @return the album art associated with all current players, including for any tracks loaded in their hot cue slots @throws IllegalStateException if the ArtFinder is not running
[ "public Map<DeckReference, AlbumArt> getLoadedArt() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, AlbumArt>(hotCache));\n }" ]
[ "public boolean removeReader(Object key, Object resourceId)\r\n {\r\n boolean result = false;\r\n ObjectLocks objectLocks = null;\r\n synchronized(locktable)\r\n {\r\n objectLocks = (ObjectLocks) locktable.get(resourceId);\r\n if(objectLocks != null)\r\n {\r\n /**\r\n * MBAIRD, last one out, close the door and turn off the lights.\r\n * if no locks (readers or writers) exist for this object, let's remove\r\n * it from the locktable.\r\n */\r\n Map readers = objectLocks.getReaders();\r\n result = readers.remove(key) != null;\r\n if((objectLocks.getWriter() == null) && (readers.size() == 0))\r\n {\r\n locktable.remove(resourceId);\r\n }\r\n }\r\n }\r\n return result;\r\n }", "public DbLicense resolve(final String licenseId) {\n\n for (final Entry<String, DbLicense> regexp : licensesRegexp.entrySet()) {\n try {\n if (licenseId.matches(regexp.getKey())) {\n return regexp.getValue();\n }\n } catch (PatternSyntaxException e) {\n LOG.error(\"Wrong pattern for the following license \" + regexp.getValue().getName(), e);\n continue;\n }\n }\n\n if(LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"No matching pattern for license %s\", licenseId));\n }\n return null;\n }", "private void registerChildInternal(IgnoreDomainResourceTypeResource child) {\n child.setParent(this);\n children.put(child.getName(), child);\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 }", "protected NodeData createBodyStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"background-color\", tf.createColor(255, 255, 255)));\n return ret;\n }", "private AlbumArt requestArtworkInternal(final DataReference artReference, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n\n // First check if we are using cached data for this slot.\n MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(artReference));\n if (cache != null) {\n final AlbumArt result = cache.getAlbumArt(null, artReference);\n if (result != null) {\n artCache.put(artReference, result);\n }\n return result;\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(artReference.getSlotReference());\n if (sourceDetails != null) {\n final AlbumArt provided = MetadataFinder.getInstance().allMetadataProviders.getAlbumArt(sourceDetails, artReference);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (MetadataFinder.getInstance().isPassive() && failIfPassive && artReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // We have to actually request the art using the dbserver protocol.\n ConnectionManager.ClientTask<AlbumArt> task = new ConnectionManager.ClientTask<AlbumArt>() {\n @Override\n public AlbumArt useClient(Client client) throws Exception {\n return getArtwork(artReference.rekordboxId, SlotReference.getSlotReference(artReference), trackType, client);\n }\n };\n\n try {\n AlbumArt artwork = ConnectionManager.getInstance().invokeWithClientSession(artReference.player, task, \"requesting artwork\");\n if (artwork != null) { // Our cache file load or network request succeeded, so add to the level 2 cache.\n artCache.put(artReference, artwork);\n }\n return artwork;\n } catch (Exception e) {\n logger.error(\"Problem requesting album art, returning null\", e);\n }\n return null;\n }", "public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int written = 0;\n for (int i = 0; i < srcLen; ++i) {\n written += Character.toChars(src[srcOff + i], dest, destOff + written);\n }\n return written;\n }", "public static <T> FastEvent<T> of(Class<T> type, BeanManagerImpl manager, ObserverNotifier notifier, Annotation... qualifiers) {\n ResolvedObservers<T> resolvedObserverMethods = notifier.<T> resolveObserverMethods(type, qualifiers);\n if (resolvedObserverMethods.isMetadataRequired()) {\n EventMetadata metadata = new EventMetadataImpl(type, null, qualifiers);\n CurrentEventMetadata metadataService = manager.getServices().get(CurrentEventMetadata.class);\n return new FastEventWithMetadataPropagation<T>(resolvedObserverMethods, metadata, metadataService);\n } else {\n return new FastEvent<T>(resolvedObserverMethods);\n }\n }", "public static base_responses add(nitro_service client, dbdbprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdbdbprofile addresources[] = new dbdbprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dbdbprofile();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].interpretquery = resources[i].interpretquery;\n\t\t\t\taddresources[i].stickiness = resources[i].stickiness;\n\t\t\t\taddresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\taddresources[i].conmultiplex = resources[i].conmultiplex;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Return a vector of values corresponding to a given vector of times. @param times A given vector of times. @return A vector of values corresponding to the given vector of times.
[ "public RandomVariable[] getValues(double[] times) {\n\t\tRandomVariable[] values = new RandomVariable[times.length];\n\n\t\tfor(int i=0; i<times.length; i++) {\n\t\t\tvalues[i] = getValue(null, times[i]);\n\t\t}\n\n\t\treturn values;\n\t}" ]
[ "public static int getProfileIdFromPathID(int path_id) throws Exception {\n return (Integer) SQLService.getInstance().getFromTable(Constants.GENERIC_PROFILE_ID, Constants.GENERIC_ID, path_id, Constants.DB_TABLE_PATH);\n }", "public static protocoludp_stats get(nitro_service service) throws Exception{\n\t\tprotocoludp_stats obj = new protocoludp_stats();\n\t\tprotocoludp_stats[] response = (protocoludp_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "public void setResourceCalendar(ProjectCalendar calendar)\n {\n set(ResourceField.CALENDAR, calendar);\n if (calendar == null)\n {\n setResourceCalendarUniqueID(null);\n }\n else\n {\n calendar.setResource(this);\n setResourceCalendarUniqueID(calendar.getUniqueID());\n }\n }", "public ItemRequest<Task> dependencies(String task) {\n \n String path = String.format(\"/tasks/%s/dependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }", "public byte[] encrypt(byte[] plainData) {\n checkArgument(plainData.length >= OVERHEAD_SIZE,\n \"Invalid plainData, %s bytes\", plainData.length);\n\n // workBytes := initVector || payload || zeros:4\n byte[] workBytes = plainData.clone();\n ByteBuffer workBuffer = ByteBuffer.wrap(workBytes);\n boolean success = false;\n\n try {\n // workBytes := initVector || payload || I(signature)\n int signature = hmacSignature(workBytes);\n workBuffer.putInt(workBytes.length - SIGNATURE_SIZE, signature);\n // workBytes := initVector || E(payload) || I(signature)\n xorPayloadToHmacPad(workBytes);\n\n if (logger.isDebugEnabled()) {\n logger.debug(dump(\"Encrypted\", plainData, workBytes));\n }\n\n success = true;\n return workBytes;\n } finally {\n if (!success && logger.isDebugEnabled()) {\n logger.debug(dump(\"Encrypted (failed)\", plainData, workBytes));\n }\n }\n }", "public long remove(final String... fields) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.hdel(getKey(), fields);\n }\n });\n }", "@Beta(SinceVersion.V1_1_0)\n public void close() {\n httpClient.dispatcher().executorService().shutdown();\n httpClient.connectionPool().evictAll();\n synchronized (httpClient.connectionPool()) {\n httpClient.connectionPool().notifyAll();\n }\n synchronized (AsyncTimeout.class) {\n AsyncTimeout.class.notifyAll();\n }\n }", "public void setMenuView(int layoutResId) {\n mMenuContainer.removeAllViews();\n mMenuView = LayoutInflater.from(getContext()).inflate(layoutResId, mMenuContainer, false);\n mMenuContainer.addView(mMenuView);\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 }" ]
Write project properties. @param record project properties @throws IOException
[ "private void writeProjectProperties(ProjectProperties record) throws IOException\n {\n // the ProjectProperties class from MPXJ has the details of how many days per week etc....\n // so I've assigned these variables in here, but actually use them in other methods\n // see the write task method, that's where they're used, but that method only has a Task object\n m_minutesPerDay = record.getMinutesPerDay().doubleValue();\n m_minutesPerWeek = record.getMinutesPerWeek().doubleValue();\n m_daysPerMonth = record.getDaysPerMonth().doubleValue();\n\n // reset buffer to be empty, then concatenate data as required by USACE\n m_buffer.setLength(0);\n m_buffer.append(\"PROJ \");\n m_buffer.append(m_formatter.format(record.getStartDate()).toUpperCase() + \" \"); // DataDate\n m_buffer.append(SDEFmethods.lset(record.getManager(), 4) + \" \"); // ProjIdent\n m_buffer.append(SDEFmethods.lset(record.getProjectTitle(), 48) + \" \"); // ProjName\n m_buffer.append(SDEFmethods.lset(record.getSubject(), 36) + \" \"); // ContrName\n m_buffer.append(\"P \"); // ArrowP\n m_buffer.append(SDEFmethods.lset(record.getKeywords(), 7)); // ContractNum\n m_buffer.append(m_formatter.format(record.getStartDate()).toUpperCase() + \" \"); // ProjStart\n m_buffer.append(m_formatter.format(record.getFinishDate()).toUpperCase()); // ProjEnd\n m_writer.println(m_buffer);\n }" ]
[ "public static base_responses delete(nitro_service client, String sitename[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite deleteresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tdeleteresources[i] = new gslbsite();\n\t\t\t\tdeleteresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static DMatrixRMaj diagonal(int numRows , int numCols , double min , double max , Random rand ) {\n if( max < min )\n throw new IllegalArgumentException(\"The max must be >= the min\");\n\n DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);\n\n int N = Math.min(numRows,numCols);\n\n double r = max-min;\n\n for( int i = 0; i < N; i++ ) {\n ret.set(i,i, rand.nextDouble()*r+min);\n }\n\n return ret;\n }", "public ServerSetup[] build(Properties properties) {\n List<ServerSetup> serverSetups = new ArrayList<>();\n\n String hostname = properties.getProperty(\"greenmail.hostname\", ServerSetup.getLocalHostAddress());\n long serverStartupTimeout =\n Long.parseLong(properties.getProperty(\"greenmail.startup.timeout\", \"-1\"));\n\n // Default setups\n addDefaultSetups(hostname, properties, serverSetups);\n\n // Default setups for test\n addTestSetups(hostname, properties, serverSetups);\n\n // Default setups\n for (String protocol : ServerSetup.PROTOCOLS) {\n addSetup(hostname, protocol, properties, serverSetups);\n }\n\n for (ServerSetup setup : serverSetups) {\n if (properties.containsKey(GREENMAIL_VERBOSE)) {\n setup.setVerbose(true);\n }\n if (serverStartupTimeout >= 0L) {\n setup.setServerStartupTimeout(serverStartupTimeout);\n }\n }\n\n return serverSetups.toArray(new ServerSetup[serverSetups.size()]);\n }", "public void moveDown(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if ((index >= 0) && (index < (m_container.getComponentCount() - 1))) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index + 1);\n }\n updateButtonBars();\n }", "public double getProgressFromResponse(ResponseOnSingeRequest myResponse) {\n\n double progress = 0.0;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return progress;\n }\n\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(progressRegex);\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n String progressStr = matcher.group(1);\n progress = Double.parseDouble(progressStr);\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n\n return progress;\n }", "public ItemRequest<Task> addProject(String task) {\n \n String path = String.format(\"/tasks/%s/addProject\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "private static void query(String filename) throws Exception\n {\n ProjectFile mpx = new UniversalProjectReader().read(filename);\n\n listProjectProperties(mpx);\n\n listResources(mpx);\n\n listTasks(mpx);\n\n listAssignments(mpx);\n\n listAssignmentsByTask(mpx);\n\n listAssignmentsByResource(mpx);\n\n listHierarchy(mpx);\n\n listTaskNotes(mpx);\n\n listResourceNotes(mpx);\n\n listRelationships(mpx);\n\n listSlack(mpx);\n\n listCalendars(mpx);\n\n }", "public RandomVariable[] getValues(double[] times) {\n\t\tRandomVariable[] values = new RandomVariable[times.length];\n\n\t\tfor(int i=0; i<times.length; i++) {\n\t\t\tvalues[i] = getValue(null, times[i]);\n\t\t}\n\n\t\treturn values;\n\t}", "public static base_response renumber(nitro_service client) throws Exception {\n\t\tnspbr6 renumberresource = new nspbr6();\n\t\treturn renumberresource.perform_operation(client,\"renumber\");\n\t}" ]
Method for reporting SQLException. This is used by the treenodes if retrieving information for a node is not successful. @param message The message describing where the error occurred @param sqlEx The exception to be reported.
[ "public void reportSqlError(String message, java.sql.SQLException sqlEx)\r\n {\r\n StringBuffer strBufMessages = new StringBuffer();\r\n java.sql.SQLException currentSqlEx = sqlEx;\r\n do\r\n {\r\n strBufMessages.append(\"\\n\" + sqlEx.getErrorCode() + \":\" + sqlEx.getMessage());\r\n currentSqlEx = currentSqlEx.getNextException();\r\n } while (currentSqlEx != null); \r\n System.err.println(message + strBufMessages.toString());\r\n sqlEx.printStackTrace();\r\n }" ]
[ "public static void addActionsTo(\n SourceBuilder code,\n Set<MergeAction> mergeActions,\n boolean forBuilder) {\n SetMultimap<String, String> nounsByVerb = TreeMultimap.create();\n mergeActions.forEach(mergeAction -> {\n if (forBuilder || !mergeAction.builderOnly) {\n nounsByVerb.put(mergeAction.verb, mergeAction.noun);\n }\n });\n List<String> verbs = ImmutableList.copyOf(nounsByVerb.keySet());\n String lastVerb = getLast(verbs, null);\n for (String verb : nounsByVerb.keySet()) {\n code.add(\", %s%s\", (verbs.size() > 1 && verb.equals(lastVerb)) ? \"and \" : \"\", verb);\n List<String> nouns = ImmutableList.copyOf(nounsByVerb.get(verb));\n for (int i = 0; i < nouns.size(); ++i) {\n String separator = (i == 0) ? \"\" : (i == nouns.size() - 1) ? \" and\" : \",\";\n code.add(\"%s %s\", separator, nouns.get(i));\n }\n }\n }", "private static <T> void writeConfig(BufferedWriter writer, DatabaseTableConfig<T> config) throws IOException,\n\t\t\tSQLException {\n\t\twriter.append(CONFIG_FILE_START_MARKER);\n\t\twriter.newLine();\n\t\tif (config.getDataClass() != null) {\n\t\t\twriter.append(FIELD_NAME_DATA_CLASS).append('=').append(config.getDataClass().getName());\n\t\t\twriter.newLine();\n\t\t}\n\t\tif (config.getTableName() != null) {\n\t\t\twriter.append(FIELD_NAME_TABLE_NAME).append('=').append(config.getTableName());\n\t\t\twriter.newLine();\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_START);\n\t\twriter.newLine();\n\t\tif (config.getFieldConfigs() != null) {\n\t\t\tfor (DatabaseFieldConfig field : config.getFieldConfigs()) {\n\t\t\t\tDatabaseFieldConfigLoader.write(writer, field, config.getTableName());\n\t\t\t}\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_END);\n\t\twriter.newLine();\n\t\twriter.append(CONFIG_FILE_END_MARKER);\n\t\twriter.newLine();\n\t}", "private static boolean containsGreekLetter(String s) {\r\n Matcher m = biogreek.matcher(s);\r\n return m.find();\r\n }", "public static responderhtmlpage get(nitro_service service, String name) throws Exception{\n\t\tresponderhtmlpage obj = new responderhtmlpage();\n\t\tobj.set_name(name);\n\t\tresponderhtmlpage response = (responderhtmlpage) obj.get_resource(service);\n\t\treturn response;\n\t}", "public T findById(Object id) throws RowNotFoundException, TooManyRowsException {\n return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult();\n }", "private void pushDeviceToken(final String token, final boolean register, final PushType type) {\n pushDeviceToken(this.context, token, register, type);\n }", "public static double I(int n, double x) {\r\n if (n < 0)\r\n throw new IllegalArgumentException(\"the variable n out of range.\");\r\n else if (n == 0)\r\n return I0(x);\r\n else if (n == 1)\r\n return I(x);\r\n\r\n if (x == 0.0)\r\n return 0.0;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n double tox = 2.0 / Math.abs(x);\r\n double bip = 0, ans = 0.0;\r\n double bi = 1.0;\r\n\r\n for (int j = 2 * (n + (int) Math.sqrt(ACC * n)); j > 0; j--) {\r\n double bim = bip + j * tox * bi;\r\n bip = bi;\r\n bi = bim;\r\n\r\n if (Math.abs(bi) > BIGNO) {\r\n ans *= BIGNI;\r\n bi *= BIGNI;\r\n bip *= BIGNI;\r\n }\r\n\r\n if (j == n)\r\n ans = bip;\r\n }\r\n\r\n ans *= I0(x) / bi;\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }", "public String getTypeDescriptor() {\n if (typeDescriptor == null) {\n StringBuilder buf = new StringBuilder(name.length() + parameters.length * 10);\n buf.append(returnType.getName());\n buf.append(' ');\n buf.append(name);\n buf.append('(');\n for (int i = 0; i < parameters.length; i++) {\n if (i > 0) {\n buf.append(\", \");\n }\n Parameter param = parameters[i];\n buf.append(formatTypeName(param.getType()));\n }\n buf.append(')');\n typeDescriptor = buf.toString();\n }\n return typeDescriptor;\n }", "public void putInWakeUpQueue(SerialMessage serialMessage) {\r\n\t\tif (this.wakeUpQueue.contains(serialMessage)) {\r\n\t\t\tlogger.debug(\"Message already on the wake-up queue for node {}. Discarding.\", this.getNode().getNodeId());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\t\r\n\t\tlogger.debug(\"Putting message in wakeup queue for node {}.\", this.getNode().getNodeId());\r\n\t\tthis.wakeUpQueue.add(serialMessage);\r\n\t}" ]
Creates the string mappings. @param mtasTokenIdFactory the mtas token id factory @param level the level @param stringValue the string value @param offsetStart the offset start @param offsetEnd the offset end @param position the position @throws IOException Signals that an I/O exception has occurred.
[ "private void createStringMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int position) throws IOException {\n // System.out.println(\"createStringMappings string \");\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n if (stringValues.length > 0 && !stringValues[0].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"t\", filterString(stringValues[0].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n if (stringValues.length > 1 && !stringValues[1].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"lemma\", filterString(stringValues[1].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n }" ]
[ "private static String handleRichError(final Response response, final String body) {\n if (!response.getHeaders().containsKey(Headers.CONTENT_TYPE)\n || !response.getHeaders().get(Headers.CONTENT_TYPE).equals(ContentTypes.APPLICATION_JSON)) {\n return body;\n }\n\n final Document doc;\n try {\n doc = BsonUtils.parseValue(body, Document.class);\n } catch (Exception e) {\n return body;\n }\n\n if (!doc.containsKey(Fields.ERROR)) {\n return body;\n }\n final String errorMsg = doc.getString(Fields.ERROR);\n if (!doc.containsKey(Fields.ERROR_CODE)) {\n return errorMsg;\n }\n\n final String errorCode = doc.getString(Fields.ERROR_CODE);\n throw new StitchServiceException(errorMsg, StitchServiceErrorCode.fromCodeName(errorCode));\n }", "public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deployment = entities.stream()\n .filter(hm -> hm instanceof Deployment)\n .map(hm -> (Deployment) hm)\n .map(rc -> rc.getMetadata().getName()).findFirst();\n\n deployment.ifPresent(name -> this.applicationName = name);\n }\n }", "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}", "public void setSegmentReject(String reject) {\n\t\tif (!StringUtils.hasText(reject)) {\n\t\t\treturn;\n\t\t}\n\t\tInteger parsedLimit = null;\n\t\ttry {\n\t\t\tparsedLimit = Integer.parseInt(reject);\n\t\t\tsegmentRejectType = SegmentRejectType.ROWS;\n\t\t} catch (NumberFormatException e) {\n\t\t}\n\t\tif (parsedLimit == null && reject.contains(\"%\")) {\n\t\t\ttry {\n\t\t\t\tparsedLimit = Integer.parseInt(reject.replace(\"%\", \"\").trim());\n\t\t\t\tsegmentRejectType = SegmentRejectType.PERCENT;\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t}\n\t\t}\n\t\tsegmentRejectLimit = parsedLimit;\n\t}", "public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline,\n Class<? extends WindupVertexFrame> clazz)\n {\n pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz));\n return pipeline;\n }", "public boolean checkContains(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.contains(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 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 }", "protected boolean prepareClose() {\n synchronized (lock) {\n final State state = this.state;\n if (state == State.OPEN) {\n this.state = State.CLOSING;\n lock.notifyAll();\n return true;\n }\n }\n return false;\n }", "private static String get(Properties p, String key, String defaultValue, Set<String> used){\r\n String rtn = p.getProperty(key, defaultValue);\r\n used.add(key);\r\n return rtn;\r\n }" ]
Create and add model controller handler to an existing management channel handler. @param handler the channel handler @return the created client
[ "public static ModelControllerClient createAndAdd(final ManagementChannelHandler handler) {\n final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler);\n handler.addHandlerFactory(client);\n return client;\n }" ]
[ "private int runCommitScript() {\n\n if (m_checkout && !m_fetchAndResetBeforeImport) {\n m_logStream.println(\"Skipping script....\");\n return 0;\n }\n try {\n m_logStream.flush();\n String commandParam;\n if (m_resetRemoteHead) {\n commandParam = resetRemoteHeadScriptCommand();\n } else if (m_resetHead) {\n commandParam = resetHeadScriptCommand();\n } else if (m_checkout) {\n commandParam = checkoutScriptCommand();\n } else {\n commandParam = checkinScriptCommand();\n }\n String[] cmd = {\"bash\", \"-c\", commandParam};\n m_logStream.println(\"Calling the script as follows:\");\n m_logStream.println();\n m_logStream.println(cmd[0] + \" \" + cmd[1] + \" \" + cmd[2]);\n ProcessBuilder builder = new ProcessBuilder(cmd);\n m_logStream.close();\n m_logStream = null;\n Redirect redirect = Redirect.appendTo(new File(DEFAULT_LOGFILE_PATH));\n builder.redirectOutput(redirect);\n builder.redirectError(redirect);\n Process scriptProcess = builder.start();\n int exitCode = scriptProcess.waitFor();\n scriptProcess.getOutputStream().close();\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, true));\n return exitCode;\n } catch (InterruptedException | IOException e) {\n e.printStackTrace(m_logStream);\n return -1;\n }\n\n }", "public void waitForAsyncFlush() {\n long numAdded = asyncBatchesAdded.get();\n\n synchronized (this) {\n while (numAdded > asyncBatchesProcessed) {\n try {\n wait();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n }", "public void loadPhysics(String filename, GVRScene scene) throws IOException\n {\n GVRPhysicsLoader.loadPhysicsFile(getGVRContext(), filename, true, scene);\n }", "public static <T, X> ObserverMethodImpl<T, X> create(EnhancedAnnotatedMethod<T, ? super X> method, RIBean<X> declaringBean, BeanManagerImpl manager, boolean isAsync) {\n if (declaringBean instanceof ExtensionBean) {\n return new ExtensionObserverMethodImpl<T, X>(method, declaringBean, manager, isAsync);\n }\n return new ObserverMethodImpl<T, X>(method, declaringBean, manager, isAsync);\n }", "public static vpnvserver_authenticationsamlpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationsamlpolicy_binding obj = new vpnvserver_authenticationsamlpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationsamlpolicy_binding response[] = (vpnvserver_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static <T> List<T> copyOf(T[] elements) {\n Preconditions.checkNotNull(elements);\n return ofInternal(elements.clone());\n }", "@Override\n public EnvironmentConfig setSetting(@NotNull final String key, @NotNull final Object value) {\n return (EnvironmentConfig) super.setSetting(key, value);\n }", "public static <T> T assertNull(T value, String message) {\n if (value != null)\n throw new IllegalStateException(message);\n return value;\n }", "public int getIndexFromOffset(int offset)\n {\n int result = -1;\n\n for (int loop = 0; loop < m_offset.length; loop++)\n {\n if (m_offset[loop] == offset)\n {\n result = loop;\n break;\n }\n }\n\n return (result);\n }" ]
Compute the key to use. @param ref The reference number. @param filename The filename. @param extension The file extension.
[ "protected String getKey(final String ref, final String filename, final String extension) {\n return prefix + ref + \"/\" + filename + \".\" + extension;\n }" ]
[ "public List<I_CmsEditableGroupRow> getRows() {\n\n List<I_CmsEditableGroupRow> result = Lists.newArrayList();\n for (Component component : m_container) {\n if (component instanceof I_CmsEditableGroupRow) {\n result.add((I_CmsEditableGroupRow)component);\n }\n }\n return result;\n }", "public static void copyThenClose(InputStream input, OutputStream output)\r\n throws IOException {\r\n copy(input, output);\r\n input.close();\r\n output.close();\r\n }", "public void stopServer() throws Exception {\n if (!externalDatabaseHost) {\n try (Connection sqlConnection = getConnection()) {\n sqlConnection.prepareStatement(\"SHUTDOWN\").execute();\n } catch (Exception e) {\n }\n\n try {\n server.stop();\n } catch (Exception e) {\n }\n }\n }", "private static String quoteSort(Sort[] sort) {\n LinkedList<String> sorts = new LinkedList<String>();\n for (Sort pair : sort) {\n sorts.add(String.format(\"{%s: %s}\", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString())));\n }\n return sorts.toString();\n }", "public TimephasedCostContainer getBaselineCost(ProjectCalendar calendar, TimephasedCostNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedCostContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedCost> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 16; // 16 byte header\n int blockSize = 20;\n double previousTotalCost = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n index += blockSize;\n\n while (index + blockSize <= data.length)\n {\n Date blockEndDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n double currentTotalCost = (double) ((long) MPPUtility.getDouble(data, index + 8)) / 100;\n if (!costEquals(previousTotalCost, currentTotalCost))\n {\n TimephasedCost cost = new TimephasedCost();\n cost.setStart(blockStartDate);\n cost.setFinish(blockEndDate);\n cost.setTotalAmount(Double.valueOf(currentTotalCost - previousTotalCost));\n\n if (list == null)\n {\n list = new LinkedList<TimephasedCost>();\n }\n list.add(cost);\n //System.out.println(cost);\n\n previousTotalCost = currentTotalCost;\n }\n\n blockStartDate = blockEndDate;\n index += blockSize;\n }\n\n if (list != null)\n {\n result = new DefaultTimephasedCostContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }", "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 }", "public static Set<String> listDeployments(Resource deploymentRootResource, Set<String> runtimeNames) {\n Set<Pattern> set = new HashSet<>();\n for (String wildcardExpr : runtimeNames) {\n Pattern pattern = DeploymentOverlayIndex.getPattern(wildcardExpr);\n set.add(pattern);\n }\n return listDeploymentNames(deploymentRootResource, set);\n }", "public void add(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n boolean matchFilter = declarationFilter.matches(declaration.getMetadata());\n declarations.put(declarationSRef, matchFilter);\n }", "private void updateWaveform(WaveformPreview preview) {\n this.preview.set(preview);\n if (preview == null) {\n waveformImage.set(null);\n } else {\n BufferedImage image = new BufferedImage(preview.segmentCount, preview.maxHeight, BufferedImage.TYPE_INT_RGB);\n Graphics g = image.getGraphics();\n g.setColor(Color.BLACK);\n g.fillRect(0, 0, preview.segmentCount, preview.maxHeight);\n for (int segment = 0; segment < preview.segmentCount; segment++) {\n g.setColor(preview.segmentColor(segment, false));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, false));\n if (preview.isColor) { // We have a front color segment to draw on top.\n g.setColor(preview.segmentColor(segment, true));\n g.drawLine(segment, preview.maxHeight, segment, preview.maxHeight - preview.segmentHeight(segment, true));\n }\n }\n waveformImage.set(image);\n }\n }" ]
Changes to a new sub-view and stores a report to be displayed by that subview.<p< @param newState the new state @param thread the report thread which should be displayed in the sub view @param label the label to display for the report
[ "public void openReport(String newState, A_CmsReportThread thread, String label) {\n\n setReport(newState, thread);\n m_labels.put(thread, label);\n openSubView(newState, true);\n }" ]
[ "public void refresh(String[] configLocations) throws GeomajasException {\n\t\ttry {\n\t\t\tsetConfigLocations(configLocations);\n\t\t\trefresh();\n\t\t} catch (Exception e) {\n\t\t\tthrow new GeomajasException(e, ExceptionCode.REFRESH_CONFIGURATION_FAILED);\n\t\t}\n\t}", "protected void removeWatermark(URLTemplate itemUrl) {\n URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID());\n URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public Collection getReaders(Object obj)\r\n\t{\r\n\t\tCollection result = null;\r\n try\r\n {\r\n Identity oid = new Identity(obj, getBroker());\r\n byte selector = (byte) 'r';\r\n byte[] requestBarr = buildRequestArray(oid, selector);\r\n \r\n HttpURLConnection conn = getHttpUrlConnection();\r\n \r\n //post request\r\n BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());\r\n out.write(requestBarr,0,requestBarr.length);\r\n out.flush();\t\t\r\n \r\n // read result from \r\n InputStream in = conn.getInputStream();\r\n ObjectInputStream ois = new ObjectInputStream(in);\r\n result = (Collection) ois.readObject();\r\n \r\n // cleanup\r\n ois.close();\r\n out.close();\r\n conn.disconnect();\t\t\r\n }\r\n catch (Throwable t)\r\n {\r\n throw new PersistenceBrokerException(t);\r\n }\r\n return result;\r\n\t}", "public BoxFileUploadSessionPart uploadPart(byte[] data, long offset, int partSize,\n long totalSizeOfFile) {\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n MessageDigest digestInstance = null;\n try {\n digestInstance = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64.\n byte[] digestBytes = digestInstance.digest(data);\n String digest = Base64.encode(digestBytes);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n //Content-Range: bytes offset-part/totalSize\n request.addHeader(HttpHeaders.CONTENT_RANGE,\n \"bytes \" + offset + \"-\" + (offset + partSize - 1) + \"/\" + totalSizeOfFile);\n\n //Creates the body\n request.setBody(new ByteArrayInputStream(data));\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n BoxFileUploadSessionPart part = new BoxFileUploadSessionPart((JsonObject) jsonObject.get(\"part\"));\n return part;\n }", "private void disableCertificateVerification()\n throws KeyManagementException, NoSuchAlgorithmException {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] { new CustomTrustManager() };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new SecureRandom());\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);\n final HostnameVerifier verifier = new HostnameVerifier() {\n @Override\n public boolean verify(final String hostname,\n final SSLSession session) {\n return true;\n }\n };\n\n HttpsURLConnection.setDefaultHostnameVerifier(verifier);\n }", "public static int nullity(SingularValueDecomposition_F64 svd , double threshold ) {\n int ret = 0;\n\n double w[]= svd.getSingularValues();\n\n int N = svd.numberOfSingularValues();\n\n int numCol = svd.numCols();\n\n for( int j = 0; j < N; j++ ) {\n if( w[j] <= threshold) ret++;\n }\n return ret + numCol-N;\n }", "@NotThreadsafe\n private void initFileStreams(int chunkId) {\n /**\n * {@link Set#add(Object)} returns false if the element already existed in the set.\n * This ensures we initialize the resources for each chunk only once.\n */\n if (chunksHandled.add(chunkId)) {\n try {\n this.indexFileSizeInBytes[chunkId] = 0L;\n this.valueFileSizeInBytes[chunkId] = 0L;\n this.checkSumDigestIndex[chunkId] = CheckSum.getInstance(checkSumType);\n this.checkSumDigestValue[chunkId] = CheckSum.getInstance(checkSumType);\n this.position[chunkId] = 0;\n this.taskIndexFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf),\n getStoreName() + \".\"\n + Integer.toString(chunkId) + \"_\"\n + this.taskId + INDEX_FILE_EXTENSION\n + fileExtension);\n this.taskValueFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf),\n getStoreName() + \".\"\n + Integer.toString(chunkId) + \"_\"\n + this.taskId + DATA_FILE_EXTENSION\n + fileExtension);\n if(this.fs == null)\n this.fs = this.taskIndexFileName[chunkId].getFileSystem(conf);\n if(isValidCompressionEnabled) {\n this.indexFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskIndexFileName[chunkId]),\n DEFAULT_BUFFER_SIZE)));\n this.valueFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskValueFileName[chunkId]),\n DEFAULT_BUFFER_SIZE)));\n\n } else {\n this.indexFileStream[chunkId] = fs.create(this.taskIndexFileName[chunkId]);\n this.valueFileStream[chunkId] = fs.create(this.taskValueFileName[chunkId]);\n\n }\n fs.setPermission(this.taskIndexFileName[chunkId],\n new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION));\n logger.info(\"Setting permission to 755 for \" + this.taskIndexFileName[chunkId]);\n fs.setPermission(this.taskValueFileName[chunkId],\n new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION));\n logger.info(\"Setting permission to 755 for \" + this.taskValueFileName[chunkId]);\n\n logger.info(\"Opening \" + this.taskIndexFileName[chunkId] + \" and \"\n + this.taskValueFileName[chunkId] + \" for writing.\");\n } catch(IOException e) {\n throw new RuntimeException(\"Failed to open Input/OutputStream\", e);\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 }", "public void _solveVectorInternal( double []vv )\n {\n // Solve L*Y = B\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sum = vv[ip];\n vv[ip] = vv[i];\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*n + ii-1;\n for( int j = ii-1; j < i; j++ )\n sum -= dataLU[index++]*vv[j];\n } else if( sum != 0.0 ) {\n ii=i+1;\n }\n vv[i] = sum;\n }\n\n // Solve U*X = Y;\n TriangularSolver_DDRM.solveU(dataLU,vv,n);\n }" ]
Remove a bean from the context, calling the destruction callback if any. @param name bean name @return previous value
[ "public Object remove(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null != bean) {\n\t\t\tbeans.remove(name);\n\t\t\tbean.destructionCallback.run();\n\t\t\treturn bean.object;\n\t\t}\n\t\treturn null;\n\t}" ]
[ "public static <V> V doWorkInPoolNicely(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) {\n final V result;\n try {\n result = doWorkInPool(pool, work);\n } catch (RuntimeException re) {\n throw re;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n return result;\n }", "public static Multimap<String, String> convertToMultiMap(final PObject objectParams) {\n Multimap<String, String> params = HashMultimap.create();\n if (objectParams != null) {\n Iterator<String> customParamsIter = objectParams.keys();\n while (customParamsIter.hasNext()) {\n String key = customParamsIter.next();\n if (objectParams.isArray(key)) {\n final PArray array = objectParams.optArray(key);\n for (int i = 0; i < array.size(); i++) {\n params.put(key, array.getString(i));\n }\n } else {\n params.put(key, objectParams.optString(key, \"\"));\n }\n }\n }\n\n return params;\n }", "private int getPositiveInteger(String number) {\n try {\n return Math.max(0, Integer.parseInt(number));\n } catch (NumberFormatException e) {\n return 0;\n }\n }", "public boolean removeHandlerFor(final GVRSceneObject sceneObject) {\n sceneObject.detachComponent(GVRCollider.getComponentType());\n return null != touchHandlers.remove(sceneObject);\n }", "public static base_response update(nitro_service client, clusterinstance resource) throws Exception {\n\t\tclusterinstance updateresource = new clusterinstance();\n\t\tupdateresource.clid = resource.clid;\n\t\tupdateresource.deadinterval = resource.deadinterval;\n\t\tupdateresource.hellointerval = resource.hellointerval;\n\t\tupdateresource.preemption = resource.preemption;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static cacheobject[] get(nitro_service service) throws Exception{\n\t\tcacheobject obj = new cacheobject();\n\t\tcacheobject[] response = (cacheobject[])obj.get_resources(service);\n\t\treturn response;\n\t}", "protected List<CmsResource> getTopFolders(List<CmsResource> folders) {\n\n List<String> folderPaths = new ArrayList<String>();\n List<CmsResource> topFolders = new ArrayList<CmsResource>();\n Map<String, CmsResource> foldersByPath = new HashMap<String, CmsResource>();\n for (CmsResource folder : folders) {\n folderPaths.add(folder.getRootPath());\n foldersByPath.put(folder.getRootPath(), folder);\n }\n Collections.sort(folderPaths);\n Set<String> topFolderPaths = new HashSet<String>(folderPaths);\n for (int i = 0; i < folderPaths.size(); i++) {\n for (int j = i + 1; j < folderPaths.size(); j++) {\n if (folderPaths.get(j).startsWith((folderPaths.get(i)))) {\n topFolderPaths.remove(folderPaths.get(j));\n } else {\n break;\n }\n }\n }\n for (String path : topFolderPaths) {\n topFolders.add(foldersByPath.get(path));\n }\n return topFolders;\n }", "@SuppressWarnings(\"SameParameterValue\")\n private byte[] readResponseWithExpectedSize(InputStream is, int size, String description) throws IOException {\n byte[] result = receiveBytes(is);\n if (result.length != size) {\n logger.warn(\"Expected \" + size + \" bytes while reading \" + description + \" response, received \" + result.length);\n }\n return result;\n }", "public void drawGeometry(Geometry geometry, SymbolInfo symbol, Color fillColor, Color strokeColor, float lineWidth,\n\t\t\tfloat[] dashArray, Rectangle clipRect) {\n\t\ttemplate.saveState();\n\t\t// clipping code\n\t\tif (clipRect != null) {\n\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(), clipRect\n\t\t\t\t\t.getHeight());\n\t\t\ttemplate.clip();\n\t\t\ttemplate.newPath();\n\t\t}\n\t\tsetStroke(strokeColor, lineWidth, dashArray);\n\t\tsetFill(fillColor);\n\t\tdrawGeometry(geometry, symbol);\n\t\ttemplate.restoreState();\n\t}" ]
Returns an interval representing the addition of the given interval with this one. @param other interval to add to this one @return interval sum
[ "public DiscreteInterval plus(DiscreteInterval other) {\n return new DiscreteInterval(this.min + other.min, this.max + other.max);\n }" ]
[ "public void logAttributeWarning(PathAddress address, ModelNode operation, String message, String attribute) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attribute));\n }", "void lockSharedInterruptibly(final Integer permit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n sync.acquireSharedInterruptibly(permit);\n }", "void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file) throws IOException, StartException {\n persist(key, value, enableDisableMode, disable, file, null);\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<EthiopicDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<EthiopicDate>) super.localDateTime(temporal);\n }", "private Properties mapToProperties(Map<String, String> map) {\r\n\t\t Properties p = new Properties();\r\n\t\t for (Map.Entry<String,String> entry : map.entrySet()) {\r\n\t\t p.put(entry.getKey(), entry.getValue());\r\n\t\t }\r\n\t\t return p;\r\n\t\t }", "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 }", "public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) {\n\t\tdouble[] swapTenor = new double[fixingDates.length+1];\n\t\tSystem.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);\n\t\tswapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];\n\n\t\tTimeDiscretization fixTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tTimeDiscretization floatTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);\n\t\tdouble payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]);\n\t\treturn AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]);\n\t}", "private void readProjectProperties(Document cdp)\n {\n WorkspaceProperties props = cdp.getWorkspaceProperties();\n ProjectProperties mpxjProps = m_projectFile.getProjectProperties();\n mpxjProps.setSymbolPosition(props.getCurrencyPosition());\n mpxjProps.setCurrencyDigits(props.getCurrencyDigits());\n mpxjProps.setCurrencySymbol(props.getCurrencySymbol());\n mpxjProps.setDaysPerMonth(props.getDaysPerMonth());\n mpxjProps.setMinutesPerDay(props.getHoursPerDay());\n mpxjProps.setMinutesPerWeek(props.getHoursPerWeek());\n\n m_workHoursPerDay = mpxjProps.getMinutesPerDay().doubleValue() / 60.0;\n }", "@SuppressWarnings(\"SameParameterValue\")\n private void sendField(Field field) throws IOException {\n if (isConnected()) {\n try {\n field.write(channel);\n } catch (IOException e) {\n logger.warn(\"Problem trying to write field to dbserver, closing connection\", e);\n close();\n throw e;\n }\n return;\n }\n throw new IOException(\"sendField() called after dbserver connection was closed\");\n }" ]
Update the server group's name @param serverGroupId ID of server group @param name new name of server group @return updated ServerGroup
[ "public ServerGroup updateServerGroupName(int serverGroupId, String name) {\n ServerGroup serverGroup = null;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", name),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP + \"/\" + serverGroupId, params));\n serverGroup = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return serverGroup;\n }" ]
[ "public boolean process( int sideLength,\n double diag[] ,\n double off[] ,\n double eigenvalues[] ) {\n if( diag != null )\n helper.init(diag,off,sideLength);\n if( Q == null )\n Q = CommonOps_DDRM.identity(helper.N);\n helper.setQ(Q);\n\n this.followingScript = true;\n this.eigenvalues = eigenvalues;\n this.fastEigenvalues = false;\n\n return _process();\n }", "public static synchronized void unregisterDao(ConnectionSource connectionSource, Dao<?, ?> dao) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tremoveDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()));\n\t}", "public Result cmd(String cliCommand) {\n try {\n // The intent here is to return a Response when this is doable.\n if (ctx.isWorkflowMode() || ctx.isBatchMode()) {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n handler.parse(ctx.getCurrentNodePath(), cliCommand, ctx);\n if (handler.getFormat() == OperationFormat.INSTANCE) {\n ModelNode request = ctx.buildRequest(cliCommand);\n ModelNode response = ctx.execute(request, cliCommand);\n return new Result(cliCommand, request, response);\n } else {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n } catch (CommandLineException cfe) {\n throw new IllegalArgumentException(\"Error handling command: \"\n + cliCommand, cfe);\n } catch (IOException ioe) {\n throw new IllegalStateException(\"Unable to send command \"\n + cliCommand + \" to server.\", ioe);\n }\n }", "public void add(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n BinderDescriptor binderDescriptor = new BinderDescriptor(declarationBinderRef);\n declarationBinders.put(declarationBinderRef, binderDescriptor);\n }", "public static <T> T load(String resourcePath, BeanSpec spec) {\n return load(resourcePath, spec, false);\n }", "public static ServiceActivator create(final ModelNode endpointConfig, final URI managementURI, final String serverName, final String serverProcessName,\n final String authKey, final boolean managementSubsystemEndpoint, final Supplier<SSLContext> sslContextSupplier) {\n\n return new DomainServerCommunicationServices(endpointConfig, managementURI, serverName, serverProcessName, authKey, managementSubsystemEndpoint, sslContextSupplier);\n }", "public static snmpalarm get(nitro_service service, String trapname) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tobj.set_trapname(trapname);\n\t\tsnmpalarm response = (snmpalarm) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void putToSessionCache(Identity oid, CacheEntry entry, boolean onlyIfNew)\r\n {\r\n if(onlyIfNew)\r\n {\r\n // no synchronization needed, because session cache was used per broker instance\r\n if(!sessionCache.containsKey(oid)) sessionCache.put(oid, entry);\r\n }\r\n else\r\n {\r\n sessionCache.put(oid, entry);\r\n }\r\n }", "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 }" ]
Add a value to this activity code. @param uniqueID value unique ID @param name value name @param description value description @return ActivityCodeValue instance
[ "public ActivityCodeValue addValue(Integer uniqueID, String name, String description)\n {\n ActivityCodeValue value = new ActivityCodeValue(this, uniqueID, name, description);\n m_values.add(value);\n return value;\n }" ]
[ "public static base_responses clear(nitro_service client, bridgetable resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable clearresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new bridgetable();\n\t\t\t\tclearresources[i].vlan = resources[i].vlan;\n\t\t\t\tclearresources[i].ifnum = resources[i].ifnum;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}", "public static Method findSetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)\n\t\t\tthrows IllegalArgumentException {\n\t\tMethod fieldSetMethod = findMethodFromNames(field, false, throwExceptions,\n\t\t\t\tmethodFromField(field, \"set\", databaseType, true), methodFromField(field, \"set\", databaseType, false));\n\t\tif (fieldSetMethod == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (fieldSetMethod.getReturnType() != void.class) {\n\t\t\tif (throwExceptions) {\n\t\t\t\tthrow new IllegalArgumentException(\"Return type of set method \" + fieldSetMethod.getName() + \" returns \"\n\t\t\t\t\t\t+ fieldSetMethod.getReturnType() + \" instead of void\");\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn fieldSetMethod;\n\t}", "private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "public static void setTime(Calendar cal, Date time)\n {\n if (time != null)\n {\n Calendar startCalendar = popCalendar(time);\n cal.set(Calendar.HOUR_OF_DAY, startCalendar.get(Calendar.HOUR_OF_DAY));\n cal.set(Calendar.MINUTE, startCalendar.get(Calendar.MINUTE));\n cal.set(Calendar.SECOND, startCalendar.get(Calendar.SECOND));\n pushCalendar(startCalendar);\n }\n }", "protected String getKey(final String ref, final String filename, final String extension) {\n return prefix + ref + \"/\" + filename + \".\" + extension;\n }", "public RendererBuilder<T> withPrototype(Renderer<? extends T> renderer) {\n if (renderer == null) {\n throw new NeedsPrototypesException(\n \"RendererBuilder can't use a null Renderer<T> instance as prototype\");\n }\n this.prototypes.add(renderer);\n return this;\n }", "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 Shell createConsoleShell(String prompt, String appName, Object mainHandler) {\n return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }", "public static base_response add(nitro_service client, onlinkipv6prefix resource) throws Exception {\n\t\tonlinkipv6prefix addresource = new onlinkipv6prefix();\n\t\taddresource.ipv6prefix = resource.ipv6prefix;\n\t\taddresource.onlinkprefix = resource.onlinkprefix;\n\t\taddresource.autonomusprefix = resource.autonomusprefix;\n\t\taddresource.depricateprefix = resource.depricateprefix;\n\t\taddresource.decrementprefixlifetimes = resource.decrementprefixlifetimes;\n\t\taddresource.prefixvalidelifetime = resource.prefixvalidelifetime;\n\t\taddresource.prefixpreferredlifetime = resource.prefixpreferredlifetime;\n\t\treturn addresource.add_resource(client);\n\t}" ]
Detects if the current device is a Nintendo game device. @return detection of Nintendo
[ "public boolean detectNintendo() {\r\n\r\n if ((userAgent.indexOf(deviceNintendo) != -1)\r\n || (userAgent.indexOf(deviceWii) != -1)\r\n || (userAgent.indexOf(deviceNintendoDs) != -1)) {\r\n return true;\r\n }\r\n return false;\r\n }" ]
[ "public <T> T find(Class<T> classType, String id, String rev) {\n assertNotEmpty(classType, \"Class\");\n assertNotEmpty(id, \"id\");\n assertNotEmpty(id, \"rev\");\n final URI uri = new DatabaseURIHelper(dbUri).documentUri(id, \"rev\", rev);\n return couchDbClient.get(uri, classType);\n }", "public void clear() {\n\t\tfor (Bean bean : beans.values()) {\n\t\t\tif (null != bean.destructionCallback) {\n\t\t\t\tbean.destructionCallback.run();\n\t\t\t}\n\t\t}\n\t\tbeans.clear();\n\t}", "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 }", "private void highlightSlice(PieModel _Slice) {\n\n int color = _Slice.getColor();\n _Slice.setHighlightedColor(Color.argb(\n 0xff,\n Math.min((int) (mHighlightStrength * (float) Color.red(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.green(color)), 0xff),\n Math.min((int) (mHighlightStrength * (float) Color.blue(color)), 0xff)\n ));\n }", "@Override\n public void registerCapabilities(ManagementResourceRegistration resourceRegistration) {\n if (capabilities!=null) {\n for (RuntimeCapability c : capabilities) {\n resourceRegistration.registerCapability(c);\n }\n }\n if (incorporatingCapabilities != null) {\n resourceRegistration.registerIncorporatingCapabilities(incorporatingCapabilities);\n }\n assert requirements != null;\n resourceRegistration.registerRequirements(requirements);\n }", "public 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 }", "public static final String printPercent(Double value)\n {\n return value == null ? null : Double.toString(value.doubleValue() / 100.0);\n }", "private void clearDeck(CdjStatus update) {\n if (hotCache.remove(DeckReference.getDeckReference(update.getDeviceNumber(), 0)) != null) {\n deliverTrackMetadataUpdate(update.getDeviceNumber(), null);\n }\n }", "public PhotoList<Photo> photosForLocation(GeoData location, Set<String> extras, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n parameters.put(\"method\", METHOD_PHOTOS_FOR_LOCATION);\r\n\r\n if (extras.size() > 0) {\r\n parameters.put(\"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 parameters.put(\"lat\", Float.toString(location.getLatitude()));\r\n parameters.put(\"lon\", Float.toString(location.getLongitude()));\r\n parameters.put(\"accuracy\", Integer.toString(location.getAccuracy()));\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 photoElements = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }" ]
Webkit based browsers require that we set the webkit-user-drag style attribute to make an element draggable.
[ "@Override\n public void setDraggable(Element elem, String draggable) {\n super.setDraggable(elem, draggable);\n if (\"true\".equals(draggable)) {\n elem.getStyle().setProperty(\"webkitUserDrag\", \"element\");\n } else {\n elem.getStyle().clearProperty(\"webkitUserDrag\");\n }\n }" ]
[ "public void updateConfig(String appName, Map<String, String> config) {\n connection.execute(new ConfigUpdate(appName, config), apiKey);\n }", "@NonNull\n @Override\n public Loader<SortedList<File>> getLoader() {\n return new AsyncTaskLoader<SortedList<File>>(getActivity()) {\n\n FileObserver fileObserver;\n\n @Override\n public SortedList<File> loadInBackground() {\n File[] listFiles = mCurrentPath.listFiles();\n final int initCap = listFiles == null ? 0 : listFiles.length;\n\n SortedList<File> files = new SortedList<>(File.class, new SortedListAdapterCallback<File>(getDummyAdapter()) {\n @Override\n public int compare(File lhs, File rhs) {\n return compareFiles(lhs, rhs);\n }\n\n @Override\n public boolean areContentsTheSame(File file, File file2) {\n return file.getAbsolutePath().equals(file2.getAbsolutePath()) && (file.isFile() == file2.isFile());\n }\n\n @Override\n public boolean areItemsTheSame(File file, File file2) {\n return areContentsTheSame(file, file2);\n }\n }, initCap);\n\n\n files.beginBatchedUpdates();\n if (listFiles != null) {\n for (java.io.File f : listFiles) {\n if (isItemVisible(f)) {\n files.add(f);\n }\n }\n }\n files.endBatchedUpdates();\n\n return files;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n // Start watching for changes\n fileObserver = new FileObserver(mCurrentPath.getPath(),\n FileObserver.CREATE |\n FileObserver.DELETE\n | FileObserver.MOVED_FROM | FileObserver.MOVED_TO\n ) {\n\n @Override\n public void onEvent(int event, String path) {\n // Reload\n onContentChanged();\n }\n };\n fileObserver.startWatching();\n\n forceLoad();\n }\n\n /**\n * Handles a request to completely reset the Loader.\n */\n @Override\n protected void onReset() {\n super.onReset();\n\n // Stop watching\n if (fileObserver != null) {\n fileObserver.stopWatching();\n fileObserver = null;\n }\n }\n };\n }", "protected String getQueryModifier() {\n\n String queryModifier = parseOptionalStringValue(m_configObject, JSON_KEY_QUERY_MODIFIER);\n return (null == queryModifier) && (null != m_baseConfig)\n ? m_baseConfig.getGeneralConfig().getQueryModifier()\n : queryModifier;\n }", "public void addModuleDir(final String moduleDir) {\n if (moduleDir == null) {\n throw LauncherMessages.MESSAGES.nullParam(\"moduleDir\");\n }\n // Validate the path\n final Path path = Paths.get(moduleDir).normalize();\n modulesDirs.add(path.toString());\n }", "private MapRow getRow(int index)\n {\n MapRow result;\n\n if (index == m_rows.size())\n {\n result = new MapRow(this, new HashMap<FastTrackField, Object>());\n m_rows.add(result);\n }\n else\n {\n result = m_rows.get(index);\n }\n\n return result;\n }", "public 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 }", "public void fillEllipse(Rectangle rect, Color color) {\n\t\ttemplate.saveState();\n\t\tsetFill(color);\n\t\ttemplate.ellipse(origX + rect.getLeft(), origY + rect.getBottom(), origX + rect.getRight(),\n\t\t\t\torigY + rect.getTop());\n\t\ttemplate.fill();\n\t\ttemplate.restoreState();\n\t}", "public static boolean bidiagOuterBlocks( final int blockLength ,\n final DSubmatrixD1 A ,\n final double gammasU[],\n final double gammasV[])\n {\n// System.out.println(\"---------- Orig\");\n// A.original.print();\n\n int width = Math.min(blockLength,A.col1-A.col0);\n int height = Math.min(blockLength,A.row1-A.row0);\n\n int min = Math.min(width,height);\n\n for( int i = 0; i < min; i++ ) {\n //--- Apply reflector to the column\n\n // compute the householder vector\n if (!computeHouseHolderCol(blockLength, A, gammasU, i))\n return false;\n\n // apply to rest of the columns in the column block\n rank1UpdateMultR_Col(blockLength,A,i,gammasU[A.col0+i]);\n\n // apply to the top row block\n rank1UpdateMultR_TopRow(blockLength,A,i,gammasU[A.col0+i]);\n\n System.out.println(\"After column stuff\");\n A.original.print();\n\n //-- Apply reflector to the row\n if(!computeHouseHolderRow(blockLength,A,gammasV,i))\n return false;\n \n // apply to rest of the rows in the row block\n rank1UpdateMultL_Row(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After update row\");\n A.original.print();\n\n // apply to the left column block\n // TODO THIS WON'T WORK!!!!!!!!!!!!!\n // Needs the whole matrix to have been updated by the left reflector to compute the correct solution\n// rank1UpdateMultL_LeftCol(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After row stuff\");\n A.original.print();\n }\n\n return true;\n }", "@UiThread\n public int getChildAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) {\n return RecyclerView.NO_POSITION;\n }\n\n return mExpandableAdapter.getChildPosition(flatPosition);\n }" ]
Returns the full record for the given webhook. @param webhook The webhook to get. @return Request object
[ "public ItemRequest<Webhook> getById(String webhook) {\n \n String path = String.format(\"/webhooks/%s\", webhook);\n return new ItemRequest<Webhook>(this, Webhook.class, path, \"GET\");\n }" ]
[ "public ConfigOptionBuilder setDefaultWith( Object defaultValue ) {\n co.setHasDefault( true );\n co.setValue( defaultValue );\n return setOptional();\n }", "public static Boolean askConfirm(Boolean confirm, String opDesc) throws IOException {\n if(confirm) {\n System.out.println(\"Confirmed \" + opDesc + \" in command-line.\");\n return true;\n } else {\n System.out.println(\"Are you sure you want to \" + opDesc + \"? (yes/no)\");\n BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));\n String text = buffer.readLine().toLowerCase(Locale.ENGLISH);\n boolean go = text.equals(\"yes\") || text.equals(\"y\");\n if (!go) {\n System.out.println(\"Did not confirm; \" + opDesc + \" aborted.\");\n }\n return go;\n }\n }", "private StepFormatter.Formatting<?, ?> getFormatting( Annotation[] annotations, Set<Class<?>> visitedTypes,\n Annotation originalAnnotation, String parameterName ) {\n List<StepFormatter.Formatting<?, ?>> foundFormatting = Lists.newArrayList();\n Table tableAnnotation = null;\n for( Annotation annotation : annotations ) {\n try {\n if( annotation instanceof Format ) {\n Format arg = (Format) annotation;\n foundFormatting.add( new StepFormatter.ArgumentFormatting( ReflectionUtil.newInstance( arg.value() ), arg.args() ) );\n } else if( annotation instanceof Table ) {\n tableAnnotation = (Table) annotation;\n } else if( annotation instanceof AnnotationFormat ) {\n AnnotationFormat arg = (AnnotationFormat) annotation;\n foundFormatting.add( new StepFormatter.ArgumentFormatting(\n new StepFormatter.AnnotationBasedFormatter( arg.value().newInstance(), originalAnnotation ) ) );\n } else {\n Class<? extends Annotation> annotationType = annotation.annotationType();\n if( !visitedTypes.contains( annotationType ) ) {\n visitedTypes.add( annotationType );\n StepFormatter.Formatting<?, ?> formatting = getFormatting( annotationType.getAnnotations(), visitedTypes,\n annotation, parameterName );\n if( formatting != null ) {\n foundFormatting.add( formatting );\n }\n }\n }\n } catch( Exception e ) {\n throw Throwables.propagate( e );\n }\n }\n\n if( foundFormatting.size() > 1 ) {\n Formatting<?, ?> innerFormatting = Iterables.getLast( foundFormatting );\n foundFormatting.remove( innerFormatting );\n\n ChainedFormatting<?> chainedFormatting = new StepFormatter.ChainedFormatting<Object>( (ObjectFormatter<Object>) innerFormatting );\n for( StepFormatter.Formatting<?, ?> formatting : Lists.reverse( foundFormatting ) ) {\n chainedFormatting.addFormatting( (StepFormatter.Formatting<?, String>) formatting );\n }\n\n foundFormatting.clear();\n foundFormatting.add( chainedFormatting );\n }\n\n if( tableAnnotation != null ) {\n ObjectFormatter<?> objectFormatter = foundFormatting.isEmpty()\n ? DefaultFormatter.INSTANCE\n : foundFormatting.get( 0 );\n return getTableFormatting( annotations, parameterName, tableAnnotation, objectFormatter );\n }\n\n if( foundFormatting.isEmpty() ) {\n return null;\n }\n\n return foundFormatting.get( 0 );\n }", "String getStatus(CmsUser user, boolean disabled, boolean newUser) {\n\n if (disabled) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_0);\n }\n if (newUser) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_0);\n }\n if (OpenCms.getLoginManager().isUserTempDisabled(user.getName())) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_UNLOCK_USER_STATUS_0);\n }\n if (isUserPasswordReset(user)) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_0);\n }\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_ACTIVE_0);\n }", "protected String generateCacheKey(\n CmsObject cms,\n String targetSiteRoot,\n String detailPagePart,\n String absoluteLink) {\n\n return cms.getRequestContext().getSiteRoot() + \":\" + targetSiteRoot + \":\" + detailPagePart + absoluteLink;\n }", "public void setCapture(boolean capture, float fps) {\n capturing = capture;\n NativeTextureCapturer.setCapture(getNative(), capture, fps);\n }", "public static CuratorFramework newFluoCurator(FluoConfiguration config) {\n return newCurator(config.getInstanceZookeepers(), config.getZookeeperTimeout(),\n config.getZookeeperSecret());\n }", "private void writeResourceAssignment(ResourceAssignment record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(formatResource(record.getResource()));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatUnits(record.getUnits())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getBaselineWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getActualWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getOvertimeWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getBaselineCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getActualCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTime(record.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTime(record.getFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getDelay())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getResourceUniqueID()));\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n\n ResourceAssignmentWorkgroupFields workgroup = record.getWorkgroupAssignment();\n if (workgroup == null)\n {\n workgroup = ResourceAssignmentWorkgroupFields.EMPTY;\n }\n writeResourceAssignmentWorkgroupFields(workgroup);\n\n m_eventManager.fireAssignmentWrittenEvent(record);\n }", "public static RgbaColor fromRgb(String rgb) {\n if (rgb.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbParts(rgb).split(\",\");\n if (parts.length == 3) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]));\n }\n else {\n return getDefaultColor();\n }\n }" ]
Append a Handler to a portion of the handler tree @param parent The parent to add the child to @param child The Handler to add.
[ "protected static void appendHandler(LogRecordHandler parent, LogRecordHandler child){\r\n RecordHandlerTree p = handlers.find(parent);\r\n if(p != null){\r\n p.addChild(child);\r\n } else {\r\n throw new IllegalArgumentException(\"No such parent handler: \" + parent);\r\n }\r\n }" ]
[ "public static void saveContentMap(Map<String, String> map, File file) throws IOException {\n\n FileWriter out = new FileWriter(file);\n for (String key : map.keySet()) {\n if (map.get(key) != null) {\n out.write(key.replace(\":\", \"#escapedtwodots#\") + \":\"\n + map.get(key).replace(\":\", \"#escapedtwodots#\") + \"\\r\\n\");\n }\n }\n out.close();\n }", "private List<TimephasedCost> getTimephasedActualCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n double actualCost = getActualCost().doubleValue();\n\n if (actualCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(getCalendar(), actualCost, getActualStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(getCalendar(), actualCost, getActualFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently; have to 'fill up' each\n //day with the standard amount before going to the next one\n double numWorkingDays = getCalendar().getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n result.addAll(splitCostProrated(getCalendar(), actualCost, standardAmountPerDay, getActualStart()));\n }\n }\n\n return result;\n }", "public void dispatchKeyEvent(int code, int action) {\n int keyCode = 0;\n int keyAction = 0;\n if (code == BUTTON_1) {\n keyCode = KeyEvent.KEYCODE_BUTTON_1;\n } else if (code == BUTTON_2) {\n keyCode = KeyEvent.KEYCODE_BUTTON_2;\n }\n\n if (action == ACTION_DOWN) {\n keyAction = KeyEvent.ACTION_DOWN;\n } else if (action == ACTION_UP) {\n keyAction = KeyEvent.ACTION_UP;\n }\n\n KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);\n setKeyEvent(keyEvent);\n }", "private void populateDateTimeSettings(Record record, ProjectProperties properties)\n {\n properties.setDateOrder(record.getDateOrder(0));\n properties.setTimeFormat(record.getTimeFormat(1));\n\n Date time = getTimeFromInteger(record.getInteger(2));\n if (time != null)\n {\n properties.setDefaultStartTime(time);\n }\n\n Character c = record.getCharacter(3);\n if (c != null)\n {\n properties.setDateSeparator(c.charValue());\n }\n\n c = record.getCharacter(4);\n if (c != null)\n {\n properties.setTimeSeparator(c.charValue());\n }\n\n properties.setAMText(record.getString(5));\n properties.setPMText(record.getString(6));\n properties.setDateFormat(record.getDateFormat(7));\n properties.setBarTextDateFormat(record.getDateFormat(8));\n }", "void writeBestRankTriples() {\n\t\tfor (Resource resource : this.rankBuffer.getBestRankedStatements()) {\n\t\t\ttry {\n\t\t\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\t\t\tRdfWriter.RDF_TYPE, RdfWriter.WB_BEST_RANK.toString());\n\t\t\t} catch (RDFHandlerException e) {\n\t\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t\tthis.rankBuffer.clear();\n\t}", "public static UndeployDescription of(final DeploymentDescription deploymentDescription) {\n Assert.checkNotNullParam(\"deploymentDescription\", deploymentDescription);\n return of(deploymentDescription.getName()).addServerGroups(deploymentDescription.getServerGroups());\n }", "public void seekToDayOfMonth(String dayOfMonth) {\n int dayOfMonthInt = Integer.parseInt(dayOfMonth);\n assert(dayOfMonthInt >= 1 && dayOfMonthInt <= 31);\n \n markDateInvocation();\n \n dayOfMonthInt = Math.min(dayOfMonthInt, _calendar.getActualMaximum(Calendar.DAY_OF_MONTH));\n _calendar.set(Calendar.DAY_OF_MONTH, dayOfMonthInt);\n }", "private String getSignature(String sharedSecret, Map<String, String> params) {\r\n StringBuffer buffer = new StringBuffer();\r\n buffer.append(sharedSecret);\r\n for (Map.Entry<String, String> entry : params.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append(entry.getValue());\r\n }\r\n\r\n try {\r\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\r\n return ByteUtilities.toHexString(md.digest(buffer.toString().getBytes(\"UTF-8\")));\r\n } catch (NoSuchAlgorithmException e) {\r\n throw new RuntimeException(e);\r\n } catch (UnsupportedEncodingException u) {\r\n throw new RuntimeException(u);\r\n }\r\n }", "public static <T> T[] concat(T firstElement, T... array) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] result = (T[]) Array.newInstance( firstElement.getClass(), 1 + array.length );\n\t\tresult[0] = firstElement;\n\t\tSystem.arraycopy( array, 0, result, 1, array.length );\n\n\t\treturn result;\n\t}" ]
Get the FieldDescriptor for the PathInfo @param aTableAlias @param aPathInfo @return FieldDescriptor
[ "protected FieldDescriptor getFieldDescriptor(TableAlias aTableAlias, PathInfo aPathInfo)\r\n {\r\n FieldDescriptor fld = null;\r\n String colName = aPathInfo.column;\r\n\r\n if (aTableAlias != null)\r\n {\r\n fld = aTableAlias.cld.getFieldDescriptorByName(colName);\r\n if (fld == null)\r\n {\r\n ObjectReferenceDescriptor ord = aTableAlias.cld.getObjectReferenceDescriptorByName(colName);\r\n if (ord != null)\r\n {\r\n fld = getFldFromReference(aTableAlias, ord);\r\n }\r\n else\r\n {\r\n fld = getFldFromJoin(aTableAlias, colName);\r\n }\r\n }\r\n }\r\n\r\n return fld;\r\n }" ]
[ "@Override\n public <K, V> StoreClient<K, V> getStoreClient(final String storeName,\n final InconsistencyResolver<Versioned<V>> resolver) {\n // wrap it in LazyStoreClient here so any direct calls to this method\n // returns a lazy client\n return new LazyStoreClient<K, V>(new Callable<StoreClient<K, V>>() {\n\n @Override\n public StoreClient<K, V> call() throws Exception {\n Store<K, V, Object> clientStore = getRawStore(storeName, resolver);\n return new RESTClient<K, V>(storeName, clientStore);\n }\n }, true);\n }", "public static String copyToString(InputStream in, Charset charset) throws IOException {\n\t\tAssert.notNull(in, \"No InputStream specified\");\n\t\tStringBuilder out = new StringBuilder();\n\t\tInputStreamReader reader = new InputStreamReader(in, charset);\n\t\tchar[] buffer = new char[BUFFER_SIZE];\n\t\tint bytesRead = -1;\n\t\twhile ((bytesRead = reader.read(buffer)) != -1) {\n\t\t\tout.append(buffer, 0, bytesRead);\n\t\t}\n\t\treturn out.toString();\n\t}", "public void put(String key, Object object, Envelope envelope) {\n\t\tindex.put(key, envelope);\n\t\tcache.put(key, object);\n\t}", "public void seekToDayOfWeek(String direction, String seekType, String seekAmount, String dayOfWeek) {\n int dayOfWeekInt = Integer.parseInt(dayOfWeek);\n int seekAmountInt = Integer.parseInt(seekAmount);\n assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT));\n assert(seekType.equals(SEEK_BY_DAY) || seekType.equals(SEEK_BY_WEEK));\n assert(dayOfWeekInt >= 1 && dayOfWeekInt <= 7);\n \n markDateInvocation();\n \n int sign = direction.equals(DIR_RIGHT) ? 1 : -1;\n if(seekType.equals(SEEK_BY_WEEK)) {\n // set our calendar to this weeks requested day of the week,\n // then add or subtract the week(s)\n _calendar.set(Calendar.DAY_OF_WEEK, dayOfWeekInt);\n _calendar.add(Calendar.DAY_OF_YEAR, seekAmountInt * 7 * sign);\n }\n \n else if(seekType.equals(SEEK_BY_DAY)) {\n // find the closest day\n do {\n _calendar.add(Calendar.DAY_OF_YEAR, sign);\n } while(_calendar.get(Calendar.DAY_OF_WEEK) != dayOfWeekInt);\n \n // now add/subtract any additional days\n if(seekAmountInt > 0) {\n _calendar.add(Calendar.WEEK_OF_YEAR, (seekAmountInt - 1) * sign);\n }\n }\n }", "public void trace(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.TRACE, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "private List<SynchroTable> readTableHeaders(InputStream is) throws IOException\n {\n // Read the headers\n List<SynchroTable> tables = new ArrayList<SynchroTable>();\n byte[] header = new byte[48];\n while (true)\n {\n is.read(header);\n m_offset += 48;\n SynchroTable table = readTableHeader(header);\n if (table == null)\n {\n break;\n }\n tables.add(table);\n }\n\n // Ensure sorted by offset\n Collections.sort(tables, new Comparator<SynchroTable>()\n {\n @Override public int compare(SynchroTable o1, SynchroTable o2)\n {\n return o1.getOffset() - o2.getOffset();\n }\n });\n\n // Calculate lengths\n SynchroTable previousTable = null;\n for (SynchroTable table : tables)\n {\n if (previousTable != null)\n {\n previousTable.setLength(table.getOffset() - previousTable.getOffset());\n }\n\n previousTable = table;\n }\n\n for (SynchroTable table : tables)\n {\n SynchroLogger.log(\"TABLE\", table);\n }\n\n return tables;\n }", "public Token add( Variable variable ) {\n Token t = new Token(variable);\n push( t );\n return t;\n }", "public static String makePropertyName(String name) {\n char[] buf = new char[name.length() + 3];\n int pos = 0;\n buf[pos++] = 's';\n buf[pos++] = 'e';\n buf[pos++] = 't';\n\n for (int ix = 0; ix < name.length(); ix++) {\n char ch = name.charAt(ix);\n if (ix == 0)\n ch = Character.toUpperCase(ch);\n else if (ch == '-') {\n ix++;\n if (ix == name.length())\n break;\n ch = Character.toUpperCase(name.charAt(ix));\n }\n\n buf[pos++] = ch;\n }\n\n return new String(buf, 0, pos);\n }", "private String getLogRequestIdentifier() {\n if (logIdentifier == null) {\n logIdentifier = String.format(\"%s-%s %s %s\", Integer.toHexString(hashCode()),\n numberOfRetries, connection.getRequestMethod(), connection.getURL());\n }\n return logIdentifier;\n }" ]
Checks if the method being invoked should be wrapped by a service. It looks the method name up in the methodList. If its in the list, then the method should be wrapped. If the list is null, then all methods are wrapped. @param methodName The method being called @return boolean
[ "private boolean shouldWrapMethodCall(String methodName) {\n if (methodList == null) {\n return true; // Wrap all by default\n }\n\n if (methodList.contains(methodName)) {\n return true; //Wrap a specific method\n }\n\n // If I get to this point, I should not wrap the call.\n return false;\n }" ]
[ "public static int cudnnSoftmaxForward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnSoftmaxForwardNative(handle, algo, mode, alpha, xDesc, x, beta, yDesc, y));\n }", "public Jar setListAttribute(String name, Collection<?> values) {\n return setAttribute(name, join(values));\n }", "public synchronized T get(Scope scope) {\n if (instance != null) {\n return instance;\n }\n\n if (providerInstance != null) {\n if (isProvidingSingletonInScope) {\n instance = providerInstance.get();\n //gc\n providerInstance = null;\n return instance;\n }\n\n return providerInstance.get();\n }\n\n if (factoryClass != null && factory == null) {\n factory = FactoryLocator.getFactory(factoryClass);\n //gc\n factoryClass = null;\n }\n\n if (factory != null) {\n if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) {\n return factory.createInstance(scope);\n }\n instance = factory.createInstance(scope);\n //gc\n factory = null;\n return instance;\n }\n\n if (providerFactoryClass != null && providerFactory == null) {\n providerFactory = FactoryLocator.getFactory(providerFactoryClass);\n //gc\n providerFactoryClass = null;\n }\n\n if (providerFactory != null) {\n if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) {\n instance = providerFactory.createInstance(scope).get();\n //gc\n providerFactory = null;\n return instance;\n }\n if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) {\n providerInstance = providerFactory.createInstance(scope);\n //gc\n providerFactory = null;\n return providerInstance.get();\n }\n\n return providerFactory.createInstance(scope).get();\n }\n\n throw new IllegalStateException(\"A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen.\");\n }", "private static void waitUntilFinished(FluoConfiguration config) {\n try (Environment env = new Environment(config)) {\n List<TableRange> ranges = getRanges(env);\n\n outer: while (true) {\n long ts1 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n for (TableRange range : ranges) {\n boolean sawNotifications = waitTillNoNotifications(env, range);\n if (sawNotifications) {\n ranges = getRanges(env);\n // This range had notifications. Processing those notifications may have created\n // notifications in previously scanned ranges, so start over.\n continue outer;\n }\n }\n long ts2 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp();\n\n // Check to ensure the Oracle issued no timestamps during the scan for notifications.\n if (ts2 - ts1 == 1) {\n break;\n }\n }\n } catch (Exception e) {\n log.error(\"An exception was thrown -\", e);\n System.exit(-1);\n }\n }", "public List getFeedback()\n\t {\n\t List<?> messages = new ArrayList();\n\t for ( ValueSource vs : valueSources )\n\t {\n\t List feedback = vs.getFeedback();\n\t if ( feedback != null && !feedback.isEmpty() )\n\t {\n\t messages.addAll( feedback );\n\t }\n\t }\n\n\t return messages;\n\t }", "public String getProfileIdFromClientId(int id) {\n return (String) sqlService.getFromTable(Constants.CLIENT_PROFILE_ID, Constants.GENERIC_ID, id, Constants.DB_TABLE_CLIENT);\n }", "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 }", "public static Configuration loadFromString(String config)\n throws IOException, SAXException {\n ConfigurationImpl cfg = new ConfigurationImpl();\n\n XMLReader parser = XMLReaderFactory.createXMLReader();\n parser.setContentHandler(new ConfigHandler(cfg, null));\n Reader reader = new StringReader(config);\n parser.parse(new InputSource(reader));\n return cfg;\n }", "private void increaseBeliefCount(String bName) {\n Object belief = this.getBelief(bName);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n this.setBelief(bName, count + 1);\n }" ]
Handle click on "Add" button. @param e the click event.
[ "@UiHandler(\"m_addButton\")\r\n void addButtonClick(ClickEvent e) {\r\n\r\n if (null != m_newDate.getValue()) {\r\n m_dateList.addDate(m_newDate.getValue());\r\n m_newDate.setValue(null);\r\n if (handleChange()) {\r\n m_controller.setDates(m_dateList.getDates());\r\n }\r\n }\r\n }" ]
[ "public ConfigOptionBuilder setCommandLineOptionWithoutArgument( CommandLineOption commandLineOption, Object value ) {\n co.setCommandLineOption( commandLineOption );\n co.setValue( value );\n return this;\n }", "public PhotoList<Photo> getPublicPhotos(String userId, Set<String> extras, 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_GET_PUBLIC_PHOTOS);\r\n\r\n parameters.put(\"user_id\", userId);\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 if (extras != null) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n 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 }", "boolean openStream() throws InterruptedException, IOException {\n logger.info(\"stream START\");\n final boolean isOpen;\n final Set<BsonValue> idsToWatch = nsConfig.getSynchronizedDocumentIds();\n\n if (!networkMonitor.isConnected()) {\n logger.info(\"stream END - Network disconnected\");\n return false;\n }\n\n if (idsToWatch.isEmpty()) {\n logger.info(\"stream END - No synchronized documents\");\n return false;\n }\n\n nsLock.writeLock().lockInterruptibly();\n try {\n if (!authMonitor.isLoggedIn()) {\n logger.info(\"stream END - Logged out\");\n return false;\n }\n\n final Document args = new Document();\n args.put(\"database\", namespace.getDatabaseName());\n args.put(\"collection\", namespace.getCollectionName());\n args.put(\"ids\", idsToWatch);\n\n currentStream =\n service.streamFunction(\n \"watch\",\n Collections.singletonList(args),\n ResultDecoders.changeEventDecoder(BSON_DOCUMENT_CODEC));\n\n if (currentStream != null && currentStream.isOpen()) {\n this.nsConfig.setStale(true);\n isOpen = true;\n } else {\n isOpen = false;\n }\n } finally {\n nsLock.writeLock().unlock();\n }\n return isOpen;\n }", "@SuppressWarnings(\"unused\")\n public Handedness getHandedness()\n {\n if ((currentControllerEvent == null) || currentControllerEvent.isRecycled())\n {\n return null;\n }\n return currentControllerEvent.handedness == 0.0f ?\n Handedness.LEFT : Handedness.RIGHT;\n }", "public void dispatchKeyEvent(int code, int action) {\n int keyCode = 0;\n int keyAction = 0;\n if (code == BUTTON_1) {\n keyCode = KeyEvent.KEYCODE_BUTTON_1;\n } else if (code == BUTTON_2) {\n keyCode = KeyEvent.KEYCODE_BUTTON_2;\n }\n\n if (action == ACTION_DOWN) {\n keyAction = KeyEvent.ACTION_DOWN;\n } else if (action == ACTION_UP) {\n keyAction = KeyEvent.ACTION_UP;\n }\n\n KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);\n setKeyEvent(keyEvent);\n }", "public URI withEmptyAuthority(final URI uri) {\n URI _xifexpression = null;\n if ((uri.isFile() && (uri.authority() == null))) {\n _xifexpression = URI.createHierarchicalURI(uri.scheme(), \"\", uri.device(), uri.segments(), uri.query(), uri.fragment());\n } else {\n _xifexpression = uri;\n }\n return _xifexpression;\n }", "private void executeRequest(HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n PluginResponse httpServletResponse,\n History history) throws Exception {\n int intProxyResponseCode = 999;\n // Create a default HttpClient\n HttpClient httpClient = new HttpClient();\n HttpState state = new HttpState();\n\n try {\n httpMethodProxyRequest.setFollowRedirects(false);\n ArrayList<String> headersToRemove = getRemoveHeaders();\n\n httpClient.getParams().setSoTimeout(60000);\n\n httpServletRequest.setAttribute(\"com.groupon.odo.removeHeaders\", headersToRemove);\n\n // exception handling for httpclient\n HttpMethodRetryHandler noretryhandler = new HttpMethodRetryHandler() {\n public boolean retryMethod(\n final HttpMethod method,\n final IOException exception,\n int executionCount) {\n return false;\n }\n };\n\n httpMethodProxyRequest.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noretryhandler);\n\n intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest.getHostConfiguration(), httpMethodProxyRequest, state);\n } catch (Exception e) {\n // Return a gateway timeout\n httpServletResponse.setStatus(504);\n httpServletResponse.setHeader(Constants.HEADER_STATUS, \"504\");\n httpServletResponse.flushBuffer();\n return;\n }\n logger.info(\"Response code: {}, {}\", intProxyResponseCode,\n HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));\n\n // Pass the response code back to the client\n httpServletResponse.setStatus(intProxyResponseCode);\n\n // Pass response headers back to the client\n Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();\n for (Header header : headerArrayResponse) {\n // remove transfer-encoding header. The http libraries will handle this encoding\n if (header.getName().toLowerCase().equals(\"transfer-encoding\")) {\n continue;\n }\n\n httpServletResponse.setHeader(header.getName(), header.getValue());\n }\n\n // there is no data for a HTTP 304 or 204\n if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED &&\n intProxyResponseCode != HttpServletResponse.SC_NO_CONTENT) {\n // Send the content to the client\n httpServletResponse.resetBuffer();\n httpServletResponse.getOutputStream().write(httpMethodProxyRequest.getResponseBody());\n }\n\n // copy cookies to servlet response\n for (Cookie cookie : state.getCookies()) {\n javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());\n\n if (cookie.getPath() != null) {\n servletCookie.setPath(cookie.getPath());\n }\n\n if (cookie.getDomain() != null) {\n servletCookie.setDomain(cookie.getDomain());\n }\n\n // convert expiry date to max age\n if (cookie.getExpiryDate() != null) {\n servletCookie.setMaxAge((int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / 1000));\n }\n\n servletCookie.setSecure(cookie.getSecure());\n\n servletCookie.setVersion(cookie.getVersion());\n\n if (cookie.getComment() != null) {\n servletCookie.setComment(cookie.getComment());\n }\n\n httpServletResponse.addCookie(servletCookie);\n }\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 }", "public int compareTo(WordLemmaTag wordLemmaTag) {\r\n int first = word().compareTo(wordLemmaTag.word());\r\n if (first != 0)\r\n return first;\r\n int second = lemma().compareTo(wordLemmaTag.lemma());\r\n if (second != 0)\r\n return second;\r\n else\r\n return tag().compareTo(wordLemmaTag.tag());\r\n }" ]
The % Work Complete field contains the current status of a task, expressed as the percentage of the task's work that has been completed. You can enter percent work complete, or you can have Microsoft Project calculate it for you based on actual work on the task. @return percentage as float
[ "public Number getPercentageWorkComplete()\n {\n Number pct = (Number) getCachedValue(AssignmentField.PERCENT_WORK_COMPLETE);\n if (pct == null)\n {\n Duration actualWork = getActualWork();\n Duration work = getWork();\n if (actualWork != null && work != null && work.getDuration() != 0)\n {\n pct = Double.valueOf((actualWork.getDuration() * 100) / work.convertUnits(actualWork.getUnits(), getParentFile().getProjectProperties()).getDuration());\n set(AssignmentField.PERCENT_WORK_COMPLETE, pct);\n }\n }\n return pct;\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 sslcipher_individualcipher_binding[] get_filtered(nitro_service service, String ciphergroupname, filtervalue[] filter) 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_filter(filter);\n\t\tsslcipher_individualcipher_binding[] response = (sslcipher_individualcipher_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public static java.sql.Date newDate() {\n return new java.sql.Date((System.currentTimeMillis() / DAY_MILLIS) * DAY_MILLIS);\n }", "public HashMap<K2, HashMap<K3, V>> get(final K1 firstKey) {\n\t\treturn map.get(firstKey);\n\t}", "public static base_responses add(nitro_service client, cmppolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcmppolicylabel addresources[] = new cmppolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cmppolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public void start() {\n instanceLock.writeLock().lock();\n try {\n for (final Map.Entry<MongoNamespace, NamespaceChangeStreamListener> streamerEntry :\n nsStreamers.entrySet()) {\n streamerEntry.getValue().start();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }", "public final List<Throwable> validate() {\n List<Throwable> validationErrors = new ArrayList<>();\n this.accessAssertion.validate(validationErrors, this);\n\n for (String jdbcDriver: this.jdbcDrivers) {\n try {\n Class.forName(jdbcDriver);\n } catch (ClassNotFoundException e) {\n try {\n Configuration.class.getClassLoader().loadClass(jdbcDriver);\n } catch (ClassNotFoundException e1) {\n validationErrors.add(new ConfigurationException(String.format(\n \"Unable to load JDBC driver: %s ensure that the web application has the jar \" +\n \"on its classpath\", jdbcDriver)));\n }\n }\n }\n\n if (this.configurationFile == null) {\n validationErrors.add(new ConfigurationException(\"Configuration file is field on configuration \" +\n \"object is null\"));\n }\n if (this.templates.isEmpty()) {\n validationErrors.add(new ConfigurationException(\"There are not templates defined.\"));\n }\n for (Template template: this.templates.values()) {\n template.validate(validationErrors, this);\n }\n\n for (HttpProxy proxy: this.proxies) {\n proxy.validate(validationErrors, this);\n }\n\n try {\n ColorParser.toColor(this.opaqueTileErrorColor);\n } catch (RuntimeException ex) {\n validationErrors.add(new ConfigurationException(\"Cannot parse opaqueTileErrorColor\", ex));\n }\n\n try {\n ColorParser.toColor(this.transparentTileErrorColor);\n } catch (RuntimeException ex) {\n validationErrors.add(new ConfigurationException(\"Cannot parse transparentTileErrorColor\", ex));\n }\n\n if (smtp != null) {\n smtp.validate(validationErrors, this);\n }\n\n return validationErrors;\n }", "public PhotoList<Photo> photosForLocation(GeoData location, Set<String> extras, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n parameters.put(\"method\", METHOD_PHOTOS_FOR_LOCATION);\r\n\r\n if (extras.size() > 0) {\r\n parameters.put(\"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 parameters.put(\"lat\", Float.toString(location.getLatitude()));\r\n parameters.put(\"lon\", Float.toString(location.getLongitude()));\r\n parameters.put(\"accuracy\", Integer.toString(location.getAccuracy()));\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 photoElements = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "public List<Pair<int[][][], int[]>> documentsToDataAndLabelsList(Collection<List<IN>> documents) {\r\n int numDatums = 0;\r\n\r\n List<Pair<int[][][], int[]>> docList = new ArrayList<Pair<int[][][], int[]>>();\r\n for (List<IN> doc : documents) {\r\n Pair<int[][][], int[]> docPair = documentToDataAndLabels(doc);\r\n docList.add(docPair);\r\n numDatums += doc.size();\r\n }\r\n\r\n System.err.println(\"numClasses: \" + classIndex.size() + ' ' + classIndex);\r\n System.err.println(\"numDocuments: \" + docList.size());\r\n System.err.println(\"numDatums: \" + numDatums);\r\n System.err.println(\"numFeatures: \" + featureIndex.size());\r\n return docList;\r\n }" ]
Send a DEBUG log message with specified subsystem. If subsystem is not enabled the message will not be logged @param subsystem logging subsystem @param tag Used to identify the source of a log message. It usually identifies the class or activity where the log call occurs. @param pattern The message pattern @return
[ "public static void d(ISubsystem subsystem, String tag, String pattern, Object... parameters) {\n if (!isEnabled(subsystem)) return;\n d(subsystem, tag, format(pattern, parameters));\n }" ]
[ "public final void notifyFooterItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n// if (position < 0 || position >= newFooterItemCount) {\n// throw new IndexOutOfBoundsException(\"The given position \" + position\n// + \" is not within the position bounds for footer items [0 - \"\n// + (newFooterItemCount - 1) + \"].\");\n// }\n notifyItemInserted(position + newHeaderItemCount + newContentItemCount);\n }", "@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic Map<String, PrimitiveAttribute<?>> getAttributes() {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\treturn (Map) attributes;\n\t}", "public static void readAndCheckVersion(ObjectInput input, int supportedVersion, Class<?> externalizedType) throws IOException {\n\t\tint version = input.readInt();\n\n\t\tif ( version != supportedVersion ) {\n\t\t\tthrow LOG.unexpectedKeyVersion( externalizedType, version, supportedVersion );\n\t\t}\n\t}", "public static ProducerRequest readFrom(ByteBuffer buffer) {\n String topic = Utils.readShortString(buffer);\n int partition = buffer.getInt();\n int messageSetSize = buffer.getInt();\n ByteBuffer messageSetBuffer = buffer.slice();\n messageSetBuffer.limit(messageSetSize);\n buffer.position(buffer.position() + messageSetSize);\n return new ProducerRequest(topic, partition, new ByteBufferMessageSet(messageSetBuffer));\n }", "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}", "public List<List<IN>> classifyRaw(String str,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromString(str, readerAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n // TaggedWord word = new TaggedWord(wi.word(), wi.answer());\r\n // sentence.add(word);\r\n sentence.add(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }", "public void adjustLinks(String sourceFolder, String targetFolder) throws CmsException {\n\n String rootSourceFolder = addSiteRoot(sourceFolder);\n String rootTargetFolder = addSiteRoot(targetFolder);\n String siteRoot = getRequestContext().getSiteRoot();\n getRequestContext().setSiteRoot(\"\");\n try {\n CmsLinkRewriter linkRewriter = new CmsLinkRewriter(this, rootSourceFolder, rootTargetFolder);\n linkRewriter.rewriteLinks();\n } finally {\n getRequestContext().setSiteRoot(siteRoot);\n }\n }", "DeleteResult deleteMany(final MongoNamespace namespace,\n final Bson filter) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final List<ChangeEvent<BsonDocument>> eventsToEmit = new ArrayList<>();\n final DeleteResult result;\n final NamespaceSynchronizationConfig nsConfig = this.syncConfig.getNamespaceConfig(namespace);\n final Lock lock = nsConfig.getLock().writeLock();\n lock.lock();\n try {\n final MongoCollection<BsonDocument> localCollection = getLocalCollection(namespace);\n final MongoCollection<BsonDocument> undoCollection = getUndoCollection(namespace);\n final Set<BsonValue> idsToDelete =\n localCollection\n .find(filter)\n .map(new Function<BsonDocument, BsonValue>() {\n @Override\n @NonNull\n public BsonValue apply(@NonNull final BsonDocument bsonDocument) {\n undoCollection.insertOne(bsonDocument);\n return BsonUtils.getDocumentId(bsonDocument);\n }\n }).into(new HashSet<>());\n\n result = localCollection.deleteMany(filter);\n\n for (final BsonValue documentId : idsToDelete) {\n final CoreDocumentSynchronizationConfig config =\n syncConfig.getSynchronizedDocument(namespace, documentId);\n\n if (config == null) {\n continue;\n }\n\n final ChangeEvent<BsonDocument> event =\n ChangeEvents.changeEventForLocalDelete(namespace, documentId, true);\n\n // this block is to trigger coalescence for a delete after insert\n if (config.getLastUncommittedChangeEvent() != null\n && config.getLastUncommittedChangeEvent().getOperationType()\n == OperationType.INSERT) {\n desyncDocumentsFromRemote(nsConfig, config.getDocumentId())\n .commitAndClear();\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n continue;\n }\n\n config.setSomePendingWritesAndSave(logicalT, event);\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n eventsToEmit.add(event);\n }\n checkAndDeleteNamespaceListener(namespace);\n } finally {\n lock.unlock();\n }\n for (final ChangeEvent<BsonDocument> event : eventsToEmit) {\n eventDispatcher.emitEvent(nsConfig, event);\n }\n return result;\n } finally {\n ongoingOperationsGroup.exit();\n }\n }", "protected synchronized void doClose()\r\n {\r\n try\r\n {\r\n LockManager lm = getImplementation().getLockManager();\r\n Enumeration en = objectEnvelopeTable.elements();\r\n while (en.hasMoreElements())\r\n {\r\n ObjectEnvelope oe = (ObjectEnvelope) en.nextElement();\r\n lm.releaseLock(this, oe.getIdentity(), oe.getObject());\r\n }\r\n\r\n //remove locks for objects which haven't been materialized yet\r\n for (Iterator it = unmaterializedLocks.iterator(); it.hasNext();)\r\n {\r\n lm.releaseLock(this, it.next());\r\n }\r\n\r\n // this tx is no longer interested in materialization callbacks\r\n unRegisterFromAllIndirectionHandlers();\r\n unRegisterFromAllCollectionProxies();\r\n }\r\n finally\r\n {\r\n /**\r\n * MBAIRD: Be nice and close the table to release all refs\r\n */\r\n if (log.isDebugEnabled())\r\n log.debug(\"Close Transaction and release current PB \" + broker + \" on tx \" + this);\r\n // remove current thread from LocalTxManager\r\n // to avoid problems for succeeding calls of the same thread\r\n implementation.getTxManager().deregisterTx(this);\r\n // now cleanup and prepare for reuse\r\n refresh();\r\n }\r\n }" ]
Starts the scavenger.
[ "public final void begin() {\n this.file = this.getAppender().getIoFile();\n if (this.file == null) {\n this.getAppender().getErrorHandler()\n .error(\"Scavenger not started: missing log file name\");\n return;\n }\n if (this.getProperties().getScavengeInterval() > -1) {\n final Thread thread = new Thread(this, \"Log4J File Scavenger\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }" ]
[ "public void writeLock(EntityKey key, int timeout) {\n\t\tReadWriteLock lock = getLock( key );\n\t\tLock writeLock = lock.writeLock();\n\t\tacquireLock( key, timeout, writeLock );\n\t}", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getInboxMessageUnreadCount(){\n synchronized (inboxControllerLock) {\n if (this.ctInboxController != null) {\n return ctInboxController.unreadCount();\n } else {\n getConfigLogger().debug(getAccountId(), \"Notification Inbox not initialized\");\n return -1;\n }\n }\n }", "@Override\r\n public String upload(InputStream in, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(in);\r\n return sendUploadRequest(metaData, payload);\r\n }", "public static base_responses update(nitro_service client, gslbsite resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbsite updateresources[] = new gslbsite[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbsite();\n\t\t\t\tupdateresources[i].sitename = resources[i].sitename;\n\t\t\t\tupdateresources[i].metricexchange = resources[i].metricexchange;\n\t\t\t\tupdateresources[i].nwmetricexchange = resources[i].nwmetricexchange;\n\t\t\t\tupdateresources[i].sessionexchange = resources[i].sessionexchange;\n\t\t\t\tupdateresources[i].triggermonitor = resources[i].triggermonitor;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public Automaton getAutomatonById(String id) throws IOException {\n if (idToVersion.containsKey(id)) {\n List<BytesRef> bytesArray = new ArrayList<>();\n Set<String> data = get(id);\n if (data != null) {\n Term term;\n for (String item : data) {\n term = new Term(\"dummy\", item);\n bytesArray.add(term.bytes());\n }\n Collections.sort(bytesArray);\n return Automata.makeStringUnion(bytesArray);\n }\n }\n return null;\n }", "@Override\n public Future<GcsFileMetadata> readObjectAsync(final ByteBuffer dst, final GcsFilename filename,\n long startOffsetBytes, long timeoutMillis) {\n Preconditions.checkArgument(startOffsetBytes >= 0, \"%s: offset must be non-negative: %s\", this,\n startOffsetBytes);\n final int n = dst.remaining();\n Preconditions.checkArgument(n > 0, \"%s: dst full: %s\", this, dst);\n final int want = Math.min(READ_LIMIT_BYTES, n);\n\n final HTTPRequest req = makeRequest(filename, null, GET, timeoutMillis);\n req.setHeader(\n new HTTPHeader(RANGE, \"bytes=\" + startOffsetBytes + \"-\" + (startOffsetBytes + want - 1)));\n final HTTPRequestInfo info = new HTTPRequestInfo(req);\n return new FutureWrapper<HTTPResponse, GcsFileMetadata>(urlfetch.fetchAsync(req)) {\n @Override\n protected GcsFileMetadata wrap(HTTPResponse resp) throws IOException {\n long totalLength;\n switch (resp.getResponseCode()) {\n case 200:\n totalLength = getLengthFromHeader(resp, X_GOOG_CONTENT_LENGTH);\n break;\n case 206:\n totalLength = getLengthFromContentRange(resp);\n break;\n case 404:\n throw new FileNotFoundException(\"Could not find: \" + filename);\n case 416:\n throw new BadRangeException(\"Requested Range not satisfiable; perhaps read past EOF? \"\n + URLFetchUtils.describeRequestAndResponse(info, resp));\n default:\n throw HttpErrorHandler.error(info, resp);\n }\n byte[] content = resp.getContent();\n Preconditions.checkState(content.length <= want, \"%s: got %s > wanted %s\", this,\n content.length, want);\n dst.put(content);\n return getMetadataFromResponse(filename, resp, totalLength);\n }\n\n @Override\n protected Throwable convertException(Throwable e) {\n return OauthRawGcsService.convertException(info, e);\n }\n };\n }", "@Override\n public final Optional<Boolean> tryOverrideValidation(final MatchInfo matchInfo) throws SocketException,\n UnknownHostException, MalformedURLException {\n for (AddressHostMatcher addressHostMatcher: this.matchersForHost) {\n if (addressHostMatcher.matches(matchInfo)) {\n return Optional.empty();\n }\n }\n\n return Optional.of(false);\n }", "public Info changeMessage(String newMessage) {\n Info newInfo = new Info();\n newInfo.setMessage(newMessage);\n\n URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(newInfo.getPendingChanges());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonResponse = JsonObject.readFrom(response.getJSON());\n\n return new Info(jsonResponse);\n }", "public static String getLocalizedKey(Map<String, ?> propertiesMap, String key, Locale locale) {\n\n List<String> localizedKeys = CmsLocaleManager.getLocaleVariants(key, locale, true, false);\n for (String localizedKey : localizedKeys) {\n if (propertiesMap.containsKey(localizedKey)) {\n return localizedKey;\n }\n }\n return key;\n }" ]